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
fix([cos-agent-output-write-amplification]): drain batched output on user terminate/kill before marking complete
[._.]/ Adam Eivy4e76ba3823e1
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 40d427571c..0bd40424f7 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -423,6 +423,14 @@ export async function spawnDirectly({// the agent is finalized. (output.txt is written separately below.)const outputBatcher = createAgentOutputBatcher(agentId);+ // Expose a drain hook on the activeAgents entry so the user-terminate/kill+ // paths (agentManagement.js) can flush pending batched output before they+ // mark the agent complete — otherwise up to one debounce window of+ // stdout/stderr could land after the terminal record. (The close handler+ // still drains too; flush() is idempotent.)+ const cliAgentEntry = activeAgents.get(agentId);+ if (cliAgentEntry) cliAgentEntry.flushOutput = () => outputBatcher.flush();+const stopForImmediateFallbackSignal = (text) => {if (immediateFallbackAnalysis || claudeProcess.killed) return;const analysis = detectImmediateFallbackSignal(text);diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex b8954fa340..955dc38b94 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -37,6 +37,13 @@ async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReasif (agentInfo?.initializationTimeout) clearTimeout(agentInfo.initializationTimeout);const result = await runnerFn(agentId).catch(err => ({ success: false, error: err.message }));if (result.success) {+ // Drain + drop this agent's runner output batcher before the terminal+ // record so pending ~250ms-batched output lands first, and the Map entry+ // doesn't leak if the runner never emits a later completion event. Dynamic+ // import avoids a static cycle (subAgentSpawner statically re-exports this+ // module). flushRunnerOutputBatcher is a no-op if no batcher exists.+ const { flushRunnerOutputBatcher } = await import('./subAgentSpawner.js');+ await flushRunnerOutputBatcher(agentId);await completeAgent(agentId, { success: false, error: errorMessage });const task = agentInfo?.task;if (task) {@@ -178,6 +185,10 @@ export async function terminateAgent(agentId) {// Track as user-terminated so the close handler doesn't re-queueuserTerminatedAgents.add(agentId);+ // Drain pending batched stdout/stderr before the terminal record so it+ // doesn't land after completion (the close handler also drains; idempotent).+ await agent.flushOutput?.();+// Mark agent as completed immediately with termination statusawait completeAgent(agentId, { success: false, error: 'Agent terminated by user' });@@ -266,6 +277,10 @@ export async function killAgent(agentId) {// Track as user-terminated so the close handler doesn't re-queueuserTerminatedAgents.add(agentId);+ // Drain pending batched stdout/stderr before the terminal record so it+ // doesn't land after completion (the close handler also drains; idempotent).+ await agent.flushOutput?.();+// Mark agent as completed immediately with kill statusawait completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex c309be7b77..5ce6364ee8 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -39,6 +39,7 @@ const normalizeEol = (s) => s.replace(/\r\n/g, '\n');const AGENT_CLI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentCliSpawning.js'), 'utf-8'));const AGENT_TUI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentTuiSpawning.js'), 'utf-8'));const AGENT_LIFECYCLE_SRC = normalizeEol(readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8'));+const AGENT_MANAGEMENT_SRC = normalizeEol(readFileSync(join(__dirname, 'agentManagement.js'), 'utf-8'));vi.mock('./cos.js', () => ({updateTask: vi.fn().mockResolvedValue(true),@@ -608,3 +609,42 @@ describe('close-handler skip-finalization — source contract', () => {expect(guardToReturn).toMatch(/runnerAgents\.delete\(agentId\)/);});});++describe('terminate/kill drains batched output before completion — source contract', () => {+ function fnBody(src, signature) {+ const start = src.indexOf(signature);+ if (start === -1) return '';+ const braceStart = src.indexOf('{', start);+ let depth = 0;+ for (let i = braceStart; i < src.length; i++) {+ if (src[i] === '{') depth++;+ else if (src[i] === '}') { depth--; if (depth === 0) return src.slice(braceStart, i + 1); }+ }+ return '';+ }++ it('terminateRunnerAgent flushes the runner output batcher before completeAgent', () => {+ const body = fnBody(AGENT_MANAGEMENT_SRC, 'async function terminateRunnerAgent');+ expect(body).toMatch(/flushRunnerOutputBatcher\(agentId\)/);+ const flushPos = body.indexOf('flushRunnerOutputBatcher(agentId)');+ const completePos = body.indexOf('completeAgent(');+ expect(flushPos, 'runner batcher must drain before completeAgent').toBeGreaterThan(-1);+ expect(flushPos).toBeLessThan(completePos);+ });++ it('terminateAgent (direct) drains agent.flushOutput before completeAgent', () => {+ const body = fnBody(AGENT_MANAGEMENT_SRC, 'export async function terminateAgent');+ expect(body).toMatch(/agent\.flushOutput\?\.\(\)/);+ const flushPos = body.indexOf('agent.flushOutput?.()');+ const completePos = body.indexOf('completeAgent(');+ expect(flushPos).toBeLessThan(completePos);+ });++ it('killAgent (direct) drains agent.flushOutput before completeAgent', () => {+ const body = fnBody(AGENT_MANAGEMENT_SRC, 'export async function killAgent');+ expect(body).toMatch(/agent\.flushOutput\?\.\(\)/);+ const flushPos = body.indexOf('agent.flushOutput?.()');+ const completePos = body.indexOf('completeAgent(');+ expect(flushPos).toBeLessThan(completePos);+ });+});diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 17cb21bd0d..6b979def9a 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -48,7 +48,7 @@ function getRunnerOutputBatcher(agentId) {return batcher;}-async function flushRunnerOutputBatcher(agentId) {+export async function flushRunnerOutputBatcher(agentId) {const batcher = runnerOutputBatchers.get(agentId);if (!batcher) return;// Flush BEFORE deleting: the agent is still in `runnerAgents` at this point