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: keep CoS TUI agents alive across server restarts (#3202)
[._.]/ Adam Eivy2e9703609935
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5a7f72024b..ab90e5046d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,7 @@- **[issue-3193] OpenCode agents now run in the app you selected, not the PortOS folder** — even with a correct Repository Path, agents on an OpenCode provider wrote their files into the PortOS directory and reported the PortOS path as their working folder. OpenCode decides where it is by reading an environment variable that describes the folder PortOS itself was started in, rather than the folder it was actually handed, so the workspace you picked was quietly ignored — only on OpenCode, which is why Codex, Claude Code, and Gemini looked fine. PortOS now sets that variable to the real working directory everywhere it starts an agent, a provider run, a TUI session, or a terminal. Troubleshooting steps for telling this apart from a mistyped Repository Path are in `docs/TROUBLESHOOTING.md`.- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.- **[issue-3202] Restarting PortOS no longer marks a running agent "completed" or burns its retry budget** — a restart kills every agent PortOS owns, and the terminal-based ones reported that as a clean finish. The task was recorded as done with nothing but two startup lines to show for it, and the folder holding its work was deleted on the way out. When the task did come back, the restart was counted against it as a failure: three routine restarts were enough to block the task outright, and two in a row left it sitting in a 30-minute cooldown. PortOS now recognizes that it was the one that pulled the plug. An agent cut short by a restart — terminal-based or headless — is recorded as interrupted rather than finished, its working folder is left untouched, and the task returns to the queue immediately, resuming from what the interrupted run left behind with no retry charged and no cooldown. An agent that had already reported its results still completes normally, one you terminated yourself is still recorded as terminated, and agents that genuinely fail on their own are unaffected. Agents still stop when PortOS restarts; keeping them running across one is separate work.+- **[issue-3202] CoS terminal agents now stay alive through a PortOS server restart** — their interactive processes run under the standalone CoS runner, while the web server reconnects to the surviving session, restores its Shell view and status stream, and continues without launching a duplicate. A deliberate full-stack restart still terminates the runner and its agents.- **[issue-3211] Orphaned agents now close their run history during recovery** — a process that disappeared before normal completion left its run permanently unfinished, with no end time, outcome, transcript size, or usage reconciliation. The recovery sweep now closes that run exactly once before requeuing the task, records PortOS-restart interruptions separately from ordinary failures, and safely handles older agents or missing run data.- **A brief internet outage no longer kills a working CoS agent.** When the machine lost its connection, a running agent's terminal went quiet — it couldn't reach the model — and after a few minutes the idle watchdog mistook that silence for a hung or finished agent and reaped it, throwing away in-progress work. PortOS now checks whether the machine is actually online before reaping an idle agent: while the connection is down, the reap is deferred and the agent is left alone to resume the moment the network returns (with a short grace so it isn't reaped in the instant between reconnecting and picking back up). Genuinely stuck agents on a healthy connection are still reaped on the same schedule as before, and the long absolute run-time ceiling still bounds an agent kept alive through a very long outage.- **Agents are now told nobody is there to answer them, and a run that stalled on a question says so.** An agent PortOS launches runs unattended, but nothing in its briefing said that — so an agent that hit a multiple-choice question or an approval gate would sit there presenting it to an empty room until the idle watchdog killed the run and discarded the work. One task was retried into the same question three times and filed nothing. Every agent briefing now states that no human is present, to decide for itself and record the assumption rather than ask, and to invoke slash commands in their non-interactive form. When a run does stall this way, the failure is no longer reported as a bare idle-out — PortOS notices the transcript ends on an unanswered prompt and says that's what happened, so the next step is skipping the gate rather than hunting for a stalled provider.diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 894740a22a..af1e530876 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -10,6 +10,7 @@import express from 'express';import { spawn } from 'child_process';+import * as pty from 'node-pty';import { join, basename } from 'path';import { writeFile, readFile } from 'fs/promises';import { existsSync } from 'fs';@@ -26,6 +27,8 @@ import { getProcessStats, checkProcessRunning } from './processStats.js';import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';import { PORTS } from '../lib/ports.js';import { setupProcessErrorHandlers } from '../lib/errorHandler.js';+import { parseSentinelPayload } from '../lib/agentSentinel.js';+import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';// Process-level safety net (defense-in-depth, see issue #1878). The main server// (server/index.js) already wires this same shared helper via@@ -45,6 +48,7 @@ setupProcessErrorHandlers();const SIGKILL_GRACE_MS = 5000; // wait after SIGTERM before forcing SIGKILLconst ORPHAN_CLEANUP_DELAY_MS = 3000; // delay on boot before reaping orphaned agentsconst SHUTDOWN_DRAIN_MS = 5000; // SIGTERM drain window before closing the server+const TUI_DONE_POLL_MS = 2000;// Path + listen constants. These lived adjacent to the command allowlist before// it was extracted to ./allowedCommands.js; they must stay here — they're@@ -58,6 +62,15 @@ const HOST = process.env.HOST || '127.0.0.1';// Active agent processes (in memory)const activeAgents = new Map();+const TUI_SIGNALS = new Set(['SIGTERM', 'SIGKILL', 'SIGINT']);++const terminateRunnerProcess = (agent, signal = 'SIGTERM') => {+ if (agent.kind === 'tui') {+ agent.process.kill(signal);+ return;+ }+ killProcessTree(agent.process, signal);+};// Express app setupconst app = express();@@ -103,12 +116,161 @@ app.get('/agents', async (req, res) => {processActive: stats.active,cpu: stats.cpu,memoryMb: stats.memoryMb,- state: stats.state+ state: stats.state,+ kind: agent.kind || 'cli',+ sessionId: agent.sessionId || null,+ command: agent.command || null,+ workspacePath: agent.workspacePath || null,});}res.json(agents);});+/**+ * Spawn an interactive TUI in a runner-owned PTY. PortOS remains responsible+ * for prompt timing and rich completion analysis while it is connected; the+ * runner owns process survival and emits normal agent completion if the server+ * restarts before the TUI exits.+ */+app.post('/spawn-tui', async (req, res) => {+ const {+ agentId,+ taskId,+ sessionId = agentId,+ command,+ args = [],+ workspacePath,+ envVars = {},+ cols = 80,+ rows = 24,+ doneSentinelPath = null,+ } = req.body;++ if (!agentId || !taskId || !sessionId || !isAllowedCommand(command)) {+ return res.status(400).json({ error: 'Missing or invalid TUI spawn fields' });+ }+ if (!Array.isArray(args)) {+ return res.status(400).json({ error: 'Invalid args: expected an array' });+ }+ if (activeAgents.has(agentId)) {+ return res.status(409).json({ error: `Agent ${agentId} is already running` });+ }++ const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;+ const childEnv = buildCliChildEnv({ before: envVars, cwd });+ // Windows coding CLIs are commonly npm .cmd shims. ConPTY cannot execute a+ // batch shim directly, so keep it behind cmd.exe; POSIX can own the CLI+ // process directly.+ const ptyCommand = process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : command;+ const ptyArgs = process.platform === 'win32' ? ['/d', '/s', '/c', command, ...args] : args;+ const tuiProcess = pty.spawn(ptyCommand, ptyArgs, {+ name: 'xterm-256color',+ cols,+ rows,+ cwd,+ env: childEnv,+ });+ const startedAt = Date.now();+ const agent = {+ kind: 'tui',+ process: tuiProcess,+ taskId,+ pid: tuiProcess.pid,+ startedAt,+ outputBuffer: '',+ workspacePath: cwd,+ sessionId,+ command,+ doneSentinelPath,+ completedBySentinel: false,+ doneTimer: null,+ };+ activeAgents.set(agentId, agent);++ tuiProcess.onData((data) => {+ const current = activeAgents.get(agentId);+ if (!current) return;+ current.outputBuffer += data;+ if (current.outputBuffer.length > 512 * 1024) {+ current.outputBuffer = current.outputBuffer.slice(-512 * 1024);+ }+ io.emit('tui:output', { sessionId, agentId, data });+ });++ tuiProcess.onExit(async ({ exitCode, signal }) => {+ try {+ const current = activeAgents.get(agentId);+ if (!current) return;+ if (current.doneTimer) clearInterval(current.doneTimer);+ const duration = Date.now() - current.startedAt;+ const success = current.completedBySentinel;+ const effectiveExitCode = success ? 0 : exitCode;+ const effectiveSignal = success ? 0 : signal;+ io.emit('tui:exit', { sessionId, agentId, exitCode: effectiveExitCode, signal: effectiveSignal });+ 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];+ });+ activeAgents.delete(agentId);+ } catch (err) {+ console.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);+ activeAgents.delete(agentId);+ }+ });++ if (doneSentinelPath) {+ agent.doneTimer = setInterval(async () => {+ try {+ const current = activeAgents.get(agentId);+ if (!current || !existsSync(doneSentinelPath)) return;+ current.completedBySentinel = true;+ clearInterval(current.doneTimer);+ current.doneTimer = null;+ const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {+ console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);+ return '';+ });+ const { summary } = parseSentinelPayload(contents);+ if (summary) {+ emitToServer('agent:output', {+ agentId,+ text: `${SENTINEL_COMPLETION_MARKER}\n${summary.slice(0, 4096)}\n`,+ });+ }+ current.process.kill();+ } catch (err) {+ console.error(`❌ TUI agent ${agentId} sentinel poll failed: ${err.message}`);+ }+ }, TUI_DONE_POLL_MS);+ }++ await withState((state) => {+ state.agents[agentId] = {+ pid: tuiProcess.pid,+ taskId,+ startedAt,+ kind: 'tui',+ sessionId,+ workspacePath: cwd,+ doneSentinelPath,+ };+ state.stats.spawned++;+ });++ console.log(`📟 Runner-owned TUI ${agentId} started (PID: ${tuiProcess.pid})`);+ res.json({ success: true, agentId, sessionId, pid: tuiProcess.pid });+});+/*** Get process stats for a specific agent*/@@ -423,13 +585,13 @@ app.post('/terminate/:agentId', (req, res) => {// killProcessTree (not .kill) so a Windows cmd.exe-wrapped CLI shim's real// child is taken down too, not orphaned (#2243). No-op difference on POSIX.- killProcessTree(agent.process, 'SIGTERM');+ terminateRunnerProcess(agent, 'SIGTERM');// Force kill after timeout; store handle so it can be cancelled if the// process exits cleanly before the grace window expires.agent.killTimer = setTimeout(() => {if (activeAgents.has(agentId)) {- killProcessTree(agent.process, 'SIGKILL');+ terminateRunnerProcess(agent, 'SIGKILL');activeAgents.delete(agentId);}}, SIGKILL_GRACE_MS);@@ -452,7 +614,7 @@ app.post('/kill/:agentId', async (req, res) => {// Use SIGKILL for immediate termination — killProcessTree so a Windows// cmd.exe-wrapped shim's real child isn't orphaned (#2243). POSIX unchanged.- killProcessTree(agent.process, 'SIGKILL');+ terminateRunnerProcess(agent, 'SIGKILL');// Clean up immediatelyactiveAgents.delete(agentId);@@ -487,11 +649,11 @@ app.post('/pause/:agentId', async (req, res) => {agent.pauseReason = reason;// killProcessTree so a Windows cmd.exe-wrapped shim's child isn't orphaned (#2243).- killProcessTree(agent.process, 'SIGTERM');+ terminateRunnerProcess(agent, 'SIGTERM');// Store handle so the close handler can clear it when the process exits first.agent.killTimer = setTimeout(() => {const current = activeAgents.get(agentId);- if (current?.paused) killProcessTree(current.process, 'SIGKILL');+ if (current?.paused) terminateRunnerProcess(current, 'SIGKILL');}, SIGKILL_GRACE_MS);res.json({ success: true, agentId, pid: agent.pid, pausedAt });@@ -511,10 +673,10 @@ app.post('/terminate-all', async (req, res) => {const agent = activeAgents.get(agentId);if (agent) {// killProcessTree so a Windows cmd.exe-wrapped shim's child isn't orphaned (#2243).- killProcessTree(agent.process, 'SIGTERM');+ terminateRunnerProcess(agent, 'SIGTERM');agent.killTimer = setTimeout(() => {if (activeAgents.has(agentId)) {- killProcessTree(agent.process, 'SIGKILL');+ terminateRunnerProcess(agent, 'SIGKILL');activeAgents.delete(agentId);}}, SIGKILL_GRACE_MS);@@ -585,6 +747,36 @@ app.get('/agents/:agentId/output', (req, res) => {io.on('connection', (socket) => {console.log(`🔌 Client connected: ${socket.id}`);+ socket.on('tui:input', ({ sessionId, data }) => {+ try {+ const agent = [...activeAgents.values()].find(candidate => candidate.sessionId === sessionId);+ if (agent?.kind === 'tui' && typeof data === 'string') agent.process.write(data);+ } catch (err) {+ console.error(`❌ TUI input relay failed: ${err.message}`);+ }+ });++ socket.on('tui:resize', ({ sessionId, cols, rows }) => {+ try {+ const agent = [...activeAgents.values()].find(candidate => candidate.sessionId === sessionId);+ if (agent?.kind !== 'tui') return;+ if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 1 || rows < 1) return;+ agent.process.resize(cols, rows);+ } catch (err) {+ console.error(`❌ TUI resize relay failed: ${err.message}`);+ }+ });++ socket.on('tui:kill', ({ sessionId, signal = 'SIGTERM' }) => {+ try {+ if (!TUI_SIGNALS.has(signal)) return;+ const agent = [...activeAgents.values()].find(candidate => candidate.sessionId === sessionId);+ if (agent?.kind === 'tui') terminateRunnerProcess(agent, signal);+ } catch (err) {+ console.error(`❌ TUI termination relay failed: ${err.message}`);+ }+ });+socket.on('disconnect', () => {console.log(`🔌 Client disconnected: ${socket.id}`);});@@ -659,7 +851,7 @@ process.on('SIGTERM', async () => {// Terminate all agentsfor (const [agentId, agent] of activeAgents) {console.log(`🔪 Terminating agent ${agentId}`);- killProcessTree(agent.process, 'SIGTERM'); // tree-kill so Windows cmd.exe shims aren't orphaned (#2243)+ terminateRunnerProcess(agent, 'SIGTERM');}// Wait for agents to terminatediff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex d43d45fe58..a5a92a4a8a 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -78,14 +78,25 @@ describe('cos-runner termination — Windows tree-kill for cmd.exe-wrapped shims);});- it('terminates agent processes via killProcessTree, not a bare .kill(), so the wrapped child is not orphaned', () => {+ it('tree-kills wrapped CLI agents while using node-pty kill for TUI handles', () => {// Once an agent is spawned as `cmd.exe /c opencode.cmd …` on Windows, a// plain agent.process.kill() signals only cmd.exe and orphans the real CLI.- // Every agent-process termination must route through killProcessTree.- expect(RUNNER_SRC).toMatch(/killProcessTree\(agent\.process,\s*'SIGTERM'\)/);- expect(RUNNER_SRC).toMatch(/killProcessTree\(agent\.process,\s*'SIGKILL'\)/);- // Guard against a regression that reverts an agent-process kill to bare .kill().- expect(RUNNER_SRC).not.toMatch(/agent\.process\.kill\(/);- expect(RUNNER_SRC).not.toMatch(/current\.process\.kill\(/);+ // node-pty handles are the exception: their own kill API releases the+ // native PTY resources correctly.+ expect(RUNNER_SRC).toMatch(+ /if\s*\(\s*agent\.kind\s*===\s*'tui'\s*\)\s*\{[\s\S]{0,100}?agent\.process\.kill\(signal\)[\s\S]{0,100}?return;/+ );+ expect(RUNNER_SRC).toMatch(/killProcessTree\(agent\.process,\s*signal\)/);+ });+});++describe('cos-runner durable TUI ownership (#3202)', () => {+ it('spawns the PTY in the runner and keeps Windows npm shims behind cmd.exe', () => {+ expect(RUNNER_SRC).toMatch(/app\.post\('\/spawn-tui'/);+ expect(RUNNER_SRC).toMatch(/const ptyCommand = process\.platform === 'win32'/);+ expect(RUNNER_SRC).toMatch(/pty\.spawn\(ptyCommand,\s*ptyArgs/);+ expect(RUNNER_SRC).toMatch(/io\.emit\('tui:output'/);+ expect(RUNNER_SRC).toMatch(/parseSentinelPayload\(contents\)/);+ expect(RUNNER_SRC).toMatch(/emitToServer\('agent:completed'/);});});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 251e402d0d..a9aff203b1 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -401,7 +401,7 @@ async function runAgentSpawn(task) {workspacePath,appName: resolvedAppName});- const executionMode = isTui ? 'tui' : useRunner ? 'runner' : 'direct';+ const executionMode = isTui ? (useRunner ? 'runner-tui' : 'tui') : useRunner ? 'runner' : 'direct';// Register the agent with model info.//@@ -437,7 +437,7 @@ async function runAgentSpawn(task) {modelReason: modelSelection.reason,runId,phase: 'initializing',- useRunner: isTui ? false : useRunner,+ useRunner,executionMode,taskAnalysisType: task.metadata?.analysisType || null,taskReviewType: task.metadata?.reviewType || null,@@ -562,6 +562,7 @@ async function runAgentSpawn(task) {cleanupWorktreeFn: cleanupAgentWorktree,isTruthyMetaFn: isTruthyMeta,leanMode,+ useDurableRunner: useRunner,});}if (useRunner) {diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 371877af4a..b40fac0f45 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -342,6 +342,16 @@ describe('runAgentSpawn source — handedOff pre-spawn vs post-handoff split', (});});+describe('runAgentSpawn source — durable TUI ownership (#3202)', () => {+ it('routes TUI providers through the runner when it is available', () => {+ expect(RUN_SPAWN_BODY).toMatch(+ /const executionMode = isTui \? \(useRunner \? 'runner-tui' : 'tui'\)/+ );+ expect(RUN_SPAWN_BODY).toMatch(/spawnTuiAgent\(\{[\s\S]{0,1000}?useDurableRunner:\s*useRunner/);+ expect(RUN_SPAWN_BODY).not.toMatch(/useRunner:\s*isTui\s*\?\s*false\s*:\s*useRunner/);+ });+});+// Source-level assertion (issue #989): the synthetic app-review marker bound by// `bindAppReviewAgent` before this spawn MUST be released on every// pre-completion `return null` path, or the app reads "in review" until the nextdiff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex e6eb7cc5f7..5ef12c3fda 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -11,9 +11,10 @@* or `agentManagement.js` (enforced by `agentImportCycles.test.js`).*/-import { getActiveAgentsFromRunner } from './cosRunnerClient.js';+import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import { isInternalTaskId } from '../lib/taskParser.js';import { runnerAgents } from './agentState.js';+import * as shellService from './shell.js';/*** Sync running agents from the runner (recovery after server restart).@@ -63,6 +64,19 @@ export async function syncRunnerAgents() {hasStartedWorking: true,startedAt: agent.startedAt});+ if (agent.kind === 'tui' && agent.sessionId && !shellService.getSession(agent.sessionId)) {+ const session = connectTuiSessionViaRunner(agent);+ shellService.registerExternalSession(agent.sessionId, session.ptyProcess, {+ cwd: agent.workspacePath,+ kind: 'agent-tui',+ agentId: agent.id,+ label: `Recovered TUI ${agent.id}`,+ command: agent.command,+ });+ session.ptyProcess.onExit(({ exitCode }) => {+ shellService.unregisterExternalSession(agent.sessionId, { exitCode });+ });+ }console.log(`🔄 Recovered agent ${agent.id} (task: ${agent.taskId})`);syncedCount++;}diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.jsnew file mode 100644index 0000000000..8a1b55b88c--- /dev/null+++ b/server/services/agentRunnerSync.test.js@@ -0,0 +1,74 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const recoveredPty = {+ onData: vi.fn(),+ onExit: vi.fn(),+ write: vi.fn(),+ resize: vi.fn(),+ kill: vi.fn(),+};++vi.mock('./cosRunnerClient.js', () => ({+ getActiveAgentsFromRunner: vi.fn(),+ connectTuiSessionViaRunner: vi.fn(() => ({+ sessionId: 'tui-session-1',+ pid: 1234,+ ptyProcess: recoveredPty,+ })),+}));++vi.mock('./shell.js', () => ({+ getSession: vi.fn(),+ registerExternalSession: vi.fn(),+ unregisterExternalSession: vi.fn(),+}));++vi.mock('./cos.js', () => ({+ getAllTasks: vi.fn().mockResolvedValue({+ user: { grouped: { active: [{ id: 'task-1', description: 'Example task' }] } },+ cos: { grouped: {} },+ }),+}));++import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';+import * as shellService from './shell.js';+import { runnerAgents } from './agentState.js';+import { syncRunnerAgents } from './agentRunnerSync.js';++describe('syncRunnerAgents runner-owned TUI recovery', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ runnerAgents.clear();+ vi.mocked(shellService.getSession).mockReturnValue(null);+ });++ it('reconciles one surviving TUI and restores its attachable shell relay', async () => {+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{+ id: 'agent-1',+ taskId: 'task-1',+ pid: 1234,+ startedAt: Date.now(),+ kind: 'tui',+ sessionId: 'tui-session-1',+ command: 'codex',+ workspacePath: '/tmp/example-workspace',+ }]);++ await expect(syncRunnerAgents()).resolves.toBe(1);++ expect(runnerAgents.has('agent-1')).toBe(true);+ expect(connectTuiSessionViaRunner).toHaveBeenCalledWith(expect.objectContaining({+ sessionId: 'tui-session-1',+ pid: 1234,+ }));+ expect(shellService.registerExternalSession).toHaveBeenCalledWith(+ 'tui-session-1',+ recoveredPty,+ expect.objectContaining({+ agentId: 'agent-1',+ kind: 'agent-tui',+ command: 'codex',+ }),+ );+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 84888c1d42..ae450889a2 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -26,6 +26,7 @@ import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';import { normalizeReviewers } from '../lib/validation.js';import * as git from './git.js';import { resolveReviewLoopOptions } from './codeReview.js';+import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';import { shellQuote } from '../lib/shellQuote.js';import { resolveCliModel, buildEffortArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';@@ -120,7 +121,48 @@ const DONE_POLL_INTERVAL_MS = 2000;* to create the session, `sessionId` is null and the caller is expected* to bail out via its `finish` path.*/-export function createAgentTuiSession({ agentId, provider, model, tuiConfig, cwd, forgeTokenEnv = {}, onData, onExit, onInitialCommandSent }) {+export async function createAgentTuiSession({+ agentId,+ taskId,+ provider,+ model,+ tuiConfig,+ cwd,+ forgeTokenEnv = {},+ doneSentinelPath = null,+ useDurableRunner = false,+ onData,+ onExit,+ onInitialCommandSent,+}) {+ const env = { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() };+ if (useDurableRunner) {+ // The runner launches the TUI command directly (there is no intermediate+ // login-shell readiness probe), so output can arrive before the spawn HTTP+ // response. Open the readiness gate before handing off to avoid discarding+ // the TUI's first bracketed-paste/input-ready signals.+ onInitialCommandSent?.();+ const session = await spawnTuiSessionViaRunner({+ agentId,+ taskId,+ command: tuiConfig.command,+ args: tuiConfig.args,+ workspacePath: cwd,+ envVars: env,+ doneSentinelPath,+ onData,+ onExit,+ });+ shellService.registerExternalSession(session.sessionId, session.ptyProcess, {+ cwd,+ kind: 'agent-tui',+ agentId,+ label: `${provider.name} ${agentId}`,+ command: tuiConfig.commandLine,+ });+ return session;+ }+const sessionId = shellService.createShellSession(null, {cwd,kind: 'agent-tui',@@ -149,7 +191,7 @@ export function createAgentTuiSession({ agentId, provider, model, tuiConfig, cwd// and NOT what buildCliChildEnv's `guard` does, because this is an overlay// whose real base env is assembled downstream. Only AI agent sessions get// the shim; the user's own Shell page does not.- env: { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() },+ env,onData,onExit,});@@ -248,6 +290,7 @@ export async function spawnTuiAgent({cleanupWorktreeFn,isTruthyMetaFn,leanMode = false,+ useDurableRunner = false,checkOnlineFn = isMachineOnline,}) {const outputFile = join(agentDir, 'output.txt');@@ -817,13 +860,16 @@ export async function spawnTuiAgent({? {}: await git.resolveForgeTokenEnv(cwd);- const session = createAgentTuiSession({+ const session = await createAgentTuiSession({agentId,+ taskId: task.id,provider,model,tuiConfig,cwd,forgeTokenEnv,+ doneSentinelPath,+ useDurableRunner,onData: handleData,onExit: handleExit,onInitialCommandSent: () => { commandInjected = true; },@@ -1454,7 +1500,7 @@ export async function spawnTuiAgent({pid,metadata: {phase: 'working',- executionMode: 'tui',+ executionMode: useDurableRunner ? 'runner-tui' : 'tui',tuiSessionId: sessionId,tuiCommand: tuiConfig.commandLine,tuiKind,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex ba65223f58..df8da1615d 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -9,7 +9,12 @@ vi.mock('./shell.js', () => ({killSession: vi.fn(),getSession: vi.fn(),getSessionProcess: vi.fn(),- getLastInputAt: vi.fn().mockReturnValue(null)+ getLastInputAt: vi.fn().mockReturnValue(null),+ registerExternalSession: vi.fn(),+}));++vi.mock('./cosRunnerClient.js', () => ({+ spawnTuiSessionViaRunner: vi.fn(),}));vi.mock('./cosEvents.js', () => ({@@ -178,6 +183,7 @@ import { existsSync } from 'fs';import { readFile } from 'fs/promises';import { execFile } from 'child_process';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';+import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import * as agentLifecycle from './agentFinalization.js';import * as agentErrorAnalysis from './agentErrorAnalysis.js';@@ -422,6 +428,7 @@ describe('spawnTuiAgent runtime', () => {executionId,laneName,checkOnlineFn,+ useDurableRunner: overrides.useDurableRunner ?? false,...helpers,});}@@ -460,6 +467,22 @@ describe('spawnTuiAgent runtime', () => {vi.mocked(shellService.getSessionProcess).mockReturnValue(null);vi.mocked(shellService.getSession).mockReturnValue({ id: SESSION_ID });+ vi.mocked(spawnTuiSessionViaRunner).mockImplementation(async (options) => {+ capturedOnData = options.onData;+ capturedOnExit = options.onExit;+ return {+ sessionId: SESSION_ID,+ pid: 4321,+ ptyProcess: {+ pid: 4321,+ onData: vi.fn(),+ onExit: vi.fn(),+ write: vi.fn(),+ resize: vi.fn(),+ kill: vi.fn(),+ },+ };+ });// Reset sentinel state: no .agent-done on disk, empty read. The// completion-sentinel test overrides both. clearAllMocks keeps the factory@@ -491,6 +514,27 @@ describe('spawnTuiAgent runtime', () => {// calls — those are covered by agentLifecycle.test.js.// ── GH_TOKEN pinning: the agent's own `gh pr create` must auth as the repo owner ─+ it('uses a runner-owned PTY and registers it as an attachable shell session', async () => {+ runSpawn({ useDurableRunner: true });+ await flushMicrotasks();++ expect(spawnTuiSessionViaRunner).toHaveBeenCalledWith(expect.objectContaining({+ agentId: 'agent-1',+ taskId: 'task-1',+ command: 'codex',+ workspacePath: '/tmp/ws',+ doneSentinelPath: '/tmp/ws/.agent-done',+ }));+ expect(shellService.createShellSession).not.toHaveBeenCalled();+ expect(shellService.registerExternalSession).toHaveBeenCalledWith(+ SESSION_ID,+ expect.objectContaining({ pid: 4321 }),+ expect.objectContaining({ agentId: 'agent-1', kind: 'agent-tui' }),+ );++ await capturedOnExit({ exitCode: 1, signal: 15 });+ });+it('passes the repo-owner-pinned GH_TOKEN into the TUI session env (buildSafeEnv would otherwise strip it)', async () => {let resolveComplete;const completeDone = new Promise((r) => { resolveComplete = r; });diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 118f3877d4..946c8216d7 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -30,6 +30,57 @@ const readRunnerJson = (response) =>let socket = null;// Map of event name -> array of handlers (supports multiple listeners per event)const eventHandlers = new Map();+// Runner-owned TUI PTYs are represented locally by small node-pty-compatible+// proxies. The callbacks survive Socket.IO reconnects within this server+// process; after a full server restart, runner-agent reconciliation owns the+// still-running process and its eventual completion.+const tuiSessions = new Map();++const dispatchTuiEvent = (event, data) => {+ const session = tuiSessions.get(data?.sessionId);+ if (!session) return;+ const handlers = event === 'tui:output' ? session.dataHandlers : session.exitHandlers;+ for (const handler of handlers) {+ try {+ const result = handler(event === 'tui:output'+ ? data.data+ : { exitCode: data.exitCode, signal: data.signal });+ if (result && typeof result.then === 'function') {+ result.catch(err => console.error(`🔌 CoS runner ${event} handler rejected: ${err.message}`));+ }+ } catch (err) {+ console.error(`🔌 CoS runner ${event} handler threw: ${err.message}`);+ }+ }+ if (event === 'tui:exit') tuiSessions.delete(data.sessionId);+};++const createTuiProxy = (sessionId, pid, state) => {+ const subscribe = (handlers, handler) => {+ handlers.add(handler);+ return { dispose: () => handlers.delete(handler) };+ };+ const emitControl = (event, payload = {}) => {+ if (!socket?.connected) {+ state.pendingControls.push({ event, payload });+ return true;+ }+ socket.emit(event, { sessionId, ...payload });+ return true;+ };+ return {+ sessionId,+ pid,+ ptyProcess: {+ pid,+ onData: (handler) => subscribe(state.dataHandlers, handler),+ onExit: (handler) => subscribe(state.exitHandlers, handler),+ write: (data) => emitControl('tui:input', { data }),+ resize: (cols, rows) => emitControl('tui:resize', { cols, rows }),+ kill: (signal = 'SIGTERM') => emitControl('tui:kill', { signal }),+ },+ };+};/*** Initialize connection to CoS Runner@@ -62,6 +113,11 @@ export function initCosRunnerConnection() {socket.on('connect', () => {console.log('🔌 Connected to CoS Runner');+ for (const [sessionId, state] of tuiSessions) {+ for (const { event, payload } of state.pendingControls.splice(0)) {+ socket.emit(event, { sessionId, ...payload });+ }+ }dispatch('connection:ready', undefined);});@@ -79,11 +135,59 @@ export function initCosRunnerConnection() {socket.on('agent:completed', (data) => dispatch('agent:completed', data));socket.on('agent:error', (data) => dispatch('agent:error', data));socket.on('agent:btw', (data) => dispatch('agent:btw', data));+ socket.on('tui:output', (data) => dispatchTuiEvent('tui:output', data));+ socket.on('tui:exit', (data) => dispatchTuiEvent('tui:exit', data));// Batch orphaned agents event (startup cleanup)socket.on('agents:orphaned', (data) => dispatch('agents:orphaned', data));}+/**+ * Spawn a TUI PTY in the durable CoS runner and return a node-pty-compatible+ * proxy used by the existing Shell/TUI orchestration.+ */+export async function spawnTuiSessionViaRunner(options) {+ const { onData, onExit, ...requestOptions } = options;+ const sessionId = requestOptions.sessionId || requestOptions.agentId;+ const state = {+ dataHandlers: new Set(onData ? [onData] : []),+ exitHandlers: new Set(onExit ? [onExit] : []),+ pendingControls: [],+ };+ tuiSessions.set(sessionId, state);+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/spawn-tui`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ...requestOptions, sessionId }),+ }, 60000).catch(err => {+ tuiSessions.delete(sessionId);+ throw err;+ });+ if (!response.ok) {+ tuiSessions.delete(sessionId);+ const error = await readRunnerJson(response);+ throw new Error(error.error || 'Failed to spawn runner-owned TUI session');+ }++ const result = await readRunnerJson(response);+ const pid = result.pid;++ return createTuiProxy(sessionId, pid, state);+}++/**+ * Recreate the local relay for a TUI that survived a portos-server restart.+ */+export function connectTuiSessionViaRunner({ sessionId, pid }) {+ const state = tuiSessions.get(sessionId) || {+ dataHandlers: new Set(),+ exitHandlers: new Set(),+ pendingControls: [],+ };+ tuiSessions.set(sessionId, state);+ return createTuiProxy(sessionId, pid, state);+}+/*** Register event handler (multiple handlers per event are supported)*/diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsindex 28a168a8bc..c6f8e6ad04 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -11,6 +11,7 @@ vi.mock('socket.io-client', () => ({capturedSocket = {on: vi.fn(socketOn),emit: vi.fn(),+ connected: true,disconnect: vi.fn()};return capturedSocket;@@ -34,7 +35,9 @@ import {killAgentViaRunner,getAgentStatsFromRunner,terminateAllAgentsViaRunner,- getAgentOutputFromRunner+ getAgentOutputFromRunner,+ spawnTuiSessionViaRunner,+ connectTuiSessionViaRunner,} from './cosRunnerClient.js';// The client reads the body via text() and tolerantly JSON.parses it, so a@@ -245,6 +248,58 @@ describe('cosRunnerClient', () => {});});+ describe('runner-owned TUI relay', () => {+ it('spawns a durable PTY and relays output, input, resize, and exit', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, {+ sessionId: 'agent-tui-1',+ pid: 4321,+ }));+ const session = await spawnTuiSessionViaRunner({+ agentId: 'agent-tui-1',+ taskId: 'task-1',+ command: 'codex',+ args: [],+ workspacePath: '/tmp/example-workspace',+ });+ const onData = vi.fn();+ const onExit = vi.fn();+ session.ptyProcess.onData(onData);+ session.ptyProcess.onExit(onExit);++ capturedSocketListeners['tui:output']({ sessionId: session.sessionId, data: 'working' });+ session.ptyProcess.write('hello');+ session.ptyProcess.resize(120, 40);+ capturedSocketListeners['tui:exit']({ sessionId: session.sessionId, exitCode: 0, signal: 0 });++ expect(onData).toHaveBeenCalledWith('working');+ expect(onExit).toHaveBeenCalledWith({ exitCode: 0, signal: 0 });+ expect(capturedSocket.emit).toHaveBeenCalledWith('tui:input', {+ sessionId: 'agent-tui-1',+ data: 'hello',+ });+ expect(capturedSocket.emit).toHaveBeenCalledWith('tui:resize', {+ sessionId: 'agent-tui-1',+ cols: 120,+ rows: 40,+ });+ expect(JSON.parse(fetchWithTimeout.mock.calls[0][1].body)).toMatchObject({+ agentId: 'agent-tui-1',+ sessionId: 'agent-tui-1',+ });+ });++ it('rebuilds a relay for a TUI discovered after server restart', () => {+ const session = connectTuiSessionViaRunner({ sessionId: 'recovered-tui', pid: 9876 });+ const onData = vi.fn();+ session.ptyProcess.onData(onData);++ capturedSocketListeners['tui:output']({ sessionId: 'recovered-tui', data: 'still alive' });++ expect(session.pid).toBe(9876);+ expect(onData).toHaveBeenCalledWith('still alive');+ });+ });+// ===========================================================================// getActiveAgentsFromRunner// ===========================================================================diff --git a/server/services/shell.js b/server/services/shell.jsindex 1a6cbe66f2..c5ed1bc961 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -346,7 +346,7 @@ function releaseExternalViews(socket, exceptId = null) {* @param {string} sessionId — typically the runId, so the Shell view correlates* with the /runs record.* @param {object} ptyProcess — the live node-pty IPty.- * @param {object} [options] — { label, command, cwd, kind }.+ * @param {object} [options] — { label, command, cwd, kind, agentId }.* @returns {string} sessionId (idempotent — returns the id if already registered).*/export function registerExternalSession(sessionId, ptyProcess, options = {}) {@@ -367,7 +367,7 @@ export function registerExternalSession(sessionId, ptyProcess, options = {}) {createdAt: Date.now(),label: options.label || null,kind: options.kind || 'tui-run',- agentId: null,+ agentId: options.agentId || null,command: options.command || null,onData: null,onExit: null,diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex cbecd1fca7..ecfe8781de 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -455,6 +455,7 @@ describe('registerExternalSession / unregisterExternalSession', () => {const pty = makeFakePty();const id = shell.registerExternalSession('run-123', pty, {label: 'pipeline-manuscript-completeness',+ agentId: 'agent-123',command: 'claude --model x',cwd: '/work',});@@ -463,6 +464,7 @@ describe('registerExternalSession / unregisterExternalSession', () => {expect(info).toMatchObject({sessionId: 'run-123',label: 'pipeline-manuscript-completeness',+ agentId: 'agent-123',kind: 'tui-run',command: 'claude --model x',external: true,diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex f020ff06f8..014b54bb58 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -145,9 +145,11 @@ async function runInitSpawner() {onCosRunnerEvent('agent:completed', async (data) => {const { agentId, exitCode, success, duration } = data;const agent = runnerAgents.get(agentId);- if (agent) {- clearTimeout(agent.initializationTimeout);- }+ // A runner-owned TUI is finalized by spawnTuiAgent while this server+ // remains connected. Only a TUI recovered into runnerAgents after a+ // server restart should use the generic runner completion path.+ if (!agent) return;+ clearTimeout(agent.initializationTimeout);// Drain pending output before completion so the final lines land in// state before handleAgentCompletion writes the terminal record.await flushRunnerOutputBatcher(agentId);