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

surface one-shot TUI runs as interactive sessions in the Shell page

[._.]/ Adam Eivy9891d3d839a0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3f19039fdb..7d44d3e7ec 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,8 @@
- **Public API surface with per-API auth gating (Voice/TTS + sdapi):** PortOS can now serve individual services as HTTP APIs on your tailnet. A new **Settings → API Access** tab exposes per-API toggles — *Expose on the network* (off by default) and *Require auth* (off = passwordless) — so you can keep the whole app behind your PortOS password while leaving the **Voice/TTS** and **Image Gen (sdapi)** APIs open for other machines to call. A deliberately-minimal `POST /api/voice/public/synthesize` (plus `/voices` and `/engines`) turns text into WAV audio with any engine/voice/rate; config and process-control endpoints always stay gated. A single in-tree registry (`server/lib/apiRegistry.js`) drives the auth-gate exemptions, the settings UI, and a native **OpenAPI 3.1 spec** at `GET /api/api-docs/openapi.json` (no swagger dependency — request bodies are generated from the same Zod schemas the routes validate against). The API Access tab shows each API's public base URL and a copy-paste `curl` example, and the Voice settings tab links to it. Defaults are safe: both APIs ship not-exposed and passwordless-once-exposed, with a migration seeding the key for existing installs.
+- **Live TUI runs are now viewable AND drivable in the Shell page** — one-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) — like the manuscript editor's editorial review and pipeline stages — now appear in **Developer Tools → Shell** as fully interactive session tabs (a pulsing bot-icon "live" tab, plus a live-run count in the header). Previously these spawned an invisible PTY you couldn't see; now you can open the tab to watch the run's live output, scroll its recent history (last 50 KB buffered for late attach), **type into it** to answer a question the model is waiting on or steer it mid-run, and **Stop** it if it hangs. So a watched run isn't snapped shut while you're reading or about to answer, the runner pauses its 8-second idle-auto-complete while you have the tab open — the run then ends on natural exit, an explicit Stop, or its configured max-time backstop (unattended pipeline runs keep the snappy idle timing). Tabs are labelled by the run's source (e.g. `pipeline-manuscript-completeness`), don't count toward the shell-session cap, and are skipped by Shell's auto-attach (you opt in by clicking), so the default "give me a shell" behavior is unchanged. The interactive-shell cap was also raised from 5 to 20. (`server/services/shell.js`, `server/lib/tuiPromptRunner.js`, `client/src/pages/Shell.jsx`)
+
## Fixed
- **[issue-1080] Notes synced from other machines become searchable promptly** — a Brain note, daily-log entry, person, project, or idea created or edited on one of your machines is now re-indexed into semantic memory on the others as soon as it syncs, instead of waiting for a full manual re-sync. Edits and deletes that arrive from a peer also refresh or retire the matching memory entry, so search no longer surfaces stale copies of records that changed elsewhere. A new **Refresh embeddings** button on the Brain graph re-indexes everything in one pass to heal anything that drifted before this fix.
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index 95611683ac..67d549a6ba 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -5,12 +5,12 @@ import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import '@xterm/xterm/css/xterm.css';
import { useSocket } from '../hooks/useSocket';
-import { RefreshCw, Power, PowerOff, FolderOpen, ChevronDown, Plus, X, Terminal as TerminalIcon, ClipboardPaste, OctagonX, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft } from 'lucide-react';
+import { RefreshCw, Power, PowerOff, FolderOpen, ChevronDown, Plus, X, Terminal as TerminalIcon, ClipboardPaste, OctagonX, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft, Bot } from 'lucide-react';
import * as api from '../services/api';
import { readClipboard } from '../lib/clipboard';
// Must match MAX_TOTAL_SESSIONS in server/services/shell.js
-const MAX_SESSIONS = 5;
+const MAX_SESSIONS = 20;
const QUICK_COMMANDS = [
// `--system-prompt .` replaces Claude's default system prompt with a single
@@ -426,9 +426,11 @@ export default function Shell() {
sessionsRef.current = sessionList;
setSessions(sessionList);
// Auto-pick helper: skip sessions already attached to another socket so we don't
- // steal them via the shell:detached takeover. Manual tab clicks bypass this.
+ // steal them via the shell:detached takeover. Also skip external read-only TUI
+ // runs — those are opt-in views the user clicks into, never the default landing
+ // session. Manual tab clicks bypass this.
const pickUnattachedSurvivor = (list) => {
- const free = list.filter(s => !s.attached);
+ const free = list.filter(s => !s.attached && !s.external);
return free.length > 0 ? free[free.length - 1] : null;
};
// On first load, auto-attach to existing session or create new
@@ -564,8 +566,9 @@ export default function Shell() {
// complete instead of overriding it with our fallback. The handleShellAttached
// response will install the new session and the user's intent wins.
if (pendingAttachRef.current.target) return;
- // Auto-attach to a survivor not already driving another tab (don't steal).
- const free = sessionsRef.current.filter(s => s.sessionId !== sid && !s.attached);
+ // Auto-attach to a survivor not already driving another tab (don't steal,
+ // and don't auto-adopt a read-only TUI-run view).
+ const free = sessionsRef.current.filter(s => s.sessionId !== sid && !s.attached && !s.external);
if (free.length > 0) {
// Claim pending immediately so the shell:sessions broadcast that follows
// shell:exit doesn't race the timeout — the bare-/shell adoption branch
@@ -644,7 +647,7 @@ export default function Shell() {
// No previously-displayed session to restore (e.g. initial deep-link attach
// failed before any session was active). Fall back to a free survivor so the
// user isn't stranded on /shell/<dead-id> with only the error message visible.
- const free = live.filter(s => !s.attached && s.sessionId !== failedTarget);
+ const free = live.filter(s => !s.attached && s.sessionId !== failedTarget && !s.external);
if (free.length > 0) {
attachToSession(free[free.length - 1].sessionId, { claim: true });
} else if (urlSessionIdRef.current) {
@@ -657,7 +660,7 @@ export default function Shell() {
// isn't already attached elsewhere; claim:true protects against multi-tab
// adopt races. activateSession will update the URL on success.
clearActiveSession();
- const free = live.filter(s => !s.attached && s.sessionId !== failedTarget);
+ const free = live.filter(s => !s.attached && s.sessionId !== failedTarget && !s.external);
if (free.length > 0) {
attachToSession(free[free.length - 1].sessionId, { claim: true });
} else {
@@ -747,6 +750,14 @@ export default function Shell() {
}
}, [urlSessionId, switchToSession]);
+ // External TUI runs (editorial review, pipeline stages, etc.) are surfaced as
+ // opt-in, fully-interactive tabs — you can watch and step in. They're labelled
+ // distinctly and don't count toward the shell cap.
+ const interactiveCount = sessions.filter(s => !s.external).length;
+ const liveRunCount = sessions.filter(s => s.external).length;
+ const activeSession = sessions.find(s => s.sessionId === activeSessionId);
+ const isLiveRun = !!activeSession?.external;
+
return (
<div className="h-full flex flex-col p-4 md:p-6">
{/* Header */}
@@ -758,11 +769,18 @@ export default function Shell() {
<div className={`w-2 h-2 rounded-full ${connected ? 'bg-green-500' : 'bg-gray-500'}`} />
{connected ? 'Connected' : 'Disconnected'}
</div>
- {sessions.length > 0 && (
- <span className="text-xs text-gray-500 font-mono">{sessions.length}/{MAX_SESSIONS}</span>
+ {interactiveCount > 0 && (
+ <span className="text-xs text-gray-500 font-mono">{interactiveCount}/{MAX_SESSIONS}</span>
+ )}
+ {liveRunCount > 0 && (
+ <span className="flex items-center gap-1 text-xs text-port-accent font-mono" title={`${liveRunCount} live TUI run${liveRunCount > 1 ? 's' : ''}`}>
+ <Bot size={12} />
+ {liveRunCount} live
+ </span>
)}
<div className="flex items-center gap-2 ml-auto">
- {connected && (
+ {/* Restart (kill + new shell) is meaningless for a TUI-run view. */}
+ {connected && !isLiveRun && (
<button
onClick={() => { stopSession(); setTimeout(() => { if (mountedRef.current) startSession(); }, 1000); }}
className="flex items-center gap-1.5 px-2.5 py-2 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded-lg text-sm transition-colors border border-port-border min-h-[40px]"
@@ -776,7 +794,7 @@ export default function Shell() {
<button
onClick={stopSession}
className="flex items-center gap-1.5 px-2.5 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg text-sm transition-colors min-h-[40px]"
- title="Kill current session"
+ title={isLiveRun ? 'Stop this TUI run' : 'Kill current session'}
>
<PowerOff size={16} />
<span className="hidden sm:inline">Stop</span>
@@ -799,26 +817,33 @@ export default function Shell() {
{sessions.map((s) => {
const isActive = s.sessionId === activeSessionId;
const label = s.label || s.cwd?.split('/').pop() || shortId(s.sessionId);
+ // External TUI runs get a distinct bot icon + accent tint + pulsing
+ // dot so they read as "live run you can watch and drive".
+ const isRun = s.external;
+ const TabIcon = isRun ? Bot : TerminalIcon;
return (
<div
key={s.sessionId}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs font-mono transition-colors cursor-pointer min-h-[40px] ${
isActive
? 'bg-port-accent/20 text-port-accent border border-port-accent/40'
- : 'bg-port-card hover:bg-port-border text-gray-400 hover:text-white border border-port-border'
+ : isRun
+ ? 'bg-port-accent/5 hover:bg-port-accent/15 text-port-accent/80 hover:text-port-accent border border-port-accent/20'
+ : 'bg-port-card hover:bg-port-border text-gray-400 hover:text-white border border-port-border'
}`}
onClick={() => !isActive && switchToSession(s.sessionId)}
- title={`${s.label || s.cwd || shortId(s.sessionId)} — ${formatAge(s.createdAt)} old`}
+ title={`${isRun ? 'Live TUI run — ' : ''}${s.label || s.cwd || shortId(s.sessionId)} — ${formatAge(s.createdAt)} old`}
>
- <TerminalIcon size={12} className="shrink-0" />
+ <TabIcon size={12} className="shrink-0" />
<span className="min-w-0 break-all">{label}</span>
+ {isRun && <span className="w-1.5 h-1.5 rounded-full bg-port-accent animate-pulse shrink-0" title="Live" />}
<span className="text-[10px] opacity-60 shrink-0">{formatAge(s.createdAt)}</span>
<button
onClick={(e) => { e.stopPropagation(); killOtherSession(s.sessionId); }}
className={`shrink-0 ml-0.5 p-0.5 rounded transition-colors ${
isActive ? 'text-port-accent/60 hover:text-red-400' : 'text-gray-600 hover:text-red-400'
}`}
- title="Kill session"
+ title={isRun ? 'Stop run' : 'Kill session'}
>
<X size={14} />
</button>
@@ -835,6 +860,18 @@ export default function Shell() {
</div>
)}
+ {/* Live TUI run banner — these views are interactive: type to answer or
+ correct the model, or Stop to end it. It won't auto-close while open. */}
+ {connected && isLiveRun && (
+ <div className="flex items-center gap-2 mb-3 px-3 py-2 rounded bg-port-accent/10 border border-port-accent/30 text-port-accent text-xs">
+ <Bot size={14} className="shrink-0" />
+ <span>
+ Live run <span className="font-mono">{activeSession?.label || 'TUI'}</span> — you can type to answer or correct it,
+ or <span className="font-semibold">Stop</span> to end it. It won't idle-close while you have it open.
+ </span>
+ </div>
+ )}
+
{/* Quick commands toolbar */}
{connected && (
<div className="flex items-center gap-2 mb-3 flex-wrap">
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 35a804b157..dfe24853fd 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -624,7 +624,9 @@ async function executeProviderRunOnce({ provider, prompt, source, model, runId:
}, effectiveTimeout);
executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: [], onData, onComplete }).catch(safeReject);
} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
- executeTuiRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);
+ // `source` (e.g. 'pipeline-manuscript-completeness') labels the read-only
+ // live view this TUI run surfaces in the Shell page.
+ executeTuiRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, onData, onComplete, timeout: effectiveTimeout, label: source }).catch(safeReject);
} else {
safeReject(new Error(`Unsupported provider type: ${effectiveProvider.type}`));
}
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index 371e48aaaa..056bf82497 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -32,6 +32,7 @@ import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';
import { createStreamingAnsiStripper } from './ansiStrip.js';
import { createImmediateFallbackSignalDetector } from './aiToolkit/errorDetection.js';
import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun } from '../services/runner.js';
+import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached } from '../services/shell.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
PASTE_MARKER_POLL_MS,
@@ -89,9 +90,12 @@ const PTY_ROWS = 50;
* AFTER this fires.
* @param {number} [options.timeout] — hard cap on a single run (ms). Falls back to
* `provider.timeout`, then `DEFAULT_TIMEOUT_MS`.
+ * @param {string} [options.label] — human label for the live Shell view (the
+ * run `source`, e.g. `'pipeline-manuscript-completeness'`). Surfaced in the
+ * Shell page's session tab; falls back to `command · model` when absent.
* @returns {Promise<void>}
*/
-export async function executeTuiRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout }) {
+export async function executeTuiRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout, label }) {
if (!provider || typeof provider !== 'object') {
throw new Error('executeTuiRun: provider is required');
}
@@ -171,6 +175,21 @@ ${prompt}`;
// any SSE-based "active run" UI never see TUI runs as in-flight.
emitRunStarted({ runId, provider, model: provider.defaultModel });
+ // Surface this one-shot run as an interactive session in the Shell UI so the
+ // user can watch its live output and step in — answer a question, correct it,
+ // or interrupt it (it bypasses services/shell.js for *spawning*, but
+ // registering the already-live PTY for *viewing/driving* doesn't re-introduce
+ // the cap/login-shell concerns the spawn bypass avoids).
+ const viewLabel = (typeof label === 'string' && label)
+ ? label
+ : `${command} · ${provider.defaultModel || 'tui'}`;
+ registerExternalSession(runId, ptyProcess, {
+ label: viewLabel,
+ command: `${command} ${args.join(' ')}`.trim(),
+ cwd: workingDir,
+ kind: 'tui-run',
+ });
+
const startTime = Date.now();
let outputBuffer = '';
let rawBuffer = '';
@@ -204,6 +223,11 @@ ${prompt}`;
finalized = true;
cleanupTimers();
unregisterActiveRun(runId);
+ // Drop the live Shell view the moment the run ends (notifies any attached
+ // viewer via shell:exit). Idempotent — safe even if no viewer ever
+ // attached. Runs before the kill below so the session disappears from the
+ // list immediately rather than waiting on PTY teardown.
+ unregisterExternalSession(runId, { exitCode });
// Kill the PTY if still alive — one-shot runs don't leave a session
// behind for the user to interact with.
@@ -275,6 +299,12 @@ ${prompt}`;
// Significant on parallel fan-out paths (arc planner).
idleWatchTimer = setInterval(() => {
if (finalized) return;
+ // Don't auto-complete a run a human is actively watching in the Shell
+ // page — they may be reading the output or about to type a correction
+ // or an answer the model is waiting on. The run then ends only on
+ // natural process exit or an explicit Stop. Unattended pipeline runs
+ // keep the snappy idle threshold for throughput.
+ if (isExternalSessionAttached(runId)) return;
const idle = Date.now() - lastOutputAt;
if (idle >= idleThresholdMs) {
finish({ success: true, exitCode: 0, reason: 'idle-complete' });
@@ -374,7 +404,10 @@ ${prompt}`;
// (idleWatchTimer is created inside onData once firstResponseAt is set.)
// Hard timeout — covers stuck-banner, no-response, and runaway-response
- // cases. Provider-configurable via `timeout`; defaults to 5 min.
+ // cases, and is the honest backstop that bounds a run a viewer left open on
+ // a backgrounded tab (idle-completion is paused while watched, but this is
+ // not — a run can't exceed its configured max time). Provider-configurable
+ // via `timeout`; defaults to 5 min.
hardTimeoutTimer = setTimeout(() => {
if (finalized) return;
finish({
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
index d5e368765c..c04d43ceab 100644
--- a/server/lib/tuiPromptRunner.test.js
+++ b/server/lib/tuiPromptRunner.test.js
@@ -9,7 +9,7 @@ import { join } from 'path';
// real run directories the SUT never needs in these tests). Mocks live
// inside vi.hoisted so the vi.mock factories (which are themselves hoisted
// to the top of the file) can reference them.
-const { ptyInstances, ptySpawnMock, runnerMocks, runsTmpDirRef } = vi.hoisted(() => ({
+const { ptyInstances, ptySpawnMock, runnerMocks, shellMocks, runsTmpDirRef } = vi.hoisted(() => ({
ptyInstances: [],
ptySpawnMock: vi.fn(),
runsTmpDirRef: { current: null },
@@ -20,11 +20,21 @@ const { ptyInstances, ptySpawnMock, runnerMocks, runsTmpDirRef } = vi.hoisted(()
unregisterActiveRun: vi.fn(),
getRunsPath: vi.fn(),
},
+ // shell.js is mocked so the runner's Shell-view registration is observable
+ // here without dragging in the real session registry singleton.
+ // isExternalSessionAttached defaults to "no viewer" so idle/timeout fire as
+ // they would for an unattended pipeline run; tests flip it to assert the pause.
+ shellMocks: {
+ registerExternalSession: vi.fn(),
+ unregisterExternalSession: vi.fn(),
+ isExternalSessionAttached: vi.fn(() => false),
+ },
}));
runnerMocks.getRunsPath.mockImplementation(() => runsTmpDirRef.current);
vi.mock('node-pty', () => ({ spawn: (...args) => ptySpawnMock(...args) }));
vi.mock('../services/runner.js', () => runnerMocks);
+vi.mock('../services/shell.js', () => shellMocks);
vi.mock('./fileUtils.js', async () => {
const actual = await vi.importActual('./fileUtils.js');
return { ...actual, ensureDir: vi.fn(async () => {}) };
@@ -252,6 +262,10 @@ describe('executeTuiRun', () => {
runnerMocks.registerActiveRun.mockClear();
runnerMocks.unregisterActiveRun.mockClear();
runnerMocks.getRunsPath.mockClear();
+ shellMocks.registerExternalSession.mockClear();
+ shellMocks.unregisterExternalSession.mockClear();
+ shellMocks.isExternalSessionAttached.mockReset();
+ shellMocks.isExternalSessionAttached.mockReturnValue(false);
vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(console, 'error').mockImplementation(() => {});
});
@@ -314,6 +328,41 @@ describe('executeTuiRun', () => {
await promise;
});
+ it('registers a read-only Shell view (labelled by source) and tears it down on finish', async () => {
+ const provider = { id: 'claude', type: 'tui', command: 'claude', defaultModel: 'claude-fable-5' };
+ const promise = executeTuiRun({
+ runId: 'run-view', provider, prompt: 'review this manuscript', workspacePath: '/work',
+ label: 'pipeline-manuscript-completeness',
+ });
+ await flushAsync();
+
+ expect(shellMocks.registerExternalSession).toHaveBeenCalledWith(
+ 'run-view',
+ ptyInstances[0],
+ expect.objectContaining({
+ label: 'pipeline-manuscript-completeness',
+ kind: 'tui-run',
+ cwd: '/work',
+ }),
+ );
+ expect(shellMocks.unregisterExternalSession).not.toHaveBeenCalled();
+
+ ptyInstances[0].emitExit({ exitCode: 0 });
+ await promise;
+ expect(shellMocks.unregisterExternalSession).toHaveBeenCalledWith('run-view', { exitCode: 0 });
+ });
+
+ it('falls back to a command·model label when no source label is supplied', async () => {
+ const provider = { id: 'codex', type: 'tui', command: 'codex', defaultModel: 'gpt-x' };
+ const promise = executeTuiRun({ runId: 'run-nolabel', provider, prompt: 'do the thing', workspacePath: '/w' });
+ await flushAsync();
+ expect(shellMocks.registerExternalSession).toHaveBeenCalledWith(
+ 'run-nolabel', ptyInstances[0], expect.objectContaining({ label: 'codex · gpt-x' }),
+ );
+ ptyInstances[0].emitExit({ exitCode: 0 });
+ await promise;
+ });
+
it('merges provider.envVars and strips CLAUDECODE from the child env so a nested Claude Code TUI is not detected as nested', async () => {
// Save + restore the original value: a PortOS-inside-Claude-Code dev
// run starts the worker with CLAUDECODE already set, and an
@@ -390,6 +439,45 @@ describe('executeTuiRun', () => {
}));
});
+ it('does NOT idle-complete while a Shell viewer is attached, then completes once they detach', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],
+ });
+ // A human is watching this run in the Shell page.
+ shellMocks.isExternalSessionAttached.mockReturnValue(true);
+ const provider = {
+ id: 'claude', type: 'tui', command: 'echo',
+ tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500,
+ };
+ const onComplete = vi.fn();
+ const promise = executeTuiRun({ runId: 'run-watched', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: '/cwd', onComplete, timeout: 60000 });
+ await flushAsync();
+
+ const pty = ptyInstances[0];
+ pty.emitData('claude code ready> ');
+ await vi.advanceTimersByTimeAsync(2000); // paste
+ await vi.advanceTimersByTimeAsync(4000); // enter
+ pty.emitData('model response chunk'); // arms idleWatchTimer
+
+ // Idle well past the threshold — but a viewer is attached, so the run must
+ // NOT auto-complete.
+ await vi.advanceTimersByTimeAsync(5000);
+ await flushAsync();
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(runnerMocks.unregisterActiveRun).not.toHaveBeenCalled();
+
+ // Viewer detaches → next idle tick completes the run normally.
+ shellMocks.isExternalSessionAttached.mockReturnValue(false);
+ await vi.advanceTimersByTimeAsync(1100);
+ await flushAsync();
+ await promise;
+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({
+ runId: 'run-watched',
+ success: true,
+ extras: expect.objectContaining({ completionReason: 'idle-complete' }),
+ }));
+ });
+
it('finishes with reason "timeout" and exitCode 124 when the hard timeout fires before any completion', async () => {
vi.useFakeTimers({
toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],
@@ -415,6 +503,28 @@ describe('executeTuiRun', () => {
expect(ptyInstances[0].kill).toHaveBeenCalled();
});
+ it('still hard-times-out a watched run (the backstop is not paused while attached)', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],
+ });
+ shellMocks.isExternalSessionAttached.mockReturnValue(true); // a viewer is watching
+ const provider = { id: 'claude', type: 'tui', command: 'echo' };
+ const promise = executeTuiRun({ runId: 'run-tmo-watched', provider, prompt: 'a prompt long enough to clear the guard', workspacePath: '/cwd', timeout: 500 });
+ await flushAsync();
+
+ // The hard timeout fires even though a viewer is attached — only idle
+ // auto-completion is paused while watched, not the max-time backstop.
+ await vi.advanceTimersByTimeAsync(600);
+ await flushAsync();
+ await promise;
+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({
+ runId: 'run-tmo-watched',
+ success: false,
+ exitCode: 124,
+ extras: expect.objectContaining({ completionReason: 'timeout' }),
+ }));
+ });
+
it('early-fails with reason "command-not-found" and exitCode 127 when "command not found" appears pre-paste', async () => {
const provider = { id: 'codex', type: 'tui', command: 'no-such-tui' };
const promise = executeTuiRun({ runId: 'run-missing', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
diff --git a/server/services/shell.js b/server/services/shell.js
index 3109825b5c..6fc7d5d238 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -5,7 +5,11 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
// Store active shell sessions (persist across socket reconnects)
const shellSessions = new Map();
-const MAX_TOTAL_SESSIONS = 5;
+// Soft ceiling on concurrent user-spawned interactive shells. Each session is a
+// single idle PTY (a few MB, one OS process), and the deployment is single-user
+// on a private network — so this is a sanity bound against runaway tab-spamming,
+// not a resource/abuse defense. External read-only views (TUI runs) don't count.
+const MAX_TOTAL_SESSIONS = 20;
// 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
@@ -58,7 +62,11 @@ function getDefaultShell() {
* Create a new shell session
*/
export function createShellSession(socket, options = {}) {
- if (shellSessions.size >= MAX_TOTAL_SESSIONS) {
+ // Only user-spawned interactive shells count toward the cap. External
+ // read-only views (one-shot TUI runs registered via registerExternalSession)
+ // are governed by their own runner and must not consume a shell slot.
+ const interactiveCount = [...shellSessions.values()].filter(s => !s.external).length;
+ if (interactiveCount >= MAX_TOTAL_SESSIONS) {
console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);
socket?.emit?.('shell:error', { error: `Max ${MAX_TOTAL_SESSIONS} shell sessions. Kill an existing session first.` });
return null;
@@ -141,6 +149,10 @@ export function createShellSession(socket, options = {}) {
broadcastSessionList();
});
+ // Starting a fresh shell means the user moved on from whatever they were
+ // viewing — release any TUI-run views they held so those runs resume normal
+ // completion instead of staying paused for a tab they've left.
+ releaseExternalViews(socket, sessionId);
broadcastSessionList();
if (options.initialCommand) {
setTimeout(() => writeToSession(sessionId, `${options.initialCommand}\n`), options.initialCommandDelayMs ?? 200);
@@ -148,6 +160,120 @@ export function createShellSession(socket, options = {}) {
return sessionId;
}
+/**
+ * A socket can stay bound to multiple sessions (the registry allows it), but a
+ * user views one at a time. `isExternalSessionAttached` keys off socket binding,
+ * so without this a TUI run stays "watched" (and its completion stays paused)
+ * after the user switches to another tab. When a socket starts viewing a
+ * different session, drop its binding to any OTHER external (TUI-run) view so
+ * that run resumes normal idle/timeout completion. Interactive shells keep their
+ * lingering binding (the registry's one-socket-many-shells model is unchanged).
+ */
+function releaseExternalViews(socket, exceptId = null) {
+ if (!socket) return;
+ for (const [id, session] of shellSessions.entries()) {
+ if (session.external && session.socket === socket && id !== exceptId) {
+ session.socket = null;
+ }
+ }
+}
+
+/**
+ * Register a PTY spawned OUTSIDE this service (one-shot TUI runs in
+ * `lib/tuiPromptRunner.js`) as an attachable session so it shows up in the Shell
+ * UI where the user can watch its live output AND interact with it — type
+ * corrections, answer questions the model is waiting on, or interrupt it.
+ *
+ * Why this exists separately from createShellSession:
+ * - The TUI runner deliberately spawns its own PTY (it bypasses the session
+ * cap and the login-shell wrapper — see tuiPromptRunner.js's header). This
+ * helper only *surfaces* that already-running PTY; it does not spawn one.
+ * - `external: true` keeps it out of the interactive-session cap count and out
+ * of Shell's auto-attach (you opt into watching a run by clicking its tab).
+ *
+ * Input and resize are NOT blocked — these views are fully interactive. To keep
+ * a run from being killed out from under an engaged human, the runner pauses its
+ * idle-completion and hard-timeout while a viewer is attached (see
+ * `isExternalSessionAttached` + tuiPromptRunner's completion watch).
+ *
+ * node-pty fans `onData` out to every registered listener, so the listener we
+ * add here streams to the Shell viewer without disturbing the runner's own
+ * output capture. Lifecycle is owned by the runner: it calls
+ * unregisterExternalSession from its single finish() funnel when the run ends.
+ *
+ * @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 }.
+ * @returns {string} sessionId (idempotent — returns the id if already registered).
+ */
+export function registerExternalSession(sessionId, ptyProcess, options = {}) {
+ if (shellSessions.has(sessionId)) return sessionId;
+
+ // Mirror createShellSession's 50KB re-attach ring buffer so a viewer who
+ // opens the run mid-stream still sees the recent screen state.
+ const outputBuffer = [];
+ let bufferSize = 0;
+ const MAX_BUFFER = 50 * 1024;
+
+ shellSessions.set(sessionId, {
+ _id: sessionId.slice(0, 8),
+ hookQueue: Promise.resolve(),
+ pty: ptyProcess,
+ socket: null,
+ cwd: options.cwd || null,
+ createdAt: Date.now(),
+ label: options.label || null,
+ kind: options.kind || 'tui-run',
+ agentId: null,
+ command: options.command || null,
+ onData: null,
+ onExit: null,
+ external: true,
+ outputBuffer,
+ bufferSize: () => bufferSize
+ });
+
+ ptyProcess.onData((data) => {
+ outputBuffer.push(data);
+ bufferSize += data.length;
+ while (bufferSize > MAX_BUFFER && outputBuffer.length > 1) {
+ bufferSize -= outputBuffer.shift().length;
+ }
+ // Re-read the session each time — the attached socket changes as viewers
+ // come and go; a null socket (no viewer) just drops the emit.
+ shellSessions.get(sessionId)?.socket?.emit('shell:output', { sessionId, data });
+ });
+
+ console.log(`🐚 Registered external TUI session ${sessionId.slice(0, 8)} (${options.label || options.command || 'tui'})`);
+ broadcastSessionList();
+ return sessionId;
+}
+
+/**
+ * Remove an external session from the registry and notify any attached viewer
+ * that the run finished. Idempotent and external-only — a no-op if the id is
+ * unknown or belongs to an interactive shell (those clean up via PTY onExit).
+ */
+export function unregisterExternalSession(sessionId, { exitCode = 0 } = {}) {
+ const session = shellSessions.get(sessionId);
+ if (!session || !session.external) return false;
+ shellSessions.delete(sessionId);
+ session.socket?.emit('shell:exit', { sessionId, code: exitCode });
+ broadcastSessionList();
+ return true;
+}
+
+/**
+ * True when an external (TUI-run) session exists and a Shell viewer is currently
+ * attached to it. The runner consults this to pause auto-completion/timeout while
+ * a human is watching, so the run isn't killed mid-interaction.
+ */
+export function isExternalSessionAttached(sessionId) {
+ const session = shellSessions.get(sessionId);
+ return !!(session && session.external && session.socket);
+}
+
/**
* Attach an existing session to a new socket
*
@@ -176,6 +302,9 @@ export function attachSession(sessionId, socket, { claim = false } = {}) {
prevSocket.emit('shell:detached', { sessionId, reason: 'attached-elsewhere' });
}
session.socket = socket;
+ // Switching view releases any TUI-run this socket was watching, so that run
+ // resumes normal completion rather than staying paused for a tab left behind.
+ releaseExternalViews(socket, sessionId);
console.log(`🐚 Attached session ${sessionId.slice(0, 8)} to socket ${socket.id}`);
// Broadcast so other clients pick up the new `attached: true` state and skip
// this session in their auto-pick flow.
@@ -230,6 +359,7 @@ export function listAllSessions(forSocket = null) {
kind: session.kind,
agentId: session.agentId,
command: session.command,
+ external: !!session.external,
attached: forSocket
? (!!session.socket && session.socket !== forSocket)
: !!session.socket
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index ff493f67e8..34294af192 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -96,17 +96,17 @@ describe('createShellSession', () => {
});
it('emits shell:error and returns null when max sessions reached', () => {
- for (let i = 0; i < 5; i++) shell.createShellSession(makeSocket(`s${i}`));
+ for (let i = 0; i < 20; i++) shell.createShellSession(makeSocket(`s${i}`));
const socket = makeSocket('over');
const id = shell.createShellSession(socket);
expect(id).toBeNull();
expect(socket.emit).toHaveBeenCalledWith('shell:error', {
- error: 'Max 5 shell sessions. Kill an existing session first.',
+ error: 'Max 20 shell sessions. Kill an existing session first.',
});
});
it('does not throw when over-cap and socket is missing', () => {
- for (let i = 0; i < 5; i++) shell.createShellSession(makeSocket(`s${i}`));
+ for (let i = 0; i < 20; i++) shell.createShellSession(makeSocket(`s${i}`));
expect(() => shell.createShellSession(null)).not.toThrow();
});
@@ -355,6 +355,121 @@ describe('detachSocketSessions', () => {
});
});
+describe('registerExternalSession / unregisterExternalSession', () => {
+ it('registers an external session that lists with metadata', () => {
+ const pty = makeFakePty();
+ const id = shell.registerExternalSession('run-123', pty, {
+ label: 'pipeline-manuscript-completeness',
+ command: 'claude --model x',
+ cwd: '/work',
+ });
+ expect(id).toBe('run-123');
+ const [info] = shell.listAllSessions(makeSocket());
+ expect(info).toMatchObject({
+ sessionId: 'run-123',
+ label: 'pipeline-manuscript-completeness',
+ kind: 'tui-run',
+ command: 'claude --model x',
+ external: true,
+ });
+ });
+
+ it('is idempotent — re-registering the same id is a no-op returning the id', () => {
+ const pty = makeFakePty();
+ shell.registerExternalSession('run-1', pty, { label: 'first' });
+ const again = shell.registerExternalSession('run-1', makeFakePty(), { label: 'second' });
+ expect(again).toBe('run-1');
+ expect(shell.getSession('run-1').label).toBe('first');
+ });
+
+ it('does NOT count toward the interactive session cap', () => {
+ // Fill the cap with external sessions — interactive creation must still work.
+ for (let i = 0; i < 6; i++) shell.registerExternalSession(`run-${i}`, makeFakePty(), {});
+ const id = shell.createShellSession(makeSocket());
+ expect(typeof id).toBe('string');
+ });
+
+ it('streams output to the attached viewer and buffers for re-attach', () => {
+ const pty = makeFakePty();
+ const id = shell.registerExternalSession('run-x', pty, {});
+ // No viewer yet — output buffers without throwing.
+ pty.emitData('early');
+ const viewer = makeSocket('viewer');
+ const result = shell.attachSession(id, viewer);
+ expect(result.bufferedOutput).toBe('early');
+ pty.emitData('live');
+ expect(viewer.emit).toHaveBeenCalledWith('shell:output', { sessionId: id, data: 'live' });
+ });
+
+ it('is fully interactive — input writes through and resize works', () => {
+ const pty = makeFakePty();
+ const id = shell.registerExternalSession('run-rw', pty, {});
+ expect(shell.writeToSession(id, 'yes\n')).toBe(true);
+ expect(pty.write).toHaveBeenCalledWith('yes\n');
+ expect(shell.resizeSession(id, 120, 40)).toBe(true);
+ expect(pty.resize).toHaveBeenCalledWith(120, 40);
+ });
+
+ it('isExternalSessionAttached reflects whether a viewer is bound', () => {
+ const pty = makeFakePty();
+ const id = shell.registerExternalSession('run-att', pty, {});
+ expect(shell.isExternalSessionAttached(id)).toBe(false); // registered, no viewer
+ shell.attachSession(id, makeSocket('viewer'));
+ expect(shell.isExternalSessionAttached(id)).toBe(true);
+ shell.detachSocketSessions(shell.getSession(id).socket);
+ expect(shell.isExternalSessionAttached(id)).toBe(false);
+ // Never true for unknown ids or interactive shells.
+ expect(shell.isExternalSessionAttached('missing')).toBe(false);
+ const shellId = shell.createShellSession(makeSocket('owner'));
+ expect(shell.isExternalSessionAttached(shellId)).toBe(false);
+ });
+
+ it('releases a watched run when the same socket attaches to another session', () => {
+ const viewer = makeSocket('viewer');
+ const runId = shell.registerExternalSession('run-watch', makeFakePty(), {});
+ shell.attachSession(runId, viewer);
+ expect(shell.isExternalSessionAttached(runId)).toBe(true);
+ // Same socket switches to a shell — the run is released so it resumes
+ // normal completion instead of staying paused for a tab left behind.
+ const shellId = shell.createShellSession(viewer);
+ expect(shell.isExternalSessionAttached(runId)).toBe(false);
+ expect(shell.getSession(runId)).toBeTruthy(); // still alive, just unwatched
+ // The new shell is unaffected.
+ expect(shell.getSession(shellId).socket).toBe(viewer);
+ });
+
+ it('releases a watched run when the same socket attaches to a different run', () => {
+ const viewer = makeSocket('viewer');
+ const runA = shell.registerExternalSession('run-A', makeFakePty(), {});
+ const runB = shell.registerExternalSession('run-B', makeFakePty(), {});
+ shell.attachSession(runA, viewer);
+ shell.attachSession(runB, viewer);
+ expect(shell.isExternalSessionAttached(runA)).toBe(false);
+ expect(shell.isExternalSessionAttached(runB)).toBe(true);
+ });
+
+ it('unregister removes the session, emits shell:exit to the viewer, broadcasts', () => {
+ const observer = makeSocket('obs');
+ shell.subscribeSessionList(observer);
+ const viewer = makeSocket('viewer');
+ const pty = makeFakePty();
+ const id = shell.registerExternalSession('run-done', pty, {});
+ shell.attachSession(id, viewer);
+ expect(shell.unregisterExternalSession(id, { exitCode: 0 })).toBe(true);
+ expect(shell.getSession(id)).toBeNull();
+ expect(viewer.emit).toHaveBeenCalledWith('shell:exit', { sessionId: id, code: 0 });
+ const last = observer.emit.mock.calls.filter(c => c[0] === 'shell:sessions').pop();
+ expect(last[1]).toHaveLength(0);
+ });
+
+ it('unregister is a no-op for unknown ids and for interactive sessions', () => {
+ expect(shell.unregisterExternalSession('nope')).toBe(false);
+ const id = shell.createShellSession(makeSocket());
+ expect(shell.unregisterExternalSession(id)).toBe(false);
+ expect(shell.getSession(id)).toBeTruthy();
+ });
+});
+
describe('getSession / getSessionProcess / getSessionCount', () => {
it('getSession returns the session record or null', () => {
const id = shell.createShellSession(makeSocket());