diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index e7d42f03b7..6706a7da9b 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -51,21 +51,29 @@ const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${t const AGENT_SETTLED_RETENTION_LIMIT = 50; const AGENT_USAGE_MATERIAL_STEP = 25_000; +// Fields must satisfy the contract's NonNegativeInt or the persisted roster +// row becomes undecodable on the client. +function usageCount(value: unknown): number | undefined { + return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined; +} + function taskUsage(value: unknown): ThreadAgentUsage | undefined { if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined; const usage = value as Record; - if (typeof usage.totalTokens !== "number" || usage.totalTokens < 0) return undefined; + const totalTokens = usageCount(usage.totalTokens); + if (totalTokens === undefined) return undefined; + const inputTokens = usageCount(usage.inputTokens); + const cachedInputTokens = usageCount(usage.cachedInputTokens); + const outputTokens = usageCount(usage.outputTokens); + const reasoningOutputTokens = usageCount(usage.reasoningOutputTokens); + const toolUses = usageCount(usage.toolUses); return { - totalTokens: usage.totalTokens, - ...(typeof usage.inputTokens === "number" ? { inputTokens: usage.inputTokens } : {}), - ...(typeof usage.cachedInputTokens === "number" - ? { cachedInputTokens: usage.cachedInputTokens } - : {}), - ...(typeof usage.outputTokens === "number" ? { outputTokens: usage.outputTokens } : {}), - ...(typeof usage.reasoningOutputTokens === "number" - ? { reasoningOutputTokens: usage.reasoningOutputTokens } - : {}), - ...(typeof usage.toolUses === "number" ? { toolUses: usage.toolUses } : {}), + totalTokens, + ...(inputTokens !== undefined ? { inputTokens } : {}), + ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}), + ...(outputTokens !== undefined ? { outputTokens } : {}), + ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}), + ...(toolUses !== undefined ? { toolUses } : {}), }; } @@ -192,14 +200,16 @@ export function foldTaskAgentEvent( ...((payload.outputFile ?? previous?.outputFile) ? { outputFile: payload.outputFile ?? previous?.outputFile } : {}), + // A re-activated agent starts a fresh run: prior result/error text would + // read as the live run's output, so clear both unless this event sets them. ...(event.type === "task.completed" && event.payload.summary ? { resultSummary: event.payload.summary } - : previous?.resultSummary + : !reactivated && previous?.resultSummary ? { resultSummary: previous.resultSummary } : {}), ...(event.type === "task.updated" && event.payload.errorMessage ? { errorMessage: event.payload.errorMessage } - : previous?.errorMessage + : !reactivated && previous?.errorMessage ? { errorMessage: previous.errorMessage } : {}), recentActivity, @@ -1561,12 +1571,14 @@ const make = Effect.gen(function* () { if (agentRosterMaterial) { pruneSettledAgents(threadAgents); const roster = Array.from(threadAgents.values()); - const running = roster.filter((agent) => agent.status === "running").length; - const settled = roster.filter( - (agent) => agent.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(agent.status), + // "active" covers everything non-settled (running/pending/waiting) so a + // roster of blocked agents doesn't read as "0 agents settled". + const active = roster.filter( + (agent) => agent.status !== "idle" && !THREAD_AGENT_TERMINAL_STATUSES.has(agent.status), ).length; - const count = running > 0 ? running : settled; - const summary = `${count} ${count === 1 ? "agent" : "agents"} ${running > 0 ? "running" : "settled"}`; + const settled = roster.length - active; + const count = active > 0 ? active : settled; + const summary = `${count} ${count === 1 ? "agent" : "agents"} ${active > 0 ? "active" : "settled"}`; const snapshotUuid = yield* crypto.randomUUIDv4; const activity: OrchestrationThreadActivity = { id: EventId.make(`${event.eventId}:agent-snapshot:${snapshotUuid}`), @@ -1577,13 +1589,26 @@ const make = Effect.gen(function* () { payload: { agents: roster }, turnId: toTurnId(event.turnId) ?? null, }; - yield* orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId: yield* providerCommandId(event, "agent-snapshot-append"), - threadId: thread.id, - activity, - createdAt: activity.createdAt, - }); + // The reducer map was already mutated; if the append fails, drop the + // hydration marker so the next event re-hydrates from the last + // *persisted* snapshot and re-detects the missed material change — + // otherwise the roster silently stays stale until the next transition. + yield* orchestrationEngine + .dispatch({ + type: "thread.activity.append", + commandId: yield* providerCommandId(event, "agent-snapshot-append"), + threadId: thread.id, + activity, + createdAt: activity.createdAt, + }) + .pipe( + Effect.tapError(() => + Effect.sync(() => { + hydratedAgentThreads.delete(thread.id); + agentsByThread.delete(thread.id); + }), + ), + ); agentSnapshotDispatchCount += 1; yield* Effect.logDebug("provider agent snapshot appended", { threadId: thread.id, diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index ad796bd125..e96ad34c55 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -554,6 +554,14 @@ function mapCollabAgentActivity( payload: { taskId: base.payload.taskId, status: "idle", timelineBypass: true }, }, ]; + case "subAgent/interrupted": + return [ + { + ...base, + type: "task.completed", + payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true }, + }, + ]; case "thread/status/changed": { const payload = readPayload( EffectCodexSchema.V2ThreadStatusChangedNotification, @@ -576,6 +584,21 @@ function mapCollabAgentActivity( }, ]; } + if (status.type === "systemError") { + return [ + { + ...base, + type: "task.completed", + payload: { + taskId: base.payload.taskId, + status: "failed", + summary: "Codex reported a system error for this agent", + timelineBypass: true, + }, + }, + ]; + } + // notLoaded/idle are covered by turn lifecycle events. return []; } case "thread/closed": @@ -600,7 +623,9 @@ function mapCollabAgentActivity( payload: { ...base.payload, usage: { - totalTokens: usage.usedTokens, + // Cumulative across the child's activations; `usedTokens` is + // only the latest context window and can shrink on follow-ups. + totalTokens: usage.totalProcessedTokens ?? usage.usedTokens, ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}), ...(usage.cachedInputTokens !== undefined ? { cachedInputTokens: usage.cachedInputTokens } diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 18a3fba8ec..ab21b3eaa1 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -586,7 +586,7 @@ function readRouteFields(notification: CodexServerNotification): { } interface CollabChildAgent { - readonly agentPath: string; + readonly agentPath: string | undefined; readonly interrupted: boolean; } @@ -595,23 +595,26 @@ interface CollabChildAgent { * the parent stream (the probe shows no child `thread/started`, and v2 * `collabAgentToolCall` items carry empty receiver lists). Track them so their * notifications can be folded into agent telemetry instead of leaking into the - * parent timeline as unattributed items. + * parent timeline as unattributed items. Returns the interruption transition + * when this notification carries one, so the caller can emit a terminal event. */ function rememberSubAgentActivity( childAgents: Map, notification: CodexServerNotification, -): void { +): { readonly agentThreadId: string; readonly agentPath: string } | undefined { if (notification.method !== "item/started" && notification.method !== "item/completed") { - return; + return undefined; } const item = notification.params.item; if (item.type !== "subAgentActivity") { - return; + return undefined; } - childAgents.set(item.agentThreadId, { - agentPath: item.agentPath, - interrupted: item.kind === "interrupted", - }); + const interrupted = item.kind === "interrupted"; + const previous = childAgents.get(item.agentThreadId); + childAgents.set(item.agentThreadId, { agentPath: item.agentPath, interrupted }); + return interrupted && !previous?.interrupted + ? { agentThreadId: item.agentThreadId, agentPath: item.agentPath } + : undefined; } /** Synthetic method carrying an intercepted child-thread notification. */ @@ -869,17 +872,49 @@ export const makeCodexSessionRuntime = ( : undefined; rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId); - rememberSubAgentActivity(collabChildAgents, notification); + const interruption = rememberSubAgentActivity(collabChildAgents, notification); yield* Ref.set(collabChildAgentsRef, collabChildAgents); + if (interruption) { + // Surface the interruption as its own child event so the agent + // tracker can terminalize the child (the child thread itself goes + // silent when interrupted). + yield* emitEvent({ + kind: "notification", + threadId: options.threadId, + method: COLLAB_AGENT_ACTIVITY_METHOD, + payload: { + agentThreadId: interruption.agentThreadId, + agentPath: interruption.agentPath, + method: "subAgent/interrupted", + }, + }); + } // v2 collab child threads: their notifications arrive on this // connection keyed by the child threadId. Divert the whole stream into // a synthetic collab/agentActivity event for the agent tracker and keep - // it out of the parent timeline. - const childAgent = notificationThreadId + // it out of the parent timeline. A child's first event can arrive + // BEFORE the parent's subAgentActivity registers it (probe: child + // thread/status/changed lands first), so any thread that is neither + // the session's own provider thread nor a v1 collab receiver is + // treated as an unregistered child. + const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef)); + const knownChild = notificationThreadId ? collabChildAgents.get(notificationThreadId) : undefined; - if (childAgent && notificationThreadId) { + const isForeignThread = + notificationThreadId !== undefined && + providerThreadId !== undefined && + notificationThreadId !== providerThreadId && + !collabReceiverTurns.has(notificationThreadId); + if (notificationThreadId && (knownChild || isForeignThread)) { + if (!knownChild) { + yield* Ref.update(collabChildAgentsRef, (current) => { + const next = new Map(current); + next.set(notificationThreadId, { agentPath: undefined, interrupted: false }); + return next; + }); + } yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); yield* emitEvent({ kind: "notification", @@ -887,7 +922,7 @@ export const makeCodexSessionRuntime = ( method: COLLAB_AGENT_ACTIVITY_METHOD, payload: { agentThreadId: notificationThreadId, - agentPath: childAgent.agentPath, + ...(knownChild?.agentPath ? { agentPath: knownChild.agentPath } : {}), method: notification.method, params: payload, }, diff --git a/apps/web/src/components/AgentsPanel.tsx b/apps/web/src/components/AgentsPanel.tsx index 2acd979bae..1c27f0ad5a 100644 --- a/apps/web/src/components/AgentsPanel.tsx +++ b/apps/web/src/components/AgentsPanel.tsx @@ -12,6 +12,7 @@ import { cn } from "~/lib/utils"; import { Badge } from "./ui/badge"; import { ScrollArea } from "./ui/scroll-area"; import { formatDuration } from "../session-logic"; +import { parseTimestampDate } from "../timestampFormat"; interface AgentsPanelProps { agents: ReadonlyArray; @@ -57,19 +58,18 @@ function AgentStatusDot({ status }: { status: ThreadAgentSnapshot["status"] }) { function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) { const textRef = useRef(null); const settled = isTerminalAgentStatus(agent.status) || agent.status === "idle"; - const startMs = Date.parse(agent.firstStartedAt); - const endMs = agent.endedAt - ? Date.parse(agent.endedAt) - : settled - ? Date.parse(agent.lastActivityAt) - : null; - const initialText = formatDuration((endMs ?? Date.now()) - startMs); + const startMs = parseTimestampDate(agent.firstStartedAt)?.getTime() ?? null; + const endMs = + (agent.endedAt ? parseTimestampDate(agent.endedAt)?.getTime() : null) ?? + (settled ? (parseTimestampDate(agent.lastActivityAt)?.getTime() ?? null) : null); + const initialText = + startMs === null ? null : formatDuration(Math.max(0, (endMs ?? Date.now()) - startMs)); useEffect(() => { - if (endMs !== null) return; + if (startMs === null || endMs !== null) return; const update = () => { if (textRef.current) { - textRef.current.textContent = formatDuration(Date.now() - startMs); + textRef.current.textContent = formatDuration(Math.max(0, Date.now() - startMs)); } }; update(); @@ -77,6 +77,9 @@ function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) { return () => clearInterval(id); }, [startMs, endMs]); + if (initialText === null) { + return null; + } return ( {initialText} @@ -183,8 +186,12 @@ function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) { } function PhaseHeader({ phase }: { phase: AgentPanelPhase }) { - const runningCount = phase.agents.filter((agent) => agent.status === "running").length; - const doneCount = phase.agents.filter((agent) => isTerminalAgentStatus(agent.status)).length; + // "active" (not just status==="running"): a phase whose agents are all + // pending/waiting is still in progress and must not read "0 running". + const doneCount = phase.agents.filter( + (agent) => agent.status === "idle" || isTerminalAgentStatus(agent.status), + ).length; + const activeCount = phase.agents.length - doneCount; return (
{phase.status === "running" ? ( - {runningCount} running{doneCount > 0 ? ` · ${doneCount} done` : ""} + {activeCount} active{doneCount > 0 ? ` · ${doneCount} done` : ""} ) : phase.status === "pending" ? ( pending diff --git a/apps/web/src/components/chat/AgentsLiveStrip.tsx b/apps/web/src/components/chat/AgentsLiveStrip.tsx index 0c158be439..f85f8d9051 100644 --- a/apps/web/src/components/chat/AgentsLiveStrip.tsx +++ b/apps/web/src/components/chat/AgentsLiveStrip.tsx @@ -48,8 +48,13 @@ const AgentsLiveStrip = memo(function AgentsLiveStrip({ ) : null} {runningPhase ? ( - {runningPhase.title} · {runningPhase.agents.filter((a) => a.status === "running").length}{" "} - running + {runningPhase.title} ·{" "} + { + runningPhase.agents.filter( + (a) => a.status === "running" || a.status === "pending" || a.status === "waiting", + ).length + }{" "} + active ) : null} diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index 31cc41798e..cce5b141c6 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -40,7 +40,7 @@ function getTimestampFormatter( return formatter; } -function parseTimestampDate(isoDate: string): Date | null { +export function parseTimestampDate(isoDate: string): Date | null { const date = new Date(isoDate); return Number.isNaN(date.getTime()) ? null : date; } diff --git a/docs/project/plans/subagent-observability-spec.html b/docs/project/plans/subagent-observability-spec.html deleted file mode 100644 index 650c54223f..0000000000 --- a/docs/project/plans/subagent-observability-spec.html +++ /dev/null @@ -1,1235 +0,0 @@ - - - - - - Subagent Observability — Audit & Tech Spec - - - -
-

- T3 Code · Plan 1 of 2 · 2026-07-20 · rev 3 (minimal transport) · companion: - UI mockups -

-

Subagent Observability: Audit & Tech Spec

-

- Expose Codex v2 subagents and Claude Code subagents + workflows in a live T3 panel: who - is running, what they're doing, token burn, elapsed time, and a drill-in. One generic - interface; both providers plug into it. -

- -
- Rev 2 — adversarially reviewed by a Fable subagent and gpt-5.6-sol (codex), - both verifying claims against source. Material corrections: (1) Codex - v2 does not emit the rich collabAgentToolCall spawn items — - that's v1; the v2 tracker is now keyed on subAgentActivity + child - thread/started metadata, and T3's child-thread suppression turns out not to - engage for v2 at all. (2) Codex agents are reusable identities, so the - snapshot now separates identity from activations and adds an idle state. - (3) Persistence is now material-transitions-only (1s ticks stay in - memory) because orchestration events are append-only and replay reads are global. Full - review notes: /tmp/subagent-audit/review/.

- Rev 3 — minimal transport. The bespoke stream event, subscriber gating, - projection table, migration, and capability flag are all deleted: the roster now ships as - one agent.snapshot activity kind through the existing - append/persist/replay channel, latest-wins on the client — the exact pattern the - context-window meter already uses. Server delta shrinks to: contract types, two adapters, - one reducer in ingestion. Rev 2's bespoke design remains in this doc's git history as the - graduation path if fleets outgrow the activity channel. -
- - - -

1 · Audit: Codex v2

-

- Sources: codex-rs @ bb947e8e (2026-07-13); T3's generated schema pin 678157ac. Initial audit - corrected by adversarial review — v1/v2 item emission re-verified handler by handler. -

- -

- The core fact: every v2 subagent is a full app-server thread. There are no - dedicated subagent RPCs — spawn/send/wait are model tools, not client methods. The - client observes subagents as ordinary threads plus parent-side thread items. -

- -
    -
  • - v1 vs v2. features.multi_agent (v1, stable) vs - features.multi_agent_v2 (under development, default off) — but the - model catalog forces v2 for gpt-5.6-sol and gpt-5.6-terra (models.json: multi_agent_version: "v2"), so on the models we care about it's on with zero config. v2 has no depth limit; - concurrency defaults to 4 (max_concurrent_threads_per_session). -
  • -
  • - Identity & lineage arrive on the standard - thread/started notification. The Thread object carries - parentThreadId, shared sessionId, - agentNickname (random, e.g. "Marlow"), agentRole (agent_type: - explorer/awaiter/custom), and - source.subAgent.threadSpawn.{depth, agentPath} with hierarchical paths like - /root/researcher. - Clients are auto-subscribed to child-thread events — no subscribe call needed. -
  • -
  • - Parent-side items — v1 and v2 emit differently (this is where the first - draft was wrong): -
      -
    • - v1 emits rich collabAgentToolCall items for - spawn/send/resume/close/wait, carrying receiverThreadIds, - prompt, model, reasoningEffort, and - agentsStates (child thread id → {status, message}). -
    • -
    • - v2 emits - subAgentActivity {kind: started|interacted|interrupted, agentThreadId, - agentPath} - on spawn/message/interrupt (multi_agents_v2/spawn.rs:142 emits - only this — verified, no CollabAgentToolCall anywhere in the v2 - spawn path). The only v2 collabAgentToolCall emitter is - wait, and it ships with empty - receiverThreadIds / - agentsStates (multi_agents_v2/wait.rs:85,90). - Model/prompt/agentsStates are not on v2 parent items. -
    • -
    - Consequence: under v2, per-agent status and model must come from the - child thread's own stream (thread/status/changed, - turn/started|completed, thread/settings/updated), not from - parent items. -
  • -
  • - Per-agent token burn is free: - thread/tokenUsage/updated {threadId, turnId, tokenUsage: {total, last, - modelContextWindow}} - fires per child thread with input/cached/output/reasoning breakdowns. No server-side tree - rollup — client sums. -
  • -
  • - Agents are reusable identities, not one-shot tasks. - send_message/followup_task re-target an existing child thread - and trigger new turns on it (interaction events at event_mapping.rs:133-178). - A child turn/completed means "this run finished", not "this agent is done" — - the agent sits idle and resumable. -
  • -
  • - Reference consumer: the Codex TUI builds its /agent UI from - notifications alone — it caches child threads from - subAgentActivity/thread/started, buffers the last ~6 item - summaries per child, labels agents "{nickname} [{role}]". -
  • -
  • - Not exposed: the live AgentRegistry (model-facing - list_agents only), tree token rollups, per-agent "current activity" endpoint. - thread/list?parentThreadId/ancestorThreadId subtree filters are - experimental-gated and newer than T3's schema pin. -
  • -
- -
- T3 schema verdict: the vendored effect-codex-app-server pin - already has everything needed — subAgentActivity, - collabAgentToolCall, - Thread.parentThreadId/agentNickname/agentRole + - source.subAgent.threadSpawn, thread/tokenUsage/updated. No - regeneration required to ship. -
- -
- T3's child-thread suppression does not engage for v2 — child chatter behavior today is - unverified. - CodexSessionRuntime.rememberCollabReceiverTurns learns child threads only from - collabAgentToolCall.receiverThreadIds; under v2 those are empty, so the - collabReceiverTurns map never populates and the suppression list is inert. What - v2 child-thread notifications actually do to the parent timeline today (leak in? get dropped - elsewhere?) must be established with a live v2 wire probe — this is the - entry gate for the Codex slice (§8). The suppression narrative in the first draft applied - only to v1 models (e.g. gpt-5.6-luna). -
- -

2 · Audit: Claude Agent SDK

-

- Sources: @anthropic-ai/claude-agent-sdk 0.3.170 type declarations, CLI 2.1.214 binary, and a - live stream-json wire probe (real subagent spawn captured). All SDK-type claims - below re-verified by both reviewers. -

- -

- The core fact: a complete task lifecycle already streams over stdio, keyed - by task_id + tool_use_id, covering subagents, background shells, - monitors, and workflows uniformly: -

- -
task_started      {task_id, tool_use_id, description, subagent_type?, task_type?, workflow_name?, prompt?}
-task_progress     {task_id, description, usage:{total_tokens, tool_uses, duration_ms}, last_tool_name?, summary?}
-task_updated      {task_id, patch:{status: pending|running|completed|failed|killed|paused, end_time?, is_backgrounded?, error?}}
-task_notification {task_id, status: completed|failed|stopped, summary, usage?, output_file}
- -
    -
  • - Subagent messages arrive on the main stream tagged - parent_tool_use_id + subagent_type + - task_description. By default only tool_use/tool_result blocks are forwarded; - forwardSubagentText: true forwards the full nested transcript. -
  • -
  • - "What it's doing right now": last_tool_name on every - progress tick and tool_progress heartbeats (tool_name, elapsed_time_seconds, parent_tool_use_id, task_id) are free. agentProgressSummaries: true additionally forks each running - subagent every ~30s for an AI-written present-tense summary in - task_progress.summary — real recurring model calls (SDK default is - off), so this is a per-instance setting, not a default (§8). -
  • -
  • - Workflows: task_started carries - task_type:'local_workflow' + workflow_name; - task_progress carries an undeclared-but-real - workflow_progress array (wire-probe confirmed) with - workflow_phase {index, title} and - workflow_agent {label, phaseIndex, phaseTitle, agentId, model, state, startedAt, - attempt, lastToolName, promptPreview, resultPreview, tokens, toolCalls, error} - entries. Not in sdk.d.ts; consume defensively behind a schema guard. - Per-agent full results are files-only (journal.jsonl, - agent-<id>.jsonl). -
  • -
  • - Usage granularity: per task (total_tokens only, no USD), per - message (if forwarded), per model + costUSD on the turn result.modelUsage, - session-wide via an explicitly-unstable control request. -
  • -
  • - Rosters: the typed background_tasks control request returns - the live task list (BackgroundTaskSummary[]) — this is the stable - roster/reconciliation source. A background_tasks_changed stream event was - also observed on the wire but is undeclared and its literal doesn't appear in the CLI - binary strings — treat as bonus signal only, never a dependency. -
  • -
  • - Gaps needing upstream: no model field on task events, no start_time on - task_started (use receive time), no per-subagent USD, - workflow_progress untyped. -
  • -
- -
- Today T3's ClaudeAdapter maps the lifecycle but strips the linkage. - task.started/progress/completed runtime events exist and are persisted, but - subagent_type, tool_use_id, workflow_name, - prompt, output_file are dropped; task_updated falls - into the unknown-subtype warning path (status transitions lost); - parent_tool_use_id traffic is filtered out of usage accounting. Raw payloads - survive in raw.payload on the ephemeral runtime events (NDJSON logs) — - recoverable at the adapter, but not from the durable store, so pre-feature - history cannot be backfilled (§5.5). -
- -

3 · Audit: T3's existing pipeline

- -
- - - - - - - - - Codex app-server - Claude SDK - (stdio) - - - Adapters - normalize - - - ProviderRuntimeEventV2 - - task.* · item.* · turn.* - - - PubSub (in-memory) - - - - Ingestion - - lossy → activities - - - SQLite + projections - - - - WS subscribe - - snapshot + deltas - - - → atoms → React - - - - - - - - - - the gap: rich runtime events are compressed into - - - append-only activity rows; linkage fields dropped - - - - -
- Two-tier pipeline: ephemeral runtime events → durable orchestration events → websocket. -
-
- -
    -
  • - The right abstractions already exist. - ProviderRuntimeEventV2 already has - task.started/progress/completed (Claude emits them today, persisted and - streamed to clients as thread.activity-appended), a - collab_agent_tool_call canonical item type, and typed - ThreadTokenUsageSnapshot. -
  • -
  • - Snapshot+delta is a solved pattern: subscribeShell/subscribeThread - do live-buffer-first attach, snapshot-or-replay with afterSequence, - sequence-deduped deltas. projection_thread_sessions is the precedent for an - upserted per-thread mutable row. -
  • -
  • - Two cost facts that constrain the design (surfaced in review): -
      -
    • - Every accepted orchestration command appends an immutable event before - updating any projection — "upsert" describes the projection, not the event store. - High-frequency dispatches are permanent rows. -
    • -
    • - subscribeThread's afterSequence catch-up reads the - global event range after the cursor and filters per-thread afterward - (ws.ts:1385-1395), and shell resume falls back to full snapshots beyond - SHELL_RESUME_MAX_GAP = 1000. Fleet-wide event volume taxes every - reconnect. -
    • -
    - → persistence must be material transitions only (§5.3). -
  • -
  • - Compat asymmetry that shaped the transport: - OrchestrationEvent is a closed Schema.Union decoded by the RPC - client — a new event type breaks old clients (fails decode) and would need - per-subscriber gating. But OrchestrationThreadActivity.kind is an open string - with payload: Schema.Unknown — a new activity kind flows through - every layer untouched. That's why §5.3 ships the roster as an activity kind, not an event - type. -
  • -
  • - Gaps: only Claude emits task.* (Codex/OpenCode emit only - item lifecycles; ACP nothing). Task payloads lack name/model/parent-linkage and - usage is untyped. Tool activities carry no owning-agent id. Turn cost never - reaches the client. -
  • -
  • - Client: the right panel (rightPanelStore surfaces: - plan/diff/files/file/preview/terminal) is the natural mount; PlanSidebar is - the structural template; WorkingTimer (DOM-write ticking, no React commits), - Badge variants, animate-status-pulse, and - SimpleWorkEntryRow are the primitives to reuse. Mobile shares state via - client-runtime but duplicates presentation — put new derivation helpers in - client-runtime. -
  • -
- -

4 · Unified data-availability matrix

-

- "Wire" = the provider protocol T3 already speaks. "T3 today" = what actually reaches the - browser now. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DatumCodex v2 wireClaude wireT3 todayPlan
Agent idyes child thread id (UUIDv7)yes task_id + tool_use_idtaskId only (Claude)normalize to agentId + keep provider
Name / label - yes nickname + role + path (child - thread/started) - yes description, subagent_type, name, workflow labeldescription onlyname + agentType
Model - partial child thread settings — not on v2 - parent items - - partial workflow agents yes; plain subagents only if - text forwarded - —optional model
Status / lifecycle - yes child thread/status + turn events (idle ≠ terminal) - yes task_updated + task_notificationstarted/completed only; task_updated dropped7-state enum incl. idle
Current activityyes child item streamyes last_tool_name; AI summaries opt-inlastToolName forwarded but not surfaced per-agentcurrentActivity + recent feed
Token burnyes per-thread breakdownsyes total_tokens per taskuntyped blobtyped usage
Start / end timeyes thread/turn timestampspartial end_time yes; start = receive timeactivity createdAtfirstStartedAt/lastActivityAt/endedAt
Parent linkageyes parentThreadId + depth + pathpartial tool_use_id, 1 level on stream—parentAgentId
Workflow phases / retriesn/a (paths encode tree) - partial undeclared - workflow_progress (incl. attempt) - —workflow agents = child agents with phaseTitle, attempt
Cost USDnopartial per-model per-turn only—out of scope v1
- -

5 · Design: the generic interface

- -

- Principle: don't invent a new pipeline — enrich the one that exists. The - task.* runtime-event family is already the provider-agnostic "unit of delegated - work". We (a) extend its payloads with the missing typed fields, (b) make the Codex adapter - synthesize the same events from v2 notifications, and (c) have ingestion fold them into one - upserted snapshot per agent that rides the existing subscribeThread stream — - with persistence limited to material transitions. -

- -

5.1 Contract: identity + activations new

-

- Review-driven shape change: a Codex agent is a durable, re-activatable identity while a - Claude task is a one-shot execution. The snapshot models the identity with rollups - of its activations, so a follow-up doesn't destroy history and elapsed time stays - meaningful. -

-
// packages/contracts/src/orchestration.ts (additive)
-ThreadAgentStatus = "pending" | "running" | "waiting" | "idle" | "completed" | "failed" | "stopped"
-  // waiting  = blocked on approval/user-input, or queued (workflow)
-  // idle     = finished a run but resumable (Codex send_message/followup; Claude paused)
-  // completed/failed/stopped = terminal
-
-ThreadAgentUsage = {
-  totalTokens: NonNegativeInt,
-  inputTokens?, cachedInputTokens?, outputTokens?, reasoningOutputTokens?,
-  toolUses?: NonNegativeInt,
-}
-
-ThreadAgentSnapshot = {
-  agentId: TrimmedNonEmptyString,        // stable identity: Claude task_id · Codex child thread id
-  provider: ProviderDriverKind,          // id-space discriminator; prevents cross-provider collisions
-  kind: "subagent" | "workflow" | "workflow_agent" | "shell" | "monitor" | "other",
-  name: TrimmedNonEmptyString,           // description · nickname · workflow label
-  agentType?: TrimmedNonEmptyString,     // subagent_type · agent_role
-  model?: TrimmedNonEmptyString,
-  status: ThreadAgentStatus,
-  currentActivity?: TrimmedNonEmptyString,
-  lastToolName?: TrimmedNonEmptyString,
-  usage?: ThreadAgentUsage,              // cumulative across activations
-  firstStartedAt: IsoDateTime,
-  lastActivityAt: IsoDateTime,
-  endedAt?: IsoDateTime,                 // cleared on re-activation
-  activationCount: NonNegativeInt,       // Codex follow-ups · workflow retry attempts
-  spawnTurnId?: TurnId,                  // turn that created it
-  lastTurnId?: TurnId,                   // latest turn that touched it (UI groups by this)
-  parentAgentId?: TrimmedNonEmptyString,
-  phaseIndex?: NonNegativeInt,           // workflow phase membership (index is authoritative;
-  phaseTitle?: TrimmedNonEmptyString,    //   title is display — titles can repeat across phases)
-  // kind === "workflow" only:
-  phases?: Array<{ index: NonNegativeInt, title: TrimmedNonEmptyString }>, // ordered phase list
-  scriptPath?: TrimmedNonEmptyString,    // persisted workflow script (WorkflowOutput.scriptPath)
-  runId?: TrimmedNonEmptyString,         // workflow run id (resume handle)
-  approvalRequestId?: ApprovalRequestId, // set while waiting on an approval → UI deep-link
-  outputFile?: TrimmedNonEmptyString,    // Claude transcript path — phase-2 drill-in needs it
-  resultSummary?: TrimmedNonEmptyString,
-  errorMessage?: TrimmedNonEmptyString,
-  recentActivity: Array<{ at: IsoDateTime, summary: string }>, // ring buffer, max 6
-  updatedAt: IsoDateTime,                // staleness + "while you were away" watermark
-}
- -

5.2 Provider mapping

-
-
-

Claude → snapshot

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SDK messageEffect
task_started - upsert: id, name=description, kind from task_type, agentType=subagent_type, - firstStartedAt=now, status=running, outputFile later -
task_progress - usage, lastToolName, currentActivity=summary; - workflow_progress[] (schema-guarded): - workflow_phase entries → the workflow snapshot's ordered - phases list; workflow_agent entries → upsert child - workflow_agent snapshots (label, phaseIndex+phaseTitle, model, state, - tokens, attempt) -
Workflow tool_result (WorkflowOutput) - scriptPath + runId onto the workflow snapshot (typed on - the tool output: "Path to the persisted workflow script for this invocation") -
task_updatedstatus patch (killed→stopped, paused→idle), endedAt=end_time, errorMessage
task_notificationterminal status, resultSummary, final usage, outputFile
tool_progress (has task_id)lastToolName + recentActivity entry
can_use_tool / approval (has agent_id)status=waiting + approvalRequestId; cleared on resolution
-

- Adapter fixes: stop dropping - subagent_type/tool_use_id/workflow_name/output_file; handle - task_updated (today: warning path). Roster reconciliation via the typed - background_tasks control request (not the undeclared stream event). - agentProgressSummaries is a per-instance setting, default off — fallback - currentActivity is last_tool_name. Not enabling - forwardSubagentText in v1. -

-
-
-

Codex v2 → snapshot (corrected)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NotificationEffect
child thread/started (source = subAgent.threadSpawn) - upsert identity: id=thread id, name=nickname, agentType=agentRole, parentAgentId, - depth/path, firstStartedAt -
subAgentActivity item (parent stream) - started → running; interacted → running + activationCount++; interrupted → stopped -
child turn/startedstatus=running (clear endedAt/resultSummary on re-activation)
child turn/completed - status=idle (resumable — not terminal), resultSummary=last - message -
child thread/status/changedactive flags waitingOnApproval/UserInput → waiting; closed → stopped
child thread/tokenUsage/updatedusage (full breakdown)
child item/started|completedcurrentActivity + recentActivity (reuse item titles)
child thread/settings/updatedmodel (v2 parent items don't carry it)
-

- collabAgentToolCall is not used for tracking (v2 emits it only for - wait, with empty receivers) — render it as a parent activity only. Runtime - change: CodexSessionRuntime learns children from - thread/started.source + subAgentActivity, routes their - notifications to the agent tracker, and filters them out of the parent timeline. - Entry gate: a live v2 wire probe to establish what child chatter - reaches T3 today (§8). -

-
-
- -

- 5.3 Transport: one activity kind, zero new machinery rev 3 -

-

- The dumb store already exists — use it. - OrchestrationThreadActivity has a free-form kind and an open - payload: Schema.Unknown, is persisted/capped/replayed, and streams over - subscribeThread today. And T3 already ships latest-wins state through it: - context-window.updated activities carry a full usage snapshot and the client - just takes the newest one (deriveLatestContextWindowSnapshot). Agents work - identically: -

-
// Ingestion keeps the per-thread agent map in memory (it must merge events anyway).
-// On a MATERIAL change — status transition · name/model/phase discovery ·
-// currentActivity change · usage crossing a 25k step · terminal fields —
-// it appends ONE activity via the EXISTING thread.activity.append command:
-{ kind: "agent.snapshot",
-  tone: "info",
-  summary: "2 agents running",               // human-readable on purpose (see compat)
-  payload: { agents: ThreadAgentSnapshot[] } } // full roster, latest-wins
-
-// Client: scan thread.activities for the newest agent.snapshot → that IS the panel state.
-// Same derivation pattern as the context-window meter. Typed decode of the payload
-// happens client-side against the contracts schema; a failed decode = ignore the row.
-

What this deletes relative to the rev-2 design — with no loss of insight:

- - - - - - - - - - - - - - - - - - - - - - - - - -
Rev 2 (bespoke transport)Rev 3 (activity channel)
- New thread.agent.upsert command + thread.agent-upserted event - in the closed union - Reuses thread.activity.append — no new command or event types
- Subscriber opt-in gating + acceptAgentEvents + old/new contract tests - (closed-union decode risk) - - Not needed: kind is an open string, payload is - Unknown — old clients decode fine and render a rare benign "2 agents - running" info row (arguably a feature) -
- projection_thread_agents table + migration + snapshot-assembly changes + - shell-refetch exclusion - - Not needed: rows land in the existing activities projection; the 500-row cap is the - retention policy -
ServerConfig.threadAgents capability flag - Not needed: presence of an agent.snapshot activity is self-describing -
Reducer hydration from the new projection - Same trick ingestion already uses for task titles: on first event for a thread, read the - latest agent.snapshot from the loaded thread detail (findTaskTitleInActivities - precedent) -
-
    -
  • - Volume: full-roster payload (≤ ~10 agents, a few KB) × material - transitions only ≈ tens of rows per agent run — same order as the - task.progress rows Claude already writes today. 1s ticks and elapsed time - stay client-derived, never persisted. -
  • -
  • - Codex-synthesized task.* events still bypass - runtimeEventToActivities - (the marker survives from rev 2) — they feed the reducer only, so slice 2 adds no timeline - spam. New clients add one skip line for agent.snapshot in - deriveWorkLogEntries (precedent: context-window.updated is - skipped the same way). -
  • -
  • - Known trade-offs, accepted: (a) the payload is untyped on the wire — the - schema lives in contracts and the client decodes tolerantly; (b) latest-wins inside a - 500-cap window means a thread with 500+ later activities loses its old roster — at that - distance the agents are ancient history, and the timeline's task.* rows - remain; (c) full-roster-per-write is O(agents) redundant — at ≤10 agents this is noise, - and it's what makes latest-wins (and therefore everything else) simple. -
  • -
  • - Escape hatch: if per-agent typed wire events or bigger fleets ever - matter, the rev-2 design (dedicated event + projection + subscriber gating, preserved in - git history of this doc) is the graduation path. Don't build it until the counter metric - (§8) says so. -
  • -
- -

5.3b What happens to child-thread events — dropped today, distilled tomorrow

-

- Today, T3 durably stores none of it. Precisely: Codex v1 child-thread - notifications are suppressed at the session runtime (their item events are re-attributed to - the parent turn; thread/turn/usage events dropped); Codex v2 child chatter is unaudited (the - suppression doesn't fire — probe gate in §8); Claude subagent traffic is reduced to the - task.* activity rows and its parent_tool_use_id stream deltas are - filtered out. The only place raw child events land is the rotating NDJSON observability logs - — not queryable, not replayed. -

-

This plan changes that to "distilled, not mirrored":

-
    -
  • - Durably stored (new): the per-agent snapshot — identity, lifecycle, usage - rollups, recentActivity (last 6 summaries), result summary, script/output - pointers — as agent.snapshot activity rows in the existing activities - projection + event store. This is what survives restarts and reconnects. -
  • -
  • - Still not stored: full child transcripts (every tool call, message delta, - reasoning block). Deliberately — mirroring child streams into the orchestration store - would multiply event volume by fleet size (§3's replay-cost facts). The providers already - persist them (Codex rollout files readable via thread/read; Claude - agent-<id>.jsonl / output_file), so the phase-2 drill-in - RPC reads them on demand from provider storage instead of duplicating them. -
  • -
  • - Caveat that falls out: transcript drill-in is only as durable as provider - storage — e.g. an ephemeral Codex thread or a cleaned /tmp output file means - the snapshot survives but the deep transcript doesn't. Acceptable: the snapshot is the - record; the transcript is an inspection tool. -
  • -
- -

5.4 Recovery & staleness new (review-driven)

-
    -
  • - Reducer bootstrap: on the first event for a thread, hydrate the in-memory - agent map from the latest persisted agent.snapshot activity (same pattern - ingestion already uses to recover task titles from activities), so a mid-run server - restart doesn't orphan records when the next task_progress arrives without - its task_started. -
  • -
  • - Orphan sweep: provider sessions are child processes of the T3 server — on - session.exited (or a new session.started for the thread), all - non-terminal agents for that thread transition to stopped with - endedAt=now and an "orphaned on session exit" errorMessage. Reconciliation on - resume: Claude via the background_tasks control request; Codex via tracked - child threads. -
  • -
  • - Client staleness: updatedAt + the client's sync watermark - distinguish "running" from "stale while disconnected"; the UI's transport states - (loading/synchronizing/live/reconnecting) come from the existing subscription status - machinery, not the snapshot. -
  • -
  • - History: pre-feature threads cannot be backfilled — dropped fields only - exist in ephemeral NDJSON logs. Documented as a non-goal. -
  • -
- -

5.5 Drill-in

-
    -
  • - Phase 1 (ships with the panel): recentActivity ring buffer + - resultSummary + prompt preview. Workflow cards get a "View script" - affordance: scriptPath opens in the right panel's existing - file: surface (read-only file preview — zero new viewer code; the path is - outside the workspace root, so the file surface needs to accept absolute session paths or - the server proxies the read). -
  • -
  • - Phase 2 (full transcript): one read RPC - orchestration.getAgentTranscript {threadId, agentId}. Codex: - thread/read on the child thread. Claude: tail outputFile / - agent-<id>.jsonl server-side (the snapshot's - outputFile field exists for exactly this), rendered with the existing - work-log row components. Avoids turning on forwardSubagentText globally. -
  • -
- -

6 · Server changes (all additive)

-

- Rev 3: no new command, event type, projection table, migration, subscription input, or - capability flag. The entire delta is contracts (types only), two adapters, and one reducer - inside ingestion. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#WhereChangeSize
1packages/contracts - ThreadAgentSnapshot + status/usage schemas and the - agent.snapshot payload schema (used for client-side decode — no - wire-protocol change); extend TaskStarted/Progress/Completed payloads - (optional - name/agentType/model/toolUseId/parentTaskId/workflowName/phaseIndex/phaseTitle/phases/attempt/scriptPath/runId/outputFile - + typed usage + timeline-bypass marker) - S
2ClaudeAdapter - Carry the dropped fields; handle task_updated; approval → agent attribution - via agent_id; workflow_progress schema-guarded parse into - child task.* events; background_tasks reconciliation; - agentProgressSummaries per-instance option (default off) - M
3CodexSessionRuntime / CodexAdapter - Gated on live v2 probe. Track children from - thread/started.source.subAgent + subAgentActivity; route child - notifications to synthesized timeline-bypassing task.* events per §5.2; - keep child chatter out of the parent timeline (new filtering — the existing suppression - doesn't fire for v2) - M–L
4ProviderRuntimeIngestion - Agent reducer (in-memory, hydrated from the latest persisted - agent.snapshot) → material-transition agent.snapshot activity - appends through the existing command; orphan sweep on session exit; dispatch-rate - counter metric - M
-

- Non-goals v1: cost USD attribution, ACP (Cursor/Grok) support (no wire signal exists), - cross-thread agent trees, controlling agents (stop/steer — Codex exposes interruption only - as a model tool today), history backfill. OpenCode: falls out automatically if its adapter - ever emits task.*. -

- -

7 · Client changes

-
    -
  • - Derivation in client-runtime (shared with mobile): - deriveLatestAgentSnapshot(activities) — newest - agent.snapshot row, tolerant payload decode (mirrors - deriveLatestContextWindowSnapshot) — plus - deriveAgentPanelState(agents, syncStatus) — group by workflow, split - running/settled (by lastTurnId), compute totals, staleness from - updatedAt + subscription state. -
  • -
  • - Web: add "agents" to - RIGHT_PANEL_KINDS (singleton surface, storage v7→8); tab + "+" add-menu entry - in RightPanelTabs (surface always addable from the menu; the tab auto-appears - once the thread has agents); an AgentsPanel branch in ChatView's - surface switch; a compact live strip near the "Working…" row; one skip line for - agent.snapshot in deriveWorkLogEntries. Reuse: - Badge, animate-status-pulse, WorkingTimer, - SimpleWorkEntryRow. -
  • -
  • - Mobile: inspector-pane tenant on tablet, sheet on phone — later slice, - shares the derivation helpers. -
  • -
  • - Visual design + feature-to-field milestones: see the - companion UI plan. -
  • -
- -

8 · Phasing, risks, open questions

-

Phasing

-
    -
  1. - Slice 1 — contracts + Claude: #1, #2, #4, #5 → panel shows Claude - subagents + workflows end-to-end. -
  2. -
  3. - Slice 2 — Codex: entry gate: live v2 wire probe (spawn agents on - gpt-5.6-sol through T3's app-server wrapper, capture exactly which child notifications - arrive and what leaks into the timeline today). Then #3 → same panel lights up for Codex - with zero client work. -
  4. -
  5. Slice 3 — drill-in transcripts + mobile.
  6. -
-

Risks

-
    -
  • - workflow_progress is undeclared in the SDK types — schema-guarded parsing; - file upstream for typing. The background_tasks_changed stream event is - probe-only evidence — never a dependency (typed control request is the roster source). -
  • -
  • - Codex child-thread routing touches turn-attribution logic — needs tests that parent - transcript behavior is unchanged for both v1 and v2 models. -
  • -
  • - Event volume: material-transition persistence bounds it, but slice 1 ships with a counter - metric on agent-upsert dispatch rate so we see reality before slice 2 multiplies it. -
  • -
  • - Compat: one test that an old client's activity handling renders (or benignly ignores) an - agent.snapshot row — the open-string channel makes this low-risk, but verify - rather than assume. -
  • -
-

Open questions

-
    -
  • Settled-agent grouping: collapse by turn (current lean) or by workflow run?
  • -
  • - Auto-open the panel on first agent spawn? (Lean: badge on the tab + the inline strip, no - auto-open.) -
  • -
  • - agentProgressSummaries: per-instance setting shipped off — do we want a UI - toggle in thread settings, or instance config only? -
  • -
-
- - diff --git a/docs/project/plans/subagent-observability-ui.html b/docs/project/plans/subagent-observability-ui.html deleted file mode 100644 index ce43a24bb4..0000000000 --- a/docs/project/plans/subagent-observability-ui.html +++ /dev/null @@ -1,1424 +0,0 @@ - - - - - - Subagent Observability — UI Mockups - - - -
-

- T3 Code · Plan 2 of 2 · 2026-07-20 · rev 2 (post-review) · companion: - audit & tech spec -

-

Subagent Observability: UI Mockups

-

- Three directions for surfacing live subagents and workflows. All three consume the same - ThreadAgentSnapshot[] from the spec, use T3's existing tokens (DM Sans, the - sky/emerald/amber status language, animate-status-pulse dots, - Badge chips), and mount without new layout regions. They differ in - where attention lives. -

-

- Rev 2 after adversarial review (Fable + gpt-5.6-sol): every promised feature is now pinned - to a contract field and milestone (table below), - transport/staleness states are specified instead of assumed free, the Stop control is - explicitly out of v1 scope, and the Agents surface stays reachable from the panel "+" menu - even before any agent has run. -

- - - - - - - - - - - - - - - - - - - - - - - - - - -
DirectionOne-linerBest when
AAgents panel (right-panel surface)A first-class "Agents" tab beside Diff/Files/Browser with one card per agentYou want to watch a fleet while reading the chat
BInline live stripA collapsed roster docked above the composer that expands in placeGlanceable awareness with zero layout cost
CMission controlTree + drill-in split view with workflow phase barHeavy workflow runs; debugging what an agent did
- - -

- Option A Agents panel — a right-panel surface - recommended core -

-

- Adds kind: "agents" to the existing right-panel workspace. A tab with a live - count badge sits beside Diff/Files/Browser; the panel shows one compact card per agent, - grouped by origin (workflow vs. direct spawns), with a summary footer aggregating burn. - Cards expand in place to the recent-activity feed. -

- -
-
-
-
- t3code · fix-auth-flow -
- ▤▥ -
-
-
-
- Audit the auth flow and fix the session-refresh race — use a workflow. -
-
-
-
-
- ⚙ Workflow: audit-auth-flow - · -
-
- Working for - · 4 agents running -
-
-
- Reply… -
↑
-
-
-
-
- ⛬ Agents 4 - DiffFiles+ -
-
-
- Workflow · audit-auth-flow - {} script -
-
- ✓ Audit -
-
-
- audit:auth-entrypoints4m 02s -
-
Found 3 candidate races · report → /tmp/audit/entry.md
-
- 118.4k tok·41 tools -
-
-
- Verify2 running · 1 done -
-
-
- verify:session-refreshsonnet -
-
▸ Reproducing the race in sessionRefresh.test.ts
-
- 41.2k tok ↑·12 tools -
-
-
-
- verify:token-rotationsonnet -
-
▸ Read apps/server/src/auth/rotate.ts
-
- 26.0k tok ↑·8 tools -
-
-
- Fixpending -
-
- Direct spawns -
-
-
- Marlowexplorercodex -
-
- Waiting on approval · /root/marlow -
-
- 61.8k tok·blocked 41s -
-
-
-
- 3 running - 1 waiting - Σ 247k tok -
-
-
-
-
- Option A — "Agents" as a peer of Diff/Files. Workflow agents group under real phase - headers (✓ done / running counts / pending) from the snapshot's phases list; - "{} script" opens the workflow's JS file in the file surface. Token burn is a plain - counter with a live-tick ▲ — burn is unbounded, so it must not look like progress toward - completion. Amber = blocked on approval (clicking jumps to the prompt). -
-
- -
-
- Pros -
    -
  • Zero new layout machinery — tab strip, docking, sheet mode, resize all exist
  • -
  • Persistent: watch agents while scrolling chat; count badge when hidden
  • -
  • Cards scale from 1 subagent to a 10-agent workflow (groups + scroll)
  • -
  • Natural home for phase-2 drill-in (card → expanded feed)
  • -
-
-
- Cons -
    -
  • Competes for the right panel with Diff/Browser (tab switching)
  • -
  • Hidden by default on <980px until the user opens the sheet
  • -
  • Discovery depends on noticing the tab badge
  • -
-
-
- - -

- Option B Inline live strip — agents live in the conversation -

-

- No panel at all: a roster strip docks between the timeline and the composer whenever ≥1 - agent is live, replacing the bare "Working…" row. Collapsed, it's one line with a face-pile - and aggregate burn; expanded, one row per agent. Terminal states fold into the timeline as - ordinary work-log entries. Inspired by the existing turn-fold ("Worked for 4m 12s") - language. -

- -
-
-
-
- t3code · fix-auth-flow -
- ▤▥ -
-
-
-
- Audit the auth flow and fix the session-refresh race — use a workflow. -
-
-
-
-
- ✓ audit:auth-entrypoints — 3 candidate races - ✓ -
-
- -
-
- - 4 agents -
- V - V - M - A -
- · Verify 2/3 · · - Σ 247k - ▾ -
-
- verify:session-refreshReproducing the race in sessionRefresh.test.ts41.2k · -
-
- verify:token-rotationRead apps/server/src/auth/rotate.ts26.0k · -
-
- Marlow explorerWaiting on approval — Review approval request61.8k · -
-
- audit:auth-entrypointsDone · 3 candidate races found118.4k · 4m 02s -
-
- -
- Reply… -
↑
-
-
-
-
-
- Option B — the roster is part of the conversation flow. Collapsed by default to a single - line; the ▾ expands rows in place. Rows click through to a drill-in sheet. -
-
- -
-
- Pros -
    -
  • Impossible to miss — agents appear exactly where you're already looking
  • -
  • Works identically on mobile/narrow (no panel dependency)
  • -
  • Cheapest build: one component + the existing work-log fold pattern
  • -
  • Keeps the right panel free for Diff/Browser
  • -
-
-
- Cons -
    -
  • Competes with the composer for vertical space when expanded
  • -
  • No room for rich per-agent detail — drill-in must open elsewhere
  • -
  • Long fleets (10+) need truncation ("+6 more")
  • -
-
-
- - -

Option C Mission control — tree + drill-in split

-

- The maximal version, for when a workflow is the main event: the right panel (or maximized - panel) becomes a two-pane console. Left: the agent tree — workflow → phases → agents, Codex - agent paths shown as real hierarchy. Right: the selected agent's live dossier — status, - model, burn breakdown, and a streaming activity feed built from - recentActivity (phase 2: full transcript). A phase progress bar sits on top. -

- -
-
-
-
- t3code · fix-auth-flow · Agents -
- ⤢ -
-
-
-
-
-
- audit-auth-flow - workflow - {} script - · - Σ 247k tok · 41 tools -
-
-
-
-
-
-
- Audit ✓Verify 2/3Fix -
-
-
-
-
- ▾Phase: Verify -
-
- verify:session-refresh41.2k -
-
- verify:token-rotation26.0k -
-
- verify:cookie-scopequeued -
-
- ▾Phase: Audit -
-
- audit:auth-entrypoints118.4k -
-
- ▾Direct · codex -
-
- Marlow explorer61.8k -
-
- /marlow/grep_worker8.1k -
-
-
-
- verify:session-refresh - sonnet - ⏹ Stop -
-
-
Elapsed
-
Tokens41.2k
-
Tools12
-
Runs1
-
-
- Prompt: “Adversarially verify: session refresh race in refreshSession() — try - to reproduce…” -
-
-
- 18:42:11▸ Bash · vp test run sessionRefresh.test.ts -
-
- 18:41:56▸ Edit · sessionRefresh.test.ts (+34) -
-
- 18:41:20▸ Read · apps/server/src/auth/refresh.ts -
-
- 18:40:58▸ Grep · "refreshSession" — 14 matches -
-
- 18:40:41Spawned · fork: last 2 turns -
-
-
-
-
-
-
-
-
- Option C — tree honors real structure: workflow phases (Claude) and nested agent paths - (Codex, /marlow/grep_worker). The dossier pane streams the recent-activity - feed. Stop is v2+ only: no per-subagent interrupt exists in T3's command - set today, and Codex exposes interruption only as a model tool — it needs its own protocol - work. -
-
- -
-
- Pros -
    -
  • Only option that shows structure: phases, nesting, queue state
  • -
  • Drill-in is first-class, not an afterthought — best debugging surface
  • -
  • Maximized mode turns T3 into a genuine fleet console
  • -
-
-
- Cons -
    -
  • Most surface area to build and maintain (~2–3× Option A)
  • -
  • Overkill for the common case of 1–2 subagents
  • -
  • Split panes need ≥ the maximized panel width to breathe
  • -
-
-
- - -

Recommendation

-
-

- Ship A, seed it with B's collapsed line, grow into C. These aren't - mutually exclusive — they're one system at three zoom levels. But (review pushback, - accepted) they are not all "the same data at more room": each step up needs - specific contract fields to exist first. The milestones below make that explicit so the UI - never promises what the wire can't deliver. -

-
    -
  1. - v1: Option A panel + Option B's - collapsed one-liner only (replacing today's bare "Working…" row; clicking it - opens the panel). Strictly limited to v1-milestone fields. -
  2. -
  3. - v1.5: in-card expansion in the panel → the recent-activity feed (C's - dossier content, without the split layout) + approval deep-links. -
  4. -
  5. - v2: when maximized, the Agents surface upgrades to C's tree + dossier - layout. Stop/steer controls land here — they need new provider-command plumbing, not - just layout. -
  6. -
-
- -

Feature → contract field → milestone

-

- Every visible affordance in the mocks, pinned to its data source. Nothing ships ahead of its - row. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
UI affordanceContract field(s)Milestone
Name, type chip, status dot, elapsed, token barname, agentType, status, firstStartedAt/lastActivityAt, usagev1
"What it's doing" line - currentActivity (AI summary when enabled) with - lastToolName fallback - v1
Workflow grouping + phase headers (✓ Audit / Verify / Fix pending) - kind, parentAgentId, phaseIndex per agent + ordered phases on - the workflow snapshot (phase status derived: done = all members settled, running = any - running, pending = no members yet) - v1
"{} script" → workflow JS in file surface - scriptPath from WorkflowOutput (Claude-only; Codex has no - workflow concept) - v1
Amber row → jump to pending approvalapprovalRequestId (spec §5.1) + existing approval panel focusv1.5
"attempt 2 — retrying" - activationCount + errorMessage (Claude workflows only — - workflow_progress.attempt; no Codex source) - v1.5
Recent-activity feed in card/dossierrecentActivity ring bufferv1.5
Result link ("report → /tmp/…")resultSummary (path rendering is client-side sniffing)v1.5
"While you were away" divider, stale badgesupdatedAt + client sync watermark from subscription statev1.5
Full transcript dossier, per-agent tool feedoutputFile + getAgentTranscript RPC (spec §5.5)v2
Stop / steer buttonsnew provider commands — not in the observability contract at allv2+
-

- Cut from the mocks after review: the "Isolation: worktree" stat (no wire source for either - provider) and the reasoning-effort chip (Codex v2 parent items don't carry effort; revisit - if a child-settings source is plumbed). The per-card provider chip is derived from the - thread's session, not a snapshot field. -

- -

Shared component inventory (all options)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PieceReuses
Status dot + pulse - animate-status-pulse, resolveThreadStatusPill color language - (sky=running, emerald=done, amber=waiting, red=failed, zinc=queued) -
Elapsed timers - WorkingTimer self-ticking DOM-write pattern (no React commits per tick) -
Model/role chipsBadge variants
Token burn counter - Plain tabular-nums count + live-tick indicator. Not a bar/ring: - burn has no denominator, and a fill implies progress. (ContextWindowMeter's - ring stays where a real denominator exists — context windows.) -
Activity feed rowsSimpleWorkEntryRow / work-log derivation, filtered by agentId
Panel shell / tabs / sheetRightPanelTabs + PreviewPanelShell resize + maximize
- -

States to design past the happy path

-
    -
  • - Empty / discovery: the tab auto-appears once the thread has any agent - (and persists with settled history), but the surface is always reachable from the - right panel's "+" add-menu with an explanatory empty state — so users can discover it - before ever triggering an agent. -
  • -
  • - Idle vs done (Codex): a Codex agent that finished a run is - idle and resumable, not completed — dimmed sky dot, "idle · resumable" label. If - the model sends it a follow-up, the card re-activates (run count increments, elapsed - resumes). Distinct from Claude's terminal green check. -
  • -
  • - Waiting on approval: amber row links straight to the pending approval via - approvalRequestId (highest-value click in the whole feature; v1.5). -
  • -
  • - Failure: red dot + errorMessage snippet on the card; Claude - workflow agents show attempt count ("attempt 2 — retrying"). Codex has no retry signal — - failed is failed. -
  • -
  • - Transport states (separate axis from agent lifecycle): loading (skeleton - cards), synchronizing, live, reconnecting (dim panel + "reconnecting…" banner, timers - freeze at lastActivityAt), and subscription-error. While disconnected, - running agents get a stale badge after 30s past updatedAt — a snapshot can't - distinguish "still running" from "died while we were away", so the UI must not pretend it - can. -
  • -
  • - Orphaned: if the provider session exits, the server sweeps non-terminal - agents to stopped ("orphaned on session exit") — the panel shows them as - stopped with that reason, no zombie spinners. -
  • -
  • - Reconnect catch-up: settled-while-away agents (settled - updatedAt newer than the client's last-sync watermark) group under a "while - you were away" divider (v1.5). -
  • -
  • - Overflow: >8 agents → group headers become sticky, settled groups - auto-collapse; the reducer caps settled agents carried in the roster at 50/thread (oldest - settled pruned first). -
  • -
- - -
- - diff --git a/packages/client-runtime/src/state/threadAgents.test.ts b/packages/client-runtime/src/state/threadAgents.test.ts index 713e936207..197bef132f 100644 --- a/packages/client-runtime/src/state/threadAgents.test.ts +++ b/packages/client-runtime/src/state/threadAgents.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; import type { OrchestrationThreadActivity, ThreadAgentSnapshot } from "@t3tools/contracts"; import { deriveAgentPanelState, diff --git a/packages/client-runtime/src/state/threadAgents.ts b/packages/client-runtime/src/state/threadAgents.ts index 276f3f379c..c0a237ed30 100644 --- a/packages/client-runtime/src/state/threadAgents.ts +++ b/packages/client-runtime/src/state/threadAgents.ts @@ -9,13 +9,35 @@ import { THREAD_AGENT_TERMINAL_STATUSES, THREAD_AGENTS_ACTIVITY_KIND, - ThreadAgentsActivityPayload, + ThreadAgentSnapshot, type OrchestrationThreadActivity, - type ThreadAgentSnapshot, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -const decodePayload = Schema.decodeUnknownOption(ThreadAgentsActivityPayload); +const decodeAgent = Schema.decodeUnknownOption(ThreadAgentSnapshot); + +/** + * Rows decode per-element: one malformed or forward-incompatible agent entry + * is skipped without discarding the rest of the roster. Only a payload with + * no decodable agents at all falls through to an older snapshot. + */ +function decodeRoster(payload: unknown): ReadonlyArray | undefined { + if (payload === null || typeof payload !== "object") { + return undefined; + } + const agents = (payload as { agents?: unknown }).agents; + if (!Array.isArray(agents)) { + return undefined; + } + const decoded: ThreadAgentSnapshot[] = []; + for (const candidate of agents) { + const result = decodeAgent(candidate); + if (result._tag === "Some") { + decoded.push(result.value); + } + } + return agents.length === 0 || decoded.length > 0 ? decoded : undefined; +} export function deriveLatestAgentSnapshot( activities: ReadonlyArray, @@ -25,9 +47,9 @@ export function deriveLatestAgentSnapshot( if (!activity || activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) { continue; } - const decoded = decodePayload(activity.payload); - if (decoded._tag === "Some") { - return decoded.value.agents; + const roster = decodeRoster(activity.payload); + if (roster !== undefined) { + return roster; } } return []; @@ -60,9 +82,15 @@ export interface AgentPanelState { readonly totalTokens: number; } +function isSettledAgentStatus(status: ThreadAgentSnapshot["status"]): boolean { + // idle counts as settled for phase/summary purposes: the run finished even + // though the agent identity could be resumed. + return status === "idle" || isTerminalAgentStatus(status); +} + function phaseStatus(agents: ReadonlyArray): "pending" | "running" | "done" { if (agents.length === 0) return "pending"; - if (agents.every((agent) => isTerminalAgentStatus(agent.status))) return "done"; + if (agents.every((agent) => isSettledAgentStatus(agent.status))) return "done"; return "running"; } @@ -119,7 +147,7 @@ export function deriveAgentPanelState(agents: ReadonlyArray for (const agent of agents) { if (agent.status === "running" || agent.status === "pending") runningCount += 1; else if (agent.status === "waiting") waitingCount += 1; - else if (isTerminalAgentStatus(agent.status)) settledCount += 1; + else settledCount += 1; // idle + terminal totalTokens += agent.usage?.totalTokens ?? 0; }