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

feat: TUI provider type — run CoS agents inside attachable PTY shell

[._.]/ Adam Eivyb029d22994a0
diff --git a/PLAN.md b/PLAN.md
index 5b24bb2e29..a0e8711e85 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -89,6 +89,11 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
### Other backlog
+- [ ] **TUI providers in manual `/api/runs`.** This PR wires `type: "tui"` providers into CoS agent spawning (`server/services/agentLifecycle.js` → `server/services/agentTuiSpawning.js`) and disables TUI execution in the AI Providers run panel, but the generic API route still lives in `server/lib/aiToolkit/routes/runs.js` and only knows `cli` and `api` execution. Add a TUI-specific runner branch there if manual devtools runs should also open attachable shell sessions. Deferred to keep the CoS-agent path focused and testable.
+- [ ] **Extract `finalizeAgent` helper shared across spawn paths.** The completion sequence (`release(lane) → completeExecution → analyzeAgentFailure → persistSimplifySummaries → completeAgent → completeAgentRun → updateTask branch → markProviderUsageLimit/RateLimited → processAgentCompletion → rm BTW.md → cleanupWorktreeFn → unregisterSpawnedAgent → activeAgents.delete`) is duplicated in `server/services/agentTuiSpawning.js:finish()`, `server/services/agentCliSpawning.js:claudeProcess.on('close')`, and `server/services/agentLifecycle.js:handleAgentCompletion`. A divergence in any leg (lane release, user-terminated branch, rate-limit marking) silently breaks one path. Skipped in this PR to keep the TUI change reviewable; should be unified next.
+- [ ] **Shared `isTuiProvider` helper + client palette helper.** `provider.type === 'tui'` is checked ~6 times in `server/services/agentLifecycle.js` and ~12 times across `client/src/pages/AIProviders.jsx` + `client/src/components/cos/TaskAddForm.jsx`. Mirror the existing `isClaudeCliProvider` pattern: add `isTuiProvider` next to it (or hoist both into a new `server/services/providerType.js`), plus a client mirror in `client/src/utils/providers.js`. Also lift `providerTypeClass` from `AIProviders.jsx` into the same client util so `AgentCard.jsx` can stop inlining the TUI badge palette.
+- [ ] **`spawnTuiAgent` / `spawnDirectly` options-object refactor.** Both currently take 11 positional args + a deps object. Convert to a single options object now while the TUI surface is small, to avoid cementing the long positional signature.
+- [ ] **Wrap `createShellSession` for agent TUIs.** The shell session contract in `server/services/shell.js` now carries agent-specific fields (`onData`, `onExit`, `initialCommand`, `initialCommandDelayMs`, `agentId`). `kind`/`label`/`command` stay generic, but the callback/initial-command wiring should move into a thin `createAgentTuiSession()` wrapper in `agentTuiSpawning.js` that registers its own `pty.onData` listener.
- [ ] **Writers Room (Phase 4–5)** — Phases 1–3 shipped (authoring core, storyboard companion, character/world/objects bibles, per-stage LLM picker, paragraph-grain Adapt, auto-queue scene image gen, Read view + render dock). Remaining: Phase 4 synced prose/script/media review, Phase 5 realtime CD feedback. See [writers-room.md](./docs/features/writers-room.md). Phase 4 now lands on the unified bible/scene model that the DRY-unification work (DONE.md 2026-05-10) brought in.
- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (Google Calendar via existing MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (needs API choice — OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js` scheduled actions).
- [ ] **Wire proactive CoS speech to real triggers.** The plumbing landed in this PR (`POST /api/voice/speak` + `server/services/voice/proactiveSpeech.js` + `voice:speak` socket event), but nothing in the CoS calls it yet. Hook points to consider: high-severity error events from `errorEvents` (read-only suppression to high-priority alerts only), `cosEvents.emit('task:ready', ...)` for "ready to start <task>?", `notificationEvents` for whatever passes the priority bar. Each integration should keep a per-source rate-limit so a stuck loop can't spam audio. Priority field is plumbed end-to-end (low/normal/high) but currently only influences the toast icon — pick a real semantic before hooking high-volume sources.
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index 9cc9e575bd..3180b4df33 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -72,13 +72,13 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
// Get models for selected provider
const selectedProvider = providers?.find(p => p.id === newTask.provider);
const availableModels = filterSelectableModels(selectedProvider?.models);
- const providerModelNote = selectedProvider
- ? isCodexProvider(selectedProvider)
- ? 'Codex uses the model configured in ~/.codex/config.toml.'
- : selectedProvider.type === 'cli'
- ? `${selectedProvider.name} uses its CLI configured default model.`
- : 'No models are configured. PortOS will use the provider default.'
- : '';
+ const providerModelNote = (() => {
+ if (!selectedProvider) return '';
+ if (selectedProvider.type === 'tui') return `${selectedProvider.name} runs in an attachable terminal UI session.`;
+ if (isCodexProvider(selectedProvider)) return 'Codex uses the model configured in ~/.codex/config.toml.';
+ if (selectedProvider.type === 'cli') return `${selectedProvider.name} uses its CLI configured default model.`;
+ return 'No models are configured. PortOS will use the provider default.';
+ })();
// Apply template to form
const applyTemplate = useCallback(async (template) => {
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 4892077ad3..e5ff1384ac 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -390,6 +390,11 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
{agent.metadata?.phase === 'initializing' ? 'Initializing' : 'Working'}
</span>
)}
+ {agent.metadata?.executionMode === 'tui' && (
+ <span className="px-2 py-0.5 text-xs rounded bg-emerald-500/20 text-emerald-400 shrink-0">
+ TUI
+ </span>
+ )}
</div>
{/* Actions - right side */}
<div className="flex items-center gap-2 shrink-0">
@@ -487,6 +492,16 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
<span className="font-mono">{processStats.memoryMb}MB</span>
</span>
)}
+ {!completed && agent.metadata?.tuiSessionId && (
+ <a
+ href={`/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>
+ )}
{/* Show zombie warning if PID exists but process is dead */}
{!completed && agent.pid && processStats && !processStats.active && (
<span className="flex items-center gap-1 px-2 py-0.5 rounded bg-port-error/20 text-port-error whitespace-nowrap"
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index ddaebbd3dc..b1ac00831d 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -4,6 +4,12 @@ import * as api from '../services/api';
import socket from '../services/socket';
import { filterSelectableModels } from '../utils/providers';
+const providerTypeClass = (type) => {
+ if (type === 'cli') return 'bg-blue-500/20 text-blue-400';
+ if (type === 'tui') return 'bg-emerald-500/20 text-emerald-400';
+ return 'bg-purple-500/20 text-purple-400';
+};
+
export default function AIProviders() {
const [providers, setProviders] = useState([]);
const [activeProviderId, setActiveProviderId] = useState(null);
@@ -91,6 +97,9 @@ export default function AIProviders() {
};
const supportsModelRefresh = (provider) => {
+ if (provider.type === 'tui') {
+ return false;
+ }
// Gemini CLI doesn't require model specification
if (provider.type === 'cli' && provider.command === 'gemini') {
return false;
@@ -170,6 +179,9 @@ export default function AIProviders() {
toast.success(`Added ${sampleProviders.length} providers`);
};
+ const selectedRunProvider = providers.find(p => p.id === activeProviderId);
+ const runProviderIsTui = selectedRunProvider?.type === 'tui';
+
if (loading) {
return (
<div className="flex items-center justify-center h-64">
@@ -243,9 +255,7 @@ export default function AIProviders() {
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-sm font-semibold text-white">{provider.name}</h3>
- <span className={`text-xs px-2 py-0.5 rounded ${
- provider.type === 'cli' ? 'bg-blue-500/20 text-blue-400' : 'bg-purple-500/20 text-purple-400'
- }`}>
+ <span className={`text-xs px-2 py-0.5 rounded ${providerTypeClass(provider.type)}`}>
{provider.type.toUpperCase()}
</span>
{!provider.enabled && (
@@ -255,7 +265,7 @@ export default function AIProviders() {
)}
</div>
<div className="mt-1 text-xs text-gray-400 space-y-0.5">
- {provider.type === 'cli' && (
+ {(provider.type === 'cli' || provider.type === 'tui') && (
<p>Command: <code className="text-gray-300">{provider.command} {provider.args?.join(' ')}</code></p>
)}
{provider.type === 'api' && (
@@ -303,7 +313,7 @@ export default function AIProviders() {
>
<option value="">Select Provider</option>
{providers.filter(p => p.enabled).map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
+ <option key={p.id} value={p.id}>{p.name}{p.type === 'tui' ? ' (CoS TUI)' : ''}</option>
))}
</select>
@@ -330,7 +340,7 @@ export default function AIProviders() {
<div className="flex justify-between items-center">
<button
onClick={handleExecuteRun}
- disabled={!runPrompt.trim() || !activeProviderId || activeRun}
+ disabled={!runPrompt.trim() || !activeProviderId || activeRun || runProviderIsTui}
className="px-6 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
>
{activeRun ? 'Running...' : 'Execute'}
@@ -346,6 +356,12 @@ export default function AIProviders() {
)}
</div>
+ {runProviderIsTui && (
+ <div className="text-xs text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 rounded-lg px-3 py-2">
+ TUI providers run through CoS agent tasks so their terminal session can be tracked and completed.
+ </div>
+ )}
+
{runOutput && (
<div className="bg-port-bg border border-port-border rounded-lg p-3 max-h-64 overflow-auto">
<pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap">{runOutput}</pre>
@@ -367,9 +383,7 @@ export default function AIProviders() {
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold text-white">{provider.name}</h3>
- <span className={`text-xs px-2 py-0.5 rounded ${
- provider.type === 'cli' ? 'bg-blue-500/20 text-blue-400' : 'bg-purple-500/20 text-purple-400'
- }`}>
+ <span className={`text-xs px-2 py-0.5 rounded ${providerTypeClass(provider.type)}`}>
{provider.type.toUpperCase()}
</span>
{provider.id === activeProviderId && (
@@ -385,7 +399,7 @@ export default function AIProviders() {
</div>
<div className="mt-2 text-sm text-gray-400 space-y-1">
- {provider.type === 'cli' && (
+ {(provider.type === 'cli' || provider.type === 'tui') && (
<p className="break-words">Command: <code className="text-gray-300 break-all">{provider.command} {provider.args?.join(' ')}</code></p>
)}
{provider.type === 'api' && (
@@ -410,6 +424,11 @@ export default function AIProviders() {
Headless: <code className="text-gray-300 break-all">{provider.headlessArgs.join(' ')}</code>
</p>
)}
+ {provider.type === 'tui' && (
+ <p className="text-xs break-words">
+ TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, idle complete <span className="text-gray-300">{provider.tuiIdleTimeoutMs || 180000}ms</span>
+ </p>
+ )}
{provider.fallbackProvider && (
<p className="text-xs">
Fallback: <span className="text-port-accent">{providers.find(p => p.id === provider.fallbackProvider)?.name || provider.fallbackProvider}</span>
@@ -567,7 +586,9 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
enabled: provider?.enabled !== false,
envVars: provider?.envVars || {},
secretEnvVars: provider?.secretEnvVars || [],
- headlessArgs: provider?.headlessArgs?.join(' ') || ''
+ headlessArgs: provider?.headlessArgs?.join(' ') || '',
+ tuiPromptDelayMs: provider?.tuiPromptDelayMs || 2500,
+ tuiIdleTimeoutMs: provider?.tuiIdleTimeoutMs || 180000
});
const [newEnvKey, setNewEnvKey] = useState('');
@@ -586,7 +607,9 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
...formData,
args: formData.args ? formData.args.split(' ').filter(Boolean) : [],
headlessArgs: formData.headlessArgs ? formData.headlessArgs.split(' ').filter(Boolean) : [],
- timeout: parseInt(formData.timeout, 10)
+ timeout: parseInt(formData.timeout, 10),
+ tuiPromptDelayMs: parseInt(formData.tuiPromptDelayMs, 10),
+ tuiIdleTimeoutMs: parseInt(formData.tuiIdleTimeoutMs, 10)
};
// Only send apiKey if user entered a new value (avoid overwriting existing key with empty string)
@@ -630,11 +653,12 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
>
<option value="cli">CLI</option>
+ <option value="tui">TUI</option>
<option value="api">API</option>
</select>
</div>
- {formData.type === 'cli' && (
+ {(formData.type === 'cli' || formData.type === 'tui') && (
<>
<div>
<label className="block text-sm text-gray-400 mb-1">Command *</label>
@@ -642,8 +666,8 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
type="text"
value={formData.command}
onChange={(e) => setFormData(prev => ({ ...prev, command: e.target.value }))}
- placeholder="claude"
- required={formData.type === 'cli'}
+ placeholder={formData.type === 'tui' ? 'codex' : 'claude'}
+ required={formData.type === 'cli' || formData.type === 'tui'}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
/>
</div>
@@ -654,24 +678,56 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
type="text"
value={formData.args}
onChange={(e) => setFormData(prev => ({ ...prev, args: e.target.value }))}
- placeholder="--print -p"
+ placeholder={formData.type === 'tui' ? '--dangerously-skip-permissions' : '--print -p'}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
/>
</div>
- <div>
- <label className="block text-sm text-gray-400 mb-1">Headless Args (for simple prompt tasks)</label>
- <input
- type="text"
- value={formData.headlessArgs}
- onChange={(e) => setFormData(prev => ({ ...prev, headlessArgs: e.target.value }))}
- placeholder='--no-session-persistence --disable-slash-commands --tools ""'
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
- />
- <p className="text-xs text-gray-500 mt-1">
- Extra CLI flags for lightweight prompt-in/text-out mode (brain classifier, etc.)
- </p>
- </div>
+ {formData.type === 'cli' && (
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Headless Args (for simple prompt tasks)</label>
+ <input
+ type="text"
+ value={formData.headlessArgs}
+ onChange={(e) => setFormData(prev => ({ ...prev, headlessArgs: e.target.value }))}
+ placeholder='--no-session-persistence --disable-slash-commands --tools ""'
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Extra CLI flags for lightweight prompt-in/text-out mode (brain classifier, etc.)
+ </p>
+ </div>
+ )}
+
+ {formData.type === 'tui' && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Prompt Paste Delay (ms)</label>
+ <input
+ type="number"
+ min="250"
+ max="60000"
+ value={formData.tuiPromptDelayMs}
+ onChange={(e) => setFormData(prev => ({ ...prev, tuiPromptDelayMs: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Idle Complete (ms)</label>
+ <input
+ type="number"
+ min="10000"
+ max="1800000"
+ value={formData.tuiIdleTimeoutMs}
+ onChange={(e) => setFormData(prev => ({ ...prev, tuiIdleTimeoutMs: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </div>
+ <p className="sm:col-span-2 text-xs text-gray-500">
+ TUI providers open an attachable shell session, paste the agent prompt, parse terminal output, and complete after the terminal is idle.
+ </p>
+ </div>
+ )}
</>
)}
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index ca2458759e..ae38ca6e8b 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -13,6 +13,7 @@ const MAX_SESSIONS = 5;
const QUICK_COMMANDS = [
{ label: 'claude', command: 'claude --dangerously-skip-permissions' },
+ { label: 'codex', command: 'codex' },
{ label: 'openclaw', command: 'openclaw tui' },
{ label: 'git status', command: 'git status' },
{ label: 'git pull', command: 'git pull --rebase --autostash' },
@@ -64,8 +65,9 @@ export default function Shell() {
if (initialOptsRef.current) return;
const cwd = searchParams.get('cwd');
const cmd = searchParams.get('cmd');
- if (cwd || cmd) {
- initialOptsRef.current = { cwd, cmd };
+ const session = searchParams.get('session');
+ if (cwd || cmd || session) {
+ initialOptsRef.current = { cwd, cmd, session };
setSearchParams({}, { replace: true });
} else {
initialOptsRef.current = {};
@@ -311,7 +313,10 @@ export default function Shell() {
hasInitializedRef.current = true;
const opts = initialOptsRef.current || {};
// If we have initial opts (cwd/cmd), always create a new session
- if (opts.cwd || opts.cmd) {
+ if (opts.session && sessionList.some(s => s.sessionId === opts.session)) {
+ attachToSession(opts.session);
+ initialOptsRef.current = {};
+ } else if (opts.cwd || opts.cmd) {
startSession();
} else if (sessionList.length > 0 && !sessionIdRef.current) {
// Attach to most recent existing session
@@ -456,7 +461,7 @@ export default function Shell() {
<div className="flex items-center gap-1.5 mb-3 overflow-x-auto pb-1">
{sessions.map((s) => {
const isActive = s.sessionId === activeSessionId;
- const label = s.cwd?.split('/').pop() || shortId(s.sessionId);
+ const label = s.label || s.cwd?.split('/').pop() || shortId(s.sessionId);
return (
<div
key={s.sessionId}
@@ -466,10 +471,10 @@ export default function Shell() {
: 'bg-port-card hover:bg-port-border text-gray-400 hover:text-white border border-port-border'
}`}
onClick={() => !isActive && switchToSession(s.sessionId)}
- title={`${s.cwd || shortId(s.sessionId)} — ${formatAge(s.createdAt)} old`}
+ title={`${s.label || s.cwd || shortId(s.sessionId)} — ${formatAge(s.createdAt)} old`}
>
<TerminalIcon size={12} className="shrink-0" />
- <span className="truncate max-w-[100px]">{label}</span>
+ <span className="truncate max-w-[140px]">{label}</span>
<span className="text-[10px] opacity-60 shrink-0">{formatAge(s.createdAt)}</span>
<button
onClick={(e) => { e.stopPropagation(); killOtherSession(s.sessionId); }}
diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index 50efb29853..b9e6de2cfc 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -54,6 +54,24 @@
"envVars": {},
"secretEnvVars": []
},
+ "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": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
+ },
"gemini-cli": {
"id": "gemini-cli",
"name": "Gemini CLI",
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 6361441425..845dbe9596 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -139,7 +139,9 @@ export function createProviderService(config = {}) {
enabled: providerData.enabled !== false,
envVars: providerData.envVars || {},
secretEnvVars: providerData.secretEnvVars || [],
- headlessArgs: providerData.headlessArgs || []
+ headlessArgs: providerData.headlessArgs || [],
+ tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,
+ tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs || 180000
};
data.providers[id] = provider;
@@ -196,7 +198,7 @@ export function createProviderService(config = {}) {
return { success: false, error: 'Provider not found' };
}
- if (provider.type === 'cli') {
+ if (provider.type === 'cli' || provider.type === 'tui') {
// Use execFile (no shell) so user-configured `provider.command` cannot
// inject extra shell commands via metacharacters.
const { stdout } = await execFileAsync('which', [provider.command])
diff --git a/server/lib/aiToolkit/routes/providers.js b/server/lib/aiToolkit/routes/providers.js
index 873bbb967f..17cb0c198b 100644
--- a/server/lib/aiToolkit/routes/providers.js
+++ b/server/lib/aiToolkit/routes/providers.js
@@ -51,8 +51,8 @@ export function createProvidersRoutes(providerService, options = {}) {
return res.status(400).json({ error: 'Name is required' });
}
- if (!type || !['cli', 'api'].includes(type)) {
- return res.status(400).json({ error: 'Type must be "cli" or "api"' });
+ if (!type || !['cli', 'api', 'tui'].includes(type)) {
+ return res.status(400).json({ error: 'Type must be "cli", "api", or "tui"' });
}
const provider = await providerService.createProvider(req.body);
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 6d23d0404d..c49d30da4a 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -6,7 +6,7 @@ export const providerSchema = z.object({
// 'Codex CLI' into 'codex-cli' and break id-keyed CLI argument handling).
id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, 'id must be lowercase alphanumeric with hyphens').max(80).optional(),
name: z.string().min(1).max(100),
- type: z.enum(['cli', 'api']),
+ type: z.enum(['cli', 'api', 'tui']),
command: z.string().optional(),
args: z.array(z.string()).optional(),
// CLI providers send `endpoint: ''` from the form; coerce empty/null to
@@ -26,7 +26,9 @@ export const providerSchema = z.object({
enabled: z.boolean().optional(),
envVars: z.record(z.string()).optional(),
secretEnvVars: z.array(z.string()).optional(),
- headlessArgs: z.array(z.string()).optional()
+ headlessArgs: z.array(z.string()).optional(),
+ tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),
+ tuiIdleTimeoutMs: z.number().int().min(10000).max(1800000).optional()
});
export const runSchema = z.object({
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 3789f11a1b..fe3b917ba0 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -284,7 +284,7 @@ export const appUpdateSchema = appSchema.partial();
// Provider schema
export const providerSchema = z.object({
name: z.string().min(1).max(100),
- type: z.enum(['cli', 'api']),
+ type: z.enum(['cli', 'api', 'tui']),
command: z.string().optional(),
args: z.array(z.string()).optional(),
endpoint: z.string().url().optional(),
@@ -293,7 +293,10 @@ export const providerSchema = z.object({
defaultModel: z.string().nullable().optional(),
timeout: z.number().int().min(1000).max(600000).optional(),
enabled: z.boolean().optional(),
- envVars: z.record(z.string()).optional()
+ envVars: z.record(z.string()).optional(),
+ headlessArgs: z.array(z.string()).optional(),
+ tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),
+ tuiIdleTimeoutMs: z.number().int().min(10000).max(1800000).optional()
});
// Run command schema
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index b402c983f8..ac4e4e0e35 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -227,6 +227,18 @@ describe('validation.js', () => {
expect(result.success).toBe(true);
});
+ it('should validate a TUI provider', () => {
+ const provider = {
+ name: 'Codex TUI',
+ type: 'tui',
+ command: 'codex',
+ tuiPromptDelayMs: 2500,
+ tuiIdleTimeoutMs: 180000
+ };
+ const result = providerSchema.safeParse(provider);
+ expect(result.success).toBe(true);
+ });
+
it('should reject invalid type', () => {
const provider = { name: 'Test', type: 'invalid' };
const result = providerSchema.safeParse(provider);
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 2b00baf694..718fb2af83 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -31,6 +31,7 @@ import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRun
import { buildAgentPrompt, getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';
import { buildCliSpawnConfig, isClaudeCliProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
+import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import { selectModelForTask } from './agentModelSelection.js';
import { processAgentCompletion } from './agentCompletion.js';
import { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } from './agentState.js';
@@ -455,6 +456,9 @@ export async function spawnAgentForTask(task) {
// Create run entry for usage tracking
const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);
+ const isTui = provider.type === 'tui';
+ const executionMode = isTui ? 'tui' : useRunner ? 'runner' : 'direct';
+
// Register the agent with model info
await registerAgent(agentId, task.id, {
workspacePath,
@@ -471,7 +475,8 @@ export async function spawnAgentForTask(task) {
modelReason: modelSelection.reason,
runId,
phase: 'initializing',
- useRunner,
+ useRunner: isTui ? false : useRunner,
+ executionMode,
taskAnalysisType: task.metadata?.analysisType || null,
taskReviewType: task.metadata?.reviewType || null,
taskApp: task.metadata?.app || null,
@@ -519,10 +524,18 @@ export async function spawnAgentForTask(task) {
cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });
}
- // Build CLI-specific spawn configuration
- const cliConfig = buildCliSpawnConfig(provider, selectedModel);
+ const cliConfig = isTui
+ ? buildTuiSpawnConfig(provider, selectedModel)
+ : buildCliSpawnConfig(provider, selectedModel);
- emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel, mode: useRunner ? 'runner' : 'direct', cli: cliConfig.command, lane: laneName, worktree: !!worktreeInfo });
+ emitLog('success', `Spawning agent for task ${task.id}`, {
+ agentId,
+ model: selectedModel,
+ mode: executionMode,
+ cli: cliConfig.command,
+ lane: laneName,
+ worktree: !!worktreeInfo
+ });
// Dedup-window fix: keep the `spawningTasks` guard active across the actual
// spawn call, not just up to the in_progress flip. Deleting between
@@ -535,6 +548,12 @@ export async function spawnAgentForTask(task) {
// closes that race. release() must NOT run here on the success path; the
// lane is released by the agent-completion handler when the work finishes.
try {
+ if (isTui) {
+ return await spawnTuiAgent(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir, toolExecution.id, laneName, {
+ cleanupWorktreeFn: cleanupAgentWorktree,
+ isTruthyMetaFn: isTruthyMeta
+ });
+ }
if (useRunner) {
return await spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider, runId, cliConfig, executionId: toolExecution.id, laneName });
}
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 757685ddc3..c777975639 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -192,46 +192,43 @@ export async function killAgent(agentId) {
* Get process stats for an agent (CPU, memory usage).
*/
export async function getAgentProcessStats(agentId) {
- // Check if agent is in runner mode - use runner endpoint
- if (runnerAgents.has(agentId) || useRunner) {
- const stats = await getAgentStatsFromRunner(agentId);
- return stats;
- }
-
- // Direct mode - get stats locally
const agent = activeAgents.get(agentId);
- if (!agent) {
- return null;
- }
-
- const { exec } = await import('child_process');
- const { promisify } = await import('util');
- const execAsync = promisify(exec);
+ if (agent) {
+ const { exec } = await import('child_process');
+ const { promisify } = await import('util');
+ const execAsync = promisify(exec);
+
+ const psCmd = process.platform === 'win32'
+ ? `tasklist /FI "PID eq ${agent.pid}" /FO CSV /NH`
+ : `ps -p ${agent.pid} -o pid=,pcpu=,rss=,state=`;
+ const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));
+ const line = result.stdout.trim();
+
+ if (!line) {
+ return { active: false, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'dead' };
+ }
- const psCmd = process.platform === 'win32'
- ? `tasklist /FI "PID eq ${agent.pid}" /FO CSV /NH`
- : `ps -p ${agent.pid} -o pid=,pcpu=,rss=,state=`;
- const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));
- const line = result.stdout.trim();
+ 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 (!line) {
- return { active: false, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'dead' };
+ return { active: true, agentId, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };
}
- 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 (runnerAgents.has(agentId) || useRunner) {
+ return await getAgentStatsFromRunner(agentId);
}
- return { active: true, agentId, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };
+ return null;
}
/**
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
new file mode 100644
index 0000000000..974370f273
--- /dev/null
+++ b/server/services/agentTuiSpawning.js
@@ -0,0 +1,313 @@
+/**
+ * Agent TUI Spawning
+ *
+ * Runs CoS agents inside an interactive PTY-backed shell session. This is for
+ * providers whose useful interface is a terminal UI rather than a headless CLI
+ * or HTTP API.
+ */
+
+import { join } from 'path';
+import { writeFile, appendFile, rm } from 'fs/promises';
+import * as shellService from './shell.js';
+import { emitLog } from './cosEvents.js';
+import { appendAgentOutput, updateAgent, completeAgent } from './cosAgents.js';
+import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
+import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';
+import { updateTask } from './cos.js';
+import { release } from './executionLanes.js';
+import { completeExecution, errorExecution } from './toolStateMachine.js';
+import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
+import { completeAgentRun } from './agentRunTracking.js';
+import { processAgentCompletion } from './agentCompletion.js';
+import { persistSimplifySummaries } from './agentLifecycle.js';
+import { activeAgents, userTerminatedAgents } from './agentState.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { resolveCliModel } from '../lib/providerModels.js';
+
+const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;
+const DEFAULT_TUI_IDLE_TIMEOUT_MS = 180000;
+const DEFAULT_TUI_MIN_RUNTIME_MS = 15000;
+const RAW_BUFFER_CAP = 512 * 1024;
+const RAW_BUFFER_HEADROOM = 640 * 1024;
+const OUTPUT_BUFFER_CAP = 1024 * 1024;
+const OUTPUT_BUFFER_HEADROOM = 1280 * 1024;
+
+const ANSI_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
+
+function stripAnsi(text) {
+ return text
+ .replace(ANSI_PATTERN, '')
+ .replace(/\x00/g, '')
+ .replace(/\u001b/g, '');
+}
+
+function shellQuote(value) {
+ const text = String(value ?? '');
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(text)) return text;
+ return `'${text.replace(/'/g, `'\\''`)}'`;
+}
+
+function appendModelArgs(args, model) {
+ const effectiveModel = resolveCliModel(model);
+ return effectiveModel ? [...args, '--model', effectiveModel] : args;
+}
+
+export function buildTuiSpawnConfig(provider, model) {
+ const command = provider?.command || (provider?.id?.includes('codex') ? 'codex' : 'claude');
+ const baseArgs = [...(provider?.args || [])];
+ const args = appendModelArgs(baseArgs, model);
+
+ return {
+ command,
+ args,
+ commandLine: [command, ...args].map(shellQuote).join(' '),
+ promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS,
+ idleTimeoutMs: provider?.tuiIdleTimeoutMs || DEFAULT_TUI_IDLE_TIMEOUT_MS
+ };
+}
+
+export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model, provider, runId, tuiConfig, agentDir, executionId, laneName, { cleanupWorktreeFn, isTruthyMetaFn }) {
+ const outputFile = join(agentDir, 'output.txt');
+ const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : PATHS.root;
+ const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
+ const commandName = tuiConfig.command.split('/').pop();
+
+ let outputBuffer = '';
+ let rawBuffer = '';
+ let finalized = false;
+ let hasStartedWorking = false;
+ let promptSentAt = null;
+ let lastOutputAt = Date.now();
+ let meaningfulLinesAfterPrompt = 0;
+ let lastLine = '';
+ let sessionId = null;
+
+ const appendLine = async (line) => {
+ const cleanLine = line.trim();
+ if (!cleanLine || cleanLine === lastLine) return;
+ if (promptPreview && cleanLine.replace(/\s+/g, ' ').includes(promptPreview)) return;
+
+ lastLine = cleanLine;
+ outputBuffer += `${cleanLine}\n`;
+ if (outputBuffer.length > OUTPUT_BUFFER_HEADROOM) {
+ outputBuffer = outputBuffer.slice(-OUTPUT_BUFFER_CAP);
+ }
+ await appendAgentOutput(agentId, cleanLine);
+ await appendFile(outputFile, `${cleanLine}\n`).catch(() => {});
+ if (promptSentAt) meaningfulLinesAfterPrompt++;
+ };
+
+ const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {
+ if (finalized) return;
+ finalized = true;
+
+ const agentData = activeAgents.get(agentId);
+ if (agentData?.idleTimer) clearInterval(agentData.idleTimer);
+ if (agentData?.promptTimer) clearTimeout(agentData.promptTimer);
+
+ const duration = Date.now() - (agentData?.startedAt || Date.now());
+ const terminatedByUser = userTerminatedAgents.has(agentId);
+ if (terminatedByUser) userTerminatedAgents.delete(agentId);
+
+ const finalSuccess = terminatedByUser ? false : success;
+ const finalError = terminatedByUser ? 'Agent terminated by user' : error;
+
+ if (agentData?.laneName || laneName) release(agentId);
+
+ const effectiveExecutionId = agentData?.executionId || executionId;
+ if (effectiveExecutionId) {
+ if (finalSuccess) {
+ completeExecution(effectiveExecutionId, { success: true, duration });
+ } else {
+ errorExecution(effectiveExecutionId, { message: finalError || `TUI agent ended: ${reason}`, code: exitCode });
+ completeExecution(effectiveExecutionId, { success: false });
+ }
+ }
+
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+
+ const analysisBuffer = rawBuffer || outputBuffer;
+ const errorAnalysis = finalSuccess ? null : analyzeAgentFailure(analysisBuffer, task, model);
+
+ if (finalSuccess) {
+ await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);
+ }
+
+ await completeAgent(agentId, {
+ success: finalSuccess,
+ exitCode,
+ duration,
+ outputLength: outputBuffer.length,
+ error: finalError || undefined,
+ errorAnalysis,
+ completionReason: reason
+ });
+
+ await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);
+
+ if (terminatedByUser) {
+ await updateTask(task.id, {
+ status: 'blocked',
+ metadata: {
+ ...task.metadata,
+ blockedReason: 'Terminated by user',
+ blockedCategory: 'user-terminated',
+ blockedAt: new Date().toISOString()
+ }
+ }, task.taskType || 'user');
+ } else if (finalSuccess) {
+ await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');
+ } else {
+ const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
+ await updateTask(task.id, failedUpdate, task.taskType || 'user');
+
+ if (errorAnalysis?.category === 'usage-limit' && errorAnalysis.requiresFallback) {
+ await markProviderUsageLimit(provider.id, errorAnalysis).catch(err => {
+ emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId: provider.id });
+ });
+ }
+ if (errorAnalysis?.category === 'rate-limit') {
+ await markProviderRateLimited(provider.id).catch(err => {
+ emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId: provider.id });
+ });
+ }
+ }
+
+ await processAgentCompletion(agentId, task, finalSuccess, outputBuffer);
+ if (workspacePath) await rm(join(workspacePath, 'BTW.md')).catch(() => {});
+
+ const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
+ const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
+ await cleanupWorktreeFn(agentId, finalSuccess, {
+ openPR: directOpenPR,
+ requestCopilotReview: directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
+ skipMerge: directReviewLoopFollowUp,
+ description: task.description,
+ agentOutput: outputBuffer,
+ originalTask: task
+ });
+
+ if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
+ activeAgents.delete(agentId);
+ if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);
+ };
+
+ const handleData = async (data) => {
+ const text = data.toString();
+ rawBuffer += text;
+ if (rawBuffer.length > RAW_BUFFER_HEADROOM) rawBuffer = rawBuffer.slice(-RAW_BUFFER_CAP);
+ lastOutputAt = Date.now();
+
+ if (!hasStartedWorking) {
+ hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `TUI agent ${agentId} working...`, { agentId, phase: 'working' });
+ }
+
+ const clean = stripAnsi(text).replace(/\r/g, '\n');
+ const lowerClean = clean.toLowerCase();
+ if (!promptSentAt && lowerClean.includes('command not found') && lowerClean.includes(commandName.toLowerCase())) {
+ await finish({
+ success: false,
+ exitCode: 127,
+ error: `TUI command not found: ${tuiConfig.command}`,
+ reason: 'command-not-found'
+ });
+ return;
+ }
+
+ const lines = clean.split('\n').map(line => line.trim()).filter(Boolean);
+ for (const line of lines) {
+ await appendLine(line);
+ }
+ };
+
+ const handleExit = async ({ exitCode, killed }) => {
+ if (finalized) return;
+ const code = typeof exitCode === 'number' ? exitCode : killed ? 130 : 0;
+ await finish({
+ success: code === 0 && !killed,
+ exitCode: code,
+ error: killed ? 'TUI shell session was killed' : null,
+ reason: killed ? 'shell-killed' : 'shell-exit'
+ });
+ };
+
+ sessionId = shellService.createShellSession(null, {
+ cwd,
+ kind: 'agent-tui',
+ agentId,
+ label: `${provider.name} ${agentId}`,
+ command: tuiConfig.commandLine,
+ initialCommand: tuiConfig.commandLine,
+ env: provider.envVars || {},
+ onData: handleData,
+ onExit: handleExit
+ });
+
+ if (!sessionId) {
+ await finish({ success: false, exitCode: 1, error: 'Failed to create TUI shell session', reason: 'spawn-error' });
+ return null;
+ }
+
+ const ptyProcess = shellService.getSessionProcess(sessionId);
+ const pid = ptyProcess?.pid || null;
+ if (pid) {
+ registerSpawnedAgent(pid, {
+ fullCommand: tuiConfig.commandLine,
+ agentId,
+ taskId: task.id,
+ model,
+ workspacePath,
+ prompt: (task.description || '').substring(0, 500)
+ });
+ }
+
+ const promptTimer = setTimeout(() => {
+ if (finalized) return;
+ promptSentAt = Date.now();
+ shellService.writeToSession(sessionId, `\x1b[200~${prompt}\x1b[201~\r`);
+ appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)}`).catch(() => {});
+ }, tuiConfig.promptDelayMs);
+
+ const idleTimer = setInterval(() => {
+ if (!promptSentAt || finalized) return;
+ const runtime = Date.now() - promptSentAt;
+ const idle = Date.now() - lastOutputAt;
+ if (runtime < DEFAULT_TUI_MIN_RUNTIME_MS) return;
+ if (meaningfulLinesAfterPrompt < 2) return;
+ if (idle >= tuiConfig.idleTimeoutMs) {
+ finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {
+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });
+ });
+ }
+ }, 5000);
+
+ activeAgents.set(agentId, {
+ process: ptyProcess || { kill: () => shellService.killSession(sessionId) },
+ taskId: task.id,
+ startedAt: Date.now(),
+ runId,
+ pid,
+ providerId: provider.id,
+ executionId,
+ laneName,
+ tuiSessionId: sessionId,
+ idleTimer,
+ promptTimer
+ });
+
+ await updateAgent(agentId, {
+ pid,
+ metadata: {
+ phase: 'working',
+ executionMode: 'tui',
+ tuiSessionId: sessionId,
+ tuiCommand: tuiConfig.commandLine,
+ tuiIdleTimeoutMs: tuiConfig.idleTimeoutMs
+ }
+ });
+
+ await appendLine(`📟 TUI session started: ${sessionId.slice(0, 8)} (${tuiConfig.commandLine})`);
+ return agentId;
+}
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
new file mode 100644
index 0000000000..6b41cecc22
--- /dev/null
+++ b/server/services/agentTuiSpawning.test.js
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest';
+import { buildTuiSpawnConfig } from './agentTuiSpawning.js';
+
+describe('agent TUI spawning', () => {
+ it('builds a codex TUI command without a model flag for the configured-default sentinel', () => {
+ const config = buildTuiSpawnConfig({
+ id: 'codex-tui',
+ name: 'Codex TUI',
+ type: 'tui',
+ command: 'codex',
+ args: []
+ }, 'codex-configured-default');
+
+ expect(config.command).toBe('codex');
+ expect(config.args).toEqual([]);
+ expect(config.commandLine).toBe('codex');
+ });
+
+ it('quotes TUI arguments and carries idle timing config', () => {
+ const config = buildTuiSpawnConfig({
+ id: 'claude-code-tui',
+ name: 'Claude TUI',
+ type: 'tui',
+ command: 'claude',
+ args: ['--dangerously-skip-permissions', '--add-dir', '/tmp/with space'],
+ tuiPromptDelayMs: 1000,
+ tuiIdleTimeoutMs: 30000
+ }, 'claude-sonnet');
+
+ expect(config.args).toEqual([
+ '--dangerously-skip-permissions',
+ '--add-dir',
+ '/tmp/with space',
+ '--model',
+ 'claude-sonnet'
+ ]);
+ expect(config.commandLine).toBe("claude --dangerously-skip-permissions --add-dir '/tmp/with space' --model claude-sonnet");
+ expect(config.promptDelayMs).toBe(1000);
+ expect(config.idleTimeoutMs).toBe(30000);
+ });
+});
diff --git a/server/services/shell.js b/server/services/shell.js
index afd1c5fcb0..706b20b33b 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -44,7 +44,7 @@ function getDefaultShell() {
export function createShellSession(socket, options = {}) {
if (shellSessions.size >= 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.` });
+ socket?.emit?.('shell:error', { error: `Max ${MAX_TOTAL_SESSIONS} shell sessions. Kill an existing session first.` });
return null;
}
@@ -65,13 +65,14 @@ export function createShellSession(socket, options = {}) {
cwd,
env: {
...buildSafeEnv(),
+ ...(options.env || {}),
TERM: 'xterm-256color',
COLORTERM: 'truecolor'
}
});
} catch (err) {
console.error(`❌ Failed to spawn PTY: ${err.message}`);
- socket.emit('shell:error', { error: `Failed to spawn shell: ${err.message}` });
+ socket?.emit?.('shell:error', { error: `Failed to spawn shell: ${err.message}` });
return null;
}
@@ -86,6 +87,12 @@ export function createShellSession(socket, options = {}) {
socket,
cwd,
createdAt: Date.now(),
+ label: options.label || null,
+ kind: options.kind || 'shell',
+ agentId: options.agentId || null,
+ command: options.command || null,
+ onData: options.onData || null,
+ onExit: options.onExit || null,
outputBuffer,
bufferSize: () => bufferSize
});
@@ -100,6 +107,7 @@ export function createShellSession(socket, options = {}) {
}
const session = shellSessions.get(sessionId);
session?.socket?.emit('shell:output', { sessionId, data });
+ session?.onData?.(data);
});
// Handle pty exit
@@ -108,11 +116,15 @@ export function createShellSession(socket, options = {}) {
const session = shellSessions.get(sessionId);
shellSessions.delete(sessionId);
session?.socket?.emit('shell:exit', { sessionId, code: exitCode });
+ session?.onExit?.({ exitCode });
// Notify all sockets about session list change
broadcastSessionList();
});
broadcastSessionList();
+ if (options.initialCommand) {
+ setTimeout(() => writeToSession(sessionId, `${options.initialCommand}\n`), options.initialCommandDelayMs || 200);
+ }
return sessionId;
}
@@ -158,12 +170,24 @@ export function listAllSessions() {
sessions.push({
sessionId,
cwd: session.cwd,
- createdAt: session.createdAt
+ createdAt: session.createdAt,
+ label: session.label,
+ kind: session.kind,
+ agentId: session.agentId,
+ command: session.command
});
}
return sessions;
}
+export function getSession(sessionId) {
+ return shellSessions.get(sessionId) || null;
+}
+
+export function getSessionProcess(sessionId) {
+ return shellSessions.get(sessionId)?.pty || null;
+}
+
/**
* Write input to a shell session
*/
@@ -197,6 +221,7 @@ export function killSession(sessionId) {
console.log(`🐚 Killing shell session ${sessionId.slice(0, 8)}`);
session.pty.kill();
shellSessions.delete(sessionId);
+ session.onExit?.({ exitCode: null, killed: true });
broadcastSessionList();
return true;
}