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: release interrupted TUI worktrees for task relaunch
Adam Eivy37bcd9a8fe49
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 4ec3a16dc5..a79704bfa5 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -33,6 +33,7 @@ import { getProcessStats, checkProcessRunning } from './processStats.js';import { usableAgentPid, runnerAgentLivenessFields } from '../lib/runnerAgentLiveness.js';import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';import { armForceKill as armForceKillShared } from './forceKill.js';+import { createTuiExitHandler } from './tuiExit.js';import { PORTS } from '../lib/ports.js';import { setupProcessErrorHandlers } from '../lib/errorHandler.js';import { parseSentinelPayload } from '../lib/agentSentinel.js';@@ -75,12 +76,6 @@ const HOST = process.env.HOST || '127.0.0.1';// Active agent processes (in memory)const activeAgents = new Map();-// `tui:output` is live telemetry, so an immediate process exit can beat its-// socket delivery. Keep a small terminal tail with the exit event: the PortOS-// spawner owns failure analysis and can persist it when no ordinary TUI chunk-// arrived. This is deliberately much smaller than the runner's 512 KiB live-// buffer and is enough to carry a CLI's startup diagnostic.-const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;const TUI_SIGNALS = new Set(['SIGTERM', 'SIGKILL', 'SIGINT']);// Bind the shared escalation to this process's map, grace window, and durable@@ -301,63 +296,9 @@ app.post('/spawn-tui', async (req, res) => {io.emit('tui:output', { sessionId, agentId, data });});- tuiProcess.onExit(async ({ exitCode, signal }) => {- try {- const current = activeAgents.get(agentId);- if (!current) return;- current.exited = true;- // Drop the handle before the awaited state write so GET /agents cannot- // publish processActive:false for a TUI whose completion event is still- // in flight (completeAgent keeps the first terminal verdict).- activeAgents.delete(agentId);- current.doneWatcher?.();- // Cancel any pending SIGKILL timer — process already exited.- if (current.killTimer) {- clearTimeout(current.killTimer);- current.killTimer = null;- }- // A paused agent's process was stopped deliberately and its record is what- // a later resume reads, so report nothing: emitting `agent:completed` here- // would finalize it as FAILED and retire the task the pause meant to keep.- // Mirrors the CLI close handler's own pause guard below. This became- // reachable when the node-pty kill started landing on Windows — before- // that, pausing a runner-owned TUI threw and the PTY simply never exited.- if (current.paused === true) {- console.log(`⏸️ TUI agent ${agentId} exited after pause`);- activeAgents.delete(agentId);- return;- }- const duration = Date.now() - current.startedAt;- const success = current.completedBySentinel;- const effectiveExitCode = success ? 0 : exitCode;- const effectiveSignal = success ? 0 : signal;- const outputTail = current.outputBuffer.slice(-TUI_EXIT_OUTPUT_TAIL_CHARS);- io.emit('tui:exit', {- sessionId,- agentId,- exitCode: effectiveExitCode,- signal: effectiveSignal,- ...(outputTail ? { outputTail } : {}),- });- emitToServer('agent:completed', {- agentId,- taskId,- exitCode: effectiveExitCode,- success,- duration,- outputLength: current.outputBuffer.length,- completionReason: current.completedBySentinel ? 'agent-signaled-done' : 'tui-exit',- });- await withState((state) => {- state.stats.completed++;- if (!success) state.stats.failed++;- delete state.agents[agentId];- });- } catch (err) {- console.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);- activeAgents.delete(agentId);- }- });+ tuiProcess.onExit(createTuiExitHandler({+ agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState,+ }));if (doneSentinelPath) {agent.doneWatcher = watchForFile(doneSentinelPath, async () => {diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex a50e60a9b5..c996bba0d2 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -109,17 +109,9 @@ describe('cos-runner termination', () => {expect(RUNNER_SRC).toContain('armForceKill(agentId, agent, { dropState: agent.paused !== true })');});- // A paused agent was stopped deliberately and its record is what a later- // resume reads. The CLI close handler always had this guard; the TUI one did- // not, and the node-pty kill fix is what made that path reachable on Windows- // (before it, the kill threw and the PTY never exited at all).- it('reports nothing when a paused TUI exits, instead of finalizing it failed', () => {- const exitIdx = RUNNER_SRC.indexOf('tuiProcess.onExit(');- expect(exitIdx, 'the TUI exit handler must exist').toBeGreaterThan(-1);- const completedIdx = RUNNER_SRC.indexOf("emitToServer('agent:completed'", exitIdx);- const handler = RUNNER_SRC.slice(exitIdx, completedIdx);- expect(handler).toContain('current.paused === true');- expect(handler).toContain('activeAgents.delete(agentId)');+ it('binds TUI exit handling to the original process record', () => {+ expect(RUNNER_SRC).toContain('tuiProcess.onExit(createTuiExitHandler({');+ expect(RUNNER_SRC).toContain('agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState,');});});@@ -158,13 +150,6 @@ describe('cos-runner durable TUI ownership (#3202)', () => {/import\s*\{[^}]*\brunnerAgentLivenessFields\b[^}]*\}\s*from\s*'\.\.\/lib\/runnerAgentLiveness\.js';/);expect(RUNNER_SRC).toMatch(/exited:\s*false/);- expect(RUNNER_SRC).toMatch(/current\.exited\s*=\s*true/);- const onExitIdx = RUNNER_SRC.indexOf('tuiProcess.onExit');- const exitedIdx = RUNNER_SRC.indexOf('current.exited = true');- expect(exitedIdx, 'onExit must stamp exited before deleting the handle').toBeGreaterThan(onExitIdx);- const deleteIdx = RUNNER_SRC.indexOf('activeAgents.delete(agentId);', exitedIdx);- expect(deleteIdx, 'onExit must drop the handle before awaiting completion I/O').toBeGreaterThan(exitedIdx);- expect(deleteIdx).toBeLessThan(RUNNER_SRC.indexOf('await withState((state) => {', exitedIdx));expect(RUNNER_SRC).toMatch(/if\s*\(\s*agent\.exited\s*===\s*true\s*\)\s*continue;/);expect(RUNNER_SRC).toMatch(/runnerAgentLivenessFields\(agent,\s*stats\)/);expect(RUNNER_SRC).toMatch(/inspectAgentProcess\(agent\)/);@@ -178,15 +163,6 @@ describe('cos-runner durable TUI ownership (#3202)', () => {expect(RUNNER_SRC).toMatch(/parseSentinelPayload\(contents\)/);expect(RUNNER_SRC).toMatch(/emitToServer\('agent:completed'/);});-- it('includes a bounded terminal output tail with TUI exit telemetry', () => {- // The live tui:output event can lose a race to an immediate process exit.- // Its terminal companion must retain a diagnostic tail for the spawner's- // raw-transcript failure analysis path.- expect(RUNNER_SRC).toContain('const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;');- expect(RUNNER_SRC).toMatch(/const outputTail = current\.outputBuffer\.slice\(-TUI_EXIT_OUTPUT_TAIL_CHARS\);/);- expect(RUNNER_SRC).toMatch(/io\.emit\('tui:exit',[\s\S]{0,350}?\.\.\.\(outputTail \? \{ outputTail \} : \{\}\)/);- });});// The runner is the second headless spawner: the same providers land here when adiff --git a/server/cos-runner/tuiExit.js b/server/cos-runner/tuiExit.jsnew file mode 100644index 0000000000..1b5e01936f--- /dev/null+++ b/server/cos-runner/tuiExit.js@@ -0,0 +1,63 @@+/** Finish a runner TUI on observed process exit, even after force-kill reaping. */+// `tui:output` is live telemetry, so an immediate process exit can beat its+// socket delivery. Keep a small terminal tail with the exit event: the PortOS+// spawner owns failure analysis and can persist it when no ordinary TUI chunk+// arrived. This is deliberately much smaller than the runner's 512 KiB live+// buffer and is enough to carry a CLI's startup diagnostic.+const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;++export function createTuiExitHandler({ agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState }) {+ return async ({ exitCode, signal }) => {+ try {+ // The force-kill timer removes the registry entry before node-pty emits+ // onExit. Keep the original handle so that exit still releases the server+ // session and the worktree. An actual exit, not a kill request, owns this.+ const current = agent;+ if (current.exited) return;+ current.exited = true;+ // Drop the handle before the awaited state write so GET /agents cannot+ // publish processActive:false for a TUI whose completion event is still+ // in flight (completeAgent keeps the first terminal verdict).+ activeAgents.delete(agentId);+ current.doneWatcher?.();+ // Cancel any pending SIGKILL timer — process already exited.+ if (current.killTimer) {+ clearTimeout(current.killTimer);+ current.killTimer = null;+ }+ const duration = Date.now() - current.startedAt;+ const success = current.completedBySentinel;+ const effectiveExitCode = success ? 0 : exitCode;+ const effectiveSignal = success ? 0 : signal;+ const outputTail = current.outputBuffer.slice(-TUI_EXIT_OUTPUT_TAIL_CHARS);+ io.emit('tui:exit', {+ sessionId,+ agentId,+ exitCode: effectiveExitCode,+ signal: effectiveSignal,+ ...(outputTail ? { outputTail } : {}),+ });+ // A pause still needs the transport exit: the server consumes it to+ // release its process map and unblock worktree adoption. Preserve the+ // durable paused record and omit the task-completion verdict.+ if (current.paused === true) return;+ emitToServer('agent:completed', {+ agentId,+ taskId,+ exitCode: effectiveExitCode,+ success,+ duration,+ outputLength: current.outputBuffer.length,+ completionReason: current.completedBySentinel ? 'agent-signaled-done' : 'tui-exit',+ });+ await withState((state) => {+ state.stats.completed++;+ if (!success) state.stats.failed++;+ delete state.agents[agentId];+ });+ } catch (err) {+ console.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);+ activeAgents.delete(agentId);+ }+ };+}diff --git a/server/cos-runner/tuiExit.test.js b/server/cos-runner/tuiExit.test.jsnew file mode 100644index 0000000000..e0b41253f1--- /dev/null+++ b/server/cos-runner/tuiExit.test.js@@ -0,0 +1,67 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('../lib/bufferedSpawn.js', () => ({ killProcessTree: vi.fn() }));++import { armForceKill } from './forceKill.js';+import { createTuiExitHandler } from './tuiExit.js';++function setup(extra = {}) {+ const agent = {+ process: {}, startedAt: Date.now(), outputBuffer: 'Usage limit reached',+ completedBySentinel: false, exited: false, doneWatcher: vi.fn(), ...extra,+ };+ const activeAgents = new Map([['agent-old', agent]]);+ const state = { agents: { 'agent-old': { status: 'paused' } }, stats: { completed: 0, failed: 0 } };+ const io = { emit: vi.fn() };+ const emitToServer = vi.fn();+ const withState = vi.fn(async fn => fn(state));+ const onExit = createTuiExitHandler({+ agentId: 'agent-old', taskId: 'task-1', sessionId: 'session-1',+ agent, activeAgents, io, emitToServer, withState,+ });+ return { agent, activeAgents, state, io, emitToServer, withState, onExit };+}++afterEach(() => vi.useRealTimers());++describe('runner TUI exit handoff', () => {+ it('delivers the exit after force-kill removed the handle, exactly once', async () => {+ vi.useFakeTimers();+ const run = setup();+ armForceKill(run.activeAgents, 'agent-old', run.agent, { graceMs: 5000 });+ vi.advanceTimersByTime(5000);+ expect(run.activeAgents.size).toBe(0);+ // Sending SIGKILL alone must not release the server's worktree hold.+ expect(run.io.emit).not.toHaveBeenCalled();++ await run.onExit({ exitCode: 0, signal: 9 });+ await run.onExit({ exitCode: 0, signal: 9 });+ expect(run.io.emit).toHaveBeenCalledExactlyOnceWith('tui:exit', {+ agentId: 'agent-old', sessionId: 'session-1', exitCode: 0, signal: 9,+ outputTail: 'Usage limit reached',+ });+ expect(run.emitToServer).toHaveBeenCalledTimes(1);+ expect(run.state.stats).toEqual({ completed: 1, failed: 1 });+ expect(run.agent.doneWatcher).toHaveBeenCalledTimes(1);+ });++ it('releases the transport on paused exit while preserving the resumable record', async () => {+ const run = setup({ paused: true });+ await run.onExit({ exitCode: 0, signal: 15 });+ expect(run.io.emit).toHaveBeenCalledWith('tui:exit', expect.objectContaining({ signal: 15 }));+ expect(run.activeAgents.size).toBe(0);+ expect(run.emitToServer).not.toHaveBeenCalled();+ expect(run.withState).not.toHaveBeenCalled();+ expect(run.state.agents['agent-old']).toEqual({ status: 'paused' });+ });++ it('retains successful sentinel completion and bounds the exit transcript', async () => {+ const run = setup({ completedBySentinel: true, outputBuffer: 'x'.repeat(20000) });+ await run.onExit({ exitCode: 1, signal: 15 });+ expect(run.io.emit).toHaveBeenCalledWith('tui:exit', expect.objectContaining({+ exitCode: 0, signal: 0, outputTail: 'x'.repeat(16 * 1024),+ }));+ expect(run.state.stats).toEqual({ completed: 1, failed: 0 });+ expect(run.state.agents).toEqual({});+ });+});diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 2a527393d2..4b2186af30 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -549,10 +549,11 @@ export async function relaunchAgent(agentId, overrides = {}) {const paused = await pauseAgent(agentId, pauseReason);if (!await whenPausedAgentExits(agentId, RELAUNCH_EXIT_TIMEOUT_MS)) {- // Proceed anyway: the task is already parked as paused, so refusing here- // would leave the user with a stopped agent and no relaunch. Say so in the- // log, since this is the window where a late exit can clean the worktree.- emitLog('warn', `⚠️ Relaunch of ${agentId} proceeded before its process exited — its worktree may not survive`, { agentId });+ // Keep the pause flag until the actual exit: retiring it early makes a late+ // exit finalize the old run and clean up the worktree the retry needs.+ throw new ServerError('The previous agent has not exited yet. Its task and worktree remain paused; resume after it stops.', {+ status: 409, code: 'AGENT_EXIT_PENDING'+ });}// `resumeAgent` already force-spawned the requeued task where it coulddiff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 3f358ca320..49255d1af8 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -1286,6 +1286,23 @@ describe('relaunchAgent — moves a running agent\'s task onto another provider'expect(stillLiveAtRequeue).toBe(false);});+ it('preserves the pause and worktree hold when process exit has not arrived', async () => {+ vi.useFakeTimers();+ try {+ activeAgents.set('agent-live-1', { process: fakeChildProcess(), taskId: 'task-abc' });+ const result = expect(relaunchAgent('agent-live-1', { provider: 'codex' }))+ .rejects.toMatchObject({ status: 409, code: 'AGENT_EXIT_PENDING' });+ await vi.advanceTimersByTimeAsync(15000);+ await result;+ expect(pausedAgents.has('agent-live-1')).toBe(true);+ expect(activeAgents.has('agent-live-1')).toBe(true);+ expect(reviveBlockedTask).not.toHaveBeenCalled();+ expect(forceSpawnTask).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+it('drops the model pinned to the provider it is moving off', async () => {// The whole point of a relaunch is leaving a provider that stopped answering.// `selectModelForTask` hands `metadata.model` to the CLI verbatim, so carrying