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

address review: ship TUI provider defaults + harden shell hooks

[._.]/ Adam Eivy928d63fcfd44
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 09957dbd5f..61fdd93524 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+<<<<<<< HEAD
- **Universe-as-Canon lock semantics — series-extracted canon arrives auto-locked.**
Every canon entry on a universe (characters/settings/objects) can now carry a
`locked: true` flag, plus `prompt`, `tags`, `source`, and `sourceSeriesId`
@@ -52,6 +53,16 @@
skips locked + extract autoLock pass-through. Full server suite (4,525
tests) passes.
+- **TUI providers — codex, claude code, gemini in attachable shells.** New
+ provider type `tui` runs CoS agents inside a PTY-backed shell session that
+ the user can attach to mid-run from the Shell page (`/shell?session=…`).
+ Ships disabled-by-default entries for `codex-tui`, `claude-code-tui`, and
+ `gemini-tui` in `data.sample/providers.json`; existing deployments pick
+ them up automatically because `scripts/setup-data.js` now JSON-merges new
+ `providers` entries on update (same starter-merge pattern as
+ `prompts/stage-config.json`). The Shell page's quick-command toolbar also
+ gains a `gemini` button alongside the existing `claude` / `codex` buttons.
+
- **Universe canon — characters, places, and objects on the universe.** Phase A
of the Universe-as-canon refactor. `universe.characters[]`/`settings[]`/
`objects[]` arrays now live on the universe record alongside the existing
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index e5ff1384ac..ee346d4ffd 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect, useMemo, useCallback } from 'react';
+import { Link } from 'react-router-dom';
import {
Cpu,
Trash2,
@@ -493,14 +494,14 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</span>
)}
{!completed && agent.metadata?.tuiSessionId && (
- <a
- href={`/shell?session=${encodeURIComponent(agent.metadata.tuiSessionId)}`}
+ <Link
+ to={`/shell?session=${encodeURIComponent(agent.metadata.tuiSessionId)}`}
className="flex items-center gap-1 px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 hover:bg-emerald-500/25 whitespace-nowrap"
title="Open TUI shell session"
>
<ExternalLink size={10} aria-hidden="true" className="shrink-0" />
<span className="font-mono">shell {agent.metadata.tuiSessionId.slice(0, 6)}</span>
- </a>
+ </Link>
)}
{/* Show zombie warning if PID exists but process is dead */}
{!completed && agent.pid && processStats && !processStats.active && (
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 7e3cd3ad43..b0cdd494a4 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -611,10 +611,15 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
headlessArgs: formData.headlessArgs ? formData.headlessArgs.split(' ').filter(Boolean) : [],
timeout: parseInt(formData.timeout, 10)
};
- if (Number.isFinite(tuiPromptDelay)) data.tuiPromptDelayMs = tuiPromptDelay;
- else delete data.tuiPromptDelayMs;
- if (Number.isFinite(tuiIdleTimeout)) data.tuiIdleTimeoutMs = tuiIdleTimeout;
- else delete data.tuiIdleTimeoutMs;
+ if (formData.type === 'tui') {
+ if (Number.isFinite(tuiPromptDelay)) data.tuiPromptDelayMs = tuiPromptDelay;
+ else delete data.tuiPromptDelayMs;
+ if (Number.isFinite(tuiIdleTimeout)) data.tuiIdleTimeoutMs = tuiIdleTimeout;
+ else delete data.tuiIdleTimeoutMs;
+ } else {
+ delete data.tuiPromptDelayMs;
+ delete data.tuiIdleTimeoutMs;
+ }
// Only send apiKey if user entered a new value (avoid overwriting existing key with empty string)
if (!data.apiKey && provider) {
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index ae38ca6e8b..12cb4d7f67 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -14,6 +14,7 @@ const MAX_SESSIONS = 5;
const QUICK_COMMANDS = [
{ label: 'claude', command: 'claude --dangerously-skip-permissions' },
{ label: 'codex', command: 'codex' },
+ { label: 'gemini', command: 'gemini' },
{ label: 'openclaw', command: 'openclaw tui' },
{ label: 'git status', command: 'git status' },
{ label: 'git pull', command: 'git pull --rebase --autostash' },
diff --git a/data.sample/providers.json b/data.sample/providers.json
index 3bb1359725..49c2de8bc2 100644
--- a/data.sample/providers.json
+++ b/data.sample/providers.json
@@ -66,6 +66,59 @@
"GEMINI_SANDBOX": "false"
}
},
+ "codex-tui": {
+ "id": "codex-tui",
+ "name": "Codex TUI",
+ "type": "tui",
+ "command": "codex",
+ "args": [],
+ "models": ["codex-configured-default"],
+ "defaultModel": "codex-configured-default",
+ "lightModel": "codex-configured-default",
+ "mediumModel": "codex-configured-default",
+ "heavyModel": "codex-configured-default",
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
+ },
+ "claude-code-tui": {
+ "id": "claude-code-tui",
+ "name": "Claude Code TUI",
+ "type": "tui",
+ "command": "claude",
+ "args": ["--dangerously-skip-permissions"],
+ "models": ["claude-haiku-4-5-20251001", "claude-sonnet-4-5-20250929", "claude-opus-4-5-20251101", "claude-opus-4-6"],
+ "defaultModel": "claude-opus-4-6",
+ "lightModel": "claude-haiku-4-5-20251001",
+ "mediumModel": "claude-sonnet-4-5-20250929",
+ "heavyModel": "claude-opus-4-6",
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
+ },
+ "gemini-tui": {
+ "id": "gemini-tui",
+ "name": "Gemini TUI",
+ "type": "tui",
+ "command": "gemini",
+ "args": [],
+ "models": ["gemini-3.1-pro", "gemini-3-flash", "gemini-2.5-pro", "gemini-2.5-flash"],
+ "defaultModel": "gemini-2.5-flash",
+ "lightModel": "gemini-2.5-flash",
+ "mediumModel": "gemini-3-flash",
+ "heavyModel": "gemini-3.1-pro",
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {
+ "GEMINI_SANDBOX": "false"
+ },
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
+ },
"lmstudio": {
"id": "lmstudio",
"name": "LM Studio",
diff --git a/scripts/setup-data.js b/scripts/setup-data.js
index 745a077eba..9e233859fc 100644
--- a/scripts/setup-data.js
+++ b/scripts/setup-data.js
@@ -66,6 +66,7 @@ if (!existsSync(dataDir)) {
const JSON_MERGE_TARGETS = [
{ relPath: 'prompts/stage-config.json', mergeKey: 'stages' },
{ relPath: 'prompts/variables.json', mergeKey: 'variables' },
+ { relPath: 'providers.json', mergeKey: 'providers' },
];
const mergeJsonStarter = (relPath, mergeKey) => {
diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index b9e6de2cfc..df13595f76 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -72,6 +72,39 @@
"tuiPromptDelayMs": 2500,
"tuiIdleTimeoutMs": 180000
},
+ "claude-code-tui": {
+ "id": "claude-code-tui",
+ "name": "Claude Code TUI",
+ "type": "tui",
+ "command": "claude",
+ "args": ["--dangerously-skip-permissions"],
+ "models": ["claude-haiku-4-5", "claude-sonnet-4-6", "claude-opus-4-7"],
+ "defaultModel": "claude-sonnet-4-6",
+ "lightModel": "claude-haiku-4-5",
+ "mediumModel": "claude-sonnet-4-6",
+ "heavyModel": "claude-opus-4-7",
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
+ },
+ "gemini-tui": {
+ "id": "gemini-tui",
+ "name": "Gemini TUI",
+ "type": "tui",
+ "command": "gemini",
+ "args": [],
+ "models": [],
+ "defaultModel": null,
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
+ },
"gemini-cli": {
"id": "gemini-cli",
"name": "Gemini CLI",
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index c777975639..2d3e7cc0bc 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -188,6 +188,25 @@ export async function killAgent(agentId) {
return { success: true, agentId, pid: agent.pid, signal: 'SIGKILL' };
}
+/**
+ * Parse a single CSV row as emitted by `tasklist /FO CSV /NH`.
+ * Handles quoted fields (quotes are stripped; commas inside quotes are not splits).
+ * Returns an array of unquoted field strings.
+ */
+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;
+}
+
/**
* Get process stats for an agent (CPU, memory usage).
*/
@@ -208,17 +227,37 @@ export async function getAgentProcessStats(agentId) {
return { active: false, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'dead' };
}
- const parts = line.split(/\s+/).filter(Boolean);
- if (parts.length >= 3) {
- return {
- active: true,
- agentId,
- pid: parseInt(parts[0], 10),
- cpu: parseFloat(parts[1]) || 0,
- memoryKb: parseInt(parts[2], 10) || 0,
- memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,
- state: parts[3] || 'unknown'
- };
+ if (process.platform === 'win32') {
+ // tasklist /FO CSV /NH columns: Image Name, PID, Session Name, Session#, Memory Usage
+ // Memory Usage looks like: 82,156 K (comma as thousands separator, space before K)
+ // CPU is not available from basic tasklist; use 0 as an honest default.
+ 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'
+ };
+ }
+ } else {
+ const parts = line.split(/\s+/).filter(Boolean);
+ if (parts.length >= 3) {
+ return {
+ active: true,
+ agentId,
+ pid: parseInt(parts[0], 10),
+ cpu: parseFloat(parts[1]) || 0,
+ memoryKb: parseInt(parts[2], 10) || 0,
+ memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,
+ state: parts[3] || 'unknown'
+ };
+ }
}
return { active: true, agentId, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 2cba058bc9..97db0ee496 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -13,6 +13,17 @@
*
* 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).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -139,3 +150,126 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {
expect(addTask).not.toHaveBeenCalled();
});
});
+
+// ─── 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' };
+}
+
+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');
+ });
+
+ 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('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('returns a single-element array for a line with no commas', () => {
+ expect(parseTasklistCsvRow('"node.exe"')).toEqual(['node.exe']);
+ });
+
+ it('handles an empty string', () => {
+ expect(parseTasklistCsvRow('')).toEqual(['']);
+ });
+});
+
+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);
+ });
+});
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index b15bcf5787..ef2a16e794 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -1,5 +1,93 @@
-import { describe, it, expect } from 'vitest';
-import { buildTuiSpawnConfig } from './agentTuiSpawning.js';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// ─── Mocks for spawnTuiAgent tests ──────────────────────────────────────────
+// All vi.mock calls must be at the top level before any imports.
+
+vi.mock('./shell.js', () => ({
+ createShellSession: vi.fn(),
+ writeToSession: vi.fn(),
+ killSession: vi.fn(),
+ getSession: vi.fn(),
+ getSessionProcess: vi.fn()
+}));
+
+vi.mock('./cosEvents.js', () => ({
+ emitLog: vi.fn()
+}));
+
+vi.mock('./cosAgents.js', () => ({
+ appendAgentOutput: vi.fn().mockResolvedValue(undefined),
+ updateAgent: vi.fn().mockResolvedValue(undefined),
+ completeAgent: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('./agents.js', () => ({
+ registerSpawnedAgent: vi.fn(),
+ unregisterSpawnedAgent: vi.fn()
+}));
+
+vi.mock('./providerStatus.js', () => ({
+ markProviderUsageLimit: vi.fn().mockResolvedValue(undefined),
+ markProviderRateLimited: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('./cos.js', () => ({
+ updateTask: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('./executionLanes.js', () => ({
+ release: vi.fn()
+}));
+
+vi.mock('./toolStateMachine.js', () => ({
+ completeExecution: vi.fn(),
+ errorExecution: vi.fn()
+}));
+
+vi.mock('./agentErrorAnalysis.js', () => ({
+ analyzeAgentFailure: vi.fn().mockReturnValue(null),
+ resolveFailedTaskUpdate: vi.fn().mockResolvedValue({ status: 'failed' })
+}));
+
+vi.mock('./agentRunTracking.js', () => ({
+ completeAgentRun: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('./agentCompletion.js', () => ({
+ processAgentCompletion: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('./agentLifecycle.js', () => ({
+ persistSimplifySummaries: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('./agentState.js', () => ({
+ activeAgents: new Map(),
+ userTerminatedAgents: new Set()
+}));
+
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ appendFile: vi.fn().mockResolvedValue(undefined),
+ rm: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { root: '/tmp/portos-root' }
+}));
+
+vi.mock('../lib/providerModels.js', () => ({
+ // Mirror the real behaviour: pass through the model string, return null for
+ // the codex-configured-default sentinel or null/undefined input.
+ resolveCliModel: vi.fn((m) => (m === 'codex-configured-default' || !m) ? null : m)
+}));
+
+import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
+import * as shellService from './shell.js';
+import * as cosAgents from './cosAgents.js';
+import * as cos from './cos.js';
+import * as agentErrorAnalysis from './agentErrorAnalysis.js';
+import { activeAgents, userTerminatedAgents } from './agentState.js';
describe('agent TUI spawning', () => {
it('builds a codex TUI command without a model flag for the configured-default sentinel', () => {
@@ -59,3 +147,210 @@ describe('agent TUI spawning', () => {
expect(config.commandLine).toBe('codex');
});
});
+
+// ─── spawnTuiAgent runtime tests ─────────────────────────────────────────────
+
+// Flush the microtask queue (pending Promise continuations). vi.runAllMicrotasksAsync
+// is not available in vitest 4.x — use Promise.resolve() ticks instead.
+const flushMicrotasks = () => Promise.resolve().then(() => Promise.resolve()).then(() => Promise.resolve());
+
+describe('spawnTuiAgent runtime', () => {
+ let capturedOnData = null;
+ let capturedOnExit = null;
+
+ const SESSION_ID = 'test-session-id-abc';
+
+ const defaultProvider = { id: 'codex-tui', name: 'Codex TUI', type: 'tui', envVars: {} };
+ // Short delays so fake timers don't need to advance huge amounts of time.
+ const defaultTuiConfig = {
+ command: 'codex',
+ args: [],
+ commandLine: 'codex',
+ promptDelayMs: 100,
+ idleTimeoutMs: 50
+ };
+
+ function runSpawn(overrides = {}) {
+ const agentId = overrides.agentId ?? 'agent-1';
+ const task = overrides.task ?? { id: 'task-1', description: 'do the thing', metadata: {} };
+ const prompt = overrides.prompt ?? 'do the thing';
+ const workspacePath = overrides.workspacePath ?? '/tmp/ws';
+ const model = overrides.model ?? null;
+ const provider = overrides.provider ?? defaultProvider;
+ const runId = overrides.runId ?? 'run-1';
+ const tuiConfig = overrides.tuiConfig ?? defaultTuiConfig;
+ const agentDir = overrides.agentDir ?? '/tmp/agentdir';
+ const executionId = overrides.executionId ?? null;
+ const laneName = overrides.laneName ?? null;
+ const helpers = overrides.helpers ?? {
+ cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),
+ isTruthyMetaFn: (v) => !!v
+ };
+ return spawnTuiAgent(agentId, task, prompt, workspacePath, model, provider, runId, tuiConfig, agentDir, executionId, laneName, helpers);
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+
+ // Clear shared mutable state between tests
+ activeAgents.clear();
+ userTerminatedAgents.clear();
+
+ capturedOnData = null;
+ capturedOnExit = null;
+
+ // Default createShellSession captures callbacks and returns a valid session id
+ vi.mocked(shellService.createShellSession).mockImplementation((_socket, opts) => {
+ capturedOnData = opts.onData;
+ capturedOnExit = opts.onExit;
+ return SESSION_ID;
+ });
+
+ vi.mocked(shellService.getSessionProcess).mockReturnValue(null);
+ vi.mocked(shellService.getSession).mockReturnValue({ id: SESSION_ID });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // ── 1. Successful idle-complete path ────────────────────────────────────────
+ it('idle-complete: calls completeAgent(success:true) and updateTask(completed) when idle fires after enough output and runtime', async () => {
+ // Wire completeAgent to resolve a promise we can await, so we can detect
+ // when the async finish() chain completes without polling.
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(cosAgents.completeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ runSpawn();
+
+ // Flush initial async setup (updateAgent calls etc.)
+ await flushMicrotasks();
+
+ // Fire the prompt timer so promptSentAt is set (promptDelayMs = 100ms)
+ await vi.advanceTimersByTimeAsync(110);
+ await flushMicrotasks();
+
+ // Feed 2 meaningful lines AFTER the prompt so meaningfulLinesAfterPrompt >= 2.
+ // These must not match the promptPreview ("do the thing").
+ await capturedOnData(Buffer.from('Agent output line one\n'));
+ await capturedOnData(Buffer.from('Agent output line two\n'));
+
+ // Advance past DEFAULT_TUI_MIN_RUNTIME_MS (15 000ms) + idleTimeoutMs (50ms).
+ // The idle setInterval ticks every 5 000ms; at the >=15s tick the conditions
+ // (runtime >= 15s, lines >= 2, idle >= 50ms) are all satisfied.
+ await vi.advanceTimersByTimeAsync(21000);
+
+ // finish() is called as fire-and-forget inside the interval callback;
+ // switch to real timers and await our sentinel promise so the full async
+ // chain (completeAgent → updateTask → ...) drains completely.
+ vi.useRealTimers();
+ await completeDone;
+
+ expect(cosAgents.completeAgent).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({ success: true, completionReason: 'idle-complete' })
+ );
+ expect(cos.updateTask).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({ status: 'completed' }),
+ expect.any(String)
+ );
+ });
+
+ // ── 2. Command-not-found path ────────────────────────────────────────────────
+ it('command-not-found: completeAgent called with exitCode 127 and task updated to failed', async () => {
+ const spawnPromise = runSpawn();
+ await flushMicrotasks();
+
+ // Feed "command not found" output BEFORE the prompt timer fires (promptSentAt === null).
+ // commandName is derived from tuiConfig.command = 'codex' via .split('/').pop().
+ await capturedOnData(Buffer.from('bash: codex: command not found\n'));
+ await flushMicrotasks();
+
+ await spawnPromise;
+
+ expect(cosAgents.completeAgent).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ success: false,
+ exitCode: 127,
+ completionReason: 'command-not-found'
+ })
+ );
+ // resolveFailedTaskUpdate mock returns { status: 'failed' }
+ expect(cos.updateTask).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({ status: 'failed' }),
+ expect.any(String)
+ );
+ });
+
+ // ── 3. Shell-exit path with non-zero exit code ───────────────────────────────
+ it('shell-exit: completeAgent called with success:false and exitCode 1 when shell exits non-zero', async () => {
+ const spawnPromise = runSpawn();
+ await flushMicrotasks();
+
+ await capturedOnExit({ exitCode: 1, killed: false });
+ await flushMicrotasks();
+
+ await spawnPromise;
+
+ expect(cosAgents.completeAgent).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ success: false,
+ exitCode: 1,
+ completionReason: 'shell-exit'
+ })
+ );
+ });
+
+ // ── 4. Killed / user-terminated path ────────────────────────────────────────
+ it('user-terminated: completeAgent receives terminated-by-user error and updateTask called with blocked+user-terminated', async () => {
+ // Mark agent as user-terminated before the exit fires
+ userTerminatedAgents.add('agent-1');
+
+ const spawnPromise = runSpawn();
+ await flushMicrotasks();
+
+ await capturedOnExit({ exitCode: 0, killed: true });
+ await flushMicrotasks();
+
+ await spawnPromise;
+
+ expect(cosAgents.completeAgent).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ success: false,
+ error: 'Agent terminated by user'
+ })
+ );
+ expect(cos.updateTask).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({
+ status: 'blocked',
+ metadata: expect.objectContaining({ blockedCategory: 'user-terminated' })
+ }),
+ expect.any(String)
+ );
+ });
+
+ // ── 5. Spawn-error path (createShellSession returns null) ────────────────────
+ it('spawn-error: function returns null and completeAgent reports spawn-error when session creation fails', async () => {
+ vi.mocked(shellService.createShellSession).mockReturnValue(null);
+
+ const result = await runSpawn();
+
+ expect(result).toBeNull();
+ expect(cosAgents.completeAgent).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ success: false,
+ error: 'Failed to create TUI shell session',
+ completionReason: 'spawn-error'
+ })
+ );
+ });
+});
diff --git a/server/services/shell.js b/server/services/shell.js
index 2214895e60..050b3e3989 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -7,12 +7,20 @@ const shellSessions = new Map();
const MAX_TOTAL_SESSIONS = 5;
-function runHook(label, sessionId, fn, arg) {
+// PTY event handlers run outside the Express middleware chain — uncaught throws here
+// crash the Node process instead of bubbling to res.next. try/catch is therefore
+// justified in this one spot despite the project-wide "no try/catch" convention.
+// Async hooks are serialized per-session via hookQueue so interleaved awaits (e.g.
+// agentTuiSpawning's handleData mutating module-level buffers) don't race.
+function runHook(label, session, fn, arg) {
if (!fn) return;
- const result = fn(arg);
- if (result && typeof result.then === 'function') {
- result.catch(err => console.error(`🐚 ${label} handler error in ${sessionId.slice(0, 8)}: ${err.message}`));
- }
+ session.hookQueue = session.hookQueue.then(() => {
+ try {
+ return Promise.resolve(fn(arg));
+ } catch (err) {
+ console.error(`🐚 ${label} sync error in ${session._id}: ${err.message}`);
+ }
+ }).catch(err => console.error(`🐚 ${label} async error in ${session._id}: ${err.message}`));
}
// Allowlist of safe environment variable prefixes to pass to PTY sessions
@@ -72,7 +80,10 @@ export function createShellSession(socket, options = {}) {
rows,
cwd,
env: {
- ...buildSafeEnv(),
+ ...buildSafeEnv(), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)
+ // options.env is the caller's explicit opt-in env (e.g. TUI provider API keys for codex/claude).
+ // Callers are responsible for not passing vars they don't want visible inside attachable shells.
+ // Single-user/single-instance deployment (Tailscale-only) makes this acceptable.
...(options.env || {}),
TERM: 'xterm-256color',
COLORTERM: 'truecolor'
@@ -91,6 +102,8 @@ export function createShellSession(socket, options = {}) {
// Store session info
shellSessions.set(sessionId, {
+ _id: sessionId.slice(0, 8),
+ hookQueue: Promise.resolve(),
pty: ptyProcess,
socket,
cwd,
@@ -115,7 +128,7 @@ export function createShellSession(socket, options = {}) {
}
const session = shellSessions.get(sessionId);
session?.socket?.emit('shell:output', { sessionId, data });
- runHook('onData', sessionId, session?.onData, data);
+ if (session) runHook('onData', session, session.onData, data);
});
// Handle pty exit
@@ -124,7 +137,7 @@ export function createShellSession(socket, options = {}) {
const session = shellSessions.get(sessionId);
shellSessions.delete(sessionId);
session?.socket?.emit('shell:exit', { sessionId, code: exitCode });
- runHook('onExit', sessionId, session?.onExit, { exitCode });
+ if (session) runHook('onExit', session, session.onExit, { exitCode });
broadcastSessionList();
});
@@ -228,7 +241,7 @@ export function killSession(sessionId) {
console.log(`🐚 Killing shell session ${sessionId.slice(0, 8)}`);
session.pty.kill();
shellSessions.delete(sessionId);
- runHook('onExit', sessionId, session.onExit, { exitCode: null, killed: true });
+ runHook('onExit', session, session.onExit, { exitCode: null, killed: true });
broadcastSessionList();
return true;
}