Skip to content

The agent that grows with you

feat(process_registry): stamp exited_at and expose it on process.list

teknium12c78b9b39e9a
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index b599795b9d3..53e62306ddf 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3041,6 +3041,8 @@ export interface ProcessEntry {
watch_hit?: boolean | null
notify_on_complete?: boolean | null
exit_code?: number | null
+ exited_at?: number | null
+ completion_reason?: string | null
detached?: boolean | null
[key: string]: unknown
}
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 1d168b64c41..fedd20e3c3d 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -18765,6 +18765,30 @@
"default": null,
"title": "Exit Code"
},
+ "exited_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Exited At"
+ },
+ "completion_reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Completion Reason"
+ },
"detached": {
"anyOf": [
{
diff --git a/hermes_cli/cli_process_dock.py b/hermes_cli/cli_process_dock.py
new file mode 100644
index 00000000000..b8432e1548e
--- /dev/null
+++ b/hermes_cli/cli_process_dock.py
@@ -0,0 +1,103 @@
+"""Background-process rows for the classic CLI live-work dock.
+
+Sibling of ``cli_subagent_monitor``: the dock paints one "Processes" block under the
+subagent rows from the same snapshot the ``process_manage`` tool reads, so a
+``terminal(background=true)`` spawn is visible the moment it starts instead of only
+when its completion notification lands.
+"""
+from __future__ import annotations
+
+import time
+
+# A finished process stays on the dock long enough to read its exit line, then
+# leaves; the completion notification in the transcript is the durable record.
+RETAIN_SECONDS = 60
+
+# Reader-thread exits report "exited"; `kill_process` / `kill_all` stamp "killed".
+_STATUS_BY_REASON = {"killed": "killed", "lost": "lost", "failed_start": "failed"}
+
+
+def _last_output_line(buffer: str) -> str:
+ for line in reversed((buffer or "").splitlines()):
+ text = " ".join(line.split())
+ if text:
+ return text
+ return ""
+
+
+def process_status(entry: dict) -> str:
+ if entry.get("status") != "exited":
+ return "running"
+ reason = _STATUS_BY_REASON.get(entry.get("completion_reason") or "")
+ if reason:
+ return reason
+ return "done" if not entry.get("exit_code") else "failed"
+
+
+def process_rows(now: float | None = None) -> list:
+ """Running processes plus those that exited within ``RETAIN_SECONDS``, newest-running first.
+
+ The classic CLI is one conversation per OS process, so every registry entry (its own
+ spawns and any a child handed back) belongs to this dock; gateway-hosted surfaces scope
+ by session key in ``tui_gateway`` instead.
+ """
+ from tools.process_registry import process_registry
+
+ now = time.time() if now is None else now
+ rows = []
+ for entry in process_registry.list_sessions():
+ proc = process_registry.get(entry["session_id"])
+ if proc is None:
+ continue
+ status = process_status(entry)
+ exited_at = proc.exited_at if status != "running" else 0.0
+ if status != "running" and now - exited_at > RETAIN_SECONDS:
+ continue
+ end = exited_at or now
+ rows.append({
+ "kind": "process",
+ "key": proc.id,
+ "id": proc.id,
+ "command": " ".join((proc.command or "").split()) or "background process",
+ "status": status,
+ "exit_code": proc.exit_code,
+ "elapsed": max(0, int(end - proc.started_at)),
+ "since_exit": max(0, int(now - exited_at)) if exited_at else 0,
+ "detail": _last_output_line(proc.output_buffer),
+ })
+ rows.sort(key=lambda r: (r["status"] != "running", -r["elapsed"] if r["status"] == "running" else r["since_exit"]))
+ return rows
+
+
+_GLYPH = {"running": "⚙", "done": "✔", "failed": "✘", "killed": "✘", "lost": "?"}
+
+
+def process_activity(row: dict) -> str:
+ """The trailing ``· …`` part of a dock line: elapsed + latest output while running, the exit
+ verdict + age once finished."""
+ if row["status"] == "running":
+ return f"{row['elapsed']}s · " + (f"last: {row['detail']}" if row["detail"] else "starting")
+ verdict = {"done": f"exit {row['exit_code']}", "failed": f"exit {row['exit_code']}",
+ "killed": "killed", "lost": "lost"}[row["status"]]
+ return f"{verdict} · {row['since_exit']}s ago"
+
+
+def process_glyph(row: dict) -> str:
+ return _GLYPH.get(row["status"], "?")
+
+
+def process_tail(process_id: str) -> str:
+ from tools.process_registry import process_registry
+
+ proc = process_registry.get(process_id)
+ if proc is None:
+ return "This process is no longer tracked."
+ text = (proc.output_buffer or "")[-32768:]
+ text = "".join(c for c in text if c.isprintable() or c in "\n\t")
+ return text or "No output yet."
+
+
+def kill(process_id: str) -> dict:
+ from tools.process_registry import process_registry
+
+ return process_registry.kill_process(process_id)
diff --git a/tests/hermes_cli/test_process_dock.py b/tests/hermes_cli/test_process_dock.py
new file mode 100644
index 00000000000..e3e0ba2a138
--- /dev/null
+++ b/tests/hermes_cli/test_process_dock.py
@@ -0,0 +1,74 @@
+"""Background processes share the classic CLI live-work dock with subagents (Processes block)."""
+import time
+from types import SimpleNamespace
+
+from prompt_toolkit.utils import get_cwidth
+
+
+def _wait(predicate, timeout=5.0):
+ deadline = time.monotonic() + timeout
+ while not predicate():
+ assert time.monotonic() < deadline, "timed out"
+ time.sleep(0.05)
+
+
+def test_dock_paints_processes_under_agents_and_retires_finished_rows(monkeypatch):
+ from hermes_cli import cli_process_dock
+ from hermes_cli.cli_subagent_monitor import SubagentMonitor
+ from tools import delegate_tool_registry as registry
+ from tools.process_registry import process_registry
+
+ monkeypatch.setattr(registry, '_active_subagents', {})
+ owner = SimpleNamespace(session_id='owner')
+ registry._register_subagent(dict(subagent_id='a1', owner_agent_session_id='owner',
+ goal='Check module', started_at=10, status='running', last_tool='read_file'))
+ quick = process_registry.spawn_local(command="echo hello-dock; exit 3", cwd='.', task_id='t', owner_task_id='t', session_key='')
+ slow = process_registry.spawn_local(command="sleep 30", cwd='.', task_id='t', owner_task_id='t', session_key='')
+ quick_id, slow_id = quick.id, slow.id
+ try:
+ _wait(lambda: process_registry.get(quick_id).exited)
+ process_registry.list_sessions() # observes the exit → exited_at stamped
+ dock = SubagentMonitor(SimpleNamespace(agent=owner))
+ assert dock.refresh()
+ text = dock.dock_text(columns=100, rows=30)
+ lines = text.splitlines()
+ assert 'Subagents · 1 live' in lines[0]
+ agents_at = next(i for i, line in enumerate(lines) if 'Check module' in line)
+ procs_at = next(i for i, line in enumerate(lines) if 'Processes · 1 running · 1 done' in line)
+ assert agents_at < procs_at
+ assert any('⚙ sleep 30' in line and 'starting' in line for line in lines)
+ assert any('✘ echo hello-dock; exit 3 · exit 3' in line for line in lines)
+ assert all(get_cwidth(line) <= 100 for line in lines)
+ # Every viewport keeps at least one row of each block.
+ narrow = dock.dock_text(columns=40, rows=14).splitlines()
+ assert any('Check module' in line for line in narrow) and any('Processes' in line for line in narrow)
+ assert all(get_cwidth(line) <= 40 for line in narrow)
+ dock.collapsed = True
+ assert dock.dock_text(columns=100, rows=30).count('\n') == 0
+ assert '1 live · 1 proc' in dock.dock_text(columns=100, rows=30)
+ # Finished rows leave after the retention window; running ones stay.
+ later = cli_process_dock.process_rows(time.time() + cli_process_dock.RETAIN_SECONDS + 1)
+ assert [r['id'] for r in later] == [slow_id]
+ finally:
+ process_registry.kill_process(slow_id)
+
+
+def test_monitor_controls_stop_processes_and_never_steer_them():
+ from hermes_cli.cli_subagent_monitor import SubagentMonitor
+ from tools.process_registry import process_registry
+
+ slow = process_registry.spawn_local(command="sleep 30", cwd='.', task_id='t', owner_task_id='t', session_key='')
+ slow_id = slow.id
+ try:
+ dock = SubagentMonitor(SimpleNamespace(agent=None))
+ dock.refresh()
+ dock.selected_id = slow_id
+ assert dock.selected_process is not None
+ assert 'error' in dock.control('steer', 'nope')
+ assert process_registry.get(slow_id).exited is False
+ assert dock.control('stop')['status'] == 'killed'
+ _wait(lambda: process_registry.get(slow_id).exited)
+ dock.refresh()
+ assert any(r['id'] == slow_id and r['status'] == 'killed' for r in dock.processes)
+ finally:
+ process_registry.kill_process(slow_id)
diff --git a/tools/process_registry.py b/tools/process_registry.py
index dae13056bd9..fd37db9f879 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -510,6 +510,7 @@ class ProcessSession:
started_at: float = 0.0 # time.time() of spawn
host_start_time: Optional[int] = None # kernel start ticks (/proc/<pid>/stat f22) — PID-reuse guard
exited: bool = False
+ exited_at: float = 0.0 # time.time() of the FIRST move to finished (0 = unknown)
exit_code: Optional[int] = None # None while running
completion_reason: str = "exited" # exited|killed|lost|failed_start|already_exited
termination_source: str = "" # process.kill|kill_all|backend_lost|failed_start
@@ -1505,6 +1506,7 @@ class ProcessRegistry(ProcessCheckpointMixin):
with self._lock:
was_running = session.id in self._running
if was_running:
+ session.exited_at = time.time()
# Keep the session tracked until its result is durable. A finite
# parent must not observe completion and exit during this write.
save_completed_result(session)
@@ -2237,6 +2239,8 @@ class ProcessRegistry(ProcessCheckpointMixin):
entry["notify_on_complete"] = True
if s.exited:
entry["exit_code"] = s.exit_code
+ entry["exited_at"] = s.exited_at
+ entry["completion_reason"] = s.completion_reason
if s.detached:
entry["detached"] = True
result.append(entry)
diff --git a/tui_gateway/contracts/tools_commands.py b/tui_gateway/contracts/tools_commands.py
index 5e636f1b09a..93fba36745d 100644
--- a/tui_gateway/contracts/tools_commands.py
+++ b/tui_gateway/contracts/tools_commands.py
@@ -106,6 +106,8 @@ class ProcessEntry(_Open):
watch_hit: bool | None = None
notify_on_complete: bool | None = None
exit_code: int | None = None
+ exited_at: float | None = None
+ completion_reason: str | None = None
detached: bool | None = None
diff --git a/ui-tui/src/__tests__/processDock.test.tsx b/ui-tui/src/__tests__/processDock.test.tsx
new file mode 100644
index 00000000000..24e30d365c9
--- /dev/null
+++ b/ui-tui/src/__tests__/processDock.test.tsx
@@ -0,0 +1,115 @@
+import { PassThrough } from 'node:stream'
+
+import { renderSync } from '@hermes/ink'
+import React from 'react'
+import stripAnsi from 'strip-ansi'
+import { expect, it } from 'vitest'
+
+import { buildProcessRows, PROCESS_RETAIN_SECONDS, type ProcessEntry } from '../app/processRoster.js'
+import { AgentsPanelView, buildProcessBlock, splitDockBudget } from '../components/agentsPanel.js'
+import { buildAgentRows, dockRowLimit } from '../lib/agentRows.js'
+import { DEFAULT_THEME } from '../theme.js'
+import type { SubagentProgress } from '../types.js'
+
+const NOW = 1_000_000_000
+
+const agent = (id: string): SubagentProgress => ({
+ id,
+ goal: 'Investigate authentication handshake',
+ depth: 0,
+ index: 0,
+ parentId: null,
+ notes: [],
+ tools: ['read_file auth.ts'],
+ thinking: [],
+ toolCount: 1,
+ taskCount: 1,
+ startedAt: NOW * 1000 - 5000,
+ status: 'running'
+})
+
+const running: ProcessEntry = {
+ session_id: 'proc_run',
+ command: 'npm run build\n',
+ status: 'running',
+ uptime_seconds: 42,
+ output_preview: 'compiling…\nbundled 300 modules\n\n'
+}
+
+const exited = (id: string, exitedAgoSeconds: number, exitCode = 0): ProcessEntry => ({
+ session_id: id,
+ command: 'pytest tests/',
+ status: 'exited',
+ uptime_seconds: 12 + exitedAgoSeconds,
+ exit_code: exitCode,
+ exited_at: NOW - exitedAgoSeconds,
+ completion_reason: 'exited'
+})
+
+const paint = (element: React.ReactElement, rows = 30): string => {
+ const stdout = Object.assign(new PassThrough(), { columns: 80, rows })
+ const frames: string[] = []
+ stdout.on('data', chunk => frames.push(chunk.toString()))
+
+ const view = renderSync(element, {
+ stdout: stdout as unknown as NodeJS.WriteStream,
+ stdin: new PassThrough() as unknown as NodeJS.ReadStream
+ })
+
+ view.unmount()
+ view.cleanup()
+
+ return stripAnsi(frames.join(''))
+}
+
+it('keeps running processes, ages finished ones out after the retention window, and carries the exit verdict', () => {
+ const rows = buildProcessRows(
+ [exited('old', PROCESS_RETAIN_SECONDS + 1), exited('fresh', 5, 1), running, exited('killed', 2)],
+ NOW * 1000
+ )
+
+ expect(rows.map(r => r.id)).toEqual(['proc_run', 'killed', 'fresh'])
+ expect(rows[0]).toMatchObject({ status: 'running', detail: 'last: bundled 300 modules', elapsedSeconds: 42 })
+ expect(rows[2]).toMatchObject({ status: 'failed', detail: 'exit 1 · 5s ago', elapsedSeconds: 12 })
+ // A checkpoint-recovered exit without a timestamp never lingers as a phantom row.
+ expect(buildProcessRows([{ ...exited('x', 1), exited_at: null }], NOW * 1000)).toEqual([])
+})
+
+it('paints a Processes block under the agents without letting either block hide the other', () => {
+ const agents = Array.from({ length: 6 }, (_, i) => agent(`child-${i}`))
+ const processes = buildProcessRows([running, exited('fresh', 5)], NOW * 1000)
+ const limit = dockRowLimit(30)
+ const budget = splitDockBudget(limit, agents.length, processes.length)
+ expect(budget.agents).toBeGreaterThanOrEqual(1)
+ expect(budget.processes).toBeGreaterThanOrEqual(1)
+ expect(budget.agents + budget.processes).toBeLessThanOrEqual(Math.max(limit, 2))
+
+ const agentRows = buildAgentRows(agents, [], NOW * 1000, budget.agents)
+ const block = buildProcessBlock(processes, budget.processes)
+ const text = paint(<AgentsPanelView cols={80} {...agentRows} processes={block} t={DEFAULT_THEME} />)
+
+ expect(text).toContain('6 live agents')
+ expect(text).toContain('Processes · 1 running · 1 done')
+ expect(text).toContain('⚙ npm run build')
+ expect(text.indexOf('live agents')).toBeLessThan(text.indexOf('Processes ·'))
+
+ // Processes alone still surface the dock, with the expand/collapse controls on their heading.
+ const alone = paint(
+ <AgentsPanelView
+ cols={80}
+ {...buildAgentRows([], [], NOW * 1000)}
+ processes={buildProcessBlock(processes, limit)}
+ t={DEFAULT_THEME}
+ />
+ )
+
+ expect(alone).toContain('Processes · 1 running · 1 done · Ctrl+T expand')
+ expect(alone).toContain('✔ pytest tests/ · exit 0 · 5s ago')
+
+ const collapsed = paint(
+ <AgentsPanelView collapsed cols={80} {...agentRows} processes={block} t={DEFAULT_THEME} />
+ )
+
+ expect(collapsed.trim().split('\n')).toHaveLength(1)
+ expect(collapsed).toContain('6 live agents · 1 procs')
+})
diff --git a/ui-tui/src/app/processRoster.ts b/ui-tui/src/app/processRoster.ts
new file mode 100644
index 00000000000..25e450bfbcd
--- /dev/null
+++ b/ui-tui/src/app/processRoster.ts
@@ -0,0 +1,125 @@
+import { useStore } from '@nanostores/react'
+import { atom } from 'nanostores'
+import { useMemo } from 'react'
+
+import { $uiState } from './uiStore.js'
+
+// Background `terminal(background=true)` processes owned by this session, as the
+// gateway's `process.list` reports them. Session-local presentation only.
+
+export interface ProcessEntry {
+ session_id: string
+ command?: string
+ status?: string
+ uptime_seconds?: number | null
+ exit_code?: number | null
+ exited_at?: number | null
+ completion_reason?: string | null
+ output_preview?: string
+}
+
+export interface ProcessRow {
+ command: string
+ /** Latest non-empty output line while running; the exit verdict once finished. */
+ detail: string
+ elapsedSeconds: number
+ id: string
+ /** Seconds since exit; 0 while running. */
+ sinceExitSeconds: number
+ status: 'done' | 'failed' | 'killed' | 'lost' | 'running'
+}
+
+/** A finished process stays on the dock long enough to read its exit line, then
+ * leaves; the completion notification in the transcript is the durable record. */
+export const PROCESS_RETAIN_SECONDS = 60
+
+export const $processSnapshot = atom<{ sid: string | null; processes: ProcessEntry[] }>({ sid: null, processes: [] })
+
+export function applyProcessSnapshot(sid: string | null, processes: ProcessEntry[] = []) {
+ const previous = $processSnapshot.get()
+
+ if (previous.sid !== sid || JSON.stringify(previous.processes) !== JSON.stringify(processes)) {
+ $processSnapshot.set({ sid, processes })
+ }
+}
+
+const REASON_STATUS: Record<string, ProcessRow['status']> = { failed_start: 'failed', killed: 'killed', lost: 'lost' }
+
+export const processStatus = (entry: ProcessEntry): ProcessRow['status'] => {
+ if (entry.status !== 'exited') {
+ return 'running'
+ }
+
+ return REASON_STATUS[entry.completion_reason ?? ''] ?? (entry.exit_code ? 'failed' : 'done')
+}
+
+const lastOutputLine = (preview: string | undefined): string => {
+ for (const line of (preview ?? '').split('\n').reverse()) {
+ const text = line.replace(/\s+/g, ' ').trim()
+
+ if (text) {
+ return text
+ }
+ }
+
+ return ''
+}
+
+export const processVerdict = (row: ProcessRow, exitCode: number | null | undefined): string => {
+ if (row.status === 'running') {
+ return row.detail ? `last: ${row.detail}` : 'starting'
+ }
+
+ const verdict = row.status === 'killed' || row.status === 'lost' ? row.status : `exit ${exitCode ?? '?'}`
+
+ return `${verdict} · ${row.sinceExitSeconds}s ago`
+}
+
+/** Running processes first (longest running first), then recently exited ones
+ * newest-exit first; exits older than the retention window are dropped. */
+export const buildProcessRows = (processes: readonly ProcessEntry[], nowMs: number): ProcessRow[] => {
+ const nowS = nowMs / 1000
+ const rows: ProcessRow[] = []
+
+ for (const entry of processes) {
+ const status = processStatus(entry)
+ const exitedAt = status === 'running' ? 0 : (entry.exited_at ?? 0)
+ const sinceExitSeconds = exitedAt ? Math.max(0, Math.floor(nowS - exitedAt)) : 0
+
+ if (status !== 'running' && (!exitedAt || sinceExitSeconds > PROCESS_RETAIN_SECONDS)) {
+ continue
+ }
+
+ const row: ProcessRow = {
+ command: (entry.command ?? '').replace(/\s+/g, ' ').trim() || 'background process',
+ detail: lastOutputLine(entry.output_preview),
+ elapsedSeconds: Math.max(0, entry.uptime_seconds ?? 0) - sinceExitSeconds,
+ id: entry.session_id,
+ sinceExitSeconds,
+ status
+ }
+
+ row.detail = processVerdict(row, entry.exit_code)
+ rows.push(row)
+ }
+
+ return rows.sort((a, b) =>
+ a.status === 'running' !== (b.status === 'running')
+ ? a.status === 'running'
+ ? -1
+ : 1
+ : a.status === 'running'
+ ? b.elapsedSeconds - a.elapsedSeconds
+ : a.sinceExitSeconds - b.sinceExitSeconds
+ )
+}
+
+export function useProcessRows(nowMs: number): ProcessRow[] {
+ const snapshot = useStore($processSnapshot)
+ const { sid } = useStore($uiState)
+
+ return useMemo(
+ () => buildProcessRows(snapshot.sid === sid ? snapshot.processes : [], nowMs),
+ [snapshot, sid, nowMs]
+ )
+}
diff --git a/ui-tui/src/lib/processGlyph.ts b/ui-tui/src/lib/processGlyph.ts
new file mode 100644
index 00000000000..2b23d6ce9f8
--- /dev/null
+++ b/ui-tui/src/lib/processGlyph.ts
@@ -0,0 +1,19 @@
+import type { ProcessRow } from '../app/processRoster.js'
+import type { Theme } from '../theme.js'
+
+// Status→glyph lookup for background-process rows; the docked panel and the
+// /agents overlay render identical glyphs so the two never drift apart.
+
+export const PROCESS_GLYPH: Record<ProcessRow['status'], { color: (t: Theme) => string; glyph: string }> = {
+ running: { color: t => t.color.accent, glyph: '⚙' },
+ done: { color: t => t.color.statusGood, glyph: '✔' },
+ failed: { color: t => t.color.error, glyph: '✘' },
+ killed: { color: t => t.color.warn, glyph: '✘' },
+ lost: { color: t => t.color.muted, glyph: '?' }
+}
+
+export const processGlyph = (status: ProcessRow['status'], t: Theme): { color: string; glyph: string } => {
+ const g = PROCESS_GLYPH[status]
+
+ return { color: g.color(t), glyph: g.glyph }
+}