Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: scan processes once per Agents refresh (#7114)
[._.]/ Adam Eivy77db11b6b5f3
diff --git a/server/services/agents.js b/server/services/agents.jsindex 540bddddcb..e3714cdb88 100644--- a/server/services/agents.js+++ b/server/services/agents.js@@ -23,7 +23,7 @@ const AGENT_PATTERNS = [* Decide whether a matched process line is a real AI-agent CLI or an OS/UI* helper that only happens to share a substring with an agent name.*- * The pattern grep is a coarse substring match, so `cursor` also matches macOS+ * Brand detection is a coarse substring match, so `cursor` also matches macOS* native helpers like the TextInputUI framework's `CursorUIViewService.xpc`* (a text-caret UI service, NOT the Cursor AI editor). Those live under system* framework / XPC-service / app-bundle paths that no agent CLI is ever invoked@@ -48,10 +48,12 @@ export function isAgentProcessCommand(command) {*/export async function getRunningAgents() {const agents = [];+ const snapshot = await readProcessSnapshot();for (const agent of AGENT_PATTERNS) {- const procs = await findProcesses(agent.pattern);- procs.forEach(proc => {+ snapshot.forEach(entry => {+ if (!entry.matchText.includes(agent.pattern)) return;+ const { matchText: _matchText, ...proc } = entry;// Enrich with spawned command data if availableconst spawnedData = getSpawnedAgent(proc.pid);@@ -81,52 +83,18 @@ export async function getRunningAgents() {return agents;}-/**- * Find processes matching a pattern- */-async function findProcesses(pattern) {- const platform = process.platform;-- if (platform === 'darwin' || platform === 'linux') {- return findUnixProcesses(pattern);- } else if (platform === 'win32') {- return findWindowsProcesses(pattern);+/** Acquire once per request; classification never launches another probe. */+async function readProcessSnapshot() {+ if (process.platform === 'darwin' || process.platform === 'linux') {+ return readUnixSnapshot();}-+ if (process.platform === 'win32') return readWindowsSnapshot();return [];}-/**- * Validate pattern to prevent command injection- * Only allows alphanumeric characters, hyphens, and underscores- */-function validatePattern(pattern) {- if (typeof pattern !== 'string' || !pattern) {- return null;- }- // Only allow safe characters for process name matching- // Reject any shell metacharacters- if (!/^[a-zA-Z0-9_-]+$/.test(pattern)) {- return null;- }- return pattern;-}--/**- * Find processes on Unix-like systems (macOS, Linux)- */-async function findUnixProcesses(pattern) {- // Security: Validate pattern to prevent command injection- const safePattern = validatePattern(pattern);- if (!safePattern) {- console.warn(`⚠️ Invalid process pattern rejected: ${pattern}`);- return [];- }-- // ps command to get process info- // -e: all processes, -o: output format, -ww: unlimited width (no truncation)- // Security: Pattern is validated above to only contain safe characters- const cmd = `ps -ww -eo pid,ppid,%cpu,%mem,etime,command | grep -i "${safePattern}" | grep -v grep`;+async function readUnixSnapshot() {+ // Keep a bounded output buffer. Failed/oversized snapshots yield no partial list.+ const cmd = 'ps -ww -eo pid,ppid,%cpu,%mem,etime,command';const result = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024 }).catch(() => ({ stdout: '' }));@@ -135,6 +103,7 @@ async function findUnixProcesses(pattern) {for (const line of lines) {const parts = line.trim().split(/\s+/);+ if (parts[0] === 'PID') continue;if (parts.length >= 6) {const pid = parseInt(parts[0], 10);const ppid = parseInt(parts[1], 10);@@ -142,6 +111,8 @@ async function findUnixProcesses(pattern) {const mem = parseFloat(parts[3]);const etime = parts[4];const command = parts.slice(5).join(' ');+ if (!Number.isInteger(pid) || pid <= 0 || !Number.isFinite(ppid)+ || !Number.isFinite(cpu) || !Number.isFinite(mem)) continue;// Skip grep, our own scanner, macOS app bundles, and the system// framework / XPC helpers that only match a name substring (e.g. the@@ -150,8 +121,10 @@ async function findUnixProcesses(pattern) {// Parse elapsed time to get start timeconst runtime = parseElapsedTime(etime);+ if (!Number.isFinite(runtime)) continue;processes.push({+ matchText: command.toLowerCase(),pid,ppid,cpu,@@ -170,13 +143,9 @@ async function findUnixProcesses(pattern) {/*** Find processes on Windows*/-async function findWindowsProcesses(pattern) {- // Security: Validate pattern to prevent command injection- const safePattern = validatePattern(pattern);- if (!safePattern) {- console.warn(`⚠️ Invalid process pattern rejected: ${pattern}`);- return [];- }+async function readWindowsSnapshot() {+ // Patterns are private fixed literals; match Name, never command-line arguments.+ const filter = AGENT_PATTERNS.map(({ pattern }) => `Name LIKE '%${pattern}%'`).join(' OR ');// WMIC, not PowerShell CIM, was the original implementation here — but// Microsoft removed wmic.exe from Windows 11 (it is gone entirely on 24H2+@@ -187,16 +156,12 @@ async function findWindowsProcesses(pattern) {// returns ISO-8601 CreationDate (rather than wmic's `YYYYMMDDHHmmss.ffffff`),// which Date.parse handles directly.//- // Security: safePattern is validated above to contain only safe characters,- // and the script is passed as a single argv element to powershell -Command- // rather than through a shell, so there is no interpolation boundary to- // escape past.// CreationDate is projected through .ToString('o') rather than emitted raw:// Windows PowerShell 5.1 serializes a DateTime as "\/Date(1786...)\/" while// PowerShell 7 emits ISO-8601, and `powershell` resolves to whichever is// installed. Formatting it in the script pins one shape for both hosts.- const script = `Get-CimInstance Win32_Process -Filter "Name LIKE '%${safePattern}%'" `- + "| Select-Object ProcessId,ParentProcessId,WorkingSetSize,CommandLine,"+ const script = `Get-CimInstance Win32_Process -Filter "${filter}" `+ + "| Select-Object Name,ProcessId,ParentProcessId,WorkingSetSize,CommandLine,"+ "@{Name='CreationDate';Expression={$_.CreationDate.ToString('o')}} "+ '| ConvertTo-Json -Compress';@@ -208,7 +173,7 @@ async function findWindowsProcesses(pattern) {// Keep the empty-result behavior (the caller treats [] as "none running"),// but never again fail SILENTLY — a broken process probe is why this was// undiagnosable for so long.- console.error(`❌ Windows process probe failed for "${safePattern}": ${err.message}`);+ console.error(`❌ Windows process probe failed: ${err.message}`);return { stdout: '' };});@@ -221,7 +186,7 @@ async function findWindowsProcesses(pattern) {try {parsed = JSON.parse(raw);} catch (err) {- console.error(`❌ Windows process probe returned unparseable JSON for "${safePattern}": ${err.message}`);+ console.error(`❌ Windows process probe returned unparseable JSON: ${err.message}`);return [];}const rows = Array.isArray(parsed) ? parsed : [parsed];@@ -230,12 +195,13 @@ async function findWindowsProcesses(pattern) {for (const row of rows) {if (!row || typeof row !== 'object') continue;const pid = parseInt(row.ProcessId, 10);- if (!Number.isFinite(pid)) continue;+ if (!Number.isFinite(pid) || typeof row.Name !== 'string') continue;const startTime = parseWindowsDate(row.CreationDate);const runtime = Date.now() - startTime;processes.push({+ matchText: row.Name.toLowerCase(),pid,ppid: parseInt(row.ParentProcessId, 10) || 0,// Win32_Process carries no CPU% column (the old wmic query asked for adiff --git a/server/services/agents.test.js b/server/services/agents.test.jsindex 6e075b35ba..bfd1f11506 100644--- a/server/services/agents.test.js+++ b/server/services/agents.test.js@@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mock child_process before importing agents.jsvi.mock('../lib/childProcess.js', () => ({exec: vi.fn(),- // agents.js probes Windows via execFile(powershell, …) — see findWindowsProcesses.+ // agents.js probes Windows via execFile(powershell, …) — see readWindowsSnapshot.execFile: vi.fn()}));@@ -42,15 +42,11 @@ import {isAgentProcessCommand} from './agents.js';-// Helper to simulate exec callback.-// By default, returns stdout unconditionally. Tests that care about which pattern-// triggered the exec call should pass a conditional function:-// mockExecWith((cmd) => cmd.includes('claude') ? '<claude line>' : '')-function mockExecWith(stdoutOrFn) {+// Each discovery fixture is one complete process snapshot.+function mockExecWith(stdout) {exec.mockImplementation((_cmd, _opts, cb) => {// handle both (cmd, cb) and (cmd, opts, cb) formsconst callback = typeof _opts === 'function' ? _opts : cb;- const stdout = typeof stdoutOrFn === 'function' ? stdoutOrFn(_cmd) : stdoutOrFn;callback(null, { stdout });});}@@ -187,11 +183,7 @@ describe('agents.js', () => {// ===========================================================================describe('getRunningAgents', () => {it('parses pid, cpu, memory, and command from ps output for claude pattern', async () => {- // Use a command-conditional mock: only return output when the exec command- // actually searches for the 'claude' pattern — verifying command construction.- mockExecWith((cmd) =>- cmd.includes('claude') ? '42000 1 2.5 0.8 05:30 /usr/local/bin/claude --model opus\n' : ''- );+ mockExecWith('PID PPID %CPU %MEM ELAPSED COMMAND\n42000 1 2.5 0.8 05:30 /usr/local/bin/claude --model opus\n');const agents = await getRunningAgents();const a = agents.find(a => a.pid === 42000);@@ -203,11 +195,42 @@ describe('agents.js', () => {expect(a.command).toBe('/usr/local/bin/claude --model opus');});+ it('classifies one mixed snapshot and observes starts/exits on the next request', async () => {+ mockExecWith('PID PPID %CPU %MEM ELAPSED COMMAND\n' ++ '101 1 1.5 0.2 01:00 CLAUDE --use codex\n' ++ '102 1 0 0 02:00 agy\n103 1 0 0 03:00 gemini\n' ++ '104 1 0 0 04:00 aider\n105 1 0 0 05:00 cursor-agent\n' ++ '106 1 0 0 06:00 copilot\n107 1 0 0 00:00 unrelated\n' ++ 'bad 1 0 0 00:01 claude\n108 1 bad 0 00:01 claude\n' ++ '109 1 0 0 bad claude\nmalformed\n');+ const agents = await getRunningAgents();+ expect(exec).toHaveBeenCalledTimes(1);+ expect(exec).toHaveBeenCalledWith('ps -ww -eo pid,ppid,%cpu,%mem,etime,command',+ { maxBuffer: 10 * 1024 * 1024 }, expect.any(Function));+ expect(agents.map(a => [a.pid, a.agentType])).toEqual([+ [101, 'claude'], [101, 'codex'], [102, 'agy'], [103, 'gemini'],+ [104, 'aider'], [105, 'cursor'], [106, 'copilot']+ ]);+ expect(agents.every(a => !('matchText' in a))).toBe(true);+ mockExecWith('200 1 0 0 00:01 codex\n');+ expect((await getRunningAgents()).map(a => a.pid)).toEqual([200]);+ expect(exec).toHaveBeenCalledTimes(2);+ });++ it.each(['ENOENT', 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'])(+ 'discards failed or oversized Unix snapshots (%s)', async (code) => {+ exec.mockImplementation((_cmd, _opts, cb) => cb(Object.assign(new Error(code),+ { code, stdout: '101 1 0 0 00:01 claude\n' })));+ await expect(getRunningAgents()).resolves.toEqual([]);+ expect(exec).toHaveBeenCalledTimes(1);+ });+it('returns empty array when ps returns no output', async () => {mockExecWith('');const agents = await getRunningAgents();expect(agents).toEqual([]);+ expect(exec).toHaveBeenCalledTimes(1);});it('sorts agents newest-first by startTime', async () => {@@ -230,11 +253,8 @@ describe('agents.js', () => {// UI service, not the Cursor AI editor. It must never appear in the agent list.const nativeCursorHelper ='/System/Library/PrivateFrameworks/TextInputUIMacHelper.framework/Versions/A/XPCServices/CursorUIViewService.xpc/Contents/MacOS/CursorUIViewService';- mockExecWith((cmd) =>- cmd.includes('cursor')- ? `6001 1 0.0 0.1 02:00 ${nativeCursorHelper}\n` ++ mockExecWith(`6001 1 0.0 0.1 02:00 ${nativeCursorHelper}\n` +'6002 1 0.5 0.2 01:00 /usr/local/bin/cursor-agent --print\n'- : '');const agents = await getRunningAgents();@@ -383,6 +403,7 @@ describe('agents.js', () => {// ===========================================================================describe('getRunningAgents on Windows', () => {const cimRow = (over = {}) => ({+ Name: 'claude.exe',ProcessId: 4242,ParentProcessId: 100,WorkingSetSize: 52428800, // 50 MB@@ -402,7 +423,7 @@ describe('agents.js', () => {it('probes with PowerShell, not the removed wmic.exe', async () => {mockCim([cimRow()]);await getRunningAgents();- expect(execFile).toHaveBeenCalled();+ expect(execFile).toHaveBeenCalledTimes(1);const [bin, args] = execFile.mock.calls[0];expect(bin).toBe('powershell');expect(args.join(' ')).toContain('Get-CimInstance Win32_Process');@@ -410,6 +431,45 @@ describe('agents.js', () => {expect(args.join(' ')).not.toContain('wmic');});+ it('matches Name rather than arguments and refreshes the mixed snapshot', async () => {+ mockCim([cimRow({ Name: 'CLAUDE-codex.exe' }),+ cimRow({ ProcessId: 42, Name: 'aider.exe', CommandLine: 'aider --prompt claude',+ CreationDate: '2026-08-14T00:00:00Z' }),+ cimRow({ ProcessId: 43, Name: 'unrelated.exe' }), null, {}, 'bad']);+ const agents = await getRunningAgents();+ expect(agents.map(a => [a.pid, a.agentType])).toEqual([+ [42, 'aider'], [4242, 'claude'], [4242, 'codex']+ ]);+ expect(agents.every(a => !('matchText' in a))).toBe(true);+ expect(execFile).toHaveBeenCalledTimes(1);+ const [, args, opts] = execFile.mock.calls[0];+ expect(args.slice(0, 3)).toEqual(['-NoProfile', '-NonInteractive', '-Command']);+ expect(args[3]).toContain("Name LIKE '%claude%' OR Name LIKE '%codex%' OR Name LIKE '%agy%' OR Name LIKE '%gemini%' OR Name LIKE '%aider%' OR Name LIKE '%cursor%' OR Name LIKE '%copilot%'");+ expect(args[3]).toContain('Select-Object Name,ProcessId');+ expect(args[3]).toContain("CreationDate.ToString('o')");+ expect(opts.maxBuffer).toBe(8 * 1024 * 1024);+ mockCim(cimRow({ ProcessId: 77 }));+ expect((await getRunningAgents()).map(a => a.pid)).toEqual([77]);+ expect(execFile).toHaveBeenCalledTimes(2);+ });++ it.each(['', '[]', 'null', '{}'])('handles empty CIM output %s with one probe', async (raw) => {+ mockCim(raw);+ await expect(getRunningAgents()).resolves.toEqual([]);+ expect(execFile).toHaveBeenCalledTimes(1);+ });++ it('logs one oversized probe failure and discards partial output', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ execFile.mockImplementation((_bin, _args, _opts, cb) => cb(Object.assign(+ new Error('stdout maxBuffer length exceeded'),+ { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER', stdout: JSON.stringify(cimRow()) })));+ await expect(getRunningAgents()).resolves.toEqual([]);+ expect(execFile).toHaveBeenCalledTimes(1);+ expect(log).toHaveBeenCalledTimes(1);+ log.mockRestore();+ });+it('maps a CIM row to the shared process shape', async () => {mockCim([cimRow()]);const agents = await getRunningAgents();