Skip to content

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

test: exercise real Windows getAgentProcessStats instead of copied parsers (#10753)

Adam Eivy82f54266b770
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index cfc88c532e..840dc71c43 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -14,16 +14,8 @@
* The guard added at agentManagement.js:381 short-circuits handleOrphanedTask
* when the task is already blocked with 'max-retries' or 'orphan-cooldown'.
*
- * Also covers the Windows tasklist CSV parsing logic in getAgentProcessStats.
- * `tasklist /FO CSV /NH` emits rows like:
- * "node.exe","12345","Console","1","82,156 K"
- * The pre-fix code called line.split(/\s+/) on this CSV, which misparses the
- * quoted, comma-separated output. The fix uses a proper CSV parser
- * (parseTasklistCsvRow, module-private) on the win32 branch.
- *
- * The Windows tests replicate the parser inline (matching project convention
- * from agentLifecycle.test.js — pure-logic copies instead of mocking the full
- * async-heavy production module).
+ * Also covers the Windows tasklist CSV handling in getAgentProcessStats,
+ * driven through the real exported function with a mocked `exec`.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -61,6 +53,13 @@ vi.mock('./cos.js', () => ({
forceSpawnTask: vi.fn().mockResolvedValue({ success: true })
}));
+// Only `exec` is replaced so the Windows tasklist cases never run a real command.
+const { execMock } = vi.hoisted(() => ({ execMock: vi.fn() }));
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ exec: execMock
+}));
+
vi.mock('./cosEvents.js', () => ({
emitLog: vi.fn()
}));
@@ -130,7 +129,7 @@ vi.mock('./creativeDirector/local.js', () => ({
vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));
-import { handleOrphanedTask, pauseAgent, resumeAgent, relaunchAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';
+import { handleOrphanedTask, pauseAgent, resumeAgent, relaunchAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent, getAgentProcessStats } from './agentManagement.js';
import { retireDeadAgent, stampLiExecutionVerdict } from './agentFinalization.js';
import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
@@ -727,126 +726,59 @@ describe('pauseAgent', () => {
});
});
-// ─── Inline replica of parseTasklistCsvRow ───────────────────────────────────
-// Keep in sync with the implementation in agentManagement.js.
-
-function parseTasklistCsvRow(line) {
- const fields = [];
- let cur = '';
- let inQuotes = false;
- for (let i = 0; i < line.length; i++) {
- const ch = line[i];
- if (ch === '"') { inQuotes = !inQuotes; continue; }
- if (ch === ',' && !inQuotes) { fields.push(cur); cur = ''; continue; }
- cur += ch;
- }
- fields.push(cur);
- return fields;
-}
-
-// ─── Inline replica of the Windows parse branch ──────────────────────────────
-// Mirrors the win32 block inside getAgentProcessStats.
-
-function parseWindowsTasklistLine(line, agentId, fallbackPid) {
- const fields = parseTasklistCsvRow(line);
- if (fields.length >= 5) {
- const pid = parseInt(fields[1], 10);
- const memoryKb = parseInt(fields[4].replace(/,/g, '').replace(/\s*K$/i, '').trim(), 10) || 0;
- return {
- active: true,
- agentId,
- pid,
- cpu: 0,
- memoryKb,
- memoryMb: Math.round(memoryKb / 1024 * 10) / 10,
- state: 'running'
- };
- }
- return { active: true, agentId, pid: fallbackPid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };
-}
+// ─── getAgentProcessStats — Windows tasklist telemetry ───────────────────────
+// Drives the real exported function with a mocked `exec` (callback contract, so
+// `promisify(exec)` resolves `{ stdout }`) and a temporary win32 platform.
-describe('parseTasklistCsvRow', () => {
- it('splits a standard tasklist CSV row into 5 fields', () => {
- const line = '"node.exe","12345","Console","1","82,156 K"';
- const fields = parseTasklistCsvRow(line);
- expect(fields).toHaveLength(5);
- expect(fields[0]).toBe('node.exe');
- expect(fields[1]).toBe('12345');
- expect(fields[2]).toBe('Console');
- expect(fields[3]).toBe('1');
- expect(fields[4]).toBe('82,156 K');
+describe('getAgentProcessStats — Windows tasklist parsing', () => {
+ const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
+ const statsFor = async (stdout, pid = 12345) => {
+ execMock.mockImplementation((_cmd, cb) => cb(null, { stdout, stderr: '' }));
+ activeAgents.set('agent-1', { pid });
+ return getAgentProcessStats('agent-1');
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', realPlatform);
+ activeAgents.clear();
});
- it('handles commas inside quoted fields without splitting', () => {
- const line = '"My, App.exe","99","Console","0","1,024 K"';
- const fields = parseTasklistCsvRow(line);
- expect(fields[0]).toBe('My, App.exe');
- expect(fields[1]).toBe('99');
- expect(fields[4]).toBe('1,024 K');
+ it('extracts pid and memory from a typical tasklist row', async () => {
+ const result = await statsFor('"node.exe","12345","Console","1","82,156 K"\r\n');
+ expect(execMock.mock.calls[0][0]).toBe('tasklist /FI "PID eq 12345" /FO CSV /NH');
+ expect(result).toEqual({
+ active: true, agentId: 'agent-1', pid: 12345, cpu: 0,
+ memoryKb: 82156, memoryMb: 80.2, state: 'running'
+ });
});
- it('handles unquoted fields gracefully', () => {
- const line = 'node.exe,12345,Console,1,82156 K';
- const fields = parseTasklistCsvRow(line);
- expect(fields).toHaveLength(5);
- expect(fields[1]).toBe('12345');
+ it('keeps commas and spaces inside a quoted image name from shifting columns', async () => {
+ const result = await statsFor('"My, App Service.exe","4321","Services","0","10,240 K"', 4321);
+ expect(result).toMatchObject({ pid: 4321, memoryKb: 10240, memoryMb: 10, state: 'running' });
});
- it('returns a single-element array for a line with no commas', () => {
- expect(parseTasklistCsvRow('"node.exe"')).toEqual(['node.exe']);
+ it('strips every thousands separator from large memory values', async () => {
+ const result = await statsFor('"node.exe","55555","Console","1","1,024,768 K"', 55555);
+ expect(result).toMatchObject({ pid: 55555, memoryKb: 1024768 });
});
- it('handles an empty string', () => {
- expect(parseTasklistCsvRow('')).toEqual(['']);
+ it('falls back to unknown state when the row has fewer than 5 fields', async () => {
+ const result = await statsFor('"node.exe","12345"');
+ expect(result).toEqual({
+ active: true, agentId: 'agent-1', pid: 12345, cpu: 0,
+ memoryKb: 0, memoryMb: 0, state: 'unknown'
+ });
});
-});
-describe('getAgentProcessStats — Windows tasklist parsing', () => {
- it('extracts pid and memoryKb from a typical tasklist row', () => {
- const line = '"node.exe","12345","Console","1","82,156 K"';
- const result = parseWindowsTasklistLine(line, 'agent-1', 12345);
- expect(result.active).toBe(true);
- expect(result.agentId).toBe('agent-1');
- expect(result.pid).toBe(12345);
- expect(result.cpu).toBe(0);
- expect(result.memoryKb).toBe(82156);
- expect(result.memoryMb).toBe(Math.round(82156 / 1024 * 10) / 10);
- expect(result.state).toBe('running');
- });
-
- it('handles small memory values without thousands separator', () => {
- const line = '"node.exe","777","Console","0","512 K"';
- const result = parseWindowsTasklistLine(line, 'agent-2', 777);
- expect(result.memoryKb).toBe(512);
- expect(result.memoryMb).toBe(Math.round(512 / 1024 * 10) / 10);
- });
-
- it('handles large memory with multiple comma separators', () => {
- const line = '"node.exe","55555","Console","1","1,024,768 K"';
- const result = parseWindowsTasklistLine(line, 'agent-3', 55555);
- expect(result.memoryKb).toBe(1024768);
- });
-
- it('falls back to unknown state when fewer than 5 fields are present', () => {
- const line = '"node.exe","12345"';
- const result = parseWindowsTasklistLine(line, 'agent-4', 12345);
- expect(result.active).toBe(true);
- expect(result.state).toBe('unknown');
- expect(result.pid).toBe(12345);
- expect(result.memoryKb).toBe(0);
- });
-
- it('cpu is always 0 (not available from basic tasklist)', () => {
- const line = '"node.exe","99","Console","0","4,096 K"';
- const result = parseWindowsTasklistLine(line, 'agent-5', 99);
- expect(result.cpu).toBe(0);
- });
-
- it('correctly parses a process name containing spaces and commas', () => {
- const line = '"My, App Service.exe","4321","Services","0","10,240 K"';
- const result = parseWindowsTasklistLine(line, 'agent-6', 4321);
- expect(result.pid).toBe(4321);
- expect(result.memoryKb).toBe(10240);
+ it('reports a dead process when tasklist prints nothing', async () => {
+ const result = await statsFor('');
+ expect(result).toMatchObject({ active: false, pid: 12345, state: 'dead' });
});
});