feat: native subagent & workflow observability #5219
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 42 commits into
main fromrefs/pull/5219/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/AgentsPanel.tsx lines 112 to 112Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +71,21 @@71+72+ useEffect(() => {73+ if (!live || !startedAt) {74+ return;75+ }76+ const update = () => {77+ if (textRef.current) {78+ textRef.current.textContent = elapsedBetween(startedAt, null);79+ }80+ };81+ update();82+ const id = setInterval(update, 1000);83+ return () => clearInterval(id);84+ }, [live, startedAt]);85+86+ if (!startedAt) {87+ return null;88+ }89+ return (90+ <span ref={textRef} className="tabular-nums">91+ {elapsedBetween(startedAt, live ? null : agent.completedAt)}packages/client-runtime/src/state/subagentRuntime.ts lines 666 to 670OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +650,21 @@650+ if (member.phaseIndex !== null && !derived.has(member.phaseIndex)) {651+ derived.set(652+ member.phaseIndex,653+ member.phaseTitle ?? `Phase ${member.phaseIndex + 1}`,654+ );655+ }656+ }657+ return Array.from(derived.entries())658+ .map(([index, title]) => ({ index, title }))659+ .toSorted((a, b) => a.index - b.index);660+ })();661+662+ const phases = knownPhases.map((phase) => {663+ const phaseMembers = workflowMembers664+ .filter((member) => member.phaseIndex === phase.index)665+ .toSorted((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));666+ const activeCount = phaseMembers.filter((member) =>667+ // Idle members count as active for phase-liveness: a resumable Codex668+ // member has not finished the phase.669+ isActiveSubagentStatus(member.status),670+ ).length;packages/client-runtime/src/state/subagentRuntime.ts lines 336 to 348Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +309,21 @@309+ const workflowName = asString(payload.workflowName);310+ if (workflowName) agent.workflowName = workflowName;311+ if (asString(payload.taskType) === "local_workflow") agent.kind = "workflow";312+ const agentIndex = asCount(payload.agentIndex);313+ if (agentIndex !== undefined) agent.agentIndex = agentIndex;314+ const phaseIndex = asCount(payload.phaseIndex);315+ if (phaseIndex !== undefined) agent.phaseIndex = phaseIndex;316+ const phaseTitle = asString(payload.phaseTitle);317+ if (phaseTitle) agent.phaseTitle = phaseTitle;318+ const attempt = asCount(payload.attempt);319+ if (attempt !== undefined) {320+ // A new attempt on a workflow slot is a reactivation of the same identity:321+ // bump the run count and clear the previous attempt's terminal detail.322+ if (agent.attempt !== null && attempt > agent.attempt) {323+ agent.activationCount += 1;324+ agent.result = null;325+ agent.error = null;326+ agent.completedAt = null;327+ }328+ agent.attempt = attempt;329+ }apps/web/src/components/chat/WorkflowRunCard.tsx lines 64 to 67OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +47,21 @@47+export function WorkflowRunCard({48+ group,49+ onOpenAgents,50+}: {51+ group: AgentPanelWorkflowGroup;52+ onOpenAgents: () => void;53+}) {54+ const { visible, overflow } = workflowCardMembers(group, INLINE_MEMBER_LIMIT);55+ const chip = workflowStatusChip(group);56+ const allMembers = [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];57+ const settled = allMembers.filter(58+ (member) =>59+ member.status === "completed" ||60+ member.status === "failed" ||61+ member.status === "cancelled" ||62+ member.status === "interrupted",63+ ).length;64+ const totalTokens = allMembers.reduce(65+ (sum, member) => sum + (member.usage?.totalTokens ?? 0),66+ group.workflow.usage?.totalTokens ?? 0,67+ );packages/client-runtime/src/state/subagentRuntime.ts lines 590 to 599Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +508,21 @@508+ break;509+ }510+ case "task.completed": {511+ const taskId = asString(payload.taskId);512+ if (!taskId) break;513+ const agent = getOrCreate(agents, taskId, payload, at);514+ fillMetadata(agent, payload);515+ if (agent.activationCount === 0) agent.activationCount = 1;516+ const status = TASK_COMPLETED_STATUS[asString(payload.status) ?? ""] ?? "completed";517+ applyStatus(agent, status, at);518+ const summary = asString(payload.summary) ?? asString(payload.detail);519+ if (summary) {520+ if (status === "failed") {521+ agent.error = agent.error ?? bounded(summary);522+ } else {523+ agent.result = bounded(summary);524+ }525+ }526+ agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));527+ agent.updatedAt = at;528+ break;apps/server/src/provider/Layers/CodexAdapter.ts line 717Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -496,0 +661,21 @@661+ ...(count(total?.outputTokens) !== undefined662+ ? { outputTokens: count(total?.outputTokens) }663+ : {}),664+ ...(count(total?.reasoningOutputTokens) !== undefined665+ ? { reasoningOutputTokens: count(total?.reasoningOutputTokens) }666+ : {}),667+ };668+ return [669+ {670+ ...base,671+ type: "task.progress",672+ payload: {673+ taskId,674+ description: title,675+ typedUsage,676+ timelineBypass: true,677+ },678+ },679+ ];680+ }681+ case "collabAgent/item": {packages/client-runtime/src/state/subagentRuntime.ts lines 692 to 694OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +674,21 @@674+ const state: "pending" | "running" | "done" =675+ phaseMembers.length === 0676+ ? "pending"677+ : activeCount > 0678+ ? "running"679+ : settledCount === phaseMembers.length680+ ? "done"681+ : "pending";682+ return {683+ index: phase.index,684+ title: phase.title,685+ members: phaseMembers,686+ state,687+ activeCount,688+ settledCount,689+ };690+ });691+692+ const unphasedMembers = workflowMembers693+ .filter((member) => member.phaseIndex === null)694+ .toSorted((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));apps/server/src/provider/Layers/CodexSessionRuntime.ts line 1079OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -857,3 +1076,4 @@8571076 return;8581077 }85910781079+ if (yield* interceptCollabChildNotification(notification)) {
- packages/client-runtime/src/state/subagentRuntime.ts line 488Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +435,21 @@435+ }436+ const payload = activity.payload as Record<string, unknown>;437+ const at = activity.createdAt;438+439+ switch (activity.kind) {440+ case "task.started": {441+ const taskId = asString(payload.taskId);442+ if (!taskId) break;443+ // Plan-mode "tasks" and other ambient work are not agents.444+ const taskType = asString(payload.taskType);445+ if (taskType === "plan") break;446+ const agent = getOrCreate(agents, taskId, payload, at);447+ fillMetadata(agent, payload);448+ // Order-robustness: a start row arriving after a terminal state is a449+ // late/out-of-order delivery and only fills metadata — it must not450+ // reopen the run. Reactivation comes exclusively from explicit451+ // status transitions (task.updated / progress status).452+ if (agent.activationCount === 0) {453+ agent.activationCount = 1;454+ agent.startedAt = agent.startedAt ?? at;455+ agent.status = "running";
- apps/web/src/components/chat/MessagesTimeline.tsx line 1975Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1923,0 +1955,21 @@1955+const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { workEntry: TimelineWorkEntry }) {1956+ const { workEntry } = props;1957+ const { agentPanelModel, onOpenAgents } = use(TimelineRowCtx);1958+ const spawn = workEntry.agentSpawn;1959+ if (!spawn) {1960+ return null;1961+ }1962+1963+ const memberIds = new Set(spawn.agentTaskIds);1964+ const workflowGroup = spawn.workflowId1965+ ? agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId)1966+ : undefined;1967+ const agents = workflowGroup1968+ ? [...workflowGroup.phases.flatMap((phase) => phase.members), ...workflowGroup.unphasedMembers]1969+ : agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id));1970+ const agentCount = Math.max(1971+ agents.length,1972+ Math.max(memberIds.size - (spawn.workflowId ? 1 : 0), 0),1973+ );1974+1975+ const running = agents.filter(apps/web/src/components/chat/MessagesTimeline.tsx lines 1975 to 1980OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1923,0 +1960,21 @@1960+ return null;1961+ }1962+1963+ const memberIds = new Set(spawn.agentTaskIds);1964+ const workflowGroup = spawn.workflowId1965+ ? agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId)1966+ : undefined;1967+ const agents = workflowGroup1968+ ? [...workflowGroup.phases.flatMap((phase) => phase.members), ...workflowGroup.unphasedMembers]1969+ : agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id));1970+ const agentCount = Math.max(1971+ agents.length,1972+ Math.max(memberIds.size - (spawn.workflowId ? 1 : 0), 0),1973+ );1974+1975+ const running = agents.filter(1976+ (agent) => agent.status === "running" || agent.status === "pending",1977+ ).length;1978+ const waiting = agents.filter((agent) => agent.status === "waiting").length;1979+ const failed = agents.filter((agent) => agent.status === "failed").length;1980+ const live = running + waiting > 0;
- apps/web/src/components/chat/MessagesTimeline.tsx line 2017Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1923,0 +1988,21 @@1988+ workflowGroup?.workflow.workflowName ?? workflowGroup?.workflow.title ?? null;1989+1990+ const dotClass = live1991+ ? waiting > 01992+ ? "bg-warning"1993+ : "bg-info"1994+ : failed > 01995+ ? "bg-destructive"1996+ : "bg-success";1997+ const lead = live1998+ ? `Kicked off ${agentCount} subagent${agentCount === 1 ? "" : "s"}`1999+ : `Ran ${agentCount} subagent${agentCount === 1 ? "" : "s"}`;2000+ const status = live2001+ ? livePhase2002+ ? `${livePhase.title} · ${livePhase.activeCount} active`2003+ : waiting > 02004+ ? `${running} running · ${waiting} waiting`2005+ : `${running} running`2006+ : failed > 02007+ ? `${failed} failed`2008+ : "✓ completed";apps/web/src/components/chat/MessagesTimeline.tsx line 2017Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1923,0 +1988,21 @@1988+ workflowGroup?.workflow.workflowName ?? workflowGroup?.workflow.title ?? null;1989+1990+ const dotClass = live1991+ ? waiting > 01992+ ? "bg-warning"1993+ : "bg-info"1994+ : failed > 01995+ ? "bg-destructive"1996+ : "bg-success";1997+ const lead = live1998+ ? `Kicked off ${agentCount} subagent${agentCount === 1 ? "" : "s"}`1999+ : `Ran ${agentCount} subagent${agentCount === 1 ? "" : "s"}`;2000+ const status = live2001+ ? livePhase2002+ ? `${livePhase.title} · ${livePhase.activeCount} active`2003+ : waiting > 02004+ ? `${running} running · ${waiting} waiting`2005+ : `${running} running`2006+ : failed > 02007+ ? `${failed} failed`2008+ : "✓ completed";
- apps/web/src/session-logic.ts line 940Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -770 +852,21 @@852+ // Subagent rows collapse by spawn group, not adjacency: a workflow run (or853+ // a turn's batch of direct spawns) is ONE narrative event in the chat — a854+ // CTA row that opens the Agents panel — no matter how many agents it855+ // contains or how their progress rows interleave (quiet-timeline856+ // guarantee).857+ const spawnRowIndex = new Map<string, number>();770858 for (const entry of entries) {859+ const isTaskRow =860+ entry.taskId !== undefined &&861+ !entry.isBackgroundTask &&862+ (entry.activityKind === "task.progress" || entry.activityKind === "task.completed");863+ if (isTaskRow && entry.taskId !== undefined) {864+ const groupKey = agentSpawnGroupKey(entry);865+ const workflowId = groupKey.startsWith("wf:") ? groupKey.slice(3) : null;866+ const existingIndex = spawnRowIndex.get(groupKey);867+ if (existingIndex !== undefined) {868+ const existing = collapsed[existingIndex]!;869+ const agentTaskIds = existing.agentSpawn?.agentTaskIds.includes(entry.taskId)870+ ? existing.agentSpawn.agentTaskIds871+ : [...(existing.agentSpawn?.agentTaskIds ?? []), entry.taskId];872+ collapsed[existingIndex] = {packages/client-runtime/src/state/subagentRuntime.ts lines 545 to 555Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +510,21 @@510+ }511+ const error = asString(payload.error);512+ if (error) agent.error = bounded(error);513+ agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));514+ agent.updatedAt = at;515+ break;516+ }517+ case "task.updated": {518+ const taskId = asString(payload.taskId);519+ if (!taskId) break;520+ if (isBackgroundTaskActivity(payload)) break;521+ const agent = getOrCreate(agents, taskId, payload, at);522+ fillMetadata(agent, payload);523+ const status = asRuntimeStatus(payload.status);524+ if (status) applyStatus(agent, status, at);525+ const error = asString(payload.error);526+ if (error) agent.error = bounded(error);527+ const endedAt = asString(payload.endedAt);528+ if (endedAt && isTerminalSubagentStatus(agent.status) && agent.completedAt === null) {529+ agent.completedAt = endedAt;530+ }packages/client-runtime/src/state/subagentRuntime.ts line 538Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +501,21 @@501+ agent.progress = bounded(summary);502+ agent.recentActivity = appendActivity(agent.recentActivity, at, summary);503+ }504+ const lastToolName = asString(payload.lastToolName);505+ if (lastToolName) {506+ agent.lastToolName = lastToolName;507+ if (!summary) {508+ agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${lastToolName}`);509+ }510+ }511+ const error = asString(payload.error);512+ if (error) agent.error = bounded(error);513+ agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));514+ agent.updatedAt = at;515+ break;516+ }517+ case "task.updated": {518+ const taskId = asString(payload.taskId);519+ if (!taskId) break;520+ if (isBackgroundTaskActivity(payload)) break;521+ const agent = getOrCreate(agents, taskId, payload, at);apps/web/src/session-logic.ts line 921Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -766,5 +839,21 @@839+ if (entry.agentSpawn?.workflowId) {840+ return `wf:${entry.agentSpawn.workflowId}`;841+ }842+ if (entry.isWorkflowCoordinator) {843+ return `wf:${taskId}`;844+ }845+ return `direct:${entry.turnId ?? "no-turn"}`;846+}847+766848 function collapseDerivedWorkLogEntries(767849 entries: ReadonlyArray<DerivedWorkLogEntry>,768850 ): DerivedWorkLogEntry[] {769851 const collapsed: DerivedWorkLogEntry[] = [];852+ // Subagent rows collapse by spawn group, not adjacency: a workflow run (or853+ // a turn's batch of direct spawns) is ONE narrative event in the chat — a854+ // CTA row that opens the Agents panel — no matter how many agents it855+ // contains or how their progress rows interleave (quiet-timeline856+ // guarantee).857+ const spawnRowIndex = new Map<string, number>();770858 for (const entry of entries) {859+ const isTaskRow =
- packages/client-runtime/src/state/subagentRuntime.ts line 119Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+const ROSTER_LIMIT = 100;107+108+/**109+ * SDK task types that are agents. Everything else (shell, monitor, plan,110+ * unknown-but-typed) is background work and stays out of the roster. Rows111+ * with no taskType at all are kept: workflow members and Codex children are112+ * synthesized without one, and excluding them would empty the panel.113+ */114+const AGENT_TASK_TYPES: ReadonlySet<string> = new Set([115+ "subagent",116+ "agent",117+ "local_workflow",118+ "remote_agent",119+ "workflow",120+]);121+122+/** True when this activity's payload describes a non-agent background task. */123+export function isBackgroundTaskActivity(payload: Record<string, unknown>): boolean {124+ const taskType = typeof payload.taskType === "string" ? payload.taskType : undefined;125+ return taskType !== undefined && !AGENT_TASK_TYPES.has(taskType);126+}
- apps/web/src/components/chat/MessagesTimeline.logic.ts line 508OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -489,5 +496,13 @@489496 } else {490497 const groupId = `work-group:${timelineEntry.id}`;491498 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;492- const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);493- const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);499+ // Agent-spawn CTA rows are always visible: a running fleet must500+ // never hide behind a "+N tool calls" toggle.501+ const overflowCandidates = visibleGroupedEntries.filter(502+ (entry) => entry.agentSpawn === undefined,503+ );504+ const pinnedSpawnEntries = visibleGroupedEntries.filter(505+ (entry) => entry.agentSpawn !== undefined,506+ );507+ const hiddenEntries = overflowCandidates.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);508+ const visibleEntries = [
- apps/web/src/components/chat/MessagesTimeline.logic.ts line 512Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -502,11 +520,3 @@502520 });503521 }504522505- nextRows.push({506- kind: "work-toggle",507- id: `work-toggle:${timelineEntry.id}`,508- createdAt: timelineEntry.createdAt,509- groupId,510- hiddenCount: hiddenEntries.length,511- expanded,512- onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),
- apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts lines 165 to 165OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -162,3 +162,4 @@162162 ORCHESTRATION_PROJECTOR_NAMES.checkpoints,163163 ] as const;164164165+import { getThreadBackgroundLiveness } from "../threadBackgroundLiveness.ts";apps/server/src/orchestration/threadBackgroundLiveness.ts lines 24 to 24OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+ * The turn can settle while native background work runs on (subagent fleets,5+ * workflow runs, Monitor watch loops); the shell previously showed nothing.6+ * Ingestion updates this registry from the task lifecycle it already7+ * processes, and the shell query reads it at mapping time — no migration and8+ * no new persisted state. Zero-migration trade-off: the registry is empty9+ * after a server restart until new task events arrive; agents orphaned by a10+ * restart read as not-live, matching their real state.11+ *12+ * "monitoring" is reserved for watch loops (Monitor tool tasks): a thread13+ * whose parent agent is babysitting a PR or tailing a log. Agent/workflow14+ * work presents as plain "working" alongside turn activity.15+ */16+17+export type ThreadBackgroundLiveness = "working" | "monitoring" | null;18+19+interface ThreadLivenessState {20+ readonly agents: Set<string>;21+ readonly monitors: Set<string>;22+}23+24+const stateByThreadId = new Map<string, ThreadLivenessState>();
- apps/server/src/orchestration/threadBackgroundLiveness.ts line 80OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +60,21 @@60+ readonly threadId: string;61+ readonly taskId: string;62+ readonly taskType: string | undefined;63+ readonly status: string | undefined;64+ readonly kind: "started" | "progress" | "updated" | "completed";65+}): void {66+ const taskType = input.taskType;67+ if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {68+ return;69+ }70+ const state = stateFor(input.threadId);71+ const bucket =72+ taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;73+74+ const terminal =75+ input.kind === "completed" ||76+ (input.status !== undefined && TERMINAL_STATUSES.has(input.status));77+ if (terminal) {78+ bucket.delete(input.taskId);79+ } else {80+ bucket.add(input.taskId);apps/server/src/orchestration/threadBackgroundLiveness.ts line 85OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+}): void {66+ const taskType = input.taskType;67+ if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {68+ return;69+ }70+ const state = stateFor(input.threadId);71+ const bucket =72+ taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;73+74+ const terminal =75+ input.kind === "completed" ||76+ (input.status !== undefined && TERMINAL_STATUSES.has(input.status));77+ if (terminal) {78+ bucket.delete(input.taskId);79+ } else {80+ bucket.add(input.taskId);81+ }82+ if (state.agents.size === 0 && state.monitors.size === 0) {83+ stateByThreadId.delete(input.threadId);84+ }85+}
- apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 1883OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1756,3 +1868,16 @@17561868 yield* rememberTaskDescription(thread.id, event.payload.taskId, description);17571869 }17581870 }1871+ // Sidebar background liveness: fed from the same lifecycle stream,1872+ // read by the shell query at mapping time (no persistence).1873+ switch (event.type) {1874+ case "task.started":1875+ case "task.progress":1876+ case "task.updated":1877+ case "task.completed": {1878+ const payload = event.payload as {1879+ taskId: string;1880+ taskType?: string;1881+ status?: string;1882+ };1883+ recordTaskLiveness({
- packages/client-runtime/src/state/subagentRuntime.ts line 119OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +99,21 @@99+ * but resumable; waiting counts as active because it needs the user. */100+export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {101+ return status === "pending" || status === "running" || status === "waiting";102+}103+104+const RECENT_ACTIVITY_LIMIT = 6;105+const SUMMARY_CHAR_LIMIT = 180;106+const ROSTER_LIMIT = 100;107+108+/**109+ * Task types that are NOT agents: background shells, watch loops, and110+ * plan-mode bookkeeping. Deliberately a denylist — the SDK's agent-flavored111+ * type names drift (subagent, local_agent, remote_agent, local_workflow, …)112+ * and an allowlist silently dropped real subagents when "local_agent"113+ * appeared (live-test finding). Unknown or absent types count as agents.114+ */115+const NON_AGENT_TASK_TYPES: ReadonlySet<string> = new Set([116+ "shell",117+ "local_bash",118+ "monitor",119+ "plan",
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 2369Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2080,0 +2322,21 @@2322+ // into the parent transcript: with forwardSubagentText off the SDK still2323+ // forwards subagent tool_use/tool_result blocks and their wrapping2324+ // text/thinking deltas, and emitting them interleaved N subagents'2325+ // narration into the chat (live-test finding). Their results reach the2326+ // UI via the task.* lifecycle; their tool blocks are attributed and2327+ // re-homed by the quiet-timeline filter.2328+ const streamParentToolUseId = (message as { parent_tool_use_id?: string | null })2329+ .parent_tool_use_id;2330+ if (2331+ streamParentToolUseId !== null &&2332+ streamParentToolUseId !== undefined &&2333+ (event.type === "content_block_start" || event.type === "content_block_delta") &&2334+ !(2335+ event.type === "content_block_start" &&2336+ (event.content_block.type === "tool_use" ||2337+ event.content_block.type === "server_tool_use" ||2338+ event.content_block.type === "mcp_tool_use")2339+ )2340+ ) {2341+ return;2342+ }
- packages/client-runtime/src/state/subagentRuntime.ts line 127OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+108+/**109+ * Task types that are NOT agents: background shells, watch loops, and110+ * plan-mode bookkeeping. Deliberately a denylist — the SDK's agent-flavored111+ * type names drift (subagent, local_agent, remote_agent, local_workflow, …)112+ * and an allowlist silently dropped real subagents when "local_agent"113+ * appeared (live-test finding). Unknown or absent types count as agents.114+ */115+const NON_AGENT_TASK_TYPES: ReadonlySet<string> = new Set([116+ "shell",117+ "local_bash",118+ "monitor",119+ "plan",120+]);121+122+/** True when this activity's payload describes a non-agent background task. */123+export function isBackgroundTaskActivity(payload: Record<string, unknown>): boolean {124+ // Owned by another agent (a subagent's internal shell): not a roster row.125+ if (typeof payload.agentId === "string" && payload.agentId.trim().length > 0) {126+ return true;127+ }
- packages/contracts/src/orchestration.ts lines 1449 to 1449OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1422,2 +1429,21 @@14221429 export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;142314301431+export const OrchestrationGetWorkflowScriptInput = Schema.Struct({1432+ threadId: ThreadId,1433+ /** Absolute path from the workflow's runHandles.scriptPath. The server1434+ * re-derives containment; the client value is a hint, never trusted. */1435+ scriptPath: TrimmedNonEmptyString,1436+});1437+export type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;1438+1439+export const OrchestrationGetWorkflowScriptResult = Schema.Struct({1440+ scriptPath: TrimmedNonEmptyString,1441+ contents: Schema.String,1442+ truncated: Schema.Boolean,1443+});1444+export type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;1445+1446+export class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(1447+ "OrchestrationGetWorkflowScriptError",1448+ {1449+ message: Schema.String,apps/server/src/orchestration/workflowScriptQuery.ts lines 42 to 42OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +22,21 @@22+const SCRIPT_BYTE_CAP = 256 * 1024;23+24+function scriptsRoot(): string {25+ return NodePath.join(NodeOS.homedir(), ".claude", "projects");26+}27+28+export const readWorkflowScript = Effect.fn("orchestration.readWorkflowScript")(function* (input: {29+ readonly scriptPath: string;30+}) {31+ const requested = input.scriptPath;32+33+ const fail = (message: string) =>34+ Effect.fail(new OrchestrationGetWorkflowScriptError({ message }));35+36+ if (!NodePath.isAbsolute(requested) || NodePath.extname(requested) !== ".js") {37+ return yield* fail("Workflow scripts must be absolute .js paths.");38+ }39+40+ const root = yield* Effect.tryPromise({41+ try: () => NodeFS.realpath(scriptsRoot()),42+ catch: () => new OrchestrationGetWorkflowScriptError({ message: "Script root unavailable." }),
- apps/server/src/orchestration/workflowScriptQuery.ts line 59OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+40+ const root = yield* Effect.tryPromise({41+ try: () => NodeFS.realpath(scriptsRoot()),42+ catch: () => new OrchestrationGetWorkflowScriptError({ message: "Script root unavailable." }),43+ });44+45+ // Realpath the FILE itself (not just its directory): a symlink named46+ // like a script inside a contained directory must not escape.47+ const resolved = yield* Effect.tryPromise({48+ try: () => NodeFS.realpath(requested),49+ catch: () => new OrchestrationGetWorkflowScriptError({ message: "Script not found." }),50+ });51+52+ if (resolved !== root && !resolved.startsWith(`${root}${NodePath.sep}`)) {53+ return yield* fail("Script path is outside the workflow scripts root.");54+ }55+ if (NodePath.extname(resolved) !== ".js") {56+ return yield* fail("Resolved script is not a .js file.");57+ }58+59+ const stat = yield* Effect.tryPromise({
- apps/server/src/orchestration/workflowScriptQuery.ts line 123Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +68,21 @@68+ try: () => NodeFS.open(resolved, "r"),69+ catch: () => new OrchestrationGetWorkflowScriptError({ message: "Script not readable." }),70+ });71+ const truncated = stat.size > SCRIPT_BYTE_CAP;72+ const buffer = Buffer.alloc(Math.min(stat.size, SCRIPT_BYTE_CAP));73+ yield* Effect.tryPromise({74+ try: async () => {75+ try {76+ await handle.read(buffer, 0, buffer.length, 0);77+ } finally {78+ await handle.close();79+ }80+ },81+ catch: () => new OrchestrationGetWorkflowScriptError({ message: "Script read failed." }),82+ });83+84+ return {85+ scriptPath: resolved,86+ contents: buffer.toString("utf8"),87+ truncated,88+ };
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 4326OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3825,3 +4307,20 @@38254307 const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(38264308 function* (threadId, _turnId) {38274309 const context = yield* requireSession(threadId);4310+ // Stop-everything semantics: users reach for Stop precisely when a4311+ // fleet ran away. interrupt() alone only ends the parent turn —4312+ // background subagents/shells keep running and keep burning tokens.4313+ // Stop every live task first (best-effort per task: one refusal must4314+ // not strand the rest or block the turn interrupt), then interrupt.4315+ const stopTask = context.query.stopTask;4316+ if (stopTask && context.liveTaskIds.size > 0) {4317+ const liveIds = Array.from(context.liveTaskIds);4318+ yield* Effect.forEach(4319+ liveIds,4320+ (taskId) =>4321+ Effect.tryPromise({4322+ try: () => stopTask(taskId),4323+ catch: () => undefined,4324+ }).pipe(Effect.ignore),4325+ { concurrency: 8, discard: true },4326+ );
- apps/server/src/orchestration/ThreadBackgroundLiveness.ts line 120Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +46,21 @@46+ const existing = stateByThreadId.get(threadId);47+ if (existing) {48+ return existing;49+ }50+ const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };51+ stateByThreadId.set(threadId, created);52+ return created;53+ };54+55+ return {56+ recordTaskLiveness: (input) => {57+ const taskType = input.taskType;58+ if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {59+ return;60+ }61+ // A subagent's internal task (its own shells) is covered by the62+ // agent's liveness; counting it separately would keep threads63+ // Monitoring/Working after the agent itself settled.64+ if (input.agentId !== undefined) {65+ return;66+ }
- apps/server/src/orchestration/Services/ThreadBackgroundLiveness.ts lines 18 to 47OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ readonly taskId: string;28+ readonly taskType: string | undefined;29+ readonly status: string | undefined;30+ readonly kind: "started" | "progress" | "updated" | "completed";31+ readonly agentId?: string | undefined;32+ }) => void;33+34+ /** Session death orphans all of a thread's background work. */35+ readonly clearThreadLiveness: (threadId: string) => void;36+37+ /**38+ * Two-state vocabulary by design: any live agent work is "working";39+ * "monitoring" only when watch loops are the ONLY live work.40+ */41+ readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;42+}43+44+export class ThreadBackgroundLivenessService extends Context.Service<45+ ThreadBackgroundLivenessService,46+ ThreadBackgroundLivenessShape47+>()("t3/orchestration/Services/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts lines 2291 to 2294OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2279,4 +2291,4 @@22792291 export const OrchestrationProjectionSnapshotQueryLive = Layer.effect(22802292 ProjectionSnapshotQuery,22812293 makeProjectionSnapshotQuery,2282-);2294+).pipe(Layer.provide(ThreadBackgroundLivenessLive));
- apps/server/src/orchestration/ThreadBackgroundLiveness.ts line 105Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +77,21 @@77+ * "monitoring" only when watch loops are the ONLY live work.78+ */79+ readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;80+ }81+>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}82+83+export function makeThreadBackgroundLiveness(): typeof ThreadBackgroundLivenessService.Service {84+ const stateByThreadId = new Map<string, ThreadLivenessState>();85+86+ const stateFor = (threadId: string): ThreadLivenessState => {87+ const existing = stateByThreadId.get(threadId);88+ if (existing) {89+ return existing;90+ }91+ const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };92+ stateByThreadId.set(threadId, created);93+ return created;94+ };95+96+ return {97+ recordTaskLiveness: (input) => {
- apps/server/src/orchestration/workflowScriptQuery.ts lines 34 to 34OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+ * never trusted beyond these checks.15+ */16+import * as NodeFSP from "node:fs/promises";17+import * as NodeOS from "node:os";18+import * as NodePath from "node:path";19+20+import { OrchestrationGetWorkflowScriptError } from "@t3tools/contracts";21+import * as Effect from "effect/Effect";22+23+const SCRIPT_BYTE_CAP = 256 * 1024;24+25+function scriptsRoot(): string {26+ return NodePath.join(NodeOS.homedir(), ".claude", "projects");27+}28+29+export const readWorkflowScript = Effect.fn("orchestration.readWorkflowScript")(function* (input: {30+ readonly scriptPath: string;31+}) {32+ const requested = input.scriptPath;33+34+ const fail = (message: string) =>apps/server/src/orchestration/ThreadBackgroundLiveness.ts lines 83 to 83OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ readonly recordTaskLiveness: (input: {64+ readonly threadId: string;65+ readonly taskId: string;66+ readonly taskType: string | undefined;67+ readonly status: string | undefined;68+ readonly kind: "started" | "progress" | "updated" | "completed";69+ readonly agentId?: string | undefined;70+ }) => void;71+72+ /** Session death orphans all of a thread's background work. */73+ readonly clearThreadLiveness: (threadId: string) => void;74+75+ /**76+ * Two-state vocabulary by design: any live agent work is "working";77+ * "monitoring" only when watch loops are the ONLY live work.78+ */79+ readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;80+ }81+>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}82+83+export function makeThreadBackgroundLiveness(): typeof ThreadBackgroundLivenessService.Service {
- packages/contracts/src/orchestration.ts lines 1449 to 1449OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1422,2 +1429,21 @@14221429 export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;142314301431+export const OrchestrationGetWorkflowScriptInput = Schema.Struct({1432+ threadId: ThreadId,1433+ /** Absolute path from the workflow's runHandles.scriptPath. The server1434+ * re-derives containment; the client value is a hint, never trusted. */1435+ scriptPath: TrimmedNonEmptyString,1436+});1437+export type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;1438+1439+export const OrchestrationGetWorkflowScriptResult = Schema.Struct({1440+ scriptPath: TrimmedNonEmptyString,1441+ contents: Schema.String,1442+ truncated: Schema.Boolean,1443+});1444+export type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;1445+1446+export class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(1447+ "OrchestrationGetWorkflowScriptError",1448+ {1449+ message: Schema.String,
- apps/web/src/components/ChatView.tsx line 4198OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -4165,3 +4181,18 @@41654181 switchGitRef,41664182 updateThreadMetadata,41674183 ]);4184+ // Background work (subagent fleets, workflow runs, watch loops) can outlive4185+ // the turn; once it settles, the composer stop button is gone, so this4186+ // banner is the only visible stop affordance. Stop routes through the4187+ // stop-everything interrupt: it kills every live background task before4188+ // interrupting, and works by session, so no active turn is needed.4189+ const activeBackgroundLiveness =4190+ !isWorking && activeThread ? (activeThreadShell?.backgroundLiveness ?? null) : null;4191+ const [isStoppingBackgroundWork, setIsStoppingBackgroundWork] = useState(false);4192+ useEffect(() => {4193+ // "Stopping..." holds until the liveness clears (or the thread changes);4194+ // the interrupt command returning only means the request was accepted.4195+ if (activeBackgroundLiveness === null) {4196+ setIsStoppingBackgroundWork(false);4197+ }4198+ }, [activeBackgroundLiveness, activeThreadId]);
- packages/client-runtime/src/state/subagentRuntime.ts line 616OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +596,21 @@596+ const endedAt = asString(payload.endedAt);597+ if (endedAt && !wasTerminal && isTerminalSubagentStatus(agent.status)) {598+ agent.completedAt = endedAt;599+ }600+ agent.updatedAt = at;601+ break;602+ }603+ case "task.completed": {604+ const taskId = asString(payload.taskId);605+ if (!taskId) break;606+ // Membership is sticky per taskId: rows after the first (terminal607+ // rows often carry only taskId+status, no marker fields) inherit the608+ // first row's classification instead of being re-judged.609+ if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;610+ const agent = getOrCreate(agents, taskId, payload, at);611+ fillMetadata(agent, payload);612+ if (agent.activationCount === 0) agent.activationCount = 1;613+ // Duplicate terminal rows are fully idempotent: first write wins for614+ // result/error/updatedAt too, not just status/timestamps (review615+ // finding: a duplicate completion replaced the first result).616+ if (isTerminalSubagentStatus(agent.status)) break;apps/mobile/src/lib/threadActivity.ts line 306Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -243,3 +296,5 @@243296 for (const activity of ordered) {244297 if (activity.kind === "tool.started") continue;245298 if (activity.kind === "task.started") continue;299+ // Terminal bypassed updates pass: Codex children's only terminal signal.300+ if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
- apps/server/src/provider/Layers/CodexAdapter.ts line 669Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -496,0 +649,21 @@649+ );650+ return [651+ {652+ ...base,653+ type: "task.updated",654+ payload: { taskId, status: waiting ? "waiting" : "running", ...statusLinkage },655+ },656+ ];657+ }658+ if (statusType === "idle") {659+ return [660+ {661+ ...base,662+ type: "task.updated",663+ payload: { taskId, status: "idle", ...statusLinkage },664+ },665+ ];666+ }667+ return [];668+ }669+ case "collabAgent/tokenUsage": {
Sign in to join this conversation.


🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share