Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat: native subagent & workflow observability (#5219)
Theo Brownea2ca89aa10f1
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.tsindex 5d323516d..ae9a93e9f 100644--- a/apps/mobile/src/lib/threadActivity.test.ts+++ b/apps/mobile/src/lib/threadActivity.test.ts@@ -532,3 +532,39 @@ describe("buildThreadFeed", () => {});});});++describe("quiet timeline: nested agents", () => {+ it("keeps a nested agent's terminal row but hides its background work", () => {+ const thread = makeThread({+ id: ThreadId.make("thread-nested"),+ projectId: ProjectId.make("project-1"),+ title: "Nested agents",+ activities: [+ // A subagent's own shell: internal, covered by the owner's liveness.+ makeActivity({+ id: EventId.make("shell-done"),+ kind: "task.completed",+ summary: "Task completed",+ createdAt: "2026-04-01T00:00:02.000Z",+ payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },+ }),+ // A nested AGENT's completion: mobile has no Agents sheet, so this+ // terminal row is the only signal it ever finished.+ makeActivity({+ id: EventId.make("nested-done"),+ kind: "task.completed",+ summary: "Task completed",+ createdAt: "2026-04-01T00:00:03.000Z",+ payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },+ }),+ ],+ });++ const feed = buildThreadFeed(thread);+ const ids = feed.flatMap((entry) =>+ entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],+ );+ expect(ids).toContain("nested-done");+ expect(ids).not.toContain("shell-done");+ });+});diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex dd568e6f0..886644bf8 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -80,6 +80,8 @@ interface WorkLogEntry {interface DerivedWorkLogEntry extends WorkLogEntry {activityKind: OrchestrationThreadActivity["kind"];collapseKey?: string;+ /** Grouping key for subagent lifecycle rows (one row per agent). */+ taskId?: string;}type RawThreadFeedEntry =@@ -235,6 +237,63 @@ function resolvePendingUserInputAnswer(return normalizeDraftAnswer(draft?.selectedOptionLabel);}+/** Codex children settle via task.updated (idle/failed/interrupted), never+ * task.completed — these rows are mobile's only terminal signal for them. */+const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([+ "idle",+ "completed",+ "failed",+ "cancelled",+ "interrupted",+]);++function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {+ if (activity.kind !== "task.updated") {+ return false;+ }+ const payload =+ activity.payload && typeof activity.payload === "object"+ ? (activity.payload as Record<string, unknown>)+ : null;+ return (+ payload?.timelineBypass === true &&+ typeof payload.status === "string" &&+ MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)+ );+}++/**+ * Quiet-timeline guarantee (mirrors web's session-logic): agent-internal+ * activity lives in the Agents sheet, not the work log. Terminal rows are+ * kept — with no Agents surface on mobile they are the terminal signal+ * (a surface that hides rows must keep its own terminal signal). That means+ * task.completed (Claude) AND terminal bypassed task.updated (Codex, whose+ * children never emit task.completed — review finding).+ */+function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {+ const payload =+ activity.payload && typeof activity.payload === "object"+ ? (activity.payload as Record<string, unknown>)+ : null;+ if (!payload) {+ return false;+ }+ const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);+ if (payload.timelineBypass === true && !isTerminalTaskRow) {+ return true;+ }+ // agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is+ // the only signal mobile gets (no Agents sheet), so it stays. Only an+ // agent's own background work (stamped "background") is internal — same+ // rule as web (review finding: hiding on agentId alone dropped nested+ // completions with no replacement UI).+ const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;+ if (!ownedByAgent) {+ return false;+ }+ return !(isTerminalTaskRow && payload.agentKind === "agent");+}+function deriveWorkLogEntries(activities: ReadonlyArray<OrchestrationThreadActivity>,): DerivedWorkLogEntry[] {@@ -243,9 +302,13 @@ function deriveWorkLogEntries(for (const activity of ordered) {if (activity.kind === "tool.started") continue;if (activity.kind === "task.started") continue;+ // Terminal bypassed updates pass: Codex children's only terminal signal.+ if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;+ if (activity.kind === "tool.progress") continue;if (activity.kind === "context-window.updated") continue;if (activity.summary === "Checkpoint captured") continue;if (isPlanBoundaryToolActivity(activity)) continue;+ if (isAgentInternalActivity(activity)) continue;entries.push(toDerivedWorkLogEntry(activity));}return collapseDerivedWorkLogEntries(entries);@@ -271,7 +334,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWoconst commandPreview = extractToolCommand(payload);const changedFiles = extractChangedFiles(payload);const title = extractToolTitle(payload);- const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";+ // task.updated included: terminal bypassed updates (Codex children's only+ // terminal signal) must carry task identity so they collapse per child+ // instead of stacking anonymous "Task idle" rows.+ const isTaskActivity =+ activity.kind === "task.progress" ||+ activity.kind === "task.completed" ||+ activity.kind === "task.updated";const taskSummary =isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0? payload.summary@@ -284,10 +353,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo? payload.detail: null;const taskLabel = taskSummary || taskDetailAsLabel;+ const taskId =+ isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0+ ? payload.taskId+ : undefined;const entry: DerivedWorkLogEntry = {id: activity.id,createdAt: activity.createdAt,turnId: activity.turnId,+ ...(taskId ? { taskId } : {}),label: taskLabel || activity.summary,tone:activity.kind === "task.progress"@@ -352,7 +426,25 @@ function collapseDerivedWorkLogEntries(entries: ReadonlyArray<DerivedWorkLogEntry>,): DerivedWorkLogEntry[] {const collapsed: DerivedWorkLogEntry[] = [];+ // Subagent rows collapse by identity, not adjacency (quiet-timeline+ // guarantee; mirrors web's session-logic).+ const taskRowIndex = new Map<string, number>();for (const entry of entries) {+ const isTaskRow =+ entry.taskId !== undefined &&+ (entry.activityKind === "task.progress" ||+ entry.activityKind === "task.completed" ||+ entry.activityKind === "task.updated");+ if (isTaskRow && entry.taskId !== undefined) {+ const existingIndex = taskRowIndex.get(entry.taskId);+ if (existingIndex !== undefined) {+ collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);+ continue;+ }+ taskRowIndex.set(entry.taskId, collapsed.length);+ collapsed.push(entry);+ continue;+ }const previous = collapsed.at(-1);if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.tsindex ebc4f984b..c3f77d677 100644--- a/apps/server/integration/OrchestrationEngineHarness.integration.ts+++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts@@ -50,6 +50,7 @@ import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityReimport { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";@@ -305,7 +306,7 @@ export const makeOrchestrationIntegrationHarness = (checkpointStoreLayer,providerLayer,RuntimeReceiptBusTest,- );+ ).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));const serverSettingsLayer = ServerSettingsService.layerTest();const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(Layer.provideMerge(runtimeServicesLayer),diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex c1d9f786a..2aa057ee0 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -22,6 +22,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];*/export const RPC_REQUIRED_SCOPES = {[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,+ [ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,[ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.test.ts b/apps/server/src/orchestration/ActivityPayloadProjection.test.tsnew file mode 100644index 000000000..7ea1e3ea0--- /dev/null+++ b/apps/server/src/orchestration/ActivityPayloadProjection.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vite-plus/test";+import type { OrchestrationThreadActivity } from "@t3tools/contracts";+import { projectActivityPayload } from "./ActivityPayloadProjection.ts";++function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {+ return {+ id: "activity-1",+ tone: "tool",+ kind: "tool.completed",+ summary: "Tool",+ payload,+ turnId: null,+ createdAt: "2026-08-01T10:00:00.000Z",+ } as unknown as OrchestrationThreadActivity;+}++/**+ * Wire-survival regression: the slimming pass rewrites payload.data but must+ * never strip the top-level per-agent fields the subagent fold depends on.+ * If slimming ever moves to an allowlist over the whole payload, these+ * assertions are the tripwire.+ */+describe("projectActivityPayload agent-field survival", () => {+ it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {+ const projected = projectActivityPayload(+ activity({+ itemType: "command_execution",+ agentId: "task-123",+ parentToolUseId: "toolu_abc",+ data: {+ toolName: "Bash",+ input: { command: "ls" },+ command: "ls",+ rawOutput: { content: "x".repeat(10) },+ somethingClientNeverReads: { big: "blob" },+ },+ }),+ );+ const payload = projected.payload as Record<string, unknown>;+ expect(payload.agentId).toBe("task-123");+ expect(payload.parentToolUseId).toBe("toolu_abc");+ // Slimming itself still applies to data.+ const data = payload.data as Record<string, unknown>;+ expect(data.somethingClientNeverReads).toBeUndefined();+ });++ it("passes task lifecycle payloads (no data field) through untouched", () => {+ const source = activity({+ taskId: "task-9",+ title: "Audit auth",+ role: "explorer",+ model: "opus",+ effort: "high",+ workflowName: "audit-flow",+ phases: [{ index: 0, title: "Audit" }],+ typedUsage: { totalTokens: 1200 },+ runHandles: { runId: "run-1", scriptPath: "/tmp/wf.js" },+ timelineBypass: true,+ });+ const projected = projectActivityPayload(source);+ expect(projected.payload).toEqual(source.payload);+ });+});diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.tsindex e72a10006..ddb525cd5 100644--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts@@ -39,6 +39,7 @@ import { CheckpointReactorLive } from "./CheckpointReactor.ts";import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";@@ -294,6 +295,7 @@ describe("CheckpointReactor", () => {);const orchestrationLayer = OrchestrationEngineLive.pipe(Layer.provide(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(OrchestrationProjectionPipelineLive),Layer.provide(OrchestrationEventStoreLive),Layer.provide(OrchestrationCommandReceiptRepositoryLive),@@ -301,6 +303,7 @@ describe("CheckpointReactor", () => {Layer.provide(SqlitePersistenceMemory),);const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(RepositoryIdentityResolver.layer),Layer.provide(SqlitePersistenceMemory),);diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex 9ffe50d13..857f5b887 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -31,6 +31,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResimport { OrchestrationEngineLive } from "./OrchestrationEngine.ts";import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";import {OrchestrationProjectionPipeline,@@ -55,6 +56,7 @@ async function createOrchestrationSystem() {),OrchestrationProjectionSnapshotQueryLive,).pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(OrchestrationEventStoreLive),Layer.provide(OrchestrationCommandReceiptRepositoryLive),Layer.provide(RepositoryIdentityResolver.layer),@@ -817,6 +819,7 @@ describe("OrchestrationEngine", () => {const runtime = ManagedRuntime.make(OrchestrationEngineLive.pipe(Layer.provide(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(OrchestrationProjectionPipelineLive),Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),Layer.provide(OrchestrationCommandReceiptRepositoryLive),@@ -922,6 +925,7 @@ describe("OrchestrationEngine", () => {const runtime = ManagedRuntime.make(OrchestrationEngineLive.pipe(Layer.provide(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),Layer.provide(OrchestrationEventStoreLive),Layer.provide(OrchestrationCommandReceiptRepositoryLive),@@ -1065,6 +1069,7 @@ describe("OrchestrationEngine", () => {const runtime = ManagedRuntime.make(OrchestrationEngineLive.pipe(Layer.provide(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),Layer.provide(OrchestrationCommandReceiptRepositoryLive),diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex 926182a3e..9c4caf4c9 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -31,6 +31,7 @@ import {OrchestrationProjectionPipelineLive,} from "./ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";import { ServerConfig } from "../../config.ts";@@ -2664,6 +2665,7 @@ it.effect("restores pending turn-start metadata across projection pipeline restaconst engineLayer = it.layer(OrchestrationEngineLive.pipe(Layer.provide(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(OrchestrationProjectionPipelineLive),Layer.provide(OrchestrationEventStoreLive),Layer.provide(OrchestrationCommandReceiptRepositoryLive),diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex 9c4a81b18..b7b630a16 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -17,6 +17,7 @@ import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";const asProjectId = (value: string): ProjectId => ProjectId.make(value);@@ -27,6 +28,7 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(valconst projectionSnapshotLayer = it.layer(OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provideMerge(RepositoryIdentityResolver.layer),Layer.provideMerge(SqlitePersistenceMemory),Layer.provideMerge(NodeServices.layer),@@ -443,6 +445,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {hasPendingApprovals: true,hasPendingUserInput: false,hasActionableProposedPlan: false,+ backgroundLiveness: null,},]);@@ -1825,6 +1828,7 @@ it.effect(() => {const resolveCalls: string[] = [];const layer = OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provideMerge(Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {resolve: (cwd: string) =>diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex 766f8a93d..2d8a98d8c 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -43,6 +43,7 @@ import {type ProjectionRepositoryError,} from "../../persistence/Errors.ts";import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";+import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";@@ -308,6 +309,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st}const makeProjectionSnapshotQuery = Effect.gen(function* () {+ const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;const sql = yield* SqlClient.SqlClient;const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;const repositoryIdentityResolutionConcurrency = 4;@@ -1678,6 +1680,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {hasPendingApprovals: row.pendingApprovalCount > 0,hasPendingUserInput: row.pendingUserInputCount > 0,hasActionableProposedPlan: row.hasActionableProposedPlan > 0,+ backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(+ row.threadId,+ ),} satisfies OrchestrationThreadShell): Result.failVoid,),@@ -1818,6 +1823,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {hasPendingApprovals: row.pendingApprovalCount > 0,hasPendingUserInput: row.pendingUserInputCount > 0,hasActionableProposedPlan: row.hasActionableProposedPlan > 0,+ backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(+ row.threadId,+ ),}),),updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",@@ -2090,6 +2098,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,+ backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(+ threadRow.value.threadId,+ ),} satisfies OrchestrationThreadShell);});diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsindex 97379b94b..f355bfc45 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts@@ -48,6 +48,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResimport { OrchestrationEngineLive } from "./OrchestrationEngine.ts";import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";import {providerErrorLabel,providerErrorLabelFromInstanceHint,@@ -345,6 +346,7 @@ describe("ProviderCommandReactor", () => {const orchestrationLayer = OrchestrationEngineLive.pipe(Layer.provide(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(OrchestrationProjectionPipelineLive),Layer.provide(OrchestrationEventStoreLive),Layer.provide(OrchestrationCommandReceiptRepositoryLive),@@ -352,6 +354,7 @@ describe("ProviderCommandReactor", () => {Layer.provide(SqlitePersistenceMemory),);const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),Layer.provide(RepositoryIdentityResolver.layer),Layer.provide(SqlitePersistenceMemory),);diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.tsindex 74ece50cd..31e30c4d1 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts@@ -44,6 +44,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResimport { OrchestrationEngineLive } from "./OrchestrationEngine.ts";import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";@@ -237,6 +238,9 @@ describe("ProviderRuntimeIngestion", () => {const layer = ProviderRuntimeIngestionLive.pipe(Layer.provideMerge(orchestrationLayer),Layer.provideMerge(projectionSnapshotLayer),+ // Single shared liveness instance across ingestion (writer), the+ // engine, and the snapshot query (reader).+ Layer.provideMerge(ThreadBackgroundLiveness.layer),Layer.provideMerge(SqlitePersistenceMemory),Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),@@ -3143,7 +3147,8 @@ describe("ProviderRuntimeIngestion", () => {(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started",);const progress = thread.activities.find(- (activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-progress",+ (activity: ProviderRuntimeTestActivity) =>+ activity.id === "task-progress:thread-1:turn-task-1",);const completed = thread.activities.find((activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed",@@ -3227,7 +3232,8 @@ describe("ProviderRuntimeIngestion", () => {);const progress = thread.activities.find(- (activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-progress",+ (activity: ProviderRuntimeTestActivity) =>+ activity.id === "task-progress:thread-1:named-task-1",);const completed = thread.activities.find((activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-completed",@@ -3318,7 +3324,8 @@ describe("ProviderRuntimeIngestion", () => {await waitForThread(harness.readModel, (entry) =>entry.activities.some(- (activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-progress",+ (activity: ProviderRuntimeTestActivity) =>+ activity.id === "task-progress:thread-1:swept-task-1",),);diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.tsindex c8d619270..042042093 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts@@ -7,6 +7,8 @@ import {type OrchestrationMessage,type OrchestrationProposedPlanId,CheckpointRef,+ classifyTaskAgentKind,+ EventId,isToolLifecycleItemType,ThreadId,type ThreadTokenUsageSnapshot,@@ -32,6 +34,7 @@ import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTimport { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";import { isGitRepository } from "../../git/Utils.ts";import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";+import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";import {ProviderRuntimeIngestionService,@@ -307,6 +310,52 @@ function requestKindFromCanonicalRequestType(}}+/**+ * Copies the optional TaskAgentLinkage bundle from a task.* runtime payload+ * into the persisted activity payload. Identity fields ride on every row so+ * client folds survive activity retention; absent fields stay absent.+ */+function taskLinkageActivityFields(payload: Record<string, unknown>): Record<string, unknown> {+ const fields: Record<string, unknown> = {+ // Server-stamped classification: persisted rows are self-describing, so+ // clients trust the stamp instead of re-deriving agent-vs-background+ // from taskType denylists and marker heuristics (legacy rows without a+ // stamp keep the client fallback).+ agentKind: classifyTaskAgentKind({+ taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,+ agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,+ }),+ };+ for (const key of [+ "taskType",+ "agentId",+ "title",+ "role",+ "model",+ "effort",+ "toolUseId",+ "parentAgentId",+ "workflowName",+ "agentIndex",+ "phaseIndex",+ "phaseTitle",+ "phases",+ "attempt",+ "runHandles",+ "outputFile",+ "agentPath",+ "timelineBypass",+ "typedUsage",+ "status",+ "error",+ ] as const) {+ if (payload[key] !== undefined) {+ fields[key] = payload[key];+ }+ }+ return fields;+}+export function runtimeEventToActivities(event: ProviderRuntimeEvent,taskTitle?: string,@@ -505,6 +554,7 @@ export function runtimeEventToActivities(...(event.payload.description? { detail: truncateDetail(event.payload.description) }: {}),+ ...taskLinkageActivityFields(event.payload as Record<string, unknown>),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -515,7 +565,16 @@ export function runtimeEventToActivities(case "task.progress": {return [{- id: event.eventId,+ // Stable per-task id: progress is "latest state", not history, so+ // each tick REPLACES the last via the activity upsert (PK + the+ // replace-by-id apply in projector and client reducer). Keeps one+ // progress row per task instead of thousands, so a large fleet's+ // ticks can no longer evict its own start/terminal rows out of+ // the 500-row retention window. Thread-scoped: activity_id is a+ // GLOBAL primary key and Claude task ids are session-local, so a+ // bare taskId could collide across threads and steal another+ // thread's row (review finding).+ id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),createdAt: event.createdAt,tone: "info",kind: "task.progress",@@ -532,6 +591,71 @@ export function runtimeEventToActivities(...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),+ ...taskLinkageActivityFields(event.payload as Record<string, unknown>),+ },+ turnId: toTurnId(event.turnId) ?? null,+ ...maybeSequence,+ },+ ];+ }++ case "task.updated": {+ return [+ {+ id: event.eventId,+ createdAt: event.createdAt,+ tone: event.payload.status === "failed" ? "error" : "info",+ kind: "task.updated",+ summary:+ event.payload.status === "failed"+ ? "Task failed"+ : event.payload.status+ ? `Task ${event.payload.status}`+ : "Task updated",+ payload: {+ taskId: event.payload.taskId,+ ...(event.payload.description+ ? { detail: truncateDetail(event.payload.description) }+ : {}),+ ...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}),+ ...(event.payload.isBackgrounded !== undefined+ ? { isBackgrounded: event.payload.isBackgrounded }+ : {}),+ ...taskLinkageActivityFields(event.payload as Record<string, unknown>),+ },+ turnId: toTurnId(event.turnId) ?? null,+ ...maybeSequence,+ },+ ];+ }++ case "tool.progress": {+ // Only agent-owned heartbeats are persisted: they feed the owning+ // agent's activity line. Parent-conversation tool progress stays+ // ephemeral (item lifecycle already covers it).+ if (event.payload.taskId === undefined) {+ return [];+ }+ return [+ {+ // Same stable-id treatment as task.progress: a heartbeat is+ // "what is this agent doing right now", so one row per task+ // (thread-scoped for the same global-PK collision reason).+ id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`),+ createdAt: event.createdAt,+ tone: "info",+ kind: "tool.progress",+ summary: event.payload.toolName ?? "Tool progress",+ payload: {+ taskId: event.payload.taskId,+ ...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),+ ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),+ ...(event.payload.elapsedSeconds !== undefined+ ? { elapsedSeconds: event.payload.elapsedSeconds }+ : {}),+ ...(event.payload.parentToolUseId+ ? { parentToolUseId: event.payload.parentToolUseId }+ : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -565,6 +689,7 @@ export function runtimeEventToActivities(}: {}),...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),+ ...taskLinkageActivityFields(event.payload as Record<string, unknown>),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -630,6 +755,10 @@ export function runtimeEventToActivities(...(event.payload.status ? { status: event.payload.status } : {}),...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),...(event.payload.data !== undefined ? { data: event.payload.data } : {}),+ ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),+ ...(event.payload.parentToolUseId+ ? { parentToolUseId: event.payload.parentToolUseId }+ : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -652,6 +781,10 @@ export function runtimeEventToActivities(itemType: event.payload.itemType,...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),...(event.payload.data !== undefined ? { data: event.payload.data } : {}),+ ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),+ ...(event.payload.parentToolUseId+ ? { parentToolUseId: event.payload.parentToolUseId }+ : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -673,6 +806,10 @@ export function runtimeEventToActivities(payload: {itemType: event.payload.itemType,...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),+ ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),+ ...(event.payload.parentToolUseId+ ? { parentToolUseId: event.payload.parentToolUseId }+ : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -688,6 +825,7 @@ export function runtimeEventToActivities(}const make = Effect.gen(function* () {+ const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;const crypto = yield* Crypto.Crypto;const orchestrationEngine = yield* OrchestrationEngineService;const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;@@ -1756,6 +1894,43 @@ const make = Effect.gen(function* () {yield* rememberTaskDescription(thread.id, event.payload.taskId, description);}}+ // Sidebar background liveness: fed from the same lifecycle stream,+ // read by the shell query at mapping time (no persistence).+ switch (event.type) {+ case "task.started":+ case "task.progress":+ case "task.updated":+ case "task.completed": {+ const payload = event.payload as {+ taskId: string;+ taskType?: string;+ status?: string;+ agentId?: string;+ };+ threadBackgroundLiveness.recordTaskLiveness({+ threadId: thread.id,+ taskId: payload.taskId,+ taskType: payload.taskType,+ status: payload.status,+ agentId: payload.agentId,+ kind:+ event.type === "task.started"+ ? "started"+ : event.type === "task.progress"+ ? "progress"+ : event.type === "task.updated"+ ? "updated"+ : "completed",+ });+ break;+ }+ case "session.exited":+ threadBackgroundLiveness.clearThreadLiveness(thread.id);+ break;+ default:+ break;+ }+let taskTitle: string | undefined;if (event.type === "task.completed") {taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);diff --git a/apps/server/src/orchestration/ThreadBackgroundLiveness.test.ts b/apps/server/src/orchestration/ThreadBackgroundLiveness.test.tsnew file mode 100644index 000000000..0c4841e81--- /dev/null+++ b/apps/server/src/orchestration/ThreadBackgroundLiveness.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from "vite-plus/test";+import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";++describe("ThreadBackgroundLiveness", () => {+ it("agents present as working; monitors as monitoring; agents win", () => {+ const liveness = ThreadBackgroundLiveness.make();+ const threadId = "t-live-1";+ liveness.recordTaskLiveness({+ threadId,+ taskId: "m1",+ taskType: "local_bash",+ status: undefined,+ kind: "started",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");+ liveness.recordTaskLiveness({+ threadId,+ taskId: "a1",+ taskType: "subagent",+ status: undefined,+ kind: "started",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");+ liveness.recordTaskLiveness({+ threadId,+ taskId: "a1",+ taskType: "subagent",+ status: "completed",+ kind: "completed",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");+ liveness.recordTaskLiveness({+ threadId,+ taskId: "m1",+ taskType: "local_bash",+ status: "completed",+ kind: "completed",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();+ });++ it("terminal rows without a taskType still clear monitor entries", () => {+ const liveness = ThreadBackgroundLiveness.make();+ const threadId = "t-live-2";+ liveness.recordTaskLiveness({+ threadId,+ taskId: "m1",+ taskType: "local_bash",+ status: undefined,+ kind: "started",+ });+ // Terminal tick arrives with no taskType (common on task.completed).+ liveness.recordTaskLiveness({+ threadId,+ taskId: "m1",+ taskType: undefined,+ status: "completed",+ kind: "completed",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();+ });++ it("nested agents (agentId + agent taskType) still count toward liveness", () => {+ const liveness = ThreadBackgroundLiveness.make();+ const threadId = "t-live-nested";+ liveness.recordTaskLiveness({+ threadId,+ taskId: "n1",+ taskType: "local_agent",+ status: undefined,+ kind: "started",+ agentId: "owner",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");+ liveness.recordTaskLiveness({+ threadId,+ taskId: "n1",+ taskType: "local_agent",+ status: "completed",+ kind: "completed",+ agentId: "owner",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();+ });++ it("untyped rows count as agents; idle is not live; agent-owned tasks are ignored", () => {+ const liveness = ThreadBackgroundLiveness.make();+ const threadId = "t-live-3";+ liveness.recordTaskLiveness({+ threadId,+ taskId: "wf:1",+ taskType: undefined,+ status: "running",+ kind: "progress",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");+ liveness.recordTaskLiveness({+ threadId,+ taskId: "wf:1",+ taskType: undefined,+ status: "idle",+ kind: "updated",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();+ liveness.recordTaskLiveness({+ threadId,+ taskId: "sh:1",+ taskType: "local_bash",+ status: undefined,+ kind: "started",+ agentId: "owner",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();+ });++ it("reclassification moves a task between buckets instead of duplicating it", () => {+ const liveness = ThreadBackgroundLiveness.make();+ const threadId = "t-live-reclass";+ // First seen without a taskType: counts as an agent.+ liveness.recordTaskLiveness({+ threadId,+ taskId: "x1",+ taskType: undefined,+ status: "running",+ kind: "started",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");+ // Later transition reveals it's a shell: downgrade to monitoring, not+ // a stale duplicate pinning "working".+ liveness.recordTaskLiveness({+ threadId,+ taskId: "x1",+ taskType: "local_bash",+ status: "running",+ kind: "progress",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");+ // Turning out to be inert or agent-owned drops the prior entry too.+ liveness.recordTaskLiveness({+ threadId,+ taskId: "x1",+ taskType: "local_bash",+ status: "running",+ kind: "progress",+ agentId: "owner",+ });+ expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();+ });++ it("plan tasks are inert; clear removes everything; instances are isolated", () => {+ const a = ThreadBackgroundLiveness.make();+ const b = ThreadBackgroundLiveness.make();+ a.recordTaskLiveness({+ threadId: "t",+ taskId: "p1",+ taskType: "plan",+ status: undefined,+ kind: "started",+ });+ expect(a.getThreadBackgroundLiveness("t")).toBeNull();+ a.recordTaskLiveness({+ threadId: "t",+ taskId: "a1",+ taskType: "local_workflow",+ status: undefined,+ kind: "started",+ });+ expect(a.getThreadBackgroundLiveness("t")).toBe("working");+ expect(b.getThreadBackgroundLiveness("t")).toBeNull();+ a.clearThreadLiveness("t");+ expect(a.getThreadBackgroundLiveness("t")).toBeNull();+ });+});diff --git a/apps/server/src/orchestration/ThreadBackgroundLiveness.ts b/apps/server/src/orchestration/ThreadBackgroundLiveness.tsnew file mode 100644index 000000000..8563e7665--- /dev/null+++ b/apps/server/src/orchestration/ThreadBackgroundLiveness.ts@@ -0,0 +1,160 @@+/**+ * ThreadBackgroundLivenessService - in-memory per-thread background liveness+ * for the sidebar status pill.+ *+ * The turn can settle while native background work runs on (subagent fleets,+ * workflow runs, Monitor watch loops); the shell previously showed nothing.+ * Ingestion records task lifecycle transitions and the shell query reads the+ * derived state at mapping time — no persistence, no migration. After a+ * server restart the registry is empty until new task events arrive, which+ * matches reality: orphaned background work is not live.+ *+ * "monitoring" is reserved for watch loops (monitor tasks and background+ * shells) when they are the ONLY live work; any agent work presents as+ * "working".+ *+ * @module ThreadBackgroundLivenessService+ */+import { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++export type ThreadBackgroundLiveness = "working" | "monitoring" | null;++interface ThreadLivenessState {+ readonly agents: Set<string>;+ readonly monitors: Set<string>;+}++// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:+// watch loops — monitor tasks plus background shells, which in practice are+// PR babysitting/log tails since pacing sleeps complete inside the turn;+// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's+// agentKind stamp, and the client fold can never drift apart.++const TERMINAL_STATUSES: ReadonlySet<string> = new Set([+ "completed",+ "failed",+ "stopped",+ "cancelled",+ "interrupted",+]);++export class ThreadBackgroundLivenessService extends Context.Service<+ ThreadBackgroundLivenessService,+ {+ /**+ * Feed one task lifecycle transition. taskType may be absent on+ * synthesized rows (workflow members, Codex children) — those count as+ * agents. agentId marks a task launched from inside a subagent: its+ * internal shells are covered by the owning agent's liveness, but a+ * NESTED AGENT (agentId + agent-flavored taskType) still counts — it+ * can outlive its parent and must keep the thread Working.+ */+ readonly recordTaskLiveness: (input: {+ readonly threadId: string;+ readonly taskId: string;+ readonly taskType: string | undefined;+ readonly status: string | undefined;+ readonly kind: "started" | "progress" | "updated" | "completed";+ readonly agentId?: string | undefined;+ }) => void;++ /** Session death orphans all of a thread's background work. */+ readonly clearThreadLiveness: (threadId: string) => void;++ /**+ * Two-state vocabulary by design: any live agent work is "working";+ * "monitoring" only when watch loops are the ONLY live work.+ */+ readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;+ }+>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}++export function make(): ThreadBackgroundLivenessService["Service"] {+ const stateByThreadId = new Map<string, ThreadLivenessState>();++ const stateFor = (threadId: string): ThreadLivenessState => {+ const existing = stateByThreadId.get(threadId);+ if (existing) {+ return existing;+ }+ const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };+ stateByThreadId.set(threadId, created);+ return created;+ };++ // Classification is per-transition, not sticky: a task first seen without+ // a taskType may later reveal itself as a shell, become inert, or turn out+ // to be agent-owned. Every path drops any prior entry for the taskId so a+ // stale bucket assignment can't pin the thread's status (review finding).+ const drop = (threadId: string, taskId: string) => {+ const state = stateByThreadId.get(threadId);+ if (!state) {+ return;+ }+ state.agents.delete(taskId);+ state.monitors.delete(taskId);+ if (state.agents.size === 0 && state.monitors.size === 0) {+ stateByThreadId.delete(threadId);+ }+ };++ return {+ recordTaskLiveness: (input) => {+ const taskType = input.taskType;+ if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {+ drop(input.threadId, input.taskId);+ return;+ }+ // A subagent's internal non-agent work (its own shells/monitors) is+ // covered by the owning agent's liveness. Nested agents fall through:+ // they can outlive their parent (review finding).+ if (+ input.agentId !== undefined &&+ (taskType === undefined || MONITOR_TASK_TYPES.has(taskType))+ ) {+ drop(input.threadId, input.taskId);+ return;+ }++ // Idle counts as not-live: a resting (resumable) Codex child isn't+ // doing anything, and an all-idle fleet must not pin Working.+ const terminal =+ input.kind === "completed" ||+ input.status === "idle" ||+ (input.status !== undefined && TERMINAL_STATUSES.has(input.status));+ if (terminal) {+ drop(input.threadId, input.taskId);+ return;+ }++ drop(input.threadId, input.taskId);+ const state = stateFor(input.threadId);+ const bucket =+ taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;+ bucket.add(input.taskId);+ },++ clearThreadLiveness: (threadId) => {+ stateByThreadId.delete(threadId);+ },++ getThreadBackgroundLiveness: (threadId) => {+ const state = stateByThreadId.get(threadId);+ if (!state) {+ return null;+ }+ if (state.agents.size > 0) {+ return "working";+ }+ if (state.monitors.size > 0) {+ return "monitoring";+ }+ return null;+ },+ };+}++export const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));diff --git a/apps/server/src/orchestration/runtimeLayer.ts b/apps/server/src/orchestration/runtimeLayer.tsindex a2ed58759..0bc624ec3 100644--- a/apps/server/src/orchestration/runtimeLayer.ts+++ b/apps/server/src/orchestration/runtimeLayer.ts@@ -5,6 +5,7 @@ import { OrchestrationEventStoreLive } from "../persistence/Layers/Orchestrationimport { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(OrchestrationEventStoreLive,@@ -19,7 +20,10 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(OrchestrationProjectionSnapshotQueryLive,OrchestrationEventInfrastructureLayerLive,OrchestrationProjectionPipelineLayerLive,-);+ // Shared background-liveness registry: written by runtime ingestion,+ // read by the snapshot query. provideMerge feeds the same instance to+ // the snapshot query here and re-exports it for runtime ingestion.+).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));export const OrchestrationLayerLive = Layer.mergeAll(OrchestrationInfrastructureLayerLive,diff --git a/apps/server/src/orchestration/workflowScriptQuery.test.ts b/apps/server/src/orchestration/workflowScriptQuery.test.tsnew file mode 100644index 000000000..47fe888de--- /dev/null+++ b/apps/server/src/orchestration/workflowScriptQuery.test.ts@@ -0,0 +1,75 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";+import { it as effectIt } from "@effect/vitest";+import * as Effect from "effect/Effect";+import { afterAll, assert, describe } from "vite-plus/test";+import { readWorkflowScript } from "./workflowScriptQuery.ts";++const root = NodePath.join(NodeOS.homedir(), ".claude", "projects", "__wf_script_test__");+NodeFS.mkdirSync(root, { recursive: true });+const scriptPath = NodePath.join(root, "run.js");+NodeFS.writeFileSync(scriptPath, "export const meta = {};\n");+const outside = NodePath.join(NodeOS.tmpdir(), "wf-outside.js");+NodeFS.writeFileSync(outside, "evil\n");+const link = NodePath.join(root, "sneaky.js");+try {+ NodeFS.symlinkSync(outside, link);+} catch (error) {+ // Tolerate only "already exists" from a prior run — any other failure+ // (EPERM etc.) must fail setup, or the escape test below would pass+ // vacuously on "not-found" without testing containment.+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") {+ throw error;+ }+}+if (!NodeFS.lstatSync(link).isSymbolicLink()) {+ throw new Error("test setup: sneaky.js must be a symlink");+}++afterAll(() => {+ NodeFS.rmSync(root, { recursive: true, force: true });+ NodeFS.rmSync(outside, { force: true });+});++describe("readWorkflowScript containment", () => {+ effectIt.effect("serves a real script under the projects root", () =>+ Effect.gen(function* () {+ const result = yield* readWorkflowScript({ scriptPath });+ assert.include(result.contents, "export const meta");+ assert.equal(result.truncated, false);+ }),+ );++ effectIt.effect("rejects relative and non-js paths", () =>+ Effect.gen(function* () {+ const relative = yield* Effect.exit(readWorkflowScript({ scriptPath: "run.js" }));+ assert.equal(relative._tag, "Failure");+ const nonJs = yield* Effect.exit(+ readWorkflowScript({ scriptPath: scriptPath.replace(".js", ".ts") }),+ );+ assert.equal(nonJs._tag, "Failure");+ }),+ );++ effectIt.effect("rejects paths outside the root and symlink escapes", () =>+ Effect.gen(function* () {+ const escaped = yield* Effect.exit(readWorkflowScript({ scriptPath: outside }));+ assert.equal(escaped._tag, "Failure");+ // A symlink INSIDE the root pointing outside must fail specifically on+ // realpath re-containment — a "not-found" would mean the link was+ // never exercised and the assertion proves nothing.+ const sneaky = yield* Effect.exit(+ readWorkflowScript({ scriptPath: link }).pipe(+ Effect.flip,+ Effect.map((error) => error.reason),+ ),+ );+ assert.equal(sneaky._tag, "Success");+ if (sneaky._tag === "Success") {+ assert.equal(sneaky.value, "outside-root");+ }+ }),+ );+});diff --git a/apps/server/src/orchestration/workflowScriptQuery.ts b/apps/server/src/orchestration/workflowScriptQuery.tsnew file mode 100644index 000000000..06bbd35cc--- /dev/null+++ b/apps/server/src/orchestration/workflowScriptQuery.ts@@ -0,0 +1,124 @@+// @effect-diagnostics nodeBuiltinImport:off+/**+ * Read-only access to persisted workflow scripts for the Agents surface's+ * "{} script" affordance.+ *+ * Containment rules (lifted from the reviewed #3650 inspection service):+ * - the resolved realpath must live under ~/.claude/projects (where the+ * Claude harness persists workflow scripts) — realpath re-containment+ * defeats symlink escapes, including a symlinked leaf file;+ * - only .js leaf files are served;+ * - reads are size-capped rather than failed, with a truncation marker.+ *+ * The client-supplied path is a hint from the workflow's runHandles; it is+ * never trusted beyond these checks.+ */+import * as NodeFSP from "node:fs/promises";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";++import { OrchestrationGetWorkflowScriptError } from "@t3tools/contracts";+import * as Effect from "effect/Effect";++const SCRIPT_BYTE_CAP = 256 * 1024;++function scriptsRoot(): string {+ return NodePath.join(NodeOS.homedir(), ".claude", "projects");+}++export const readWorkflowScript = Effect.fn("orchestration.readWorkflowScript")(function* (input: {+ readonly scriptPath: string;+}) {+ const requested = input.scriptPath;++ if (!NodePath.isAbsolute(requested) || NodePath.extname(requested) !== ".js") {+ return yield* Effect.fail(+ new OrchestrationGetWorkflowScriptError({ reason: "invalid-path", scriptPath: requested }),+ );+ }++ const root = yield* Effect.tryPromise({+ try: () => NodeFSP.realpath(scriptsRoot()),+ catch: (cause) =>+ new OrchestrationGetWorkflowScriptError({+ reason: "root-unavailable",+ scriptPath: requested,+ cause,+ }),+ });++ // Realpath the FILE itself (not just its directory): a symlink named+ // like a script inside a contained directory must not escape.+ const resolved = yield* Effect.tryPromise({+ try: () => NodeFSP.realpath(requested),+ catch: (cause) =>+ new OrchestrationGetWorkflowScriptError({+ reason: "not-found",+ scriptPath: requested,+ cause,+ }),+ });++ if (resolved !== root && !resolved.startsWith(`${root}${NodePath.sep}`)) {+ return yield* Effect.fail(+ new OrchestrationGetWorkflowScriptError({ reason: "outside-root", scriptPath: resolved }),+ );+ }+ if (NodePath.extname(resolved) !== ".js") {+ return yield* Effect.fail(+ new OrchestrationGetWorkflowScriptError({ reason: "not-js", scriptPath: resolved }),+ );+ }++ // TOCTOU-safe read (review finding): open FIRST, then verify what was+ // actually opened via the file descriptor. Re-checking the path after+ // open would race against a swap; fstat on the handle cannot. The two+ // containment checks fail with their own tagged reasons (not manufactured+ // Errors folded into read-failed); "read-failed" is reserved for genuine+ // platform failures with the real cause attached.+ const read = yield* Effect.tryPromise({+ try: async () => {+ const handle = await NodeFSP.open(resolved, "r");+ try {+ const stat = await handle.stat();+ if (!stat.isFile()) {+ return { failure: "not-regular-file" as const };+ }+ // The opened inode must be the same one realpath resolved to: a+ // process swapping the path between realpath and open changes the+ // inode, which this comparison catches.+ const pathStat = await NodeFSP.lstat(resolved);+ if (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {+ return { failure: "changed-during-read" as const };+ }+ const truncated = stat.size > SCRIPT_BYTE_CAP;+ const buffer = Buffer.alloc(Math.min(stat.size, SCRIPT_BYTE_CAP));+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);+ return {+ contents: buffer.subarray(0, bytesRead).toString("utf8"),+ truncated,+ };+ } finally {+ await handle.close();+ }+ },+ catch: (cause) =>+ new OrchestrationGetWorkflowScriptError({+ reason: "read-failed",+ scriptPath: resolved,+ cause,+ }),+ });+ if ("failure" in read) {+ return yield* new OrchestrationGetWorkflowScriptError({+ reason: read.failure,+ scriptPath: resolved,+ });+ }++ return {+ scriptPath: resolved,+ contents: read.contents,+ truncated: read.truncated,+ };+});diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.tsindex 760f0e7fb..8697505ef 100644--- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts+++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts@@ -55,6 +55,7 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {private failure: unknown | undefined;public readonly interruptCalls: Array<void> = [];+ public readonly stopTaskCalls: Array<string> = [];public readonly setModelCalls: Array<string | undefined> = [];public readonly setPermissionModeCalls: Array<string> = [];public readonly setMaxThinkingTokensCalls: Array<number | null> = [];@@ -98,6 +99,10 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {this.interruptCalls.push(undefined);};+ readonly stopTask = async (taskId: string): Promise<void> => {+ this.stopTaskCalls.push(taskId);+ };+readonly setModel = async (model?: string): Promise<void> => {this.setModelCalls.push(model);};@@ -1445,6 +1450,243 @@ describe("ClaudeAdapterLive", () => {);});+ it.effect("interruptTurn stops every live task before interrupting the turn", () => {+ const harness = makeHarness();+ return Effect.gen(function* () {+ const adapter = yield* ClaudeAdapter;++ // Wait for the three task.* runtime events to prove the lifecycle+ // handlers processed the emissions (no wall-clock sleeps under the+ // test clock).+ const taskEventsFiber = yield* adapter.streamEvents.pipe(+ Stream.filter((event) => event.type.startsWith("task.")),+ Stream.take(3),+ Stream.runCollect,+ Effect.forkChild,+ );++ const session = yield* adapter.startSession({+ threadId: THREAD_ID,+ provider: ProviderDriverKind.make("claudeAgent"),+ runtimeMode: "full-access",+ });+ yield* adapter.sendTurn({+ threadId: session.threadId,+ input: "spawn agents",+ attachments: [],+ });++ harness.query.emit({+ type: "system",+ subtype: "task_started",+ task_id: "task-live",+ description: "Agent A",+ task_type: "local_agent",+ uuid: "task-live-uuid",+ session_id: "sdk-session",+ } as unknown as SDKMessage);+ harness.query.emit({+ type: "system",+ subtype: "task_started",+ task_id: "task-settled",+ description: "Agent B",+ task_type: "local_agent",+ uuid: "task-settled-uuid",+ session_id: "sdk-session",+ } as unknown as SDKMessage);+ harness.query.emit({+ type: "system",+ subtype: "task_notification",+ task_id: "task-settled",+ status: "completed",+ output_file: "/tmp/task-settled.jsonl",+ summary: "done",+ uuid: "task-settled-done-uuid",+ session_id: "sdk-session",+ } as unknown as SDKMessage);++ yield* Fiber.join(taskEventsFiber);++ yield* adapter.interruptTurn(session.threadId);++ // Only the still-live task is stopped; interrupt always fires after.+ assert.deepEqual(harness.query.stopTaskCalls, ["task-live"]);+ assert.equal(harness.query.interruptCalls.length, 1);+ }).pipe(+ Effect.provideService(Random.Random, makeDeterministicRandomService()),+ Effect.provide(harness.layer),+ );+ });++ it.effect("workflow member coalescing: identical snapshots suppress, changes emit", () => {+ const harness = makeHarness();+ return Effect.gen(function* () {+ const adapter = yield* ClaudeAdapter;++ // Collect task.progress until member-0's tick-3 emission lands, then+ // evaluate member emissions.+ const progressFiber = yield* adapter.streamEvents.pipe(+ Stream.filter((event) => event.type === "task.progress"),+ Stream.takeUntil(+ // Sentinel: member-0's tick-3 emission (tokens 20) — members are+ // emitted after the coordinator row within a tick.+ (event) =>+ (event.payload as { taskId?: string }).taskId === "wf-coalesce:wf:0" &&+ (event.payload as { typedUsage?: { totalTokens?: number } }).typedUsage?.totalTokens ===+ 20,+ ),+ Stream.runCollect,+ Effect.forkChild,+ );++ const session = yield* adapter.startSession({+ threadId: THREAD_ID,+ provider: ProviderDriverKind.make("claudeAgent"),+ runtimeMode: "full-access",+ });+ yield* adapter.sendTurn({+ threadId: session.threadId,+ input: "run workflow",+ attachments: [],+ });++ const memberSnapshot = (tokens: number) => [+ { type: "workflow_phase", index: 0, title: "Work" },+ {+ type: "workflow_agent",+ index: 0,+ state: "running",+ label: "member-0",+ phaseIndex: 0,+ tokens,+ },+ {+ type: "workflow_agent",+ index: 1,+ state: "running",+ label: "member-1",+ phaseIndex: 0,+ tokens: 50,+ },+ ];+ const tick = (usageTotal: number, snapshot: ReturnType<typeof memberSnapshot>) =>+ harness.query.emit({+ type: "system",+ subtype: "task_progress",+ task_id: "wf-coalesce",+ description: "Coalescing workflow",+ usage: { total_tokens: usageTotal, tool_uses: 1, duration_ms: 10 },+ workflow_progress: snapshot,+ uuid: `wf-tick-${usageTotal}`,+ session_id: "sdk-session",+ } as unknown as SDKMessage);++ // Tick 1: both members are new -> 2 member events.+ tick(100, memberSnapshot(10));+ // Tick 2: IDENTICAL member snapshot -> 0 member events (coordinator+ // usage changed, but members did not).+ tick(200, memberSnapshot(10));+ // Tick 3: member-0's tokens advanced -> exactly 1 member event.+ tick(300, memberSnapshot(20));++ const progressEvents = Array.from(yield* Fiber.join(progressFiber));+ const byMember = new Map<string, number>();+ for (const event of progressEvents) {+ const taskId = (event.payload as { taskId: string }).taskId;+ if (!taskId.includes(":wf:")) continue;+ byMember.set(taskId, (byMember.get(taskId) ?? 0) + 1);+ }+ // member-0: tick 1 + tick 3. member-1: tick 1 only (tick 2 identical,+ // tick 3 unchanged).+ assert.equal(byMember.get("wf-coalesce:wf:0"), 2);+ assert.equal(byMember.get("wf-coalesce:wf:1"), 1);+ }).pipe(+ Effect.provideService(Random.Random, makeDeterministicRandomService()),+ Effect.provide(harness.layer),+ );+ });++ it.effect("task.started carries model/effort; subagent snapshots refine the model", () => {+ const harness = makeHarness();+ return Effect.gen(function* () {+ const adapter = yield* ClaudeAdapter;++ const taskEventsFiber = yield* adapter.streamEvents.pipe(+ Stream.filter((event) => event.type.startsWith("task.")),+ Stream.take(2),+ Stream.runCollect,+ Effect.forkChild,+ );++ const session = yield* adapter.startSession({+ threadId: THREAD_ID,+ provider: ProviderDriverKind.make("claudeAgent"),+ modelSelection: createModelSelection(+ ProviderInstanceId.make("claudeAgent"),+ "claude-opus-4-6",+ [{ id: "effort", value: "max" }],+ ),+ runtimeMode: "full-access",+ });+ yield* adapter.sendTurn({+ threadId: session.threadId,+ input: "spawn an agent",+ attachments: [],+ });++ // No explicit model/effort on the launch input: the task inherits the+ // session's selection.+ harness.query.emit({+ type: "system",+ subtype: "task_started",+ task_id: "task-model",+ description: "Agent M",+ task_type: "local_agent",+ tool_use_id: "toolu_agent_m",+ uuid: "task-model-uuid",+ session_id: "sdk-session",+ } as unknown as SDKMessage);+ // The subagent's assistant snapshot carries the authoritative API+ // model id, which refines the linkage on later rows.+ harness.query.emit({+ type: "assistant",+ parent_tool_use_id: "toolu_agent_m",+ message: {+ model: "claude-sonnet-5[1m]",+ content: [],+ },+ uuid: "subagent-snapshot-uuid",+ session_id: "sdk-session",+ } as unknown as SDKMessage);+ harness.query.emit({+ type: "system",+ subtype: "task_progress",+ task_id: "task-model",+ description: "Agent M",+ usage: { total_tokens: 100, tool_uses: 1, duration_ms: 10 },+ uuid: "task-model-progress-uuid",+ session_id: "sdk-session",+ } as unknown as SDKMessage);++ const taskEvents = Array.from(yield* Fiber.join(taskEventsFiber));+ const started = taskEvents[0];+ assert.equal(started?.type, "task.started");+ if (started?.type === "task.started") {+ assert.equal(started.payload.model, "claude-opus-4-6");+ assert.equal(started.payload.effort, "max");+ }+ const progress = taskEvents[1];+ assert.equal(progress?.type, "task.progress");+ if (progress?.type === "task.progress") {+ assert.equal(progress.payload.model, "claude-sonnet-5[1m]");+ assert.equal(progress.payload.effort, "max");+ }+ }).pipe(+ Effect.provideService(Random.Random, makeDeterministicRandomService()),+ Effect.provide(harness.layer),+ );+ });+it.effect("closes the session when the Claude stream aborts after a turn starts", () => {const harness = makeHarness();return Effect.gen(function* () {diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.tsindex 548ffe6a8..812a73109 100644--- a/apps/server/src/provider/Layers/ClaudeAdapter.ts+++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts@@ -42,6 +42,10 @@ import {RuntimeItemId,RuntimeRequestId,RuntimeTaskId,+ type RuntimeTaskStatus,+ type RuntimeTaskUsage,+ type TaskAgentLinkage,+ type TaskRunHandles,ThreadId,TurnId,type UserInputQuestion,@@ -169,6 +173,9 @@ interface ToolInFlight {readonly input: Record<string, unknown>;readonly partialInputJson: string;readonly lastEmittedInputFingerprint?: string;+ /** Owning agent when this tool ran inside a subagent (see attribution note). */+ readonly agentId?: string;+ readonly parentToolUseId?: string;}interface ClaudeTaskState {@@ -178,6 +185,28 @@ interface ClaudeTaskState {readonly blockedBy: Set<string>;}+/**+ * Agent identity captured from task_started and repeated on every subsequent+ * task.* payload, so client folds can reconstruct an agent even when its+ * start row aged out of activity retention.+ */+interface ClaudeTaskAgentState {+ readonly taskId: string;+ toolUseId: string | undefined;+ description: string | undefined;+ subagentType: string | undefined;+ taskType: string | undefined;+ workflowName: string | undefined;+ skipTranscript: boolean;+ runHandles: TaskRunHandles | undefined;+ /** Set when this task was launched from inside a subagent. */+ owningAgentId: string | undefined;+ /** Seeded from the launching tool's input; refined by the subagent's own+ * assistant snapshots (authoritative API model). */+ model: string | undefined;+ effort: string | undefined;+}+interface ClaudeSessionContext {session: ProviderSession;readonly promptQueue: Queue.Queue<PromptQueueItem>;@@ -186,6 +215,9 @@ interface ClaudeSessionContext {readonly startedAt: string;readonly basePermissionMode: PermissionMode | undefined;currentApiModelId: string | undefined;+ /** Effective effort for the session's turns; subagents without an explicit+ * effort override inherit this. */+ currentEffort: string | undefined;resumeSessionId: string | undefined;readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;@@ -195,6 +227,17 @@ interface ClaudeSessionContext {}>;readonly inFlightTools: Map<number, ToolInFlight>;readonly claudeTasks: Map<string, ClaudeTaskState>;+ readonly taskAgents: Map<string, ClaudeTaskAgentState>;+ /**+ * Last emitted workflow-member fingerprint per member slot. A coordinator+ * task_progress repeats the FULL member array every tick; without a+ * material-transition filter one provider tick fans out into up to 100+ * runtime events (event-log writes, queue pressure, client reducer work)+ * even when nothing changed for most members.+ */+ readonly workflowMemberFingerprints: Map<string, string>;+ /** Task ids that have started and not yet reached a terminal state. */+ readonly liveTaskIds: Set<string>;turnState: ClaudeTurnState | undefined;lastKnownContextWindow: number | undefined;lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;@@ -206,6 +249,8 @@ interface ClaudeSessionContext {interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {readonly interrupt: () => Promise<void>;+ /** SDK Query.stopTask — present on real queries; optional for test doubles. */+ readonly stopTask?: (taskId: string) => Promise<void>;readonly setModel: (model?: string) => Promise<void>;readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;@@ -826,6 +871,225 @@ function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep});}+/** Only http/https survive; anything else (javascript:, file:, …) is dropped. */+function sanitizeSessionUrl(value: unknown): string | undefined {+ if (typeof value !== "string") {+ return undefined;+ }+ const trimmed = value.trim();+ if (!/^https?:\/\//i.test(trimmed)) {+ return undefined;+ }+ return trimmed;+}++function nonNegativeInt(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value >= 0+ ? Math.floor(value)+ : undefined;+}++function trimmedString(value: unknown): string | undefined {+ if (typeof value !== "string") {+ return undefined;+ }+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+}++/**+ * SDK task usage ({total_tokens, tool_uses, duration_ms}, sometimes with+ * input/output/cache breakdowns) → the typed contract shape. Unknown or+ * malformed input yields undefined rather than a partial guess.+ */+function normalizeTaskUsage(usage: unknown): RuntimeTaskUsage | undefined {+ if (typeof usage !== "object" || usage === null) {+ return undefined;+ }+ const record = usage as Record<string, unknown>;+ const totalTokens = nonNegativeInt(record.total_tokens);+ if (totalTokens === undefined) {+ return undefined;+ }+ const inputTokens = nonNegativeInt(record.input_tokens);+ const cachedInputTokens = nonNegativeInt(record.cache_read_input_tokens);+ const outputTokens = nonNegativeInt(record.output_tokens);+ const toolUses = nonNegativeInt(record.tool_uses);+ const durationMs = nonNegativeInt(record.duration_ms);+ return {+ totalTokens,+ ...(inputTokens !== undefined ? { inputTokens } : {}),+ ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),+ ...(outputTokens !== undefined ? { outputTokens } : {}),+ ...(toolUses !== undefined ? { toolUses } : {}),+ ...(durationMs !== undefined ? { durationMs } : {}),+ };+}++/** SDK task_updated patch status → the shared wire vocabulary. */+const CLAUDE_TASK_PATCH_STATUS: Record<string, RuntimeTaskStatus> = {+ pending: "pending",+ running: "running",+ completed: "completed",+ failed: "failed",+ killed: "cancelled",+ paused: "idle",+};++/**+ * Resolves a stream message's parent_tool_use_id to the owning agent's+ * taskId. The Task tool's tool_use_id is remembered on task_started; any+ * subagent-forwarded block carries that id as its parent. Returns undefined+ * for parent-conversation traffic.+ */+function agentIdForParentToolUse(+ agents: Map<string, ClaudeTaskAgentState>,+ parentToolUseId: string | null | undefined,+): string | undefined {+ if (parentToolUseId === null || parentToolUseId === undefined) {+ return undefined;+ }+ for (const agent of agents.values()) {+ if (agent.toolUseId === parentToolUseId) {+ return agent.taskId;+ }+ }+ return undefined;+}++/**+ * Linkage bundle repeated on every task.* payload for `taskId`. Reads the+ * remembered identity (from task_started) so progress/terminal rows are+ * self-describing even when the start row ages out of activity retention.+ */+function taskLinkageFor(+ agents: Map<string, ClaudeTaskAgentState>,+ taskId: string,+): TaskAgentLinkage {+ const agent = agents.get(taskId);+ if (!agent) {+ return {};+ }+ return {+ ...(agent.taskType ? { taskType: agent.taskType } : {}),+ ...(agent.owningAgentId ? { agentId: agent.owningAgentId } : {}),+ ...(agent.description ? { title: agent.description } : {}),+ ...(agent.subagentType ? { role: agent.subagentType } : {}),+ ...(agent.model ? { model: agent.model } : {}),+ ...(agent.effort ? { effort: agent.effort } : {}),+ ...(agent.toolUseId ? { toolUseId: agent.toolUseId } : {}),+ ...(agent.workflowName ? { workflowName: agent.workflowName } : {}),+ ...(agent.runHandles ? { runHandles: agent.runHandles } : {}),+ };+}++const WORKFLOW_PHASE_CAP = 64;+const WORKFLOW_AGENT_CAP = 100;++interface ClaudeWorkflowAgentEntry {+ readonly index: number;+ readonly state: string;+ readonly label: string | undefined;+ readonly phaseIndex: number | undefined;+ readonly phaseTitle: string | undefined;+ readonly model: string | undefined;+ readonly attempt: number | undefined;+ readonly lastToolName: string | undefined;+ readonly startedAt: string | undefined;+ readonly error: string | undefined;+ readonly tokens: number | undefined;+ readonly toolCalls: number | undefined;+}++interface ClaudeWorkflowProgress {+ readonly phases: ReadonlyArray<{ index: number; title: string }>;+ readonly agents: ReadonlyArray<ClaudeWorkflowAgentEntry>;+}++/**+ * Defensive parse of the SDK's undeclared-but-real workflow_progress array on+ * task_progress messages (wire-confirmed; absent from sdk.d.ts). Unknown+ * shapes are skipped per-entry; phases and agents dedupe by index before+ * caps; a vanished field never throws. If the array disappears upstream the+ * caller keeps the coordinator row and plain task lifecycle.+ */+function parseWorkflowProgress(value: unknown): ClaudeWorkflowProgress | undefined {+ if (!Array.isArray(value) || value.length === 0) {+ return undefined;+ }+ const phasesByIndex = new Map<number, string>();+ const agentsByIndex = new Map<number, ClaudeWorkflowAgentEntry>();+ for (const entry of value) {+ if (typeof entry !== "object" || entry === null) {+ continue;+ }+ const record = entry as Record<string, unknown>;+ const entryType = trimmedString(record.type);+ if (entryType === "workflow_phase") {+ const index = nonNegativeInt(record.index);+ const title = trimmedString(record.title);+ if (index !== undefined && title && !phasesByIndex.has(index)) {+ phasesByIndex.set(index, title);+ }+ continue;+ }+ if (entryType !== "workflow_agent") {+ continue;+ }+ const index = nonNegativeInt(record.index);+ const state = trimmedString(record.state);+ if (index === undefined || !state || agentsByIndex.has(index)) {+ continue;+ }+ agentsByIndex.set(index, {+ index,+ state,+ label: trimmedString(record.label),+ phaseIndex: nonNegativeInt(record.phaseIndex),+ phaseTitle: trimmedString(record.phaseTitle),+ model: trimmedString(record.model),+ attempt: nonNegativeInt(record.attempt),+ lastToolName: trimmedString(record.lastToolName),+ startedAt: trimmedString(record.startedAt),+ error: trimmedString(record.error),+ tokens: nonNegativeInt(record.tokens),+ toolCalls: nonNegativeInt(record.toolCalls),+ });+ }+ if (phasesByIndex.size === 0 && agentsByIndex.size === 0) {+ return undefined;+ }+ const phases = Array.from(phasesByIndex.entries())+ .map(([index, title]) => ({ index, title }))+ .toSorted((a, b) => a.index - b.index)+ .slice(0, WORKFLOW_PHASE_CAP);+ const agents = Array.from(agentsByIndex.values())+ .toSorted((a, b) => a.index - b.index)+ .slice(0, WORKFLOW_AGENT_CAP);+ return { phases, agents };+}++/**+ * Workflow member states from workflow_progress → shared task status.+ * Unknown states read running after startedAt, pending before it.+ */+function workflowAgentStatus(entry: ClaudeWorkflowAgentEntry): RuntimeTaskStatus {+ switch (entry.state) {+ case "queued":+ case "pending":+ return "pending";+ case "start":+ case "running":+ return entry.startedAt === undefined ? "pending" : "running";+ case "done":+ return "completed";+ case "error":+ return "failed";+ default:+ return entry.startedAt === undefined ? "pending" : "running";+ }+}+function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {const commandValue = input.command ?? input.cmd;const command = typeof commandValue === "string" ? commandValue : undefined;@@ -833,17 +1097,17 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):return `${toolName}: ${command.trim().slice(0, 400)}`;}- // For agent/subagent tools, prefer human-readable description or prompt over raw JSON+ // For agent/subagent tools, prefer the human-readable description or prompt+ // over raw JSON. The structured subagent_type is carried separately on the+ // task.* payloads (role) — the label is display-only.const itemType = classifyToolItemType(toolName);if (itemType === "collab_agent_tool_call") {const description =typeof input.description === "string" ? input.description.trim() : undefined;const prompt = typeof input.prompt === "string" ? input.prompt.trim() : undefined;- const subagentType =- typeof input.subagent_type === "string" ? input.subagent_type.trim() : undefined;const label = description || (prompt ? prompt.slice(0, 200) : undefined);if (label) {- return subagentType ? `${subagentType}: ${label}` : label;+ return label;}}@@ -2078,6 +2342,32 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (const { event } = message;+ // Subagent-owned stream traffic (parent_tool_use_id set) must not write+ // into the parent transcript: with forwardSubagentText off the SDK still+ // forwards subagent tool_use/tool_result blocks and their wrapping+ // text/thinking deltas, and emitting them interleaved N subagents'+ // narration into the chat (live-test finding). Their results reach the+ // UI via the task.* lifecycle; their tool blocks are attributed and+ // re-homed by the quiet-timeline filter.+ const streamParentToolUseId = (message as { parent_tool_use_id?: string | null })+ .parent_tool_use_id;+ if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) {+ // Drop only the subagent's narration (text/thinking); tool_use blocks+ // and their input_json_delta frames must flow so attributed tool items+ // keep their inputs (review finding: dropping deltas emptied inputs).+ const dropStart =+ event.type === "content_block_start" &&+ event.content_block.type !== "tool_use" &&+ event.content_block.type !== "server_tool_use" &&+ event.content_block.type !== "mcp_tool_use";+ const dropDelta =+ event.type === "content_block_delta" &&+ (event.delta.type === "text_delta" || event.delta.type === "thinking_delta");+ if (dropStart || dropDelta) {+ return;+ }+ }+if (event.type === "message_delta") {if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {return;@@ -2205,6 +2495,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (status: "inProgress",title: nextTool.title,...(nextTool.detail ? { detail: nextTool.detail } : {}),+ ...(nextTool.agentId ? { agentId: nextTool.agentId } : {}),+ ...(nextTool.parentToolUseId ? { parentToolUseId: nextTool.parentToolUseId } : {}),data: {toolName: nextTool.toolName,input: nextTool.input,@@ -2274,6 +2566,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (const inputFingerprint =Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;+ // Attribute tools that ran inside a subagent to their owning agent so+ // clients can re-home them out of the main timeline (quiet-timeline+ // guarantee): the SDK forwards subagent tool_use blocks tagged with the+ // spawning Task tool's id as parent_tool_use_id.+ const parentToolUseId =+ (message as { parent_tool_use_id?: string | null }).parent_tool_use_id ?? undefined;+ const owningAgentId = agentIdForParentToolUse(context.taskAgents, parentToolUseId);+const tool: ToolInFlight = {itemId,itemType,@@ -2283,6 +2583,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (input: toolInput,partialInputJson: "",...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),+ ...(owningAgentId ? { agentId: owningAgentId } : {}),+ ...(parentToolUseId ? { parentToolUseId } : {}),};context.inFlightTools.set(index, tool);@@ -2300,6 +2602,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (status: "inProgress",title: tool.title,...(tool.detail ? { detail: tool.detail } : {}),+ ...(tool.agentId ? { agentId: tool.agentId } : {}),+ ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),data: {toolName: tool.toolName,input: toolInput,@@ -2378,6 +2682,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (status: toolResult.isError ? "failed" : "inProgress",title: tool.title,...(tool.detail ? { detail: tool.detail } : {}),+ ...(tool.agentId ? { agentId: tool.agentId } : {}),+ ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),data: toolData,},providerRefs: nativeProviderRefs(context, {@@ -2430,6 +2736,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (status: itemStatus,title: tool.title,...(tool.detail ? { detail: tool.detail } : {}),+ ...(tool.agentId ? { agentId: tool.agentId } : {}),+ ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),data: toolData,},providerRefs: nativeProviderRefs(context, {@@ -2442,6 +2750,43 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (},});+ // The Workflow tool's result carries the run handles (runId, scriptPath,+ // transcriptDir, sessionUrl). Attach them to the workflow's task agent so+ // the next task.* payload advertises them to clients.+ if (!toolResult.isError && tool.toolName.toLowerCase() === "workflow" && toolUseResult) {+ const workflowTaskId = trimmedString(toolUseResult.taskId);+ if (workflowTaskId) {+ const runHandles: TaskRunHandles = {+ ...(trimmedString(toolUseResult.runId)+ ? { runId: trimmedString(toolUseResult.runId) }+ : {}),+ ...(trimmedString(toolUseResult.scriptPath)+ ? { scriptPath: trimmedString(toolUseResult.scriptPath) }+ : {}),+ ...(trimmedString(toolUseResult.transcriptDir)+ ? { transcriptDir: trimmedString(toolUseResult.transcriptDir) }+ : {}),+ ...(sanitizeSessionUrl(toolUseResult.sessionUrl)+ ? { sessionUrl: sanitizeSessionUrl(toolUseResult.sessionUrl) }+ : {}),+ };+ const existing = context.taskAgents.get(workflowTaskId);+ context.taskAgents.set(workflowTaskId, {+ taskId: workflowTaskId,+ toolUseId: existing?.toolUseId ?? tool.itemId,+ description: existing?.description,+ subagentType: existing?.subagentType,+ taskType: existing?.taskType ?? "local_workflow",+ workflowName: existing?.workflowName,+ skipTranscript: existing?.skipTranscript ?? false,+ runHandles,+ owningAgentId: existing?.owningAgentId,+ model: existing?.model,+ effort: existing?.effort,+ });+ }+ }+if (!toolResult.isError &&applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)@@ -2465,6 +2810,26 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (return;}+ // Subagent-owned assistant snapshots (parent_tool_use_id set) are the+ // subagent's own conversation, not the parent's. Emitting them created+ // interleaved "Agent N done"-adjacent leak messages and spawned synthetic+ // turns per subagent completion (which also reset the Working timer).+ const assistantParentToolUseId = (message as { parent_tool_use_id?: string | null })+ .parent_tool_use_id;+ if (assistantParentToolUseId !== null && assistantParentToolUseId !== undefined) {+ // The snapshot's message.model is the authoritative API model the+ // subagent actually ran on — refine the seeded launch-time value.+ const owningTaskId = agentIdForParentToolUse(context.taskAgents, assistantParentToolUseId);+ const snapshotModel = trimmedString(message.message.model);+ const owningAgent = owningTaskId ? context.taskAgents.get(owningTaskId) : undefined;+ if (owningAgent && snapshotModel) {+ owningAgent.model = snapshotModel;+ }+ context.lastAssistantUuid = message.uuid;+ yield* updateResumeCursor(context);+ return;+ }+// Auto-start a synthetic turn for assistant messages that arrive without// an active turn (e.g., background agent/subagent responses between user prompts).if (!context.turnState) {@@ -2563,6 +2928,82 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (yield* completeTurn(context, status, errorMessage, message);});+ /**+ * Synthesizes per-member task.progress rows from the coordinator's+ * workflow_progress array. Member identity is the stable slot+ * `<coordinatorTaskId>:wf:<index>` (never the per-attempt agent id, which+ * changes on retry and would split one member into duplicate rows).+ * timelineBypass keeps these out of the parent chat; the Agents surface and+ * workflow card consume them.+ */+ const emitWorkflowMemberProgress = Effect.fn("emitWorkflowMemberProgress")(function* (+ context: ClaudeSessionContext,+ base: Omit<ProviderRuntimeEvent, "type" | "payload">,+ message: Extract<SDKMessage, { type: "system"; subtype: "task_progress" }>,+ ) {+ const progress = parseWorkflowProgress(+ (message as unknown as Record<string, unknown>).workflow_progress,+ );+ if (!progress) {+ return;+ }+ const coordinatorId = message.task_id;+ for (const entry of progress.agents) {+ const memberTaskId = `${coordinatorId}:wf:${entry.index}`;+ const status = workflowAgentStatus(entry);+ // Material-transition filter: the wire repeats every member each tick.+ // Emit only when something the client renders actually changed, so a+ // 100-agent fleet costs ~1 event per changed member instead of 100+ // per tick (review finding: unbounded event amplification).+ const fingerprint = [+ status,+ entry.label ?? "",+ entry.model ?? "",+ entry.lastToolName ?? "",+ entry.error ?? "",+ entry.tokens ?? "",+ entry.toolCalls ?? "",+ entry.phaseIndex ?? "",+ entry.phaseTitle ?? "",+ entry.attempt ?? "",+ ].join("\u001f");+ if (context.workflowMemberFingerprints.get(memberTaskId) === fingerprint) {+ continue;+ }+ context.workflowMemberFingerprints.set(memberTaskId, fingerprint);+ const stamp = yield* makeEventStamp();+ yield* offerRuntimeEvent({+ ...base,+ eventId: stamp.eventId,+ createdAt: stamp.createdAt,+ type: "task.progress",+ payload: {+ taskId: RuntimeTaskId.make(memberTaskId),+ description: entry.label ?? `agent ${entry.index}`,+ status,+ ...(entry.error ? { error: entry.error } : {}),+ ...(entry.label ? { title: entry.label } : {}),+ ...(entry.model ? { model: entry.model } : {}),+ ...(entry.lastToolName ? { lastToolName: entry.lastToolName } : {}),+ ...(entry.tokens !== undefined+ ? {+ typedUsage: {+ totalTokens: entry.tokens,+ ...(entry.toolCalls !== undefined ? { toolUses: entry.toolCalls } : {}),+ },+ }+ : {}),+ parentAgentId: coordinatorId,+ agentIndex: entry.index,+ ...(entry.phaseIndex !== undefined ? { phaseIndex: entry.phaseIndex } : {}),+ ...(entry.phaseTitle ? { phaseTitle: entry.phaseTitle } : {}),+ ...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),+ timelineBypass: true,+ },+ });+ }+ });+const handleSystemMessage = Effect.fn("handleSystemMessage")(function* (context: ClaudeSessionContext,message: SDKMessage,@@ -2678,7 +3119,46 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (},});return;- case "task_started":+ case "task_started": {+ // A task launched by a tool that itself ran inside a subagent (the+ // in-flight tool carries agentId from parent_tool_use_id) is+ // agent-internal: a subagent's background shell, not parent work.+ const launchingTool = message.tool_use_id+ ? Array.from(context.inFlightTools.values()).find(+ (tool) => tool.itemId === message.tool_use_id,+ )+ : undefined;+ const owningAgentId = launchingTool?.agentId;+ // Model/effort: the Agent tool's input carries explicit overrides;+ // absent ones inherit the session's selection (SDK behavior).+ // Subagent assistant snapshots later refine model with the+ // authoritative API id. AgentInput.effort may be a named level or an+ // integer.+ const launchInput = launchingTool?.input;+ const model =+ trimmedString(launchInput?.model) ?? trimmedString(context.session.model ?? undefined);+ const rawLaunchEffort = launchInput?.effort;+ const effort =+ trimmedString(rawLaunchEffort) ??+ (typeof rawLaunchEffort === "number" && Number.isFinite(rawLaunchEffort)+ ? String(rawLaunchEffort)+ : context.currentEffort);+ // Remember the agent identity so every later task.* payload for this+ // taskId is self-describing (identity must survive activity retention).+ context.taskAgents.set(message.task_id, {+ taskId: message.task_id,+ toolUseId: message.tool_use_id,+ description: message.description,+ subagentType: message.subagent_type,+ taskType: message.task_type,+ workflowName: message.workflow_name,+ skipTranscript: message.skip_transcript === true,+ runHandles: context.taskAgents.get(message.task_id)?.runHandles,+ owningAgentId,+ model,+ effort,+ });+ context.liveTaskIds.add(message.task_id);yield* offerRuntimeEvent({...base,type: "task.started",@@ -2686,10 +3166,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (taskId: RuntimeTaskId.make(message.task_id),description: message.description,...(message.task_type ? { taskType: message.task_type } : {}),+ ...(owningAgentId ? { agentId: owningAgentId } : {}),+ ...(message.description ? { title: message.description } : {}),+ ...(message.subagent_type ? { role: message.subagent_type } : {}),+ ...(model ? { model } : {}),+ ...(effort ? { effort } : {}),+ ...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),+ ...(message.workflow_name ? { workflowName: message.workflow_name } : {}),},});return;- case "task_progress":+ }+ case "task_progress": {yield* emitThreadTokenUsage(context,normalizeClaudeTaskProgressTokenUsage(message.usage, context),@@ -2698,6 +3186,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (rawPayload: message,},);+ const linkage = taskLinkageFor(context.taskAgents, message.task_id);+ const typedUsage = normalizeTaskUsage(message.usage);+ // Phases ride on the coordinator's ONE progress row per tick. A+ // separate phases-only row shared the stable ingestion activity id+ // with this full row, and the thinner upsert overwrote usage and+ // progress text (review finding).+ const workflowPhases = parseWorkflowProgress(+ (message as unknown as Record<string, unknown>).workflow_progress,+ )?.phases;yield* offerRuntimeEvent({...base,type: "task.progress",@@ -2706,16 +3203,48 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (description: message.description,...(message.summary ? { summary: message.summary } : {}),...(message.usage ? { usage: message.usage } : {}),+ ...(typedUsage ? { typedUsage } : {}),...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),+ ...(workflowPhases && workflowPhases.length > 0 ? { phases: workflowPhases } : {}),+ ...linkage,+ ...(message.subagent_type ? { role: message.subagent_type } : {}),},});+ yield* emitWorkflowMemberProgress(context, base, message);return;- // Task state patch (status/backgrounded/end_time). No runtime mapping- // yet — the terminal task_notification reports the outcome — but it- // must not surface as an unknown-subtype warning row.- case "task_updated":+ }+ case "task_updated": {+ // Status patch (killed/paused/backgrounded/end_time/error) — main+ // previously dropped this on the floor, losing all transitions.+ const patch = message.patch;+ const status =+ patch.status !== undefined ? CLAUDE_TASK_PATCH_STATUS[patch.status] : undefined;+ if (status === "completed" || status === "failed" || status === "cancelled") {+ context.liveTaskIds.delete(message.task_id);+ }+ const endedAt =+ typeof patch.end_time === "number" && Number.isFinite(patch.end_time)+ ? DateTime.formatIso(DateTime.makeUnsafe(patch.end_time))+ : undefined;+ yield* offerRuntimeEvent({+ ...base,+ type: "task.updated",+ payload: {+ taskId: RuntimeTaskId.make(message.task_id),+ ...(status ? { status } : {}),+ ...(patch.description ? { description: patch.description } : {}),+ ...(patch.error ? { error: patch.error } : {}),+ ...(endedAt ? { endedAt } : {}),+ ...(patch.is_backgrounded !== undefined+ ? { isBackgrounded: patch.is_backgrounded }+ : {}),+ ...taskLinkageFor(context.taskAgents, message.task_id),+ },+ });return;- case "task_notification":+ }+ case "task_notification": {+ context.liveTaskIds.delete(message.task_id);yield* emitThreadTokenUsage(context,normalizeClaudeTaskProgressTokenUsage(message.usage, context),@@ -2724,6 +3253,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (rawPayload: message,},);+ const typedUsage = normalizeTaskUsage(message.usage);yield* offerRuntimeEvent({...base,type: "task.completed",@@ -2732,9 +3262,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (status: message.status,...(message.summary ? { summary: message.summary } : {}),...(message.usage ? { usage: message.usage } : {}),+ ...(typedUsage ? { typedUsage } : {}),+ ...(message.output_file ? { outputFile: message.output_file } : {}),+ ...taskLinkageFor(context.taskAgents, message.task_id),},});return;+ }case "files_persisted":yield* offerRuntimeEvent({...base,@@ -2870,7 +3404,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (toolUseId: message.tool_use_id,toolName: message.tool_name,elapsedSeconds: message.elapsed_time_seconds,- ...(message.task_id ? { summary: `task:${message.task_id}` } : {}),+ ...(message.task_id ? { taskId: RuntimeTaskId.make(message.task_id) } : {}),+ ...(message.parent_tool_use_id !== null+ ? { parentToolUseId: message.parent_tool_use_id }+ : {}),},});return;@@ -3192,6 +3729,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();const inFlightTools = new Map<number, ToolInFlight>();const claudeTasks = new Map<string, ClaudeTaskState>();+ const taskAgents = new Map<string, ClaudeTaskAgentState>();+ const workflowMemberFingerprints = new Map<string, string>();+ const liveTaskIds = new Set<string>();const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);@@ -3628,12 +4168,16 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (startedAt,basePermissionMode: permissionMode,currentApiModelId: apiModelId,+ currentEffort: effectiveEffort ?? undefined,resumeSessionId: sessionId,pendingApprovals,pendingUserInputs,turns: [],inFlightTools,claudeTasks,+ taskAgents,+ workflowMemberFingerprints,+ liveTaskIds,turnState: undefined,lastKnownContextWindow: initialContextWindow,lastKnownTokenUsage: undefined,@@ -3750,6 +4294,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (...context.session,model: modelSelection.model,};+ const turnCaps = getClaudeModelCapabilities(modelSelection.model);+ const turnEffort = resolveClaudeEffort(+ turnCaps,+ getModelSelectionStringOptionValue(modelSelection, "effort"),+ );+ context.currentEffort =+ getEffectiveClaudeAgentEffort(turnEffort ?? null, modelSelection.model) ?? undefined;}// Apply interaction mode by switching the SDK's permission mode.@@ -3825,6 +4376,29 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(function* (threadId, _turnId) {const context = yield* requireSession(threadId);+ // Stop-everything semantics: users reach for Stop precisely when a+ // fleet ran away. interrupt() alone only ends the parent turn —+ // background subagents/shells keep running and keep burning tokens.+ // Stop every live task first (best-effort per task: one refusal must+ // not strand the rest or block the turn interrupt), then interrupt.+ if (context.query.stopTask && context.liveTaskIds.size > 0) {+ const liveIds = Array.from(context.liveTaskIds);+ // Bounded: a wedged child's stopTask promise may never settle+ // (Effect.ignore handles rejection, not non-resolution), and the+ // parent interrupt below MUST still run — Stop matters most during+ // runaway fleets (review finding). Per-task timeout keeps one hung+ // child from consuming the whole budget.+ yield* Effect.forEach(+ liveIds,+ (taskId) =>+ Effect.tryPromise({+ // Invoke through the query object: SDK methods rely on `this`.+ try: () => context.query.stopTask!(taskId),+ catch: () => undefined,+ }).pipe(Effect.timeoutOption("3 seconds"), Effect.ignore),+ { concurrency: 8, discard: true },+ ).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);+ }yield* Effect.tryPromise({try: () => context.query.interrupt(),catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.tsindex 4146121b1..6b99bf52b 100644--- a/apps/server/src/provider/Layers/CodexAdapter.ts+++ b/apps/server/src/provider/Layers/CodexAdapter.ts@@ -20,6 +20,8 @@ import {type ProviderUserInputAnswers,RuntimeItemId,RuntimeRequestId,+ RuntimeTaskId,+ type RuntimeTaskUsage,ProviderApprovalDecision,ThreadId,ProviderSendTurnInput,@@ -494,10 +496,276 @@ function mapItemLifecycle(};}+/**+ * Maps the session runtime's synthetic `collabAgent/*` events (native+ * multi-agent v2 child-thread signals) into the shared task.* lifecycle.+ * Agent identity = child thread id; nickname is the display title, role is+ * agentRole (fallback: last agentPath segment, then "general-purpose").+ * A completed child turn is idle (resumable), not terminal. timelineBypass+ * keeps these rows out of the parent chat.+ */+function mapCollabAgentEvent(+ event: ProviderEvent,+ canonicalThreadId: ThreadId,+): ReadonlyArray<ProviderRuntimeEvent> {+ const payload =+ typeof event.payload === "object" && event.payload !== null+ ? (event.payload as Record<string, unknown>)+ : undefined;+ const agentThreadId = typeof payload?.agentThreadId === "string" ? payload.agentThreadId : "";+ if (!payload || agentThreadId.length === 0) {+ return [];+ }+ const base = runtimeEventBase(event, canonicalThreadId);+ const taskId = RuntimeTaskId.make(agentThreadId);+ const agentPath = typeof payload.agentPath === "string" ? payload.agentPath : undefined;+ const pathLeaf = agentPath?.split("/").findLast((segment) => segment.length > 0);+ const nickname = typeof payload.nickname === "string" ? payload.nickname : undefined;+ const role =+ (typeof payload.role === "string" ? payload.role : undefined) ?? pathLeaf ?? "general-purpose";+ // A bare thread id is not a name. Omitting the title lets the client fold+ // keep the real one from task.started instead of clobbering it (probe+ // finding: progress rows renamed math_one to its UUID).+ const knownName = nickname ?? pathLeaf;+ const title = knownName ?? agentThreadId;+ // Identity repeated on every status patch so rows are self-describing when+ // the start row ages out of activity retention (review finding: a+ // reconstructed agent had a UUID name and no role/path).+ const statusLinkage = {+ role,+ ...(knownName ? { title: knownName } : {}),+ ...(agentPath ? { agentPath } : {}),+ timelineBypass: true,+ } as const;++ switch (event.method) {+ case "collabAgent/started":+ return [+ {+ ...base,+ type: "task.started",+ payload: {+ taskId,+ description: title,+ title,+ role,+ ...(agentPath ? { agentPath } : {}),+ ...(typeof payload.parentThreadId === "string"+ ? { parentAgentId: payload.parentThreadId }+ : {}),+ timelineBypass: true,+ },+ },+ ];+ case "collabAgent/activity": {+ const activityKind = typeof payload.activityKind === "string" ? payload.activityKind : "";+ if (activityKind === "interrupted") {+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: "interrupted", ...statusLinkage },+ },+ ];+ }+ if (activityKind === "started") {+ // Wire-probe finding: children often register via subAgentActivity+ // alone (no thread/started with a spawn source), so this is the one+ // shot at a task.started with a real name — agentPath leaf beats a+ // bare thread-id title.+ return [+ {+ ...base,+ type: "task.started",+ payload: {+ taskId,+ description: title,+ title,+ role,+ ...(agentPath ? { agentPath } : {}),+ timelineBypass: true,+ },+ },+ ];+ }+ // interacted → the child is (again) actively driven.+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: "running", ...statusLinkage },+ },+ ];+ }+ case "collabAgent/turnStarted":+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: "running", ...statusLinkage },+ },+ ];+ case "collabAgent/turnCompleted": {+ // Idle, not terminal: the identity is resumable via sendInput/resume.+ const turn =+ typeof payload.turn === "object" && payload.turn !== null+ ? (payload.turn as Record<string, unknown>)+ : undefined;+ const turnStatus = typeof turn?.status === "string" ? turn.status : undefined;+ const status =+ turnStatus === "failed"+ ? ("failed" as const)+ : turnStatus === "interrupted"+ ? ("interrupted" as const)+ : ("idle" as const);+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status, ...statusLinkage },+ },+ ];+ }+ case "collabAgent/statusChanged": {+ const status =+ typeof payload.status === "object" && payload.status !== null+ ? (payload.status as Record<string, unknown>)+ : undefined;+ const statusType = typeof status?.type === "string" ? status.type : undefined;+ if (statusType === "systemError") {+ // Silently dropping this once left children stuck running forever.+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: "failed", ...statusLinkage },+ },+ ];+ }+ if (statusType === "active") {+ const flags = Array.isArray(status?.activeFlags) ? status.activeFlags : [];+ const waiting = flags.some(+ (flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput",+ );+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: waiting ? "waiting" : "running", ...statusLinkage },+ },+ ];+ }+ if (statusType === "idle") {+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: "idle", ...statusLinkage },+ },+ ];+ }+ return [];+ }+ case "collabAgent/tokenUsage": {+ // Cumulative per child thread: always the `total` breakdown, never+ // `last` (which shrinks on follow-ups). Client folds max-merge.+ const tokenUsage =+ typeof payload.tokenUsage === "object" && payload.tokenUsage !== null+ ? (payload.tokenUsage as Record<string, unknown>)+ : undefined;+ const total =+ typeof tokenUsage?.total === "object" && tokenUsage.total !== null+ ? (tokenUsage.total as Record<string, unknown>)+ : undefined;+ const count = (value: unknown): number | undefined =>+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;+ // Same validation as every other field: RuntimeTaskUsage.totalTokens+ // is NonNegativeInt, so NaN/Infinity/negative wire values must miss.+ const totalTokens = count(total?.totalTokens);+ if (totalTokens === undefined) {+ return [];+ }+ const typedUsage: RuntimeTaskUsage = {+ totalTokens,+ ...(count(total?.inputTokens) !== undefined+ ? { inputTokens: count(total?.inputTokens) }+ : {}),+ ...(count(total?.cachedInputTokens) !== undefined+ ? { cachedInputTokens: count(total?.cachedInputTokens) }+ : {}),+ ...(count(total?.outputTokens) !== undefined+ ? { outputTokens: count(total?.outputTokens) }+ : {}),+ ...(count(total?.reasoningOutputTokens) !== undefined+ ? { reasoningOutputTokens: count(total?.reasoningOutputTokens) }+ : {}),+ };+ return [+ {+ ...base,+ type: "task.progress",+ payload: {+ taskId,+ description: title,+ ...(knownName ? { title: knownName } : {}),+ typedUsage,+ timelineBypass: true,+ },+ },+ ];+ }+ case "collabAgent/item": {+ const item =+ typeof payload.item === "object" && payload.item !== null+ ? (payload.item as Record<string, unknown>)+ : undefined;+ const itemTypeRaw = typeof item?.type === "string" ? item.type : undefined;+ if (!itemTypeRaw) {+ return [];+ }+ // A loose summary from the raw item: the child stream is untyped at+ // this boundary (synthetic event payload), so read best-effort fields+ // rather than force a schema decode.+ const looseSummary =+ (typeof item?.command === "string" ? item.command : undefined) ??+ (typeof item?.title === "string" ? item.title : undefined) ??+ (typeof item?.query === "string" ? item.query : undefined);+ const canonical = toCanonicalItemType(itemTypeRaw);+ const summary = looseSummary ?? canonical.replaceAll("_", " ");+ return [+ {+ ...base,+ type: "task.progress",+ payload: {+ taskId,+ description: title,+ ...(knownName ? { title: knownName } : {}),+ summary,+ timelineBypass: true,+ },+ },+ ];+ }+ case "collabAgent/closed":+ return [+ {+ ...base,+ type: "task.updated",+ payload: { taskId, status: "interrupted", ...statusLinkage },+ },+ ];+ default:+ return [];+ }+}+function mapToRuntimeEvents(event: ProviderEvent,canonicalThreadId: ThreadId,): ReadonlyArray<ProviderRuntimeEvent> {+ if (event.kind === "notification" && event.method.startsWith("collabAgent/")) {+ return mapCollabAgentEvent(event, canonicalThreadId);+ }if (event.kind === "error") {if (!event.message) {return [];diff --git a/apps/server/src/provider/Layers/CodexCollabRuntime.integration.test.ts b/apps/server/src/provider/Layers/CodexCollabRuntime.integration.test.tsnew file mode 100644index 000000000..3a02c45b2--- /dev/null+++ b/apps/server/src/provider/Layers/CodexCollabRuntime.integration.test.ts@@ -0,0 +1,248 @@+/**+ * Runtime-level collab regression: boots the REAL CodexSessionRuntime against+ * a scripted mock app-server peer that replays the captured multi-agent wire+ * sequence (codexMultiAgentWire.json) plus the shapes the capture alone can't+ * script (receiver-turn bookkeeping via collabAgentToolCall, child terminal+ * lifecycle, approval pass-through). This is the layer the pure routing-table+ * test can't reach: ordering between the legacy receiver-turn suppressor and+ * v2 interception, registration state, and synthetic event emission.+ */+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFS from "node:fs";+import * as NodePath from "node:path";++import * as NodeServices from "@effect/platform-node/NodeServices";+import { it } from "@effect/vitest";+import { ThreadId } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as Stream from "effect/Stream";+import { assert, describe } from "vite-plus/test";++import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };+import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";++const ROOT = wireFixture.rootThreadId;+const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];++/**+ * The captured sequence, extended with the shapes the live capture didn't+ * include: a collabAgentToolCall with receiverThreadIds (feeds the legacy+ * receiver-turn map, so ordering vs. v2 interception is exercised), child+ * terminal lifecycle, and a serverRequest/resolved addressed to a child+ * (must pass through to the parent path, not vanish).+ */+function buildScript() {+ const captured = wireFixture.notifications;+ const extras = [+ {+ method: "item/completed",+ params: {+ threadId: ROOT,+ item: {+ type: "collabAgentToolCall",+ id: "call_fixture_wait",+ tool: "wait",+ status: "completed",+ senderThreadId: ROOT,+ receiverThreadIds: [CHILD_A, CHILD_B],+ },+ },+ },+ // Child terminal lifecycle AFTER the receiver map knows the children —+ // pre-fix, the legacy suppressor dropped these before interception saw+ // them, so no synthetic agent events were emitted.+ {+ method: "turn/completed",+ params: {+ threadId: CHILD_A,+ turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },+ },+ },+ { method: "thread/closed", params: { threadId: CHILD_B } },+ // Parent-owned traffic addressed to a child conversation: must reach the+ // parent path (approval correlation cleanup), not be swallowed.+ { method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },+ ];+ return {+ rootThreadId: ROOT,+ notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],+ };+}++const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");+const peerPath = NodePath.join(import.meta.dirname, "../testFixtures/codexCollabMockPeer.sh");++describe("CodexSessionRuntime collab integration", () => {+ it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>+ Effect.gen(function* () {+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),+ );++ const runtime = yield* makeCodexSessionRuntime({+ threadId: ThreadId.make("thread-collab-integration"),+ binaryPath: peerPath,+ cwd: "/tmp",+ runtimeMode: "full-access",+ environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },+ });++ const eventsFiber = yield* runtime.events.pipe(+ Stream.takeUntil((event) => event.method === "turn/completed"),+ Stream.runCollect,+ Effect.forkScoped,+ );++ yield* runtime.start();+ yield* runtime.sendTurn({ input: "fan out" });++ const events = Array.from(yield* Fiber.join(eventsFiber));+ const methods = events.map((event) => event.method);++ // Children registered from subAgentActivity become synthetic agent+ // lifecycle — including terminal rows that arrive AFTER the receiver+ // map knows them (the ordering this test exists to pin).+ assert.include(methods, "collabAgent/activity");+ assert.include(methods, "collabAgent/turnCompleted");+ assert.include(methods, "collabAgent/closed");++ const childTurnCompleted = events.find(+ (event) =>+ event.method === "collabAgent/turnCompleted" &&+ (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,+ );+ assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");++ const childClosed = events.find(+ (event) =>+ event.method === "collabAgent/closed" &&+ (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,+ );+ assert.isDefined(childClosed, "child B's close becomes an agent event");++ // Parent-owned resolution passes through — not swallowed, not+ // re-labelled as an agent event.+ assert.include(methods, "serverRequest/resolved");++ // The root's own subAgentActivity about "/root" must NOT register the+ // root as a child: the parent turn completion still flows.+ assert.include(methods, "turn/completed");++ // No raw child conversation methods leak onto the parent stream.+ const leaked = events.filter((event) => {+ const payload = event.payload as { threadId?: string } | undefined;+ const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;+ return addressedToChild && (event.method?.startsWith("thread/") ?? false);+ });+ assert.deepEqual(+ leaked.map((event) => event.method),+ [],+ "child thread/* lifecycle must not appear as parent events",+ );++ yield* runtime.close;+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ // it.live: the runtime talks to a real child process; under it.effect's+ // TestClock the internal timers freeze and the join never completes.+ it.live("Stop interrupts every live child regardless of registration timing", () =>+ Effect.gen(function* () {+ // Ordering + liveness torture for stop-everything: child A's+ // turn/started arrives BEFORE anything registers it (foreign+ // suppression path must record the live turn); child B's arrives after+ // registration; child A's interrupt HANGS (RPC never settles — worse+ // than rejecting) and the bounded deadline must still deliver B's and+ // the parent's interrupts. The turn stays open so children are live+ // when Stop fires.+ // Build from REAL captured rows (hand-written shapes fail notification+ // schema validation and are silently dropped): reorder so child A's+ // turn/started precedes its registration, and drop terminal rows so+ // children stay live when Stop fires.+ const byIndex = wireFixture.notifications;+ const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>+ entry.method === "turn/started" &&+ (entry.params as { threadId?: string }).threadId === child;+ const isRegistration = (entry: (typeof byIndex)[number], child: string) => {+ const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;+ return item?.type === "subAgentActivity" && item.agentThreadId === child;+ };+ const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));+ const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));+ const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));+ const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));+ assert.isDefined(turnStartedA);+ assert.isDefined(turnStartedB);+ assert.isDefined(registrationA);+ assert.isDefined(registrationB);+ const script = {+ rootThreadId: ROOT,+ holdTurnOpen: true,+ hangInterruptFor: CHILD_A,+ notifications: [turnStartedA, registrationA, registrationB, turnStartedB],+ };+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");+ const interruptsPath = `${scriptPath}.interrupts`;+ NodeFS.rmSync(interruptsPath, { force: true });+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ NodeFS.rmSync(scriptPath, { force: true });+ NodeFS.rmSync(interruptsPath, { force: true });+ }),+ );++ const runtime = yield* makeCodexSessionRuntime({+ threadId: ThreadId.make("thread-collab-stop"),+ binaryPath: peerPath,+ cwd: "/tmp",+ runtimeMode: "full-access",+ environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },+ });++ // Wait for both children's turnStarted signals to be processed before+ // stopping (B via the registered-child path; A only produces live-turn+ // bookkeeping, so key on B's synthetic event).+ const childBStartedFiber = yield* runtime.events.pipe(+ Stream.filter(+ (event) =>+ event.method === "collabAgent/turnStarted" &&+ (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,+ ),+ Stream.take(1),+ Stream.runCollect,+ Effect.forkScoped,+ );++ yield* runtime.start();+ yield* runtime.sendTurn({ input: "fan out and hang" });+ const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(+ Effect.timeoutOption("15 seconds"),+ );+ assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");++ // Stop everything. A's interrupt hangs forever — the bounded child+ // deadline must expire and the parent interrupt must still be sent.+ yield* runtime.interruptTurn();++ const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };+ const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")+ .trim()+ .split("\n")+ .filter((line) => line.length > 0)+ .map(parseInterruptLine);+ const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));+ assert.isTrue(+ interruptedThreads.has(CHILD_A),+ "pre-registration child A must still receive the interrupt RPC",+ );+ assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");+ assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");++ yield* runtime.close;+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+});diff --git a/apps/server/src/provider/Layers/CodexCollabWire.test.ts b/apps/server/src/provider/Layers/CodexCollabWire.test.tsnew file mode 100644index 000000000..50e5e819d--- /dev/null+++ b/apps/server/src/provider/Layers/CodexCollabWire.test.ts@@ -0,0 +1,180 @@+/**+ * Codex multi-agent wire fixtures.+ *+ * The child-interception path is the highest-blast-radius code in the+ * subagent stack: it decides, per notification, whether traffic reaches the+ * parent timeline at all. Three shipped bugs came from that decision being+ * implicit (root thread registered as its own child; `error` and+ * `serverRequest/resolved` swallowed by a catch-all). These tests pin the+ * decision against a REAL capture rather than hand-written shapes.+ *+ * Fixture provenance: codex-cli 0.145.0 driven directly over stdio with+ * gpt-5.6-luna at low effort, prompting a two-child fan-out (alpha, beta).+ * See codexMultiAgentWire.json.+ */+import { assert, describe, it } from "vite-plus/test";++import fixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };+import { routeCodexChildNotification } from "./CodexSessionRuntime.ts";++interface WireNotification {+ readonly method: string;+ readonly params: Record<string, unknown>;+}++const notifications = fixture.notifications as ReadonlyArray<WireNotification>;+const rootThreadId = fixture.rootThreadId;+const childThreadIds = new Set(fixture.childThreadIds);++/** Mirrors readNotificationThreadId's addressing for the captured methods. */+function notificationThreadId(entry: WireNotification): string | undefined {+ const params = entry.params;+ const thread = params.thread;+ if (+ typeof thread === "object" &&+ thread !== null &&+ typeof (thread as { id?: unknown }).id === "string"+ ) {+ return (thread as { id: string }).id;+ }+ return typeof params.threadId === "string" ? params.threadId : undefined;+}++function subAgentActivityItems(): ReadonlyArray<Record<string, unknown>> {+ return notifications.flatMap((entry) => {+ const item = entry.params.item;+ if (typeof item !== "object" || item === null) return [];+ const record = item as Record<string, unknown>;+ return record.type === "subAgentActivity" ? [record] : [];+ });+}++describe("codex multi-agent wire capture", () => {+ it("captures a real two-child fan-out", () => {+ assert.equal(fixture.capturedWith.model, "gpt-5.6-luna");+ assert.equal(childThreadIds.size, 2);+ const paths = subAgentActivityItems().map((item) => item.agentPath);+ assert.include(paths, "/root/alpha");+ assert.include(paths, "/root/beta");+ });++ it("emits child traffic BEFORE the item that registers the child", () => {+ // Ordering hazard: the child's own thread/status/changed arrives before+ // the parent-side subAgentActivity naming it. Registration must tolerate+ // child-first arrival, so unregistered child traffic passes through+ // rather than being eaten (no regression vs. pre-feature behavior).+ const firstChildTraffic = notifications.findIndex((entry) => {+ const threadId = notificationThreadId(entry);+ return threadId !== undefined && childThreadIds.has(threadId);+ });+ const firstRegistration = notifications.findIndex((entry) => {+ const item = entry.params.item;+ if (typeof item !== "object" || item === null) return false;+ const record = item as Record<string, unknown>;+ return record.type === "subAgentActivity" && record.kind === "started";+ });+ assert.isAtLeast(firstChildTraffic, 0);+ assert.isAtLeast(firstRegistration, 0);+ assert.isBelow(+ firstChildTraffic,+ firstRegistration,+ "capture should exercise child-first ordering",+ );+ });++ it("contains a /root self-activity emitted from a CHILD thread", () => {+ // The bug this guards: the wire reports subAgentActivity about the ROOT+ // (agentPath "/root"). Registering it made the runtime intercept the+ // parent's own final message and turn/completed, so the thread hung+ // "working" forever. The root guard must key on agentPath/thread id,+ // never on which thread the notification arrived from.+ const rootSelfActivity = subAgentActivityItems().find((item) => item.agentPath === "/root");+ assert.isDefined(rootSelfActivity, "capture should contain a /root self-activity");+ assert.equal(rootSelfActivity?.agentThreadId, rootThreadId);+ });++ it("routes every captured child method to a defined disposition", () => {+ const childMethods = new Set(+ notifications+ .filter((entry) => {+ const threadId = notificationThreadId(entry);+ return threadId !== undefined && childThreadIds.has(threadId);+ })+ .map((entry) => entry.method),+ );+ assert.isAbove(childMethods.size, 0);+ for (const method of childMethods) {+ const route = routeCodexChildNotification(method);+ // Child lifecycle traffic must become agent events — never silently+ // dropped, never leaked to the parent timeline.+ assert.equal(route, "agent-event", `${method} should map to an agent event`);+ }+ });+});++describe("routeCodexChildNotification", () => {+ it("maps child lifecycle to agent events", () => {+ for (const method of [+ "turn/started",+ "turn/completed",+ "thread/status/changed",+ "thread/tokenUsage/updated",+ "item/started",+ "item/completed",+ "thread/closed",+ "error",+ ]) {+ assert.equal(routeCodexChildNotification(method), "agent-event", method);+ }+ });++ it("drops only enumerated child chatter", () => {+ for (const method of [+ "item/agentMessage/delta",+ "item/reasoning/textDelta",+ "item/commandExecution/outputDelta",+ "turn/plan/updated",+ "thread/name/updated",+ ]) {+ assert.equal(routeCodexChildNotification(method), "drop", method);+ }+ });++ it("never routes child-owned thread lifecycle to the parent", () => {+ // These mutate PARENT thread state in CodexAdapter (archived/compacted),+ // so a child emitting them must never reach the parent path. This list+ // mirrors shouldSuppressChildConversationNotification (the v1 collab+ // suppressor) — the two must not drift (review finding: the router+ // initially omitted them and they leaked).+ for (const method of [+ "thread/started",+ "thread/status/changed",+ "thread/archived",+ "thread/unarchived",+ "thread/closed",+ "thread/compacted",+ "thread/name/updated",+ "thread/tokenUsage/updated",+ "turn/started",+ "turn/completed",+ "turn/plan/updated",+ "item/plan/delta",+ ]) {+ assert.notEqual(+ routeCodexChildNotification(method),+ "parent",+ `${method} is child-owned and must not reach the parent path`,+ );+ }+ });++ it("sends parent-owned and UNKNOWN methods to the parent path", () => {+ // serverRequest/resolved clears the parent's approval correlation:+ // swallowing it left approvals stuck (shipped bug). Unknown methods take+ // the same route by design — a codex update that adds a notification+ // must degrade to "parent sees it", never to silent loss.+ assert.equal(routeCodexChildNotification("serverRequest/resolved"), "parent");+ assert.equal(routeCodexChildNotification("thread/somethingBrandNew"), "parent");+ assert.equal(routeCodexChildNotification("account/rateLimits/updated"), "parent");+ });+});diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.tsindex 67108dd4d..57a1162dd 100644--- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts+++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts@@ -600,6 +600,71 @@ function readRouteFields(notification: CodexServerNotification): {}}+/**+ * Native collab child-agent tracking (multi-agent v2). Under v2 subagents are+ * full app-server threads: identity arrives on `thread/started` with+ * source.subAgent.thread_spawn, lifecycle on `subAgentActivity` items and the+ * child thread's own turn/status/tokenUsage notifications. The runtime+ * registers children from those explicit signals, intercepts their+ * notifications before parent-timeline mapping, and re-emits them as+ * synthetic `collabAgent/*` provider events the adapter turns into task.*+ * runtime events (timelineBypass keeps them out of the parent chat).+ *+ * WIP, probe-gated: registration is deliberately explicit-signals-only. The+ * spec's "provisionally treat unknown foreign thread ids as v2 children" rule+ * needs a live wire capture of the packaged binary before it lands — blind+ * capture risks eating unrelated traffic. Until then a child whose first+ * notification precedes registration passes through as today (no regression+ * vs main, which passes everything through).+ */+interface CollabChildAgentState {+ readonly agentThreadId: string;+ readonly nickname: string | undefined;+ readonly role: string | undefined;+ readonly agentPath: string | undefined;+ readonly depth: number | undefined;+ readonly parentThreadId: string | undefined;+ /**+ * Parent canonical turn active when the child registered. Stamped on every+ * synthetic collabAgent/* event so clients can batch a fleet by its spawn+ * turn — without it, separate fleets in one thread collapsed into a single+ * "direct:no-turn" CTA (review finding).+ */+ readonly spawnTurnId: TurnId | undefined;+}++function readThreadSpawnSource(thread: { readonly source: unknown }):+ | {+ nickname: string | undefined;+ role: string | undefined;+ agentPath: string | undefined;+ depth: number | undefined;+ parentThreadId: string | undefined;+ }+ | undefined {+ const source = thread.source;+ if (typeof source !== "object" || source === null || !("subAgent" in source)) {+ return undefined;+ }+ const subAgent = (source as { subAgent: unknown }).subAgent;+ if (typeof subAgent !== "object" || subAgent === null || !("thread_spawn" in subAgent)) {+ return undefined;+ }+ const spawn = (subAgent as { thread_spawn: unknown }).thread_spawn;+ if (typeof spawn !== "object" || spawn === null) {+ return undefined;+ }+ const record = spawn as Record<string, unknown>;+ return {+ nickname: typeof record.agent_nickname === "string" ? record.agent_nickname : undefined,+ role: typeof record.agent_role === "string" ? record.agent_role : undefined,+ agentPath: typeof record.agent_path === "string" ? record.agent_path : undefined,+ depth: typeof record.depth === "number" ? record.depth : undefined,+ parentThreadId:+ typeof record.parent_thread_id === "string" ? record.parent_thread_id : undefined,+ };+}+function rememberCollabReceiverTurns(collabReceiverTurns: Map<string, TurnId>,notification: CodexServerNotification,@@ -641,6 +706,72 @@ function shouldSuppressChildConversationNotification();}+/**+ * How a notification addressed to a REGISTERED child thread is handled.+ *+ * Exported and pure so the routing table can be asserted against captured+ * wire traces (see codexMultiAgentWire.json) rather than only read.+ *+ * - "agent-event": map to a synthetic collabAgent/* event (Agents surface).+ * - "parent": pass through to the parent path — it carries state the parent+ * still owns (approval correlation cleanup).+ * - "drop": genuine child chatter with no parent meaning (deltas, name and+ * plan updates).+ *+ * Default is "drop" ONLY for the enumerated chatter; anything unrecognized+ * routes to "parent" so new wire methods surface instead of vanishing+ * (two shipped bugs came from a catch-all that swallowed everything).+ */+export type CodexChildNotificationRoute = "agent-event" | "parent" | "drop";++const CHILD_AGENT_EVENT_METHODS: ReadonlySet<string> = new Set([+ "turn/started",+ "turn/completed",+ "thread/status/changed",+ "thread/tokenUsage/updated",+ "item/started",+ "item/completed",+ "thread/closed",+ "error",+]);++const CHILD_CHATTER_METHODS: ReadonlySet<string> = new Set([+ "item/agentMessage/delta",+ "item/reasoning/textDelta",+ "item/reasoning/summaryTextDelta",+ "item/reasoning/summaryPartAdded",+ "item/commandExecution/outputDelta",+ "item/fileChange/outputDelta",+ "item/fileChange/patchUpdated",+ "item/plan/delta",+ "turn/plan/updated",+ "turn/diff/updated",+ "thread/name/updated",+ "thread/settings/updated",+ "rawResponseItem/completed",+ // Child-owned thread lifecycle: the parent adapter maps these onto the+ // PARENT thread (archived/compacted state), so a child compacting would+ // rewrite the parent. Mirrors the v1 suppressor list — dropping them is+ // the pre-existing behavior for collab children (review finding).+ "thread/archived",+ "thread/unarchived",+ "thread/compacted",+ // Registration path 1 handles a child's first thread/started; a repeat+ // must not reach the parent (it would restart the parent's thread state).+ "thread/started",+]);++export function routeCodexChildNotification(method: string): CodexChildNotificationRoute {+ if (CHILD_AGENT_EVENT_METHODS.has(method)) {+ return "agent-event";+ }+ if (CHILD_CHATTER_METHODS.has(method)) {+ return "drop";+ }+ // Unknown or parent-owned (serverRequest/resolved, approvals, …).+ return "parent";+}+function toCodexUserInputAnswer(questionId: string,value: ProviderUserInputAnswers[string],@@ -723,6 +854,9 @@ export const makeCodexSessionRuntime = (const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());+ const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());+ /** Child provider-thread id → its currently running provider turn id. */+ const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());const closedRef = yield* Ref.make(false);// `~` is not shell-expanded when env vars are set via@@ -839,6 +973,280 @@ export const makeCodexSessionRuntime = (),);+ /**+ * Registers v2 collab children and re-emits their notifications as+ * synthetic `collabAgent/*` events for the adapter's task.* synthesis.+ * Returns true when the notification was fully handled (must not reach+ * parent-timeline mapping).+ */+ const interceptCollabChildNotification = (notification: CodexServerNotification) =>+ Effect.gen(function* () {+ // Registration path 1: child thread announces itself with a+ // subAgent thread_spawn source.+ if (notification.method === "thread/started") {+ const thread = notification.params.thread;+ const spawn = readThreadSpawnSource(thread);+ if (!spawn) {+ return false;+ }+ // Merge with any subAgentActivity registration that got here+ // first. spawnTurnId is REGISTRATION-time-only on both paths: for+ // an already-known child we keep its value (set or unset) — a+ // later thread/started during an unrelated parent turn must not+ // backfill that turn as the spawn batch, which would stamp an old+ // child onto a new fleet's CTA (review finding). Only a genuinely+ // new registration captures the current turn.+ const existingChild = (yield* Ref.get(collabChildAgentsRef)).get(thread.id);+ const spawnTurnId = existingChild+ ? existingChild.spawnTurnId+ : ((yield* Ref.get(sessionRef)).activeTurnId ?? undefined);+ const state: CollabChildAgentState = {+ agentThreadId: thread.id,+ nickname: spawn.nickname ?? thread.agentNickname ?? existingChild?.nickname,+ role: spawn.role ?? thread.agentRole ?? existingChild?.role,+ agentPath: spawn.agentPath ?? existingChild?.agentPath,+ depth: spawn.depth ?? existingChild?.depth,+ parentThreadId:+ spawn.parentThreadId ?? thread.parentThreadId ?? existingChild?.parentThreadId,+ spawnTurnId,+ };+ yield* Ref.update(collabChildAgentsRef, (current) => {+ const next = new Map(current);+ next.set(thread.id, state);+ return next;+ });+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ method: "collabAgent/started",+ ...(state.spawnTurnId ? { turnId: state.spawnTurnId } : {}),+ payload: {+ agentThreadId: state.agentThreadId,+ ...(state.nickname ? { nickname: state.nickname } : {}),+ ...(state.role ? { role: state.role } : {}),+ ...(state.agentPath ? { agentPath: state.agentPath } : {}),+ ...(state.depth !== undefined ? { depth: state.depth } : {}),+ ...(state.parentThreadId ? { parentThreadId: state.parentThreadId } : {}),+ },+ });+ return true;+ }++ // Registration path 2: parent-side subAgentActivity item names the+ // child thread (may arrive before or after thread/started).+ if (+ (notification.method === "item/started" || notification.method === "item/completed") &&+ notification.params.item.type === "subAgentActivity"+ ) {+ const item = notification.params.item;+ // Never register the session's ROOT thread as its own child. The+ // wire emits subAgentActivity {agentPath: "/root", interacted}+ // about the root during collab runs; registering it intercepted+ // every subsequent root notification — including the final+ // assistant message and turn/completed — so the thread hung+ // "working" after all subagents finished (live-probe finding).+ const rootProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));+ if (+ item.agentThreadId === rootProviderThreadId ||+ item.agentPath === "/root" ||+ item.agentPath === "/"+ ) {+ return false;+ }+ const activitySpawnTurnId = (yield* Ref.get(sessionRef)).activeTurnId ?? undefined;+ yield* Ref.update(collabChildAgentsRef, (current) => {+ const existing = current.get(item.agentThreadId);+ const next = new Map(current);+ // Merge-late semantics: when thread/started registered first, a+ // later subAgentActivity still carries the real agentPath (and a+ // derived nickname) — fill missing fields, never clobber known+ // ones. spawnTurnId is registration-time-only: for an already+ // registered child, a later activity during an UNRELATED turn+ // must not backfill that turn as the spawn batch (review+ // finding); an unset spawn turn stays unset.+ next.set(item.agentThreadId, {+ agentThreadId: item.agentThreadId,+ nickname:+ existing?.nickname ??+ item.agentPath.split("/").findLast((segment) => segment.length > 0),+ role: existing?.role,+ agentPath: existing?.agentPath ?? item.agentPath,+ depth: existing?.depth,+ parentThreadId: existing?.parentThreadId,+ spawnTurnId: existing ? existing.spawnTurnId : activitySpawnTurnId,+ });+ return next;+ });+ const registeredChild = (yield* Ref.get(collabChildAgentsRef)).get(item.agentThreadId);+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ method: "collabAgent/activity",+ ...(registeredChild?.spawnTurnId ? { turnId: registeredChild.spawnTurnId } : {}),+ payload: {+ agentThreadId: item.agentThreadId,+ agentPath: item.agentPath,+ activityKind: item.kind,+ },+ });+ return true;+ }++ // Interception: notifications addressed to a registered child thread+ // become agent-scoped synthetic events instead of parent chatter.+ const providerConversationId = readNotificationThreadId(notification);+ if (!providerConversationId) {+ return false;+ }+ // Belt-and-braces: the root thread's traffic must never be+ // intercepted, whatever the registry says.+ const interceptRootId = currentProviderThreadId(yield* Ref.get(sessionRef));+ if (providerConversationId === interceptRootId) {+ return false;+ }+ const children = yield* Ref.get(collabChildAgentsRef);+ const child = children.get(providerConversationId);+ if (!child) {+ return false;+ }+ const childIdentity = {+ agentThreadId: child.agentThreadId,+ ...(child.nickname ? { nickname: child.nickname } : {}),+ ...(child.role ? { role: child.role } : {}),+ ...(child.agentPath ? { agentPath: child.agentPath } : {}),+ };+ switch (notification.method) {+ case "turn/started": {+ const childTurnId =+ typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === "string"+ ? ((notification.params as { turn: { id: string } }).turn.id as string)+ : undefined;+ if (childTurnId) {+ yield* Ref.update(collabChildLiveTurnsRef, (current) => {+ const next = new Map(current);+ next.set(child.agentThreadId, childTurnId);+ return next;+ });+ }+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/turnStarted",+ payload: childIdentity,+ });+ return true;+ }+ case "turn/completed":+ yield* Ref.update(collabChildLiveTurnsRef, (current) => {+ const next = new Map(current);+ next.delete(child.agentThreadId);+ return next;+ });+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/turnCompleted",+ payload: {+ ...childIdentity,+ turn: notification.params.turn,+ },+ });+ return true;+ case "thread/status/changed":+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/statusChanged",+ payload: {+ ...childIdentity,+ status: notification.params.status,+ },+ });+ return true;+ case "thread/tokenUsage/updated":+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/tokenUsage",+ payload: {+ ...childIdentity,+ tokenUsage: notification.params.tokenUsage,+ },+ });+ return true;+ case "item/started":+ case "item/completed":+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/item",+ payload: {+ ...childIdentity,+ item: notification.params.item,+ },+ });+ return true;+ case "thread/closed":+ // The child is gone: drop its live-turn entry so a later Stop+ // doesn't waste a turn/interrupt RPC on a closed thread before+ // reaching the parent (review finding).+ yield* Ref.update(collabChildLiveTurnsRef, (current) => {+ const next = new Map(current);+ next.delete(child.agentThreadId);+ return next;+ });+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/closed",+ payload: childIdentity,+ });+ return true;+ case "error": {+ // A child error must surface as a failed agent, not vanish into+ // the default swallow (review finding: the child stayed+ // "running" forever). Retryable errors (willRetry) keep the+ // child RUNNING and interruptible — mirroring the root error+ // handler; settling it would orphan a still-live child from+ // Stop (review finding). Terminal errors clean up the live turn+ // like thread/closed and reuse the statusChanged systemError+ // path.+ const willRetry = (notification.params as { willRetry?: boolean }).willRetry === true;+ if (willRetry) {+ return true;+ }+ yield* Ref.update(collabChildLiveTurnsRef, (current) => {+ const next = new Map(current);+ next.delete(child.agentThreadId);+ return next;+ });+ yield* emitEvent({+ kind: "notification",+ threadId: options.threadId,+ ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),+ method: "collabAgent/statusChanged",+ payload: {+ ...childIdentity,+ status: { type: "systemError" },+ },+ });+ return true;+ }+ default:+ // Routing table decides (single source of truth, asserted+ // against captured wire traces): enumerated chatter is dropped,+ // everything else — including methods this build has never seen+ // — falls through to the parent path rather than vanishing.+ return routeCodexChildNotification(notification.method) === "drop";+ }+ });+const handleRawNotification = (notification: CodexServerNotification) =>Effect.gen(function* () {const payload = notification.params;@@ -852,7 +1260,68 @@ export const makeCodexSessionRuntime = (})();rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);- if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {+ // Interception FIRST: a registered v2 child is usually also in the+ // receiver-turn map (collabAgentToolCall.receiverThreadIds), and the+ // legacy suppressor below would drop its lifecycle before it could+ // become synthetic collabAgent events (review finding). The+ // suppressor still covers UNREGISTERED children.+ if (yield* interceptCollabChildNotification(notification)) {+ yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);+ return;+ }++ // Suppression applies to receiver-map children (v1) AND to any+ // conversation that is not the root thread. The live capture+ // (codexMultiAgentWire.json) shows a child's thread/status/changed+ // arriving BEFORE anything registers the child — pre-registration+ // lifecycle must not reach the parent path, where the adapter maps+ // thread/* onto parent session state. Root-id-known guard keeps the+ // root's own early notifications flowing during session open.+ const suppressRootId = currentProviderThreadId(yield* Ref.get(sessionRef));+ const foreignConversation = (() => {+ const providerConversationId = readNotificationThreadId(notification);+ return (+ providerConversationId !== undefined &&+ suppressRootId !== undefined &&+ providerConversationId !== suppressRootId+ );+ })();+ if (+ (childParentTurnId !== undefined || foreignConversation) &&+ shouldSuppressChildConversationNotification(notification.method)+ ) {+ // Stop-everything must not depend on registration timing: a+ // child's turn/started can arrive before the subAgentActivity that+ // registers it (captured ordering), and suppressing it without+ // remembering the live turn would leave that child running after+ // Stop (review finding). Track live turns for ANY foreign+ // conversation; interrupts are best-effort per child, so a+ // false-positive entry costs one ignored RPC at worst.+ const foreignThreadId = readNotificationThreadId(notification);+ if (foreignThreadId !== undefined) {+ if (notification.method === "turn/started") {+ const foreignTurnId =+ typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === "string"+ ? (notification.params as { turn: { id: string } }).turn.id+ : undefined;+ if (foreignTurnId) {+ yield* Ref.update(collabChildLiveTurnsRef, (current) => {+ const next = new Map(current);+ next.set(foreignThreadId, foreignTurnId);+ return next;+ });+ }+ } else if (+ notification.method === "turn/completed" ||+ notification.method === "thread/closed"+ ) {+ yield* Ref.update(collabChildLiveTurnsRef, (current) => {+ const next = new Map(current);+ next.delete(foreignThreadId);+ return next;+ });+ }+ }yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);return;}@@ -1331,6 +1800,26 @@ export const makeCodexSessionRuntime = (Effect.gen(function* () {const providerThreadId = yield* readProviderThreadId;const session = yield* Ref.get(sessionRef);+ // Stop-everything: children are full threads with their own turns;+ // interrupting only the parent leaves the fleet running. Interrupt+ // each live child turn first, best-effort per child, BOUNDED: the+ // transport awaits an unbounded Deferred per request, so a wedged+ // child would otherwise block the parent interrupt forever —+ // exactly during the runaway fleet where Stop matters most+ // (review finding). Per-child and overall deadlines guarantee the+ // parent interrupt below always runs.+ const liveChildTurns = yield* Ref.get(collabChildLiveTurnsRef);+ yield* Effect.forEach(+ Array.from(liveChildTurns.entries()),+ ([childThreadId, childTurnId]) =>+ client+ .request("turn/interrupt", {+ threadId: childThreadId,+ turnId: childTurnId,+ })+ .pipe(Effect.timeoutOption("3 seconds"), Effect.ignore),+ { concurrency: 8, discard: true },+ ).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);const effectiveTurnId = turnId ?? session.activeTurnId;if (!effectiveTurnId) {return;diff --git a/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjs b/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjsnew file mode 100644index 000000000..59580d2c7--- /dev/null+++ b/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjs@@ -0,0 +1,93 @@+// Minimal codex app-server stand-in for runtime-level collab tests.+// Speaks just enough of the protocol for CodexSessionRuntime to start a+// session, using REAL captured responses (codexMultiAgentWire.json), then+// replays a scripted multi-agent notification sequence read from the+// T3_CODEX_COLLAB_SCRIPT env var (a JSON file path) when the first turn+// starts. Runs as a plain Node process — stdlib only.+import * as NodeFS from "node:fs";+import * as NodeReadline from "node:readline";+import * as NodePath from "node:path";+import * as NodeURL from "node:url";++const here = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));+const fixture = JSON.parse(+ NodeFS.readFileSync(NodePath.join(here, "codexMultiAgentWire.json"), "utf8"),+);+const script = JSON.parse(NodeFS.readFileSync(process.env.T3_CODEX_COLLAB_SCRIPT, "utf8"));++const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);++const rl = NodeReadline.createInterface({ input: process.stdin });+rl.on("line", (line) => {+ let message;+ try {+ message = JSON.parse(line);+ } catch {+ return;+ }+ const { id, method } = message;+ if (method === "initialize") {+ write({+ id,+ result: {+ userAgent: "t3-collab-mock/0.0.0",+ codexHome: "/tmp",+ platformFamily: "unix",+ platformOs: "linux",+ },+ });+ return;+ }+ if (method === "thread/start" || method === "thread/resume") {+ write({ id, result: fixture.responses.threadStart });+ return;+ }+ if (method === "turn/start") {+ write({ id, result: fixture.responses.turnStart });+ const rootThreadId = script.rootThreadId;+ const turn = fixture.responses.turnStart.turn;+ write({+ jsonrpc: "2.0",+ method: "turn/started",+ params: { threadId: rootThreadId, turn },+ });+ for (const notification of script.notifications) {+ write({ jsonrpc: "2.0", method: notification.method, params: notification.params });+ }+ if (script.holdTurnOpen !== true) {+ write({+ jsonrpc: "2.0",+ method: "turn/completed",+ params: {+ threadId: rootThreadId,+ turn: { ...turn, status: "completed" },+ },+ });+ }+ return;+ }+ if (method === "turn/interrupt") {+ // Record which thread/turn was interrupted (append-only sidecar file the+ // test reads) so Stop coverage can assert every live child was reached.+ // failInterruptFor simulates a dead child whose interrupt errors.+ const target = message.params?.threadId;+ NodeFS.appendFileSync(+ `${process.env.T3_CODEX_COLLAB_SCRIPT}.interrupts`,+ `${JSON.stringify({ threadId: target, turnId: message.params?.turnId })}\n`,+ );+ if (script.failInterruptFor && script.failInterruptFor === target) {+ write({ id, error: { code: -32000, message: "thread already closed" } });+ return;+ }+ if (script.hangInterruptFor && script.hangInterruptFor === target) {+ // Never respond: simulates a wedged child whose RPC neither resolves+ // nor rejects. The runtime's bounded deadline must move on.+ return;+ }+ write({ id, result: {} });+ return;+ }+ if (id !== undefined) {+ write({ id, result: {} });+ }+});diff --git a/apps/server/src/provider/testFixtures/codexCollabMockPeer.sh b/apps/server/src/provider/testFixtures/codexCollabMockPeer.shnew file mode 100755index 000000000..f6a680a49--- /dev/null+++ b/apps/server/src/provider/testFixtures/codexCollabMockPeer.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+# Wrapper so CodexSessionRuntime can spawn the mock peer: the runtime always+# passes "app-server" as the first argument (real codex CLI subcommand);+# discard it and exec node on the .mjs peer.+shift+exec node "$(dirname "$0")/codexCollabMockPeer.mjs" "$@"diff --git a/apps/server/src/provider/testFixtures/codexMultiAgentWire.json b/apps/server/src/provider/testFixtures/codexMultiAgentWire.jsonnew file mode 100644index 000000000..08316d3b6--- /dev/null+++ b/apps/server/src/provider/testFixtures/codexMultiAgentWire.json@@ -0,0 +1,445 @@+{+ "capturedWith": {+ "cli": "codex-cli 0.145.0",+ "model": "gpt-5.6-luna",+ "effort": "low"+ },+ "rootThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "childThreadIds": [+ "019fcfd6-2883-77e0-9013-4410ede70371",+ "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf"+ ],+ "notifications": [+ {+ "method": "thread/started",+ "params": {+ "thread": {+ "id": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "extra": null,+ "sessionId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "forkedFromId": null,+ "parentThreadId": null,+ "preview": "",+ "ephemeral": false,+ "historyMode": "legacy",+ "modelProvider": "openai",+ "createdAt": 1785898342,+ "updatedAt": 1785898342,+ "recencyAt": 1785898342,+ "status": {+ "type": "idle"+ },+ "path": "/fixtures/codex/rollout.jsonl",+ "cwd": "/workspace/repo",+ "cliVersion": "0.145.0",+ "source": "vscode",+ "canAcceptDirectInput": true,+ "threadSource": null,+ "agentNickname": null,+ "agentRole": null,+ "gitInfo": null,+ "name": null,+ "turns": []+ }+ }+ },+ {+ "method": "thread/status/changed",+ "params": {+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "status": {+ "type": "active",+ "activeFlags": []+ }+ }+ },+ {+ "method": "turn/started",+ "params": {+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turn": {+ "id": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "items": [],+ "itemsView": "notLoaded",+ "status": "inProgress",+ "error": null,+ "startedAt": 1785898342,+ "completedAt": null,+ "durationMs": null+ }+ }+ },+ {+ "method": "thread/status/changed",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "status": {+ "type": "idle"+ }+ }+ },+ {+ "method": "item/completed",+ "params": {+ "item": {+ "type": "subAgentActivity",+ "id": "call_S2JPiq0sMnJYS7kswVdvzEjB",+ "kind": "started",+ "agentThreadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "agentPath": "/root/alpha"+ },+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "completedAtMs": 1785898346687+ }+ },+ {+ "method": "thread/tokenUsage/updated",+ "params": {+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "tokenUsage": {+ "total": {+ "totalTokens": 18261,+ "inputTokens": 18228,+ "cachedInputTokens": 11008,+ "cacheWriteInputTokens": 0,+ "outputTokens": 33,+ "reasoningOutputTokens": 0+ },+ "last": {+ "totalTokens": 18261,+ "inputTokens": 18228,+ "cachedInputTokens": 11008,+ "cacheWriteInputTokens": 0,+ "outputTokens": 33,+ "reasoningOutputTokens": 0+ },+ "modelContextWindow": 258400+ }+ }+ },+ {+ "method": "thread/status/changed",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "status": {+ "type": "active",+ "activeFlags": []+ }+ }+ },+ {+ "method": "turn/started",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "turn": {+ "id": "019fcfd6-28bf-7e00-a873-4554526dc845",+ "items": [],+ "itemsView": "notLoaded",+ "status": "inProgress",+ "error": null,+ "startedAt": 1785898346,+ "completedAt": null,+ "durationMs": null+ }+ }+ },+ {+ "method": "thread/status/changed",+ "params": {+ "threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",+ "status": {+ "type": "idle"+ }+ }+ },+ {+ "method": "item/completed",+ "params": {+ "item": {+ "type": "subAgentActivity",+ "id": "call_A2U7sfjmdGlUn5bn6gUNI0rl",+ "kind": "started",+ "agentThreadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",+ "agentPath": "/root/beta"+ },+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "completedAtMs": 1785898348329+ }+ },+ {+ "method": "thread/status/changed",+ "params": {+ "threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",+ "status": {+ "type": "active",+ "activeFlags": []+ }+ }+ },+ {+ "method": "turn/started",+ "params": {+ "threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",+ "turn": {+ "id": "019fcfd6-2f29-79e3-aa6a-c5836a519d3f",+ "items": [],+ "itemsView": "notLoaded",+ "status": "inProgress",+ "error": null,+ "startedAt": 1785898348,+ "completedAt": null,+ "durationMs": null+ }+ }+ },+ {+ "method": "thread/tokenUsage/updated",+ "params": {+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "tokenUsage": {+ "total": {+ "totalTokens": 36576,+ "inputTokens": 36510,+ "cachedInputTokens": 28160,+ "cacheWriteInputTokens": 0,+ "outputTokens": 66,+ "reasoningOutputTokens": 0+ },+ "last": {+ "totalTokens": 18315,+ "inputTokens": 18282,+ "cachedInputTokens": 17152,+ "cacheWriteInputTokens": 0,+ "outputTokens": 33,+ "reasoningOutputTokens": 0+ },+ "modelContextWindow": 258400+ }+ }+ },+ {+ "method": "item/completed",+ "params": {+ "item": {+ "type": "subAgentActivity",+ "id": "call_2W1NboHClVo0VqAf1y3ZFinO",+ "kind": "interacted",+ "agentThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "agentPath": "/root"+ },+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",+ "completedAtMs": 1785898349265+ }+ },+ {+ "method": "thread/tokenUsage/updated",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",+ "tokenUsage": {+ "total": {+ "totalTokens": 20756,+ "inputTokens": 20713,+ "cachedInputTokens": 5888,+ "cacheWriteInputTokens": 0,+ "outputTokens": 43,+ "reasoningOutputTokens": 11+ },+ "last": {+ "totalTokens": 20756,+ "inputTokens": 20713,+ "cachedInputTokens": 5888,+ "cacheWriteInputTokens": 0,+ "outputTokens": 43,+ "reasoningOutputTokens": 11+ },+ "modelContextWindow": 258400+ }+ }+ },+ {+ "method": "item/started",+ "params": {+ "item": {+ "type": "collabAgentToolCall",+ "id": "call_XGMDYMm4O8ne7vg3Y6p4eSqz",+ "tool": "wait",+ "status": "inProgress",+ "senderThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "receiverThreadIds": [],+ "prompt": null,+ "model": null,+ "reasoningEffort": null,+ "agentsStates": {}+ },+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "startedAtMs": 1785898349931+ }+ },+ {+ "method": "item/completed",+ "params": {+ "item": {+ "type": "collabAgentToolCall",+ "id": "call_XGMDYMm4O8ne7vg3Y6p4eSqz",+ "tool": "wait",+ "status": "completed",+ "senderThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "receiverThreadIds": [],+ "prompt": null,+ "model": null,+ "reasoningEffort": null,+ "agentsStates": {}+ },+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "completedAtMs": 1785898349931+ }+ },+ {+ "method": "thread/tokenUsage/updated",+ "params": {+ "threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "tokenUsage": {+ "total": {+ "totalTokens": 54933,+ "inputTokens": 54846,+ "cachedInputTokens": 45312,+ "cacheWriteInputTokens": 0,+ "outputTokens": 87,+ "reasoningOutputTokens": 0+ },+ "last": {+ "totalTokens": 18357,+ "inputTokens": 18336,+ "cachedInputTokens": 17152,+ "cacheWriteInputTokens": 0,+ "outputTokens": 21,+ "reasoningOutputTokens": 0+ },+ "modelContextWindow": 258400+ }+ }+ },+ {+ "method": "thread/tokenUsage/updated",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",+ "tokenUsage": {+ "total": {+ "totalTokens": 41529,+ "inputTokens": 41481,+ "cachedInputTokens": 26112,+ "cacheWriteInputTokens": 0,+ "outputTokens": 48,+ "reasoningOutputTokens": 11+ },+ "last": {+ "totalTokens": 20773,+ "inputTokens": 20768,+ "cachedInputTokens": 20224,+ "cacheWriteInputTokens": 0,+ "outputTokens": 5,+ "reasoningOutputTokens": 0+ },+ "modelContextWindow": 258400+ }+ }+ },+ {+ "method": "thread/status/changed",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "status": {+ "type": "idle"+ }+ }+ },+ {+ "method": "turn/completed",+ "params": {+ "threadId": "019fcfd6-2883-77e0-9013-4410ede70371",+ "turn": {+ "id": "019fcfd6-28bf-7e00-a873-4554526dc845",+ "items": [],+ "itemsView": "notLoaded",+ "status": "completed",+ "error": null,+ "startedAt": 1785898346,+ "completedAt": 1785898350,+ "durationMs": 3792+ }+ }+ }+ ],+ "responses": {+ "threadStart": {+ "thread": {+ "id": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "extra": null,+ "sessionId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",+ "forkedFromId": null,+ "parentThreadId": null,+ "preview": "",+ "ephemeral": false,+ "historyMode": "legacy",+ "modelProvider": "openai",+ "createdAt": 1785898342,+ "updatedAt": 1785898342,+ "recencyAt": 1785898342,+ "status": {+ "type": "idle"+ },+ "path": "/fixtures/codex/rollout.jsonl",+ "cwd": "/workspace/repo",+ "cliVersion": "0.145.0",+ "source": "vscode",+ "canAcceptDirectInput": true,+ "threadSource": null,+ "agentNickname": null,+ "agentRole": null,+ "gitInfo": null,+ "name": null,+ "turns": []+ },+ "model": "gpt-5.6-sol",+ "modelProvider": "openai",+ "serviceTier": "default",+ "cwd": "/workspace/repo",+ "runtimeWorkspaceRoots": ["/workspace/repo"],+ "instructionSources": ["/fixtures/scrubbed", "/workspace/repo/AGENTS.md"],+ "approvalPolicy": "on-request",+ "approvalsReviewer": "auto_review",+ "sandbox": {+ "type": "workspaceWrite",+ "writableRoots": [],+ "networkAccess": false,+ "excludeTmpdirEnvVar": false,+ "excludeSlashTmp": false+ },+ "activePermissionProfile": null,+ "reasoningEffort": "high",+ "multiAgentMode": "explicitRequestOnly"+ },+ "turnStart": {+ "turn": {+ "id": "019fcfd6-1806-7de1-8564-de69fd55bffb",+ "items": [],+ "itemsView": "notLoaded",+ "status": "inProgress",+ "error": null,+ "startedAt": null,+ "completedAt": null,+ "durationMs": null+ }+ }+ }+}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 4ece17cc1..fc6560267 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -91,6 +91,7 @@ import { issueAssetUrl } from "./assets/AssetAccess.ts";import * as PortScanner from "./preview/PortScanner.ts";import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";+import { readWorkflowScript } from "./orchestration/workflowScriptQuery.ts";import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";@@ -1084,6 +1085,12 @@ const makeWsRpcLayer = (),{ "rpc.aggregate": "orchestration" },),+ [ORCHESTRATION_WS_METHODS.getWorkflowScript]: (input) =>+ observeRpcEffect(+ ORCHESTRATION_WS_METHODS.getWorkflowScript,+ readWorkflowScript({ scriptPath: input.scriptPath }),+ { "rpc.aggregate": "orchestration" },+ ),[ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>observeRpcEffect(ORCHESTRATION_WS_METHODS.getTurnDiff,diff --git a/apps/web/src/components/AgentsPanel.tsx b/apps/web/src/components/AgentsPanel.tsxnew file mode 100644index 000000000..169c662e5--- /dev/null+++ b/apps/web/src/components/AgentsPanel.tsx@@ -0,0 +1,568 @@+/**+ * Agents right-panel surface: the fleet view over the native subagent fold,+ * and the ONLY place the roster renders (the chat carries one CTA row per+ * spawn batch).+ *+ * Visualization rules (from live-test feedback):+ * - Live work first: running workflows and direct spawns sort above settled.+ * - Rows are flat status lines — no expansion, no per-agent tool feeds. The+ * row answers "who / what phase / how much"; anything deeper is a future+ * drill-in, not an unfold.+ * - A settled workflow run collapses to a single summary line; click it to+ * show its member list inline (the one allowed toggle — run granularity,+ * not agent granularity).+ * - Static status dots, DOM-write elapsed timers, plain token counters.+ */+import { useAtomValue } from "@effect/atom-react";+import type {+ AgentPanelModel,+ AgentPanelWorkflowGroup,+ RuntimeSubagent,+} from "@t3tools/client-runtime/state/subagentRuntime";+import {+ formatSubagentModelLabel,+ formatSubagentTokenCount,+} from "@t3tools/client-runtime/state/subagentRuntime";+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { Bot, Braces, Check, ChevronDown, ChevronRight, X } from "lucide-react";+import { useEffect, useRef, useState } from "react";++import { cn } from "~/lib/utils";+import { orchestrationEnvironment } from "~/state/orchestration";+import { ScrollArea } from "~/components/ui/scroll-area";++/**+ * In-flight states all present as Working (one steady state, per the+ * monitoring-pill design: detail belongs in the activity sub-line, and a+ * stalled/waiting/queued subagent is still the fleet doing its job, not a+ * user problem). Only settled states differentiate.+ */+const STATUS_VISUALS: Record<RuntimeSubagent["status"], { dotClass: string; label: string }> = {+ pending: { dotClass: "bg-info", label: "Working" },+ running: { dotClass: "bg-info", label: "Working" },+ waiting: { dotClass: "bg-info", label: "Working" },+ // Idle reads as settled (muted, not sky): a resting Codex child looks done+ // unless resumed — live-test: sky idle dots read as stuck in-progress.+ idle: { dotClass: "bg-muted-foreground/50", label: "Idle · resumable" },+ completed: { dotClass: "bg-success", label: "Completed" },+ failed: { dotClass: "bg-destructive", label: "Failed" },+ cancelled: { dotClass: "bg-muted-foreground/60", label: "Stopped" },+ interrupted: { dotClass: "bg-muted-foreground/60", label: "Stopped" },+};++function StatusDot({ status }: { status: RuntimeSubagent["status"] }) {+ return (+ <span+ aria-hidden+ className={cn("size-1.5 shrink-0 rounded-full", STATUS_VISUALS[status].dotClass)}+ />+ );+}++function formatElapsedSeconds(totalSeconds: number): string {+ const seconds = Math.max(0, Math.floor(totalSeconds));+ const minutes = Math.floor(seconds / 60);+ if (minutes === 0) {+ return `${seconds}s`;+ }+ const hours = Math.floor(minutes / 60);+ if (hours === 0) {+ return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;+ }+ return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;+}++function elapsedBetween(startedAt: string, endIso: string | null): string {+ const start = Date.parse(startedAt);+ const end = endIso ? Date.parse(endIso) : Date.now();+ if (Number.isNaN(start) || Number.isNaN(end)) {+ return "";+ }+ return formatElapsedSeconds((end - start) / 1000);+}++/**+ * Elapsed time for the current activation. Live agents self-tick via DOM+ * writes (zero React commits per tick); settled agents freeze at completedAt.+ */+function AgentElapsed({ agent }: { agent: RuntimeSubagent }) {+ const textRef = useRef<HTMLSpanElement>(null);+ const live = agent.status === "running" || agent.status === "waiting";+ const startedAt = agent.startedAt;++ useEffect(() => {+ if (!live || !startedAt) {+ return;+ }+ const update = () => {+ if (textRef.current) {+ textRef.current.textContent = elapsedBetween(startedAt, null);+ }+ };+ update();+ const id = setInterval(update, 1000);+ return () => clearInterval(id);+ }, [live, startedAt]);++ if (!startedAt) {+ return null;+ }+ return (+ <span ref={textRef} className="tabular-nums">+ {elapsedBetween(startedAt, live ? null : agent.completedAt)}+ </span>+ );+}++/**+ * Status-dependent activity line. Live rows lead with what is happening now;+ * settled rows lead with the outcome. Errors are the only inline previews on+ * failed rows because they explain a red row at a glance.+ */+function agentActivityText(agent: RuntimeSubagent): string | null {+ const live =+ agent.status === "running" || agent.status === "pending" || agent.status === "waiting";+ if (live) {+ return (+ agent.progress ??+ (agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??+ agent.result ??+ agent.error+ );+ }+ return (+ agent.error ??+ agent.result ??+ agent.progress ??+ (agent.lastToolName ? `▸ ${agent.lastToolName}` : null)+ );+}++/** Flat, non-interactive agent status line. No unfold. */+function AgentRow({ agent }: { agent: RuntimeSubagent }) {+ const visuals = STATUS_VISUALS[agent.status];+ const activity = agentActivityText(agent);+ const modelLabel = formatSubagentModelLabel(agent.model, agent.effort);++ return (+ <div className="rounded-md px-1.5 py-1">+ <div className="flex items-start gap-2">+ <span className="flex h-5 items-center">+ <StatusDot status={agent.status} />+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">+ <span className="truncate text-sm font-medium">{agent.title}</span>+ {agent.role ? (+ <span className="max-w-28 truncate rounded-sm border border-border/60 px-1 font-mono text-[.65rem] text-muted-foreground">+ {agent.role}+ </span>+ ) : null}+ <span className="ml-auto flex items-center gap-1 font-mono text-[.7rem] text-muted-foreground/80">+ <AgentElapsed agent={agent} />+ {agent.status === "completed" ? (+ <Check aria-hidden className="size-3 text-success" />+ ) : null}+ </span>+ </span>+ {activity ? (+ <span+ className={cn(+ "mt-0.5 block truncate text-xs",+ agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",+ )}+ >+ {activity}+ </span>+ ) : null}+ <span className="mt-0.5 flex items-center gap-1 font-mono text-[.7rem] text-muted-foreground/70">+ {modelLabel ? <span className="truncate">{modelLabel}</span> : null}+ {agent.usage ? (+ <span className="tabular-nums">+ {modelLabel ? "· " : ""}+ {formatSubagentTokenCount(agent.usage.totalTokens)} tok+ </span>+ ) : null}+ {agent.usage?.toolUses !== undefined ? (+ <span>· {agent.usage.toolUses} tools</span>+ ) : null}+ {agent.activationCount > 1 ? <span>· run {agent.activationCount}</span> : null}+ <span className="sr-only">{visuals.label}</span>+ </span>+ </span>+ </div>+ </div>+ );+}++function workflowIsLive(group: AgentPanelWorkflowGroup): boolean {+ const status = group.workflow.status;+ return (+ status !== "completed" &&+ status !== "failed" &&+ status !== "cancelled" &&+ status !== "interrupted"+ );+}++function workflowMembers(group: AgentPanelWorkflowGroup): ReadonlyArray<RuntimeSubagent> {+ return [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];+}++/**+ * Phase rail: the run's shape at a glance. One segment per phase in order,+ * separated by chevrons; each segment shows title + one dot per member.+ * The whole arc (done → live → pending) is visible without scrolling the+ * member list.+ */+function PhaseRail({ group }: { group: AgentPanelWorkflowGroup }) {+ if (group.phases.length === 0) {+ return null;+ }+ return (+ <div className="flex flex-wrap items-center gap-x-1 gap-y-1 px-1.5 pb-1 pt-1.5">+ {group.phases.map((phase, index) => (+ <div key={phase.index} className="flex items-center gap-1">+ {index > 0 ? (+ <ChevronRight aria-hidden className="size-3 text-muted-foreground/40" />+ ) : null}+ <div+ className={cn(+ "flex items-center gap-1 rounded-sm border px-1.5 py-0.5",+ phase.state === "running"+ ? "border-info/40"+ : phase.state === "done"+ ? "border-success/30"+ : "border-border/50",+ )}+ >+ <span+ className={cn(+ "font-mono text-[.65rem]",+ phase.state === "running"+ ? "text-info-foreground"+ : phase.state === "done"+ ? "text-success-foreground"+ : "text-muted-foreground/70",+ )}+ >+ {phase.state === "done" ? "✓ " : ""}+ {phase.title}+ </span>+ <span className="flex items-center gap-0.5">+ {phase.members.length === 0 ? (+ <span className="font-mono text-[.6rem] text-muted-foreground/50">–</span>+ ) : (+ phase.members.map((member) => <StatusDot key={member.id} status={member.status} />)+ )}+ </span>+ </div>+ </div>+ ))}+ </div>+ );+}++/**+ * Read-only workflow script viewer, fetched through the contained+ * getWorkflowScript RPC (never a raw filesystem read from the client).+ */+function WorkflowScriptView({+ environmentId,+ threadId,+ scriptPath,+ onClose,+}: {+ environmentId: EnvironmentId;+ threadId: ThreadId;+ scriptPath: string;+ onClose: () => void;+}) {+ const result = useAtomValue(+ orchestrationEnvironment.workflowScript({ environmentId, input: { threadId, scriptPath } }),+ );+ return (+ <div className="mx-1.5 mb-1 rounded-md border border-border/60 bg-background/60">+ <div className="flex items-center gap-2 border-b border-border/50 px-2 py-1">+ <Braces aria-hidden className="size-3 text-muted-foreground" />+ <span className="truncate font-mono text-[.65rem] text-muted-foreground">+ {scriptPath.split("/").at(-1)}+ </span>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close script"+ className="ml-auto text-muted-foreground hover:text-foreground"+ >+ <X aria-hidden className="size-3" />+ </button>+ </div>+ <div className="max-h-72 overflow-auto p-2">+ {result._tag === "Success" ? (+ <pre className="whitespace-pre-wrap break-words font-mono text-[.7rem] leading-relaxed text-foreground/90">+ {result.value.contents}+ {result.value.truncated ? "\n… (truncated)" : ""}+ </pre>+ ) : result._tag === "Failure" ? (+ <p className="text-xs text-destructive-foreground">Could not load the script.</p>+ ) : (+ <p className="text-xs text-muted-foreground">Loading…</p>+ )}+ </div>+ </div>+ );+}++/**+ * Collapsible phase section (Claude Code Background-tasks pattern): live+ * phases open by default, done phases collapsed to header + member dot row.+ * User toggles override the default and stick for the phase's lifetime.+ */+function PhaseSection({ phase }: { phase: AgentPanelWorkflowGroup["phases"][number] }) {+ const [userOpen, setUserOpen] = useState<boolean | null>(null);+ const open = userOpen ?? phase.state === "running";+ return (+ <div>+ <button+ type="button"+ onClick={() => setUserOpen(!open)}+ aria-expanded={open}+ className={cn(+ "mt-2 flex w-full items-center gap-1.5 rounded-sm px-1.5 text-left text-[.65rem] font-medium uppercase tracking-wider hover:bg-accent/40",+ phase.state === "done"+ ? "text-success-foreground"+ : phase.state === "running"+ ? "text-info-foreground"+ : "text-muted-foreground/70",+ )}+ >+ {open ? (+ <ChevronDown aria-hidden className="size-3 shrink-0" />+ ) : (+ <ChevronRight aria-hidden className="size-3 shrink-0" />+ )}+ {phase.state === "done" ? <Check aria-hidden className="size-3" /> : null}+ <span>{phase.title}</span>+ <span className="font-normal normal-case text-muted-foreground/70">+ {phase.state === "pending" && phase.members.length === 0+ ? "pending"+ : phase.state === "done"+ ? `${phase.settledCount} done`+ : `${phase.activeCount} active · ${phase.settledCount} done`}+ </span>+ {!open && phase.members.length > 0 ? (+ <span className="ml-auto flex items-center gap-0.5">+ {phase.members.map((member) => (+ <StatusDot key={member.id} status={member.status} />+ ))}+ </span>+ ) : null}+ </button>+ {open ? phase.members.map((member) => <AgentRow key={member.id} agent={member} />) : null}+ </div>+ );+}++/** Live workflow: phase rail + full phase tree. */+function LiveWorkflowSection({+ group,+ environmentId,+ threadId,+}: {+ group: AgentPanelWorkflowGroup;+ environmentId: EnvironmentId | null;+ threadId: ThreadId | null;+}) {+ const [scriptOpen, setScriptOpen] = useState(false);+ const members = workflowMembers(group);+ const settled = members.filter(+ (member) =>+ member.status === "completed" ||+ member.status === "failed" ||+ member.status === "cancelled" ||+ member.status === "interrupted",+ ).length;+ const scriptPath = group.workflow.runHandles?.scriptPath;+ const canShowScript = scriptPath !== undefined && environmentId !== null && threadId !== null;+ return (+ <section className="rounded-lg border border-border/50 bg-card/30 p-1.5">+ <div className="flex items-center gap-2 px-1.5 pt-0.5 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">+ <span aria-hidden className="size-1.5 rounded-full bg-info" />+ <span>{group.workflow.workflowName ?? group.workflow.title}</span>+ {canShowScript ? (+ <button+ type="button"+ onClick={() => setScriptOpen((value) => !value)}+ className={cn(+ "rounded-sm border border-border/60 px-1 font-mono normal-case hover:text-foreground",+ scriptOpen && "text-foreground",+ )}+ aria-expanded={scriptOpen}+ >+ {"{}"} script+ </button>+ ) : null}+ <span className="ml-auto font-mono normal-case text-muted-foreground/80">+ {settled}/{members.length} settled+ </span>+ </div>+ <PhaseRail group={group} />+ {scriptOpen && canShowScript ? (+ <WorkflowScriptView+ environmentId={environmentId}+ threadId={threadId}+ scriptPath={scriptPath}+ onClose={() => setScriptOpen(false)}+ />+ ) : null}+ {group.phases.map((phase) => (+ <PhaseSection key={phase.index} phase={phase} />+ ))}+ {group.unphasedMembers.map((member) => (+ <AgentRow key={member.id} agent={member} />+ ))}+ {group.phases.length === 0 && group.unphasedMembers.length === 0 ? (+ <AgentRow agent={group.workflow} />+ ) : null}+ </section>+ );+}++/**+ * Settled workflow: one summary line. Click toggles the member list — the+ * only expansion in the panel, at run granularity.+ */+function SettledWorkflowSection({ group }: { group: AgentPanelWorkflowGroup }) {+ const [open, setOpen] = useState(false);+ const members = workflowMembers(group);+ const failed = members.filter((member) => member.status === "failed").length;+ // Coordinator usage may already aggregate members (panel-footer rule):+ // count it only when there are no member rows to sum.+ const totalTokens = members.reduce(+ (sum, member) => sum + (member.usage?.totalTokens ?? 0),+ members.length === 0 ? (group.workflow.usage?.totalTokens ?? 0) : 0,+ );+ const elapsed =+ group.workflow.startedAt && group.workflow.completedAt+ ? elapsedBetween(group.workflow.startedAt, group.workflow.completedAt)+ : null;+ return (+ <section>+ <button+ type="button"+ onClick={() => setOpen((value) => !value)}+ className="flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left hover:bg-accent/40"+ aria-expanded={open}+ >+ <StatusDot status={failed > 0 ? "failed" : group.workflow.status} />+ <span className="truncate text-sm">+ {group.workflow.workflowName ?? group.workflow.title}+ </span>+ <span className="ml-auto flex items-center gap-1.5 font-mono text-[.7rem] text-muted-foreground/80">+ {failed > 0 ? <span className="text-destructive-foreground">{failed} failed</span> : null}+ <span>{members.length} agents</span>+ <span className="tabular-nums">· {formatSubagentTokenCount(totalTokens)} tok</span>+ {elapsed ? <span className="tabular-nums">· {elapsed}</span> : null}+ {open ? (+ <ChevronDown aria-hidden className="size-3" />+ ) : (+ <ChevronRight aria-hidden className="size-3" />+ )}+ </span>+ </button>+ {open ? (+ <div className="ms-3 border-s border-border/45 ps-2">+ {members.map((member) => (+ <AgentRow key={member.id} agent={member} />+ ))}+ </div>+ ) : null}+ </section>+ );+}++export function AgentsPanel({+ model,+ environmentId = null,+ threadId = null,+}: {+ model: AgentPanelModel;+ environmentId?: EnvironmentId | null;+ threadId?: ThreadId | null;+}) {+ if (!model.hasAgents) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">+ <Bot aria-hidden className="size-6 text-muted-foreground/60" />+ <p className="text-sm font-medium">No agents yet</p>+ <p className="max-w-56 text-xs text-muted-foreground">+ When this thread spawns subagents or runs a workflow, they show up here with live status,+ activity, and token usage.+ </p>+ </div>+ );+ }++ const liveWorkflows = model.workflows.filter(workflowIsLive);+ const settledWorkflows = model.workflows.filter((group) => !workflowIsLive(group));+ const liveDirect = model.directAgents.filter(+ (agent) =>+ agent.status === "running" || agent.status === "pending" || agent.status === "waiting",+ );+ const settledDirect = model.directAgents.filter(+ (agent) =>+ agent.status !== "running" && agent.status !== "pending" && agent.status !== "waiting",+ );++ return (+ <div className="flex h-full min-h-0 flex-col">+ <ScrollArea className="min-h-0 flex-1">+ <div className="flex flex-col gap-2 p-2">+ {liveWorkflows.map((group) => (+ <LiveWorkflowSection+ key={group.workflow.id}+ group={group}+ environmentId={environmentId}+ threadId={threadId}+ />+ ))}+ {liveDirect.length > 0 ? (+ <section>+ <div className="px-1.5 pt-1 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">+ Direct spawns+ </div>+ {liveDirect.map((agent) => (+ <AgentRow key={agent.id} agent={agent} />+ ))}+ </section>+ ) : null}+ {settledWorkflows.length > 0 || settledDirect.length > 0 ? (+ <section>+ <div className="px-1.5 pt-2 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground/70">+ Earlier+ </div>+ {settledWorkflows.map((group) => (+ <SettledWorkflowSection key={group.workflow.id} group={group} />+ ))}+ {settledDirect.map((agent) => (+ <AgentRow key={agent.id} agent={agent} />+ ))}+ </section>+ ) : null}+ </div>+ </ScrollArea>+ <footer className="flex items-center justify-between border-t border-border/60 px-3 py-1.5 font-mono text-[.7rem] text-muted-foreground">+ <span className="flex items-center gap-2">+ {model.runningCount + model.waitingCount > 0 ? (+ <span className="text-info-foreground">+ ● {model.runningCount + model.waitingCount} working+ </span>+ ) : null}+ {model.idleCount > 0 ? <span>{model.idleCount} idle</span> : null}+ {model.settledCount > 0 ? <span>{model.settledCount} settled</span> : null}+ </span>+ <span className="tabular-nums">Σ {formatSubagentTokenCount(model.totalTokens)} tok</span>+ </footer>+ </div>+ );+}diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex ad704d9e1..99e0421b4 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -140,6 +140,11 @@ import {usePreviewMiniPlayerStore,} from "../previewMiniPlayerStore";import { RightPanelTabs } from "./RightPanelTabs";+import { AgentsPanel } from "./AgentsPanel";+import {+ deriveAgentPanelModel,+ foldSubagentActivities,+} from "@t3tools/client-runtime/state/subagentRuntime";import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";import { BranchToolbar } from "./BranchToolbar";import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";@@ -2052,6 +2057,18 @@ function ChatViewContent(props: ChatViewProps) {const phase = derivePhase(activeThread?.session ?? null);const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);+ // Native subagent fold: memoized by activity-list identity, shared by the+ // Agents surface, live strip, and workflow cards. v2Projection is null+ // until orchestration-v2 lands (source precedence lives in the derive).+ // sessionLive derives interruption for agents orphaned by session death.+ const agentSessionLive = phase !== "disconnected";+ const agentPanelModel = useMemo(+ () =>+ deriveAgentPanelModel({+ agents: foldSubagentActivities(threadActivities, { sessionLive: agentSessionLive }),+ }),+ [agentSessionLive, threadActivities],+ );const pendingApprovals = useMemo(() => derivePendingApprovals(threadActivities),[threadActivities],@@ -3134,6 +3151,10 @@ function ChatViewContent(props: ChatViewProps) {if (!activeThreadRef || !activeProject) return;useRightPanelStore.getState().open(activeThreadRef, "files");}, [activeProject, activeThreadRef]);+ const addAgentsSurface = useCallback(() => {+ if (!activeThreadRef) return;+ useRightPanelStore.getState().open(activeThreadRef, "agents");+ }, [activeThreadRef]);const openFileSurface = useCallback((relativePath: string) => {if (!activeThreadRef || !activeProject) return;@@ -4167,6 +4188,85 @@ function ChatViewContent(props: ChatViewProps) {switchGitRef,updateThreadMetadata,]);+ // Background work (subagent fleets, workflow runs, watch loops) can outlive+ // the turn; once it settles, the composer stop button is gone, so this+ // banner is the only visible stop affordance. Stop routes through the+ // stop-everything interrupt: it kills every live background task before+ // interrupting, and works by session, so no active turn is needed.+ const activeBackgroundLiveness =+ !isWorking && activeThread ? (activeThreadShell?.backgroundLiveness ?? null) : null;+ const [isStoppingBackgroundWork, setIsStoppingBackgroundWork] = useState(false);+ useEffect(() => {+ // "Stopping..." holds until the liveness clears; the interrupt command+ // returning only means the request was accepted.+ if (activeBackgroundLiveness === null) {+ setIsStoppingBackgroundWork(false);+ }+ }, [activeBackgroundLiveness]);+ useEffect(() => {+ // Per-thread state: switching threads while A's stop is pending must not+ // disable B's Stop button (review finding).+ setIsStoppingBackgroundWork(false);+ }, [activeThreadId]);+ const handleStopBackgroundWork = useCallback(async () => {+ if (!activeThread) return;+ setIsStoppingBackgroundWork(true);+ const result = await interruptThreadTurn({+ environmentId,+ input: buildThreadTurnInterruptInput(activeThread),+ });+ if (result._tag === "Failure") {+ // Every failure clears the pending state — an interrupted command+ // never reached the server, so liveness would hold "Stopping..."+ // forever. Only real failures toast.+ setIsStoppingBackgroundWork(false);+ if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ setThreadError(+ activeThread.id,+ error instanceof Error ? error.message : "Failed to stop background work.",+ );+ }+ }+ }, [activeThread, environmentId, interruptThreadTurn, setThreadError]);+ const backgroundLivenessBannerItem = useMemo<ComposerBannerStackItem | null>(() => {+ if (activeBackgroundLiveness === null || !activeThread) {+ return null;+ }+ const working = activeBackgroundLiveness === "working";+ const liveCount = agentPanelModel.liveCount;+ return {+ id: `background-liveness:${activeThread.id}`,+ variant: "default",+ icon: (+ <span+ className={cn("size-1.5 rounded-full bg-foreground", working && "animate-status-pulse")}+ aria-hidden="true"+ />+ ),+ title: working+ ? liveCount > 0+ ? `${liveCount} ${liveCount === 1 ? "agent" : "agents"} working in the background`+ : "Background work running"+ : "Monitoring in the background",+ actions: (+ <Button+ size="xs"+ variant="outline"+ disabled={isStoppingBackgroundWork}+ onClick={() => void handleStopBackgroundWork()}+ >+ {isStoppingBackgroundWork ? "Stopping..." : "Stop"}+ </Button>+ ),+ };+ }, [+ activeBackgroundLiveness,+ activeThread,+ agentPanelModel.liveCount,+ handleStopBackgroundWork,+ isStoppingBackgroundWork,+ ]);// The stack renders items[0] front-most and tucks the rest behind hover, so// ordering is priority: system banners, then the branch-mismatch notice,// and the informational parked-thread banner last — it must never cover another.@@ -4219,12 +4319,15 @@ function ChatViewContent(props: ChatViewProps) {void handleSwitchCheckoutToThread();}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {+ const backgroundLivenessItems =+ backgroundLivenessBannerItem === null ? [] : [backgroundLivenessBannerItem];const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {- return [...systemComposerBannerItems, ...parkedThreadItems];+ return [...systemComposerBannerItems, ...backgroundLivenessItems, ...parkedThreadItems];}return [...systemComposerBannerItems,+ ...backgroundLivenessItems,{id: `branch-mismatch:${activeBranchMismatchKey}`,variant: "info",@@ -4268,6 +4371,7 @@ function ChatViewContent(props: ChatViewProps) {];}, [activeBranchMismatchKey,+ backgroundLivenessBannerItem,handleRestoreThreadBranch,isRestoringThreadBranch,localCheckoutBranchMismatch,@@ -5764,6 +5868,12 @@ function ChatViewContent(props: ChatViewProps) {timestampFormat={timestampFormat}mode="embedded"/>+ ) : activeRightPanelSurface?.kind === "agents" ? (+ <AgentsPanel+ model={agentPanelModel}+ environmentId={activeThreadRef?.environmentId ?? null}+ threadId={activeThreadRef?.threadId ?? null}+ />) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") &&activeProject &&activeWorkspaceRoot ? (@@ -5859,6 +5969,8 @@ function ChatViewContent(props: ChatViewProps) {<div className="relative flex min-h-0 flex-1 flex-col">{/* Messages — LegendList handles virtualization and scrolling internally */}<MessagesTimeline+ agentPanelModel={agentPanelModel}+ onOpenAgents={addAgentsSurface}key={activeThread.id}isWorking={isWorking}activeTurnInProgress={isWorking || !latestTurnSettled}@@ -6195,6 +6307,7 @@ function ChatViewContent(props: ChatViewProps) {onAddTerminal={addTerminalSurface}onAddDiff={addDiffSurface}onAddFiles={addFilesSurface}+ onAddAgents={addAgentsSurface}browserAvailable={isPreviewSupportedInRuntime()}diffAvailable={isServerThread && isGitRepo}filesAvailable={activeProject !== null}@@ -6222,6 +6335,7 @@ function ChatViewContent(props: ChatViewProps) {onAddTerminal={addTerminalSurface}onAddDiff={addDiffSurface}onAddFiles={addFilesSurface}+ onAddAgents={addAgentsSurface}browserAvailable={isPreviewSupportedInRuntime()}diffAvailable={isServerThread && isGitRepo}filesAvailable={activeProject !== null}diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex 2b9fa1660..b0f18f6e1 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -1,6 +1,6 @@import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";-import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";+import { Bot, ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";import {type MouseEvent as ReactMouseEvent,type ReactElement,@@ -44,6 +44,7 @@ interface RightPanelTabsProps {onAddTerminal: () => void;onAddDiff: () => void;onAddFiles: () => void;+ onAddAgents: () => void;browserAvailable: boolean;diffAvailable: boolean;filesAvailable: boolean;@@ -91,6 +92,7 @@ function RightPanelEmptyState(props: {onAddTerminal: () => void;onAddDiff: () => void;onAddFiles: () => void;+ onAddAgents: () => void;browserAvailable: boolean;diffAvailable: boolean;filesAvailable: boolean;@@ -128,6 +130,14 @@ function RightPanelEmptyState(props: {disabledReason: SURFACE_DISABLED_REASONS.diff,onClick: props.onAddDiff,},+ {+ label: "Agents",+ description: "Watch subagents and workflows run.",+ icon: Bot,+ available: true,+ disabledReason: null,+ onClick: props.onAddAgents,+ },] as const;return (@@ -205,6 +215,8 @@ function surfaceTitle();case "plan":return "Plan";+ case "agents":+ return "Agents";case "preview": {const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";@@ -266,6 +278,8 @@ function SurfaceIcon({return <TerminalSquare className="size-3 shrink-0" />;case "plan":return <ClipboardList className="size-3 shrink-0" />;+ case "agents":+ return <Bot className="size-3 shrink-0" />;}}@@ -466,6 +480,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {<FileDiff />Diff</SurfaceMenuItem>+ <SurfaceMenuItem available onClick={props.onAddAgents}>+ <Bot />+ Agents+ </SurfaceMenuItem></MenuPopup></Menu>) : null}@@ -480,6 +498,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {onAddTerminal={props.onAddTerminal}onAddDiff={props.onAddDiff}onAddFiles={props.onAddFiles}+ onAddAgents={props.onAddAgents}browserAvailable={props.browserAvailable}diffAvailable={props.diffAvailable}filesAvailable={props.filesAvailable}diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 8025dffe3..677e85c37 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -120,6 +120,7 @@ export function buildBulkTitleRegenerationContextMenuItem(input: {export interface ThreadStatusPill {label:| "Working"+ | "Monitoring"| "Connecting"| "Completed"| "Pending Approval"@@ -130,12 +131,16 @@ export interface ThreadStatusPill {pulse: boolean;}+// Rollup order mirrors the per-thread resolver exactly: attention states,+// then active work, then the actionable plan prompt, then passive+// monitoring. A Monitoring sibling must never hide a Plan Ready thread.const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {- "Pending Approval": 5,- "Awaiting Input": 4,- Working: 3,- Connecting: 3,- "Plan Ready": 2,+ "Pending Approval": 6,+ "Awaiting Input": 5,+ Working: 4,+ Connecting: 4,+ "Plan Ready": 3,+ Monitoring: 2,Completed: 1,};@@ -147,6 +152,7 @@ type ThreadStatusInput = Pick<| "interactionMode"| "latestTurn"| "session"+ | "backgroundLiveness"> & {lastVisitedAt?: string | undefined;};@@ -424,11 +430,11 @@ export function resolveThreadRowClassName(input: {// whether it finished, asked a question, or proposed a plan.// Unread completion is tracked separately: it describes whether a ready// thread needs attention, not what the thread is currently doing.-export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "ready";+export type SidebarV2Status = "approval" | "input" | "working" | "monitoring" | "failed" | "ready";type SidebarV2StatusInput = Pick<SidebarThreadSummary,- "hasPendingApprovals" | "hasPendingUserInput" | "session"+ "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness">;export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {@@ -441,9 +447,19 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Sif (thread.session?.status === "running" || thread.session?.status === "starting") {return "working";}+ // A failed session outranks lingering background liveness: the user must+ // see the failure, not a stale Working (review finding).if (thread.session?.status === "error") {return "failed";}+ // Background work outlives the turn: fleets read as working; monitoring+ // only when watch loops are the sole live work.+ if (thread.backgroundLiveness === "working") {+ return "working";+ }+ if (thread.backgroundLiveness === "monitoring") {+ return "monitoring";+ }return "ready";}@@ -616,6 +632,8 @@ export function resolveThreadStatusPill(input: {};}+ // An actionable plan prompt outranks lingering background work: it needs+ // the user's decision, while liveness merely reports (review finding).const hasPlanReadyPrompt =!thread.hasPendingUserInput &&thread.interactionMode === "plan" &&@@ -630,6 +648,28 @@ export function resolveThreadStatusPill(input: {};}+ // The turn can settle while native background work runs on. Subagent and+ // workflow fleets read as plain Working; Monitoring is reserved for watch+ // loops (a parent agent babysitting a PR, tailing checks) with no other+ // live work. Same recede treatment as Working per inbox-zero.+ if (thread.backgroundLiveness === "working") {+ return {+ label: "Working",+ colorClass: "text-sky-600 dark:text-sky-300/80",+ dotClass: "bg-sky-500 dark:bg-sky-300/80",+ pulse: true,+ };+ }++ if (thread.backgroundLiveness === "monitoring") {+ return {+ label: "Monitoring",+ colorClass: "text-sky-600 dark:text-sky-300/80",+ dotClass: "bg-sky-500 dark:bg-sky-300/80",+ pulse: false,+ };+ }+if (hasUnseenCompletion(thread)) {return {label: "Completed",diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsxindex e8f7f8bbb..6e4bdc0fc 100644--- a/apps/web/src/components/SidebarV2.tsx+++ b/apps/web/src/components/SidebarV2.tsx@@ -482,7 +482,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {// findable. In-flight rows recede the same as read-ready ones (inbox-zero:// working threads aren't your problem yet) — only the colored status label// stands out.- const isInFlight = status === "working" || status === "approval" || status === "input";+ const isInFlight =+ status === "working" || status === "monitoring" || status === "approval" || status === "input";const shouldRecede =(status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected;// Status hues follow the system-wide convention set by sidebar v1 and the@@ -496,37 +497,45 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {className:"animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400",}- : status === "approval"+ : status === "monitoring"? {- label: "Approval",+ // Steady label, no duty-cycled shimmer: monitoring is calm+ // background presence, not active progress (monitoring-pill D6).+ label: "Monitoring",icon: null,- className: "text-amber-700 dark:text-amber-300",+ className: "text-sky-600 dark:text-sky-400",}- : status === "input"+ : status === "approval"? {- label: "Input",+ label: "Approval",icon: null,- className: "text-indigo-600 dark:text-indigo-300",+ className: "text-amber-700 dark:text-amber-300",}- : status === "failed"+ : status === "input"? {- label: "Failed",+ label: "Input",icon: null,- className: "text-red-700 dark:text-red-300",+ className: "text-indigo-600 dark:text-indigo-300",}- : isWoke+ : status === "failed"? {- label: "Woke",- icon: "woke" as const,- className: "text-amber-700 dark:text-amber-300",+ label: "Failed",+ icon: null,+ className: "text-red-700 dark:text-red-300",}- : isUnread+ : isWoke? {- label: "Done",- icon: "done" as const,- className: "text-emerald-700 dark:text-emerald-300",+ label: "Woke",+ icon: "woke" as const,+ className: "text-amber-700 dark:text-amber-300",}- : null;+ : isUnread+ ? {+ label: "Done",+ icon: "done" as const,+ className: "text-emerald-700 dark:text-emerald-300",+ }+ : null;const gitCwd = thread.worktreePath ?? props.projectCwd;const gitStatus = useEnvironmentQuery(diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex 3227bac24..e5ecdbd20 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -352,9 +352,16 @@ function deriveTurnFolds(input: {}const hiddenEntryIds = new Set<string>();for (const entry of group.entries) {- if (entry.id !== group.terminalEntry?.id) {- hiddenEntryIds.add(entry.id);+ if (entry.id === group.terminalEntry?.id) {+ continue;}+ // Agent-spawn CTA rows never fold: workflows outlive their launching+ // turn (dynamic spawns, background execution), and folding the CTA+ // when the turn settles makes a still-running fleet invisible.+ if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {+ continue;+ }+ hiddenEntryIds.add(entry.id);}if (hiddenEntryIds.size === 0) {continue;@@ -489,9 +496,21 @@ export function deriveMessagesTimelineRows(input: {} else {const groupId = `work-group:${timelineEntry.id}`;const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;- const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);- const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);- const renderedEntries = expanded ? [...hiddenEntries, ...visibleEntries] : visibleEntries;+ // Agent-spawn CTA rows are always visible: a running fleet must+ // never hide behind a "+N tool calls" toggle. Selection is by+ // membership (spawn OR recent-tail), preserving the group's+ // chronological order in both collapsed and expanded states+ // (review finding: concatenating two filtered lists moved a+ // mid-group spawn row above earlier tool rows).+ const overflowCandidates = visibleGroupedEntries.filter(+ (entry) => entry.agentSpawn === undefined,+ );+ const hiddenEntries = overflowCandidates.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);+ const hiddenIds = new Set(hiddenEntries.map((entry) => entry.id));+ const visibleEntries = visibleGroupedEntries.filter(+ (entry) => entry.agentSpawn !== undefined || !hiddenIds.has(entry.id),+ );+ const renderedEntries = expanded ? visibleGroupedEntries : visibleEntries;for (const workEntry of renderedEntries) {nextRows.push({@@ -502,15 +521,19 @@ export function deriveMessagesTimelineRows(input: {});}- nextRows.push({- kind: "work-toggle",- id: `work-toggle:${timelineEntry.id}`,- createdAt: timelineEntry.createdAt,- groupId,- hiddenCount: hiddenEntries.length,- expanded,- onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),- });+ if (hiddenEntries.length > 0) {+ nextRows.push({+ kind: "work-toggle",+ id: `work-toggle:${timelineEntry.id}`,+ createdAt: timelineEntry.createdAt,+ groupId,+ hiddenCount: hiddenEntries.length,+ expanded,+ onlyToolEntries: visibleGroupedEntries.every((entry) =>+ workLogEntryIsToolLike(entry),+ ),+ });+ }}}index = cursor - 1;diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex a429b54de..c952eb3d1 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -6,6 +6,14 @@ import {type TurnId,} from "@t3tools/contracts";import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";+import type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime";+import {+ emptyAgentPanelModel,+ formatSubagentTokenCount,+} from "@t3tools/client-runtime/state/subagentRuntime";++const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel();+const NOOP_OPEN_AGENTS = () => {};import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";import {createContext,@@ -135,6 +143,8 @@ interface TimelineRowSharedState {onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;onToggleTurnFold: (turnId: TurnId) => void;onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;+ agentPanelModel: AgentPanelModel;+ onOpenAgents: () => void;}interface TimelineRowActivityState {@@ -156,6 +166,8 @@ const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "d// ---------------------------------------------------------------------------interface MessagesTimelineProps {+ agentPanelModel?: AgentPanelModel;+ onOpenAgents?: () => void;isWorking: boolean;activeTurnInProgress: boolean;activeTurnStartedAt: string | null;@@ -194,6 +206,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({isWorking,activeTurnInProgress,activeTurnStartedAt,+ agentPanelModel = EMPTY_AGENT_PANEL_MODEL,+ onOpenAgents = NOOP_OPEN_AGENTS,listRef,timelineEntries,latestTurn,@@ -430,6 +444,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({onOpenTurnDiff,onToggleTurnFold,onToggleWorkGroup,+ agentPanelModel,+ onOpenAgents,}),[timestampFormat,@@ -444,6 +460,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({onOpenTurnDiff,onToggleTurnFold,onToggleWorkGroup,+ agentPanelModel,+ onOpenAgents,],);const activityState = useMemo<TimelineRowActivityState>(@@ -1897,8 +1915,14 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {case "mcp_tool_call":return "wrench";case "dynamic_tool_call":- case "collab_agent_tool_call":return "hammer";+ case "collab_agent_tool_call":+ return "bot";+ }++ // Subagent lifecycle rows (grouped by taskId) get agent identity chrome.+ if (workEntry.taskId) {+ return "bot";}return workToneIcon(workEntry.tone).iconName;@@ -1921,9 +1945,115 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();+/**+ * A1 spawn CTA: one anchored row per workflow run (or per-turn direct-spawn+ * batch). Live status is derived from the shared agent panel model at render+ * time — the row itself never re-renders a roster; the Agents panel is the+ * only roster. Freezes to past tense when every member settles. Static dot,+ * no animation.+ */+const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { workEntry: TimelineWorkEntry }) {+ const { workEntry } = props;+ const { agentPanelModel, onOpenAgents } = use(TimelineRowCtx);+ const spawn = workEntry.agentSpawn;+ if (!spawn) {+ return null;+ }++ const memberIds = new Set(spawn.agentTaskIds);+ const workflowGroup = spawn.workflowId+ ? agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId)+ : undefined;+ const agents = workflowGroup+ ? [...workflowGroup.phases.flatMap((phase) => phase.members), ...workflowGroup.unphasedMembers]+ : agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id));+ const agentCount = Math.max(+ agents.length,+ Math.max(memberIds.size - (spawn.workflowId ? 1 : 0), 0),+ );++ const running = agents.filter(+ (agent) => agent.status === "running" || agent.status === "pending",+ ).length;+ const waiting = agents.filter((agent) => agent.status === "waiting").length;+ const failed = agents.filter((agent) => agent.status === "failed").length;+ // The coordinator's own status is authoritative for workflows: dynamic+ // spawns mean the member list can be momentarily all-settled while the+ // run is still mid-flight (the "completed" lie from live testing). A+ // workflow is live until the coordinator itself reaches a terminal state.+ const coordinatorStatus = workflowGroup?.workflow.status;+ const coordinatorSettled =+ coordinatorStatus === "completed" ||+ coordinatorStatus === "failed" ||+ coordinatorStatus === "cancelled" ||+ coordinatorStatus === "interrupted";+ const live = workflowGroup !== undefined ? !coordinatorSettled : running + waiting > 0;+ // Same rule as the panel footer: providers may aggregate member usage into+ // the coordinator, so count the coordinator only when no members exist.+ const totalTokens = agents.reduce(+ (sum, agent) => sum + (agent.usage?.totalTokens ?? 0),+ spawn.workflowId && agents.length === 0 ? (workflowGroup?.workflow.usage?.totalTokens ?? 0) : 0,+ );++ const livePhase = workflowGroup?.phases.find((phase) => phase.state === "running");+ const workflowName =+ workflowGroup?.workflow.workflowName ?? workflowGroup?.workflow.title ?? null;++ // One steady in-flight presentation (monitoring-pill rule): waiting and+ // stalled agents read as working; only settled states differentiate.+ const working = running + waiting;+ const dotClass = live ? "bg-info" : failed > 0 ? "bg-destructive" : "bg-success";+ const lead = live+ ? `Kicked off ${agentCount} subagent${agentCount === 1 ? "" : "s"}`+ : `Ran ${agentCount} subagent${agentCount === 1 ? "" : "s"}`;+ const status = live+ ? livePhase+ ? `${livePhase.title} · ${livePhase.activeCount} working`+ : working > 0+ ? `${working} working`+ : "working"+ : failed > 0+ ? `${failed} failed`+ : "✓ completed";++ return (+ <button+ type="button"+ onClick={onOpenAgents}+ className="-mx-1 flex w-full items-center gap-2 rounded-md border border-border/60 bg-card/50 px-2.5 py-1.5 text-left text-[13px] transition hover:bg-accent/50"+ >+ <span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", dotClass)} />+ <WorkEntryIconSvg name="bot" className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 truncate">+ <span className="font-medium">{lead}</span>+ {workflowName ? <span className="text-muted-foreground"> · {workflowName}</span> : null}+ </span>+ <span className="ml-auto flex shrink-0 items-center gap-2 font-mono text-[.7rem] text-muted-foreground">+ <span>{status}</span>+ {totalTokens > 0 ? (+ <span className="tabular-nums">Σ {formatSubagentTokenCount(totalTokens)}</span>+ ) : null}+ <span className="text-info-foreground">{live ? "Open Agents ▸" : "View ▸"}</span>+ </span>+ </button>+ );+});+const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {workEntry: TimelineWorkEntry;workspaceRoot: string | undefined;+}) {+ const { workEntry, workspaceRoot } = props;+ // Before any hooks: spawn CTA rows render their own component.+ if (workEntry.agentSpawn) {+ return <AgentSpawnCtaRow workEntry={workEntry} />;+ }+ return <PlainWorkEntryRow workEntry={workEntry} workspaceRoot={workspaceRoot} />;+});++const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {+ workEntry: TimelineWorkEntry;+ workspaceRoot: string | undefined;}) {const { workEntry, workspaceRoot } = props;const activity = use(TimelineRowActivityCtx);diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.tsindex 70d163306..cccb7238c 100644--- a/apps/web/src/rightPanelStore.ts+++ b/apps/web/src/rightPanelStore.ts@@ -14,7 +14,15 @@ import { createJSONStorage, persist } from "zustand/middleware";import { resolveStorage } from "./lib/storage";-export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;+export const RIGHT_PANEL_KINDS = [+ "plan",+ "diff",+ "files",+ "file",+ "preview",+ "terminal",+ "agents",+] as const;export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];export type RightPanelSurface =@@ -37,10 +45,11 @@ export type RightPanelSurface =revealLine: number | null;revealRequestId: number;}- | { id: "plan"; kind: "plan" };+ | { id: "plan"; kind: "plan" }+ | { id: "agents"; kind: "agents" };const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";-const RIGHT_PANEL_STORAGE_VERSION = 7;+const RIGHT_PANEL_STORAGE_VERSION = 8;export interface ThreadRightPanelState {isOpen: boolean;@@ -92,6 +101,8 @@ const singletonSurface = (return { id: "files", kind };case "plan":return { id: "plan", kind };+ case "agents":+ return { id: "agents", kind };}};diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.tsindex 0f12e672f..cdb2119ac 100644--- a/apps/web/src/session-logic.test.ts+++ b/apps/web/src/session-logic.test.ts@@ -1,4 +1,5 @@import {+ classifyTaskAgentKind,EventId,MessageId,ThreadId,@@ -35,7 +36,19 @@ function makeActivity(overrides: {turnId?: string;sequence?: number;}): OrchestrationThreadActivity {- const payload = overrides.payload ?? {};+ // Fixtures model post-ingestion rows: ingestion stamps agentKind on every+ // task.* payload. Pass an explicit agentKind to model legacy rows.+ const rawPayload = overrides.payload ?? {};+ const payload =+ overrides.kind?.startsWith("task.") && !("agentKind" in rawPayload)+ ? {+ ...rawPayload,+ agentKind: classifyTaskAgentKind({+ taskType: typeof rawPayload.taskType === "string" ? rawPayload.taskType : undefined,+ agentId: typeof rawPayload.agentId === "string" ? rawPayload.agentId : undefined,+ }),+ }+ : rawPayload;return {id: EventId.make(overrides.id ?? `activity-${nextActivityId++}`),createdAt: overrides.createdAt ?? "2026-02-23T00:00:00.000Z",@@ -1686,3 +1699,215 @@ describe("deriveActiveWorkStartedAt", () => {).toBe("2026-02-27T21:11:00.000Z");});});++describe("deriveWorkLogEntries quiet-timeline guarantee", () => {+ it("N concurrent subagents produce exactly N lifecycle rows, zero attributed tool rows", () => {+ const activities: OrchestrationThreadActivity[] = [];+ for (let agent = 0; agent < 5; agent += 1) {+ const taskId = `task-${agent}`;+ // Progress ticks (several per agent) + attributed tool rows.+ for (let tick = 0; tick < 4; tick += 1) {+ activities.push(+ makeActivity({+ kind: "task.progress",+ summary: `agent ${agent} tick ${tick}`,+ tone: "info",+ payload: { taskId, summary: `working ${tick}`, role: "explorer" },+ turnId: "turn-batch",+ sequence: agent * 20 + tick,+ }),+ );+ activities.push(+ makeActivity({+ kind: "tool.completed",+ summary: "Read",+ payload: { itemType: "dynamic_tool_call", agentId: taskId },+ sequence: agent * 20 + 10 + tick,+ }),+ );+ }+ activities.push(+ makeActivity({+ kind: "task.completed",+ summary: "Task completed",+ tone: "info",+ payload: {+ taskId,+ status: "completed",+ summary: `agent ${agent} done`,+ role: "explorer",+ },+ turnId: "turn-batch",+ sequence: agent * 20 + 19,+ }),+ );+ }++ const entries = deriveWorkLogEntries(activities);+ // A1 CTA design: all direct spawns in one turn collapse into ONE+ // call-to-action row carrying the batch's agent ids.+ const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);+ expect(spawnRows).toHaveLength(1);+ expect(spawnRows[0]!.agentSpawn!.agentTaskIds).toHaveLength(5);+ expect(spawnRows[0]!.agentSpawn!.workflowId).toBeNull();+ // No agent-attributed tool rows leak into the main log.+ expect(entries.some((entry) => entry.sourceActivityKind?.startsWith("tool."))).toBe(false);+ });++ it("a workflow run and its members collapse into one CTA row keyed to the coordinator", () => {+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.progress",+ summary: "coordinator",+ tone: "info",+ payload: { taskId: "wf-1", taskType: "local_workflow", workflowName: "math-check" },+ sequence: 1,+ }),+ makeActivity({+ kind: "task.progress",+ summary: "member",+ tone: "info",+ payload: { taskId: "wf-1:wf:0", status: "running", parentAgentId: "wf-1" },+ sequence: 2,+ }),+ makeActivity({+ kind: "task.completed",+ summary: "member done",+ tone: "info",+ payload: { taskId: "wf-1:wf:1", status: "completed", parentAgentId: "wf-1" },+ sequence: 3,+ }),+ ]);+ const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);+ expect(spawnRows).toHaveLength(1);+ expect(spawnRows[0]!.agentSpawn!.workflowId).toBe("wf-1");+ expect(spawnRows[0]!.agentSpawn!.agentTaskIds).toEqual(+ expect.arrayContaining(["wf-1", "wf-1:wf:0", "wf-1:wf:1"]),+ );+ });++ it("keeps unattributed tool rows (over-hiding loses the only signal)", () => {+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "tool.completed",+ summary: "Bash",+ payload: { itemType: "command_execution", command: "ls" },+ }),+ ]);+ expect(entries).toHaveLength(1);+ });++ it("folds timelineBypass agent rows into one CTA (Codex children, workflow members)", () => {+ // Codex children carry their parent's spawn turn (spawnTurnId stamping),+ // which is what batches a fleet into one CTA.+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.progress",+ summary: "child work",+ tone: "info",+ payload: { taskId: "child-1", timelineBypass: true },+ turnId: "turn-spawn",+ }),+ makeActivity({+ kind: "task.progress",+ summary: "child work again",+ tone: "info",+ payload: { taskId: "child-2", timelineBypass: true },+ turnId: "turn-spawn",+ }),+ ]);+ // Not suppressed outright (a Codex fleet's rows are ALL bypassed and+ // still need a CTA anchor) — but never more than the batch's single row.+ expect(entries).toHaveLength(1);+ expect(entries[0]!.agentSpawn?.agentTaskIds).toEqual(["child-1", "child-2"]);+ });++ it("timelineBypass non-agent rows (background shells) stay suppressed", () => {+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.progress",+ summary: "stall",+ tone: "info",+ payload: { taskId: "sh-1", taskType: "local_bash", timelineBypass: true },+ }),+ ]);+ expect(entries).toHaveLength(0);+ });++ it("drops task.updated and tool.progress from the work log (fold input only)", () => {+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.updated",+ summary: "Task running",+ tone: "info",+ payload: { taskId: "task-1", status: "running" },+ }),+ makeActivity({+ kind: "tool.progress",+ summary: "Read",+ tone: "info",+ payload: { taskId: "task-1", toolName: "Read" },+ }),+ ]);+ expect(entries).toHaveLength(0);+ });+});++describe("rerun workflows", () => {+ it("turn-less direct spawns do not collapse into one global batch", () => {+ // Rows that lost their turn id (defensive path) group per task, so two+ // unrelated turn-less spawns never merge into one immortal CTA.+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.started",+ summary: "Task started",+ payload: { taskId: "loose-1", taskType: "local_agent", role: "a" },+ sequence: 1,+ }),+ makeActivity({+ kind: "task.started",+ summary: "Task started",+ payload: { taskId: "loose-2", taskType: "local_agent", role: "b" },+ sequence: 2,+ }),+ ]);+ const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);+ expect(spawnRows).toHaveLength(2);+ expect(spawnRows.map((row) => row.agentSpawn!.agentTaskIds)).toEqual([+ ["loose-1"],+ ["loose-2"],+ ]);+ });++ it("each workflow run gets its own CTA row (distinct coordinator ids)", () => {+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.progress",+ summary: "run 1",+ tone: "info",+ payload: { taskId: "wf-run1", taskType: "local_workflow", workflowName: "math-check" },+ turnId: "turn-1",+ sequence: 1,+ }),+ makeActivity({+ kind: "task.completed",+ summary: "run 1 done",+ tone: "info",+ payload: { taskId: "wf-run1", status: "completed", taskType: "local_workflow" },+ turnId: "turn-1",+ sequence: 2,+ }),+ makeActivity({+ kind: "task.progress",+ summary: "run 2",+ tone: "info",+ payload: { taskId: "wf-run2", taskType: "local_workflow", workflowName: "math-check" },+ turnId: "turn-2",+ sequence: 3,+ }),+ ]);+ const spawnRows = entries.filter((entry) => entry.agentSpawn !== undefined);+ expect(spawnRows.map((row) => row.agentSpawn!.workflowId)).toEqual(["wf-run1", "wf-run2"]);+ expect(spawnRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-2"]);+ });+});diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex 5d5051f74..a1ff70bc0 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -1,5 +1,6 @@import * as Option from "effect/Option";import * as Arr from "effect/Array";+import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime";import {ApprovalRequestId,isToolLifecycleItemType,@@ -78,12 +79,30 @@ export interface WorkLogEntry {toolLifecycleStatus?: WorkLogToolLifecycleStatus;/** Originating orchestration activity kind (e.g. `user-input.requested`) for row chrome. */sourceActivityKind?: OrchestrationThreadActivity["kind"];+ /** Grouping key for subagent lifecycle rows (one row per agent). */+ taskId?: string;+ /** Agent role (subagent_type) for labeled timeline rows. */+ agentRole?: string;+ /**+ * Present on agent-spawn CTA rows: one per workflow run or per-turn batch+ * of direct spawns. The row renders as a call-to-action ("Kicked off N+ * subagents") whose live status is derived from the agent panel model at+ * render time; clicking opens the Agents panel.+ */+ agentSpawn?: {+ /** Workflow coordinator taskId, or null for a direct-spawn batch. */+ workflowId: string | null;+ agentTaskIds: ReadonlyArray<string>;+ };}interface DerivedWorkLogEntry extends WorkLogEntry {activityKind: OrchestrationThreadActivity["kind"];collapseKey?: string;toolCallId?: string;+ isWorkflowCoordinator?: boolean;+ /** Shell/monitor/plan tasks: ordinary work-log rows, never spawn CTAs. */+ isBackgroundTask?: boolean;}export interface PendingApproval {@@ -250,6 +269,12 @@ export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {/** Tool-like row with neither clear success nor failure (empty, incomplete, in progress, etc.). */export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {+ // Spawn CTA rows are never neutral-hidden: mid-run they derive from+ // task.progress (tone "thinking") and the neutral filter was swallowing+ // them exactly while the fleet ran — the one moment they matter most.+ if (entry.agentSpawn !== undefined) {+ return false;+ }if (!workLogEntryIsToolLike(entry)) {return false;}@@ -624,6 +649,67 @@ export function hasActionableProposedPlan(return proposedPlan !== null && proposedPlan.implementedAt === null;}+/**+ * Quiet-timeline guarantee: the work log carries the parent's narrative plus+ * at most one row per agent. Everything an agent does internally lives in the+ * Agents surface:+ * - timelineBypass rows (Codex children, workflow members) never render here;+ * - tool rows attributed to an owning agent (payload.agentId) are re-homed;+ * - task.progress ticks collapse into one row per taskId;+ * - task.updated is fold input only (status patches are not narrative).+ * Unattributed rows always stay: over-hiding loses the only terminal signal.+ */+/** Agent (non-background) task.started rows seed spawn CTA batches. */+function isAgentTaskStartedActivity(activity: OrchestrationThreadActivity): boolean {+ const payload =+ activity.payload && typeof activity.payload === "object"+ ? (activity.payload as Record<string, unknown>)+ : null;+ if (!payload || typeof payload.taskId !== "string") {+ return false;+ }+ return !isBackgroundTaskActivity(payload);+}++function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {+ const payload =+ activity.payload && typeof activity.payload === "object"+ ? (activity.payload as Record<string, unknown>)+ : null;+ if (!payload) {+ return false;+ }+ const isTaskRow =+ activity.kind === "task.started" ||+ activity.kind === "task.progress" ||+ activity.kind === "task.updated" ||+ activity.kind === "task.completed";+ // Task rows classify by the server stamp: a subagent's own background+ // shell (agentId + "background") is agent-internal, but a nested AGENT+ // (agentId + "agent") stays visible so its rows can anchor a spawn CTA+ // (review finding: hiding on agentId alone removed nested agents and+ // their anchors). Bypassed agent lifecycle rows also pass — collapse+ // folds every such row into its batch's single CTA row, which is how+ // Codex children (whose rows are ALL bypassed) get an anchor at the+ // spawn point.+ if (isTaskRow) {+ const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;+ if (ownedByAgent || payload.timelineBypass === true) {+ const isAgentTaskRow =+ activity.kind !== "task.updated" &&+ typeof payload.taskId === "string" &&+ !isBackgroundTaskActivity(payload);+ return !isAgentTaskRow;+ }+ return false;+ }+ if (payload.timelineBypass === true) {+ return true;+ }+ // Non-task rows (attributed tool activity) owned by an agent are internal.+ return typeof payload.agentId === "string" && payload.agentId.trim().length > 0;+}+export function deriveWorkLogEntries(activities: ReadonlyArray<OrchestrationThreadActivity>,): WorkLogEntry[] {@@ -631,10 +717,17 @@ export function deriveWorkLogEntries(const entries: DerivedWorkLogEntry[] = [];for (const activity of ordered) {if (activity.kind === "tool.started") continue;- if (activity.kind === "task.started") continue;+ // Agent task.started rows are CTA seeds: they carry the true spawn turn,+ // which is the batch key (completions of background subagents arrive+ // under later synthetic turns and must not start new batches). They+ // collapse into the batch's single CTA row, never render standalone.+ if (activity.kind === "task.started" && !isAgentTaskStartedActivity(activity)) continue;+ if (activity.kind === "task.updated") continue;+ if (activity.kind === "tool.progress") continue;if (activity.kind === "context-window.updated") continue;if (activity.summary === "Checkpoint captured") continue;if (isPlanBoundaryToolActivity(activity)) continue;+ if (isAgentInternalActivity(activity)) continue;entries.push(toDerivedWorkLogEntry(activity));}return collapseDerivedWorkLogEntries(entries).map((entry) => {@@ -682,7 +775,10 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWoconst commandPreview = extractToolCommand(payload);const changedFiles = extractChangedFiles(payload);const title = extractToolTitle(payload);- const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";+ const isTaskActivity =+ activity.kind === "task.started" ||+ activity.kind === "task.progress" ||+ activity.kind === "task.completed";const taskSummary =isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0? payload.summary@@ -756,6 +852,22 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWoif (toolLifecycleStatus) {entry.toolLifecycleStatus = toolLifecycleStatus;}+ if (isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0) {+ entry.taskId = payload.taskId;+ }+ if (isTaskActivity && typeof payload?.role === "string" && payload.role.length > 0) {+ entry.agentRole = payload.role;+ }+ if (+ isTaskActivity &&+ (payload?.taskType === "local_workflow" ||+ (typeof payload?.workflowName === "string" && payload.workflowName.length > 0))+ ) {+ entry.isWorkflowCoordinator = true;+ }+ if (isTaskActivity && payload && isBackgroundTaskActivity(payload)) {+ entry.isBackgroundTask = true;+ }const collapseKey = deriveToolLifecycleCollapseKey(entry);if (collapseKey) {entry.collapseKey = collapseKey;@@ -763,11 +875,92 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWoreturn entry;}+/**+ * Spawn-group key for a subagent lifecycle row. Workflow members and their+ * coordinator share the coordinator's group; direct spawns batch per turn.+ * One CTA row per group (A1 design): "Kicked off N subagents".+ */+function agentSpawnGroupKey(entry: DerivedWorkLogEntry): string {+ const taskId = entry.taskId ?? "";+ const workflowSlot = taskId.indexOf(":wf:");+ if (workflowSlot !== -1) {+ return `wf:${taskId.slice(0, workflowSlot)}`;+ }+ if (entry.agentSpawn?.workflowId) {+ return `wf:${entry.agentSpawn.workflowId}`;+ }+ if (entry.isWorkflowCoordinator) {+ return `wf:${taskId}`;+ }+ // No turn id means no batch signal at all: fall back to one group per+ // task. Unrelated turn-less spawns (separate fleets whose rows lost their+ // turn) must not collapse into one immortal "direct:no-turn" CTA+ // accumulating every agent the thread ever ran (review finding). Adapters+ // stamp spawn turns (Codex spawnTurnId; Claude rows ride real turns), so+ // this path is defensive.+ return entry.turnId ? `direct:${entry.turnId}` : `direct:task:${taskId}`;+}+function collapseDerivedWorkLogEntries(entries: ReadonlyArray<DerivedWorkLogEntry>,): DerivedWorkLogEntry[] {const collapsed: DerivedWorkLogEntry[] = [];+ // Subagent rows collapse by spawn group, not adjacency: a workflow run (or+ // a turn's batch of direct spawns) is ONE narrative event in the chat — a+ // CTA row that opens the Agents panel — no matter how many agents it+ // contains or how their progress rows interleave (quiet-timeline+ // guarantee).+ const spawnRowIndex = new Map<string, number>();+ // Batch membership is decided once, at the FIRST row seen for a taskId.+ // Claude background subagents settle between turns, so their completion+ // rows carry fresh synthetic turn ids (or none) — keying each row by its+ // own turn splintered one batch into a stream of "Kicked off N subagents"+ // rows (live-test finding, thread 7ac7ef05).+ const groupKeyByTaskId = new Map<string, string>();for (const entry of entries) {+ const isTaskRow =+ entry.taskId !== undefined &&+ !entry.isBackgroundTask &&+ (entry.activityKind === "task.started" ||+ entry.activityKind === "task.progress" ||+ entry.activityKind === "task.completed");+ if (isTaskRow && entry.taskId !== undefined) {+ const rememberedKey = groupKeyByTaskId.get(entry.taskId);+ const groupKey = rememberedKey ?? agentSpawnGroupKey(entry);+ if (rememberedKey === undefined) {+ groupKeyByTaskId.set(entry.taskId, groupKey);+ }+ const workflowId = groupKey.startsWith("wf:") ? groupKey.slice(3) : null;+ const existingIndex = spawnRowIndex.get(groupKey);+ if (existingIndex !== undefined) {+ const existing = collapsed[existingIndex]!;+ const agentTaskIds = existing.agentSpawn?.agentTaskIds.includes(entry.taskId)+ ? existing.agentSpawn.agentTaskIds+ : [...(existing.agentSpawn?.agentTaskIds ?? []), entry.taskId];+ collapsed[existingIndex] = {+ ...mergeDerivedWorkLogEntries(existing, entry),+ // The CTA row keeps the group's ANCHOR identity, not the last+ // agent's: id/createdAt/turnId stay pinned to the spawn point so+ // the row renders where the run launched instead of drifting to+ // the newest progress tick (mid-run it drifted below the whole+ // conversation, reading as "no visualization"), and the stable id+ // keeps React state/virtualization sane.+ id: existing.id,+ createdAt: existing.createdAt,+ turnId: existing.turnId ?? null,+ ...(existing.taskId !== undefined ? { taskId: existing.taskId } : {}),+ label: existing.label,+ agentSpawn: { workflowId, agentTaskIds },+ };+ continue;+ }+ spawnRowIndex.set(groupKey, collapsed.length);+ collapsed.push({+ ...entry,+ agentSpawn: { workflowId, agentTaskIds: [entry.taskId] },+ });+ continue;+ }const previous = collapsed.at(-1);if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);@@ -847,6 +1040,14 @@ function mergeChangedFiles(}function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {+ // Subagent lifecycle rows collapse by agent identity: one row per agent,+ // progress ticks fold into it, the terminal row wins the label.+ if (+ entry.taskId &&+ (entry.activityKind === "task.progress" || entry.activityKind === "task.completed")+ ) {+ return `task${entry.taskId}`;+ }if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {return undefined;}diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 0b7b078a5..d1daa8716 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -123,6 +123,10 @@"types": "./src/state/threads.ts","default": "./src/state/threads.ts"},+ "./state/subagentRuntime": {+ "types": "./src/state/subagentRuntime.ts",+ "default": "./src/state/subagentRuntime.ts"+ },"./state/thread-sort": {"types": "./src/state/threadSort.ts","default": "./src/state/threadSort.ts"diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex 666b3b94c..ba80275bf 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -12,6 +12,13 @@ export function createOrchestrationEnvironmentAtoms<R, E>(label: "environment-data:orchestration:turn-diff",tag: ORCHESTRATION_WS_METHODS.getTurnDiff,}),+ workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:orchestration:workflow-script",+ tag: ORCHESTRATION_WS_METHODS.getWorkflowScript,+ // Scripts are immutable per run: cache generously.+ staleTimeMs: 300_000,+ idleTtlMs: 300_000,+ }),fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:orchestration:full-thread-diff",tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.tsnew file mode 100644index 000000000..c6c758511--- /dev/null+++ b/packages/client-runtime/src/state/subagentRuntime.test.ts@@ -0,0 +1,772 @@+import { describe, expect, it } from "vite-plus/test";+import { classifyTaskAgentKind, type OrchestrationThreadActivity } from "@t3tools/contracts";+import {+ deriveAgentPanelModel,+ foldSubagentActivities,+ formatSubagentModelLabel,+ formatSubagentTokenCount,+ isAgentAttributedToolActivity,+ isSubagentActivityKind,+ isTimelineBypassActivity,+ workflowCardMembers,+} from "./subagentRuntime.ts";++let sequence = 0;+/**+ * Fixtures model POST-INGESTION rows: ingestion stamps agentKind on every+ * task.* payload, so the helper stamps too (same classifier). Pass an+ * explicit agentKind (or agentKind: undefined via legacy()) to override.+ */+function activity(+ kind: string,+ payload: Record<string, unknown>,+ at = `2026-08-01T10:00:${String(sequence).padStart(2, "0")}.000Z`,+): OrchestrationThreadActivity {+ sequence += 1;+ const stamped =+ kind.startsWith("task.") && !("agentKind" in payload)+ ? {+ ...payload,+ agentKind: classifyTaskAgentKind({+ taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,+ agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,+ }),+ }+ : payload;+ return {+ id: `activity-${sequence}`,+ tone: "info",+ kind,+ summary: kind,+ payload: stamped,+ turnId: null,+ createdAt: at,+ } as unknown as OrchestrationThreadActivity;+}++/** A pre-stamp row (legacy thread / old server): no agentKind at all. */+function legacyActivity(+ kind: string,+ payload: Record<string, unknown>,+): OrchestrationThreadActivity {+ sequence += 1;+ return {+ id: `activity-${sequence}`,+ tone: "info",+ kind,+ summary: kind,+ payload,+ turnId: null,+ createdAt: `2026-08-01T10:00:${String(sequence).padStart(2, "0")}.000Z`,+ } as unknown as OrchestrationThreadActivity;+}++function fold(rows: ReadonlyArray<OrchestrationThreadActivity>) {+ return foldSubagentActivities(rows);+}++describe("foldSubagentActivities", () => {+ it("builds an agent from start → progress → completion", () => {+ const agents = fold([+ activity("task.started", {+ taskId: "task-1",+ title: "Audit auth flow",+ role: "explorer",+ }),+ activity("task.progress", {+ taskId: "task-1",+ lastToolName: "Read",+ typedUsage: { totalTokens: 1200, toolUses: 3 },+ }),+ activity("task.completed", {+ taskId: "task-1",+ status: "completed",+ summary: "Found 2 issues",+ typedUsage: { totalTokens: 5000, toolUses: 9 },+ }),+ ]);+ expect(agents).toHaveLength(1);+ const agent = agents[0]!;+ expect(agent.title).toBe("Audit auth flow");+ expect(agent.role).toBe("explorer");+ expect(agent.status).toBe("completed");+ expect(agent.result).toBe("Found 2 issues");+ expect(agent.usage?.totalTokens).toBe(5000);+ expect(agent.activationCount).toBe(1);+ expect(agent.completedAt).not.toBeNull();+ });++ it("progress can create an agent when its start row aged out of retention", () => {+ const agents = fold([+ activity("task.progress", {+ taskId: "task-orphan",+ title: "Recovered agent",+ role: "verifier",+ typedUsage: { totalTokens: 100 },+ }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.title).toBe("Recovered agent");+ expect(agents[0]!.status).toBe("running");+ });++ it("completion before start stays terminal; a late start only fills metadata", () => {+ const agents = fold([+ activity("task.completed", {+ taskId: "task-2",+ status: "failed",+ summary: "boom",+ role: "fixer",+ }),+ activity("task.started", { taskId: "task-2", title: "Late metadata", role: "fixer" }),+ ]);+ expect(agents).toHaveLength(1);+ const agent = agents[0]!;+ expect(agent.title).toBe("Late metadata");+ expect(agent.role).toBe("fixer");+ // The late start must NOT reopen the terminal activation as a new run.+ expect(agent.status).toBe("failed");+ expect(agent.error).toBe("boom");+ });++ it("duplicate terminal events are idempotent (timestamps do not slide)", () => {+ const agents = fold([+ activity("task.started", { taskId: "task-3", taskType: "local_agent" }),+ activity(+ "task.completed",+ { taskId: "task-3", status: "completed" },+ "2026-08-01T11:00:00.000Z",+ ),+ activity(+ "task.completed",+ { taskId: "task-3", status: "completed" },+ "2026-08-01T12:00:00.000Z",+ ),+ ]);+ expect(agents[0]!.completedAt).toBe("2026-08-01T11:00:00.000Z");+ });++ it("reactivation increments the run count and clears result/error", () => {+ const agents = fold([+ activity("task.started", { taskId: "task-4", taskType: "local_agent" }),+ activity("task.completed", { taskId: "task-4", status: "completed", summary: "run 1 done" }),+ activity("task.updated", { taskId: "task-4", status: "running" }),+ ]);+ const agent = agents[0]!;+ expect(agent.activationCount).toBe(2);+ expect(agent.result).toBeNull();+ expect(agent.completedAt).toBeNull();+ expect(agent.status).toBe("running");+ });++ it("idle is nonterminal: an idle agent resumes without losing identity", () => {+ const agents = fold([+ activity("task.started", { taskId: "codex-child-1", title: "Marlow", role: "explorer" }),+ activity("task.updated", { taskId: "codex-child-1", status: "idle" }),+ activity("task.updated", { taskId: "codex-child-1", status: "running" }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.activationCount).toBe(2);+ expect(agents[0]!.status).toBe("running");+ });++ it("cumulative usage max-merges: duplicate and late frames never shrink or double-count", () => {+ const agents = fold([+ activity("task.started", { taskId: "task-5", taskType: "local_agent" }),+ activity("task.progress", {+ taskId: "task-5",+ typedUsage: { totalTokens: 900, inputTokens: 700 },+ }),+ activity("task.progress", {+ taskId: "task-5",+ typedUsage: { totalTokens: 900, inputTokens: 700 },+ }),+ activity("task.progress", { taskId: "task-5", typedUsage: { totalTokens: 500 } }),+ ]);+ expect(agents[0]!.usage).toEqual({ totalTokens: 900, inputTokens: 700 });+ });++ it("partial terminal usage preserves known breakdown fields", () => {+ const agents = fold([+ activity("task.started", { taskId: "task-6", taskType: "local_agent" }),+ activity("task.progress", {+ taskId: "task-6",+ typedUsage: { totalTokens: 800, inputTokens: 600, outputTokens: 150 },+ }),+ activity("task.completed", {+ taskId: "task-6",+ status: "completed",+ typedUsage: { totalTokens: 1000 },+ }),+ ]);+ expect(agents[0]!.usage).toEqual({ totalTokens: 1000, inputTokens: 600, outputTokens: 150 });+ });++ it("skips malformed rows individually without failing the fold", () => {+ const agents = fold([+ activity("task.started", { taskId: "task-7", title: "Good", taskType: "local_agent" }),+ activity("task.progress", { bogus: true }),+ activity("task.progress", { taskId: 42 }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.title).toBe("Good");+ });++ it("bounds repeated strings at 180 chars and the activity ring at 6 deduped entries", () => {+ const long = "x".repeat(500);+ const rows = [activity("task.started", { taskId: "task-8", taskType: "local_agent" })];+ for (let i = 0; i < 10; i += 1) {+ rows.push(activity("task.progress", { taskId: "task-8", summary: `${long}-${i}` }));+ }+ rows.push(activity("task.progress", { taskId: "task-8", summary: `${long}-9` }));+ const agents = fold(rows);+ const agent = agents[0]!;+ expect(agent.recentActivity.length).toBeLessThanOrEqual(6);+ for (const entry of agent.recentActivity) {+ expect(entry.summary.length).toBeLessThanOrEqual(180);+ }+ // Consecutive identical summaries dedupe (truncation makes them equal).+ const summaries = agent.recentActivity.map((entry) => entry.summary);+ expect(new Set(summaries).size).toBe(summaries.length);+ });++ it("plan tasks are not agents", () => {+ const agents = fold([activity("task.started", { taskId: "plan-1", taskType: "plan" })]);+ expect(agents).toHaveLength(0);+ });++ it("workflow members key by stable slot and attach to their coordinator", () => {+ const agents = fold([+ activity("task.started", {+ taskId: "wf-1",+ taskType: "local_workflow",+ title: "audit-auth-flow",+ workflowName: "audit-auth-flow",+ }),+ activity("task.progress", {+ taskId: "wf-1",+ phases: [+ { index: 0, title: "Audit" },+ { index: 1, title: "Verify" },+ ],+ }),+ activity("task.progress", {+ taskId: "wf-1:wf:0",+ title: "audit:entrypoints",+ status: "running",+ parentAgentId: "wf-1",+ agentIndex: 0,+ phaseIndex: 0,+ phaseTitle: "Audit",+ timelineBypass: true,+ }),+ ]);+ const workflow = agents.find((agent) => agent.id === "wf-1");+ const member = agents.find((agent) => agent.id === "wf-1:wf:0");+ expect(workflow?.kind).toBe("workflow");+ expect(workflow?.phases).toEqual([+ { index: 0, title: "Audit" },+ { index: 1, title: "Verify" },+ ]);+ expect(member?.kind).toBe("workflow_agent");+ expect(member?.parentAgentId).toBe("wf-1");+ });++ it("a workflow member retry (attempt bump) is a reactivation of the same slot", () => {+ const agents = fold([+ activity("task.progress", {+ taskId: "wf-2:wf:1",+ title: "verify:refresh",+ status: "failed",+ error: "attempt 1 died",+ parentAgentId: "wf-2",+ attempt: 1,+ }),+ activity("task.progress", {+ taskId: "wf-2:wf:1",+ title: "verify:refresh",+ status: "running",+ parentAgentId: "wf-2",+ attempt: 2,+ }),+ ]);+ expect(agents).toHaveLength(1);+ const member = agents[0]!;+ expect(member.activationCount).toBeGreaterThanOrEqual(2);+ expect(member.error).toBeNull();+ expect(member.status).toBe("running");+ });++ it("drops non-http(s) session urls at the fold boundary", () => {+ const agents = fold([+ activity("task.started", {+ taskId: "wf-3",+ taskType: "local_workflow",+ runHandles: { sessionUrl: "javascript:alert(1)", runId: "run-1" },+ }),+ ]);+ expect(agents[0]!.runHandles?.sessionUrl).toBeUndefined();+ expect(agents[0]!.runHandles?.runId).toBe("run-1");+ });+});++describe("deriveAgentPanelModel", () => {+ const roster = fold([+ activity("task.started", { taskId: "wf-1", taskType: "local_workflow", title: "audit" }),+ activity("task.progress", {+ taskId: "wf-1",+ phases: [+ { index: 0, title: "Audit" },+ { index: 1, title: "Verify" },+ ],+ }),+ activity("task.progress", {+ taskId: "wf-1:wf:0",+ title: "audit:a",+ status: "completed",+ parentAgentId: "wf-1",+ agentIndex: 0,+ phaseIndex: 0,+ }),+ activity("task.completed", { taskId: "wf-1:wf:0", status: "completed", parentAgentId: "wf-1" }),+ activity("task.progress", {+ taskId: "wf-1:wf:1",+ title: "verify:b",+ status: "running",+ parentAgentId: "wf-1",+ agentIndex: 1,+ phaseIndex: 1,+ typedUsage: { totalTokens: 4000 },+ }),+ activity("task.started", { taskId: "direct-1", title: "Marlow", role: "explorer" }),+ activity("task.updated", { taskId: "direct-1", status: "idle" }),+ ]);++ it("groups workflow members by phase and separates direct spawns", () => {+ const model = deriveAgentPanelModel({ agents: roster });+ expect(model.workflows).toHaveLength(1);+ const group = model.workflows[0]!;+ expect(group.phases).toHaveLength(2);+ expect(group.phases[0]!.state).toBe("done");+ expect(group.phases[1]!.state).toBe("running");+ expect(model.directAgents.map((agent) => agent.id)).toEqual(["direct-1"]);+ });++ it("counts idle deliberately and waiting as active", () => {+ const model = deriveAgentPanelModel({ agents: roster });+ expect(model.idleCount).toBe(1);+ // wf-1 coordinator + member 1 running.+ expect(model.runningCount).toBeGreaterThanOrEqual(1);+ expect(model.idleCount + model.runningCount + model.waitingCount + model.settledCount).toBe(+ roster.length,+ );+ });++ it("a phase with only pending members never reads as running", () => {+ const pendingRoster = fold([+ activity("task.started", { taskId: "wf-9", taskType: "local_workflow" }),+ activity("task.progress", {+ taskId: "wf-9",+ phases: [{ index: 0, title: "Fix" }],+ }),+ activity("task.progress", {+ taskId: "wf-9:wf:0",+ title: "fixer",+ status: "pending",+ parentAgentId: "wf-9",+ agentIndex: 0,+ phaseIndex: 0,+ }),+ ]);+ const model = deriveAgentPanelModel({ agents: pendingRoster });+ // "pending" counts as active liveness (queued work), so the phase reads+ // running only if a member is genuinely pending/running — this asserts+ // the settled-count rule: no member settled, phase not done.+ expect(model.workflows[0]!.phases[0]!.state).not.toBe("done");+ });++ it("v2 projection wins outright and sources are never merged", () => {+ const v2Agent = { ...roster[0]!, id: "v2-only", title: "From v2" };+ const model = deriveAgentPanelModel({ agents: roster, v2Projection: [v2Agent] });+ const allIds = [+ ...model.workflows.map((group) => group.workflow.id),+ ...model.directAgents.map((agent) => agent.id),+ ];+ expect(allIds).toContain("v2-only");+ expect(allIds).not.toContain("direct-1");+ });++ it("orphaned members fall back to the direct list", () => {+ const orphans = fold([+ activity("task.progress", {+ taskId: "gone:wf:0",+ title: "orphan",+ status: "running",+ parentAgentId: "gone",+ }),+ ]);+ const model = deriveAgentPanelModel({ agents: orphans });+ expect(model.workflows).toHaveLength(0);+ expect(model.directAgents.map((agent) => agent.id)).toEqual(["gone:wf:0"]);+ });+});++describe("workflowCardMembers", () => {+ it("orders by urgency (failed, running, waiting) and reports overflow", () => {+ const roster = fold([+ activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),+ ...[..."abcdefghij"].map((letter, index) =>+ activity("task.progress", {+ taskId: `wf-1:wf:${index}`,+ title: `agent-${letter}`,+ status: index === 3 ? "failed" : index < 3 ? "completed" : "running",+ ...(index === 3 ? { error: "died" } : {}),+ parentAgentId: "wf-1",+ agentIndex: index,+ phaseIndex: 0,+ phaseTitle: "Work",+ }),+ ),+ ]);+ const model = deriveAgentPanelModel({ agents: roster });+ const { visible, overflow } = workflowCardMembers(model.workflows[0]!, 8);+ expect(visible).toHaveLength(8);+ expect(overflow).toBe(2);+ expect(visible[0]!.status).toBe("failed");+ expect(visible.filter((agent) => agent.status === "completed").length).toBeLessThanOrEqual(2);+ });+});++describe("timeline predicates", () => {+ it("recognizes subagent activity kinds as fold input", () => {+ for (const kind of [+ "task.started",+ "task.progress",+ "task.updated",+ "task.completed",+ "tool.progress",+ ]) {+ expect(isSubagentActivityKind(kind)).toBe(true);+ }+ expect(isSubagentActivityKind("tool.completed")).toBe(false);+ });++ it("attributed tool rows are re-homed; unattributed rows stay in the timeline", () => {+ expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: "task-1" }))).toBe(+ true,+ );+ expect(isAgentAttributedToolActivity(activity("tool.completed", {}))).toBe(false);+ expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: " " }))).toBe(+ false,+ );+ });++ it("timelineBypass rows never render in the parent chat", () => {+ expect(isTimelineBypassActivity(activity("task.progress", { timelineBypass: true }))).toBe(+ true,+ );+ expect(isTimelineBypassActivity(activity("task.progress", {}))).toBe(false);+ });+});++describe("formatSubagentTokenCount", () => {+ it("formats plain counters", () => {+ expect(formatSubagentTokenCount(950)).toBe("950");+ expect(formatSubagentTokenCount(41200)).toBe("41.2k");+ expect(formatSubagentTokenCount(247000)).toBe("247k");+ expect(formatSubagentTokenCount(1_400_000)).toBe("1.4M");+ });+});++describe("model and effort attribution", () => {+ it("carries model/effort from start rows and refines model from later rows", () => {+ const agents = fold([+ activity("task.started", {+ taskId: "task-m",+ title: "Verify math",+ model: "sonnet",+ effort: "high",+ }),+ // Later row refines with the authoritative API model id; effort absent+ // must not clear the known value.+ activity("task.progress", { taskId: "task-m", model: "claude-sonnet-5[1m]" }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.model).toBe("claude-sonnet-5[1m]");+ expect(agents[0]!.effort).toBe("high");+ });++ it("formatSubagentModelLabel compacts ids and appends effort", () => {+ expect(formatSubagentModelLabel("claude-sonnet-5[1m]", "high")).toBe("sonnet-5[1m] · high");+ expect(formatSubagentModelLabel("claude-opus-4-20250514", null)).toBe("opus-4");+ expect(formatSubagentModelLabel("gpt-5.6-sol", "low")).toBe("gpt-5.6-sol · low");+ expect(formatSubagentModelLabel(null, "high")).toBeNull();+ });+});++describe("background task exclusion", () => {+ it("shells and monitors never join the roster (from any lifecycle row)", () => {+ const agents = fold([+ activity("task.started", { taskId: "shell-1", taskType: "shell", title: "Run 12s stall" }),+ activity("task.progress", { taskId: "shell-2", taskType: "shell", title: "Run stall" }),+ activity("task.completed", { taskId: "mon-1", taskType: "monitor", status: "completed" }),+ activity("task.started", { taskId: "agent-1", taskType: "subagent", title: "Real agent" }),+ ]);+ expect(agents.map((agent) => agent.id)).toEqual(["agent-1"]);+ });++ it("rows without a taskType stay in the roster (workflow members, Codex children)", () => {+ const agents = fold([+ activity("task.progress", { taskId: "wf-1:wf:0", status: "running", parentAgentId: "wf-1" }),+ ]);+ expect(agents).toHaveLength(1);+ });++ it("the server stamp is the only classifier: no stamp means no roster row", () => {+ const agents = fold([+ // Stamped background: agent-looking fields don't matter.+ activity("task.started", {+ taskId: "bg-1",+ agentKind: "background",+ role: "watcher",+ model: "sonnet",+ }),+ // Stamped agent: plain row still joins the roster.+ activity("task.started", { taskId: "ag-1", agentKind: "agent", detail: "plain row" }),+ // Legacy pre-stamp rows (old threads/servers) stay in the work log —+ // exactly their pre-upgrade behavior.+ legacyActivity("task.started", { taskId: "old-task", detail: "tailing logs" }),+ legacyActivity("task.progress", { taskId: "old-task", summary: "still tailing" }),+ ]);+ expect(agents.map((agent) => agent.id)).toEqual(["ag-1"]);+ });++ it("membership is sticky: a stampless later row still reaches a known agent", () => {+ const agents = fold([+ activity("task.started", { taskId: "a1", taskType: "local_agent", title: "Agent" }),+ // Terminal row missing the stamp (defensive: adapters synthesize some+ // rows) — sticky membership still routes it to the agent.+ legacyActivity("task.completed", { taskId: "a1", status: "completed", summary: "done" }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.status).toBe("completed");+ expect(agents[0]!.result).toBe("done");+ });+});++describe("session-derived interruption", () => {+ it("dead session interrupts live agents but preserves idle and settled", () => {+ const rows = [+ activity("task.started", { taskId: "live-1", taskType: "local_agent" }),+ activity("task.started", { taskId: "idle-1", taskType: "local_agent" }),+ activity("task.updated", { taskId: "idle-1", status: "idle" }),+ activity("task.started", { taskId: "done-1", taskType: "local_agent" }),+ activity("task.completed", { taskId: "done-1", status: "completed" }),+ ];+ const dead = foldSubagentActivities(rows, { sessionLive: false });+ expect(dead.find((agent) => agent.id === "live-1")?.status).toBe("interrupted");+ expect(dead.find((agent) => agent.id === "idle-1")?.status).toBe("idle");+ expect(dead.find((agent) => agent.id === "done-1")?.status).toBe("completed");+ const alive = foldSubagentActivities(rows, { sessionLive: true });+ expect(alive.find((agent) => agent.id === "live-1")?.status).toBe("running");+ });+});++describe("terminal robustness", () => {+ it("task.updated creating an agent (start row aged out) counts one activation", () => {+ const agents = fold([+ activity("task.updated", { taskId: "orphan-u", status: "running", role: "worker" }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.activationCount).toBe(1);+ expect(agents[0]!.status).toBe("running");+ });++ it("a late start after a terminal task.updated does not reopen the run", () => {+ const agents = fold([+ activity("task.updated", { taskId: "t1", status: "failed", role: "worker" }),+ activity("task.started", { taskId: "t1", taskType: "local_agent", title: "Late" }),+ ]);+ expect(agents).toHaveLength(1);+ expect(agents[0]!.status).toBe("failed");+ expect(agents[0]!.title).toBe("Late");+ });++ it("a completion after a terminal task.updated still enriches result and usage", () => {+ // Claude commonly emits terminal task.updated before task.completed;+ // the completion carries the summary and final usage the update lacked.+ const agents = fold([+ activity("task.started", { taskId: "te-1", taskType: "local_agent" }),+ activity(+ "task.updated",+ { taskId: "te-1", status: "completed", endedAt: "2026-08-01T10:59:00.000Z" },+ "2026-08-01T11:00:00.000Z",+ ),+ activity(+ "task.completed",+ {+ taskId: "te-1",+ status: "completed",+ summary: "final answer",+ typedUsage: { totalTokens: 4200, toolUses: 7 },+ },+ "2026-08-01T11:00:01.000Z",+ ),+ ]);+ const agent = agents[0]!;+ expect(agent.status).toBe("completed");+ expect(agent.result).toBe("final answer");+ expect(agent.usage?.totalTokens).toBe(4200);+ // Timestamps stay pinned to the transition that settled the run.+ expect(agent.completedAt).toBe("2026-08-01T10:59:00.000Z");+ });++ it("duplicate completions keep the FIRST result, not the last", () => {+ const agents = fold([+ activity("task.started", { taskId: "t2", taskType: "local_agent" }),+ activity("task.completed", { taskId: "t2", status: "completed", summary: "first result" }),+ activity("task.completed", { taskId: "t2", status: "completed", summary: "second result" }),+ ]);+ expect(agents[0]!.result).toBe("first result");+ });++ it("provider endedAt wins over ingestion time on the settling transition", () => {+ const agents = fold([+ activity("task.started", { taskId: "t3", taskType: "local_agent" }),+ activity(+ "task.updated",+ { taskId: "t3", status: "failed", endedAt: "2026-08-01T09:59:59.000Z" },+ "2026-08-01T10:00:30.000Z",+ ),+ ]);+ expect(agents[0]!.completedAt).toBe("2026-08-01T09:59:59.000Z");+ });++ it("workflow retries count each attempt once", () => {+ const agents = fold([+ activity("task.progress", {+ taskId: "wf-r:wf:0",+ parentAgentId: "wf-r",+ status: "running",+ attempt: 1,+ }),+ activity("task.progress", {+ taskId: "wf-r:wf:0",+ parentAgentId: "wf-r",+ status: "failed",+ attempt: 1,+ }),+ activity("task.progress", {+ taskId: "wf-r:wf:0",+ parentAgentId: "wf-r",+ status: "running",+ attempt: 2,+ }),+ ]);+ expect(agents[0]!.activationCount).toBe(2);+ });+});++describe("phase membership", () => {+ it("members with unknown phase indices land in unphasedMembers, never vanish", () => {+ const model = deriveAgentPanelModel({+ agents: fold([+ activity("task.started", {+ taskId: "wf-p",+ taskType: "local_workflow",+ phases: [{ index: 0, title: "Only phase" }],+ }),+ activity("task.progress", {+ taskId: "wf-p:wf:0",+ parentAgentId: "wf-p",+ status: "running",+ phaseIndex: 0,+ }),+ activity("task.progress", {+ taskId: "wf-p:wf:9",+ parentAgentId: "wf-p",+ status: "running",+ phaseIndex: 9,+ }),+ ]),+ });+ const group = model.workflows[0]!;+ const visible = [+ ...group.phases.flatMap((phase) => phase.members),+ ...group.unphasedMembers,+ ].map((member) => member.id);+ expect(visible).toContain("wf-p:wf:0");+ expect(visible).toContain("wf-p:wf:9");+ });+});++describe("coordinator settle cascade", () => {+ it("members without their own terminal row settle when the coordinator does", () => {+ const agents = fold([+ activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),+ activity("task.progress", {+ taskId: "wf-1:wf:0",+ title: "stalled member",+ status: "running",+ parentAgentId: "wf-1",+ }),+ activity("task.completed", {+ taskId: "wf-1",+ status: "completed",+ taskType: "local_workflow",+ }),+ ]);+ const member = agents.find((agent) => agent.id === "wf-1:wf:0");+ expect(member?.status).toBe("completed");+ expect(member?.completedAt).not.toBeNull();+ });++ it("a failed coordinator marks unfinished members interrupted, not completed", () => {+ const agents = fold([+ activity("task.started", { taskId: "wf-2", taskType: "local_workflow" }),+ activity("task.progress", {+ taskId: "wf-2:wf:0",+ status: "running",+ parentAgentId: "wf-2",+ }),+ activity("task.completed", { taskId: "wf-2", status: "failed", taskType: "local_workflow" }),+ ]);+ const member = agents.find((agent) => agent.id === "wf-2:wf:0");+ expect(member?.status).toBe("interrupted");+ });+});++describe("task type classification is a denylist", () => {+ it("unknown agent-flavored types (local_agent, future names) join the roster", () => {+ const agents = fold([+ activity("task.started", {+ taskId: "a1",+ taskType: "local_agent",+ title: "Math test 1",+ role: "claude",+ }),+ activity("task.started", { taskId: "a2", taskType: "some_future_agent_kind", title: "X" }),+ ]);+ expect(agents.map((agent) => agent.id).toSorted()).toEqual(["a1", "a2"]);+ });+});++describe("nested agents vs subagent shells", () => {+ it("a nested agent (agentId + agent taskType) stays in the roster; its shells do not", () => {+ const agents = fold([+ activity("task.started", {+ taskId: "nested-1",+ taskType: "local_agent",+ agentId: "parent-agent",+ title: "Nested researcher",+ }),+ activity("task.started", {+ taskId: "shell-1",+ taskType: "local_bash",+ agentId: "parent-agent",+ title: "Nested sleep",+ }),+ ]);+ expect(agents.map((agent) => agent.id)).toEqual(["nested-1"]);+ });+});diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.tsnew file mode 100644index 000000000..c81dd6341--- /dev/null+++ b/packages/client-runtime/src/state/subagentRuntime.ts@@ -0,0 +1,924 @@+/**+ * Native-provider subagent observability: a tolerant fold over persisted+ * task.* / tool.* thread activities into orchestration-v2-shaped subagent+ * state, plus the source-neutral panel model every client renders.+ *+ * This module is deliberately legacy-bridge code. When orchestration-v2's+ * subagent projection is available for a thread, deriveAgentPanelModel+ * prefers it (see the v2Projection parameter) and the fold is skipped; when+ * the v1 orchestrator is retired this file is deleted. Field names and+ * transition semantics copy the v2 stack (#4779) exactly so that swap is+ * mechanical.+ *+ * Invariants encoded here trace to shipped bugs in the prior PRs (#4220,+ * #3650, #4662): reusable identity vs one-shot activations, idle as a real+ * nonterminal state, provider-specific usage merges, first-write terminal+ * timestamps, reactivation clearing terminal detail, and order-robust+ * folding (completion can create an agent; a late start only fills+ * metadata).+ */+import type { OrchestrationThreadActivity } from "@t3tools/contracts";++export type RuntimeSubagentStatus =+ | "pending"+ | "running"+ | "waiting"+ | "idle"+ | "completed"+ | "failed"+ | "cancelled"+ | "interrupted";++export interface SubagentUsage {+ readonly totalTokens: number;+ readonly inputTokens?: number;+ readonly cachedInputTokens?: number;+ readonly outputTokens?: number;+ readonly reasoningOutputTokens?: number;+ readonly toolUses?: number;+ readonly durationMs?: number;+}++export interface SubagentActivityEntry {+ readonly at: string;+ readonly summary: string;+}++export interface SubagentWorkflowPhase {+ readonly index: number;+ readonly title: string;+}++export interface SubagentRunHandles {+ readonly runId?: string;+ readonly scriptPath?: string;+ readonly transcriptDir?: string;+ readonly sessionUrl?: string;+}++export interface RuntimeSubagent {+ readonly id: string;+ readonly kind: "subagent" | "workflow" | "workflow_agent";+ readonly title: string;+ readonly role: string | null;+ readonly model: string | null;+ readonly effort: string | null;+ readonly status: RuntimeSubagentStatus;+ readonly activationCount: number;+ readonly usage: SubagentUsage | null;+ readonly progress: string | null;+ readonly lastToolName: string | null;+ readonly result: string | null;+ readonly error: string | null;+ readonly outputFile: string | null;+ readonly parentAgentId: string | null;+ readonly agentIndex: number | null;+ readonly phaseIndex: number | null;+ readonly phaseTitle: string | null;+ readonly attempt: number | null;+ readonly workflowName: string | null;+ readonly phases: ReadonlyArray<SubagentWorkflowPhase>;+ readonly runHandles: SubagentRunHandles | null;+ readonly recentActivity: ReadonlyArray<SubagentActivityEntry>;+ readonly startedAt: string | null;+ readonly completedAt: string | null;+ readonly updatedAt: string;+}++const TERMINAL_STATUSES: ReadonlySet<RuntimeSubagentStatus> = new Set([+ "completed",+ "failed",+ "cancelled",+ "interrupted",+]);++export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean {+ return TERMINAL_STATUSES.has(status);+}++/** Active = the user may still need to care while it runs. Idle is settled-ish+ * but resumable; waiting counts as active because it needs the user. */+export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {+ return status === "pending" || status === "running" || status === "waiting";+}++const RECENT_ACTIVITY_LIMIT = 6;+const SUMMARY_CHAR_LIMIT = 180;+const ROSTER_LIMIT = 100;++/**+ * True when this activity's payload does NOT belong on the Agents surface.+ * Classification happens exactly once, server-side at ingestion+ * (classifyTaskAgentKind → the persisted agentKind stamp); the client only+ * reads it. Rows without a stamp — legacy threads, pre-stamp servers — are+ * background by definition: they render in the ordinary work log, exactly+ * as they did before this feature existed.+ */+export function isBackgroundTaskActivity(payload: Record<string, unknown>): boolean {+ return payload.agentKind !== "agent";+}++function bounded(value: string): string {+ return value.length <= SUMMARY_CHAR_LIMIT ? value : `${value.slice(0, SUMMARY_CHAR_LIMIT - 1)}…`;+}++/** Appends to the ring buffer, deduping consecutive identical summaries. */+function appendActivity(+ entries: ReadonlyArray<SubagentActivityEntry>,+ at: string,+ summary: string,+): ReadonlyArray<SubagentActivityEntry> {+ const boundedSummary = bounded(summary);+ if (entries.length > 0 && entries[entries.length - 1]?.summary === boundedSummary) {+ return entries;+ }+ const next = [...entries, { at, summary: boundedSummary }];+ return next.length > RECENT_ACTIVITY_LIMIT ? next.slice(-RECENT_ACTIVITY_LIMIT) : next;+}++function asString(value: unknown): string | undefined {+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;+}++function asCount(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;+}++function asUsage(value: unknown): SubagentUsage | undefined {+ if (typeof value !== "object" || value === null) {+ return undefined;+ }+ const record = value as Record<string, unknown>;+ const totalTokens = asCount(record.totalTokens);+ if (totalTokens === undefined) {+ return undefined;+ }+ const usage: {+ totalTokens: number;+ inputTokens?: number;+ cachedInputTokens?: number;+ outputTokens?: number;+ reasoningOutputTokens?: number;+ toolUses?: number;+ durationMs?: number;+ } = { totalTokens };+ const inputTokens = asCount(record.inputTokens);+ if (inputTokens !== undefined) usage.inputTokens = inputTokens;+ const cachedInputTokens = asCount(record.cachedInputTokens);+ if (cachedInputTokens !== undefined) usage.cachedInputTokens = cachedInputTokens;+ const outputTokens = asCount(record.outputTokens);+ if (outputTokens !== undefined) usage.outputTokens = outputTokens;+ const reasoningOutputTokens = asCount(record.reasoningOutputTokens);+ if (reasoningOutputTokens !== undefined) usage.reasoningOutputTokens = reasoningOutputTokens;+ const toolUses = asCount(record.toolUses);+ if (toolUses !== undefined) usage.toolUses = toolUses;+ const durationMs = asCount(record.durationMs);+ if (durationMs !== undefined) usage.durationMs = durationMs;+ return usage;+}++/**+ * Provider-specific usage merge (#4779 semantics, verbatim):+ * - max-merge (Codex-style cumulative frames): field-wise maximum, idempotent+ * under duplicate or late frames. Cumulative totals never shrink.+ * - accumulate (Claude-style activation deltas): not needed at this layer —+ * Claude's task_progress usage is itself cumulative per task, so the fold+ * also max-merges. The distinction matters when v2 sums activations.+ * Field-wise: a terminal payload carrying only totalTokens must not wipe a+ * known breakdown.+ */+function mergeUsageMax(+ current: SubagentUsage | null,+ incoming: SubagentUsage | undefined,+): SubagentUsage | null {+ if (!incoming) {+ return current;+ }+ if (!current) {+ return incoming;+ }+ const pick = (a: number | undefined, b: number | undefined): number | undefined =>+ a === undefined ? b : b === undefined ? a : Math.max(a, b);+ const merged: {+ totalTokens: number;+ inputTokens?: number;+ cachedInputTokens?: number;+ outputTokens?: number;+ reasoningOutputTokens?: number;+ toolUses?: number;+ durationMs?: number;+ } = { totalTokens: Math.max(current.totalTokens, incoming.totalTokens) };+ const inputTokens = pick(current.inputTokens, incoming.inputTokens);+ if (inputTokens !== undefined) merged.inputTokens = inputTokens;+ const cachedInputTokens = pick(current.cachedInputTokens, incoming.cachedInputTokens);+ if (cachedInputTokens !== undefined) merged.cachedInputTokens = cachedInputTokens;+ const outputTokens = pick(current.outputTokens, incoming.outputTokens);+ if (outputTokens !== undefined) merged.outputTokens = outputTokens;+ const reasoningOutputTokens = pick(current.reasoningOutputTokens, incoming.reasoningOutputTokens);+ if (reasoningOutputTokens !== undefined) merged.reasoningOutputTokens = reasoningOutputTokens;+ const toolUses = pick(current.toolUses, incoming.toolUses);+ if (toolUses !== undefined) merged.toolUses = toolUses;+ const durationMs = pick(current.durationMs, incoming.durationMs);+ if (durationMs !== undefined) merged.durationMs = durationMs;+ return merged;+}++interface MutableAgent {+ id: string;+ kind: RuntimeSubagent["kind"];+ title: string;+ role: string | null;+ model: string | null;+ effort: string | null;+ status: RuntimeSubagentStatus;+ activationCount: number;+ usage: SubagentUsage | null;+ progress: string | null;+ lastToolName: string | null;+ result: string | null;+ error: string | null;+ outputFile: string | null;+ parentAgentId: string | null;+ agentIndex: number | null;+ phaseIndex: number | null;+ phaseTitle: string | null;+ attempt: number | null;+ workflowName: string | null;+ phases: ReadonlyArray<SubagentWorkflowPhase>;+ runHandles: SubagentRunHandles | null;+ recentActivity: ReadonlyArray<SubagentActivityEntry>;+ startedAt: string | null;+ completedAt: string | null;+ updatedAt: string;+}++function kindFromPayload(+ payload: Record<string, unknown>,+ agentId: string,+): RuntimeSubagent["kind"] {+ if (asString(payload.taskType) === "local_workflow") {+ return "workflow";+ }+ if (payload.parentAgentId !== undefined || agentId.includes(":wf:")) {+ return "workflow_agent";+ }+ return "subagent";+}++/** Completion can create an agent (its start may have aged out of retention). */+function getOrCreate(+ agents: Map<string, MutableAgent>,+ id: string,+ payload: Record<string, unknown>,+ at: string,+): MutableAgent {+ const existing = agents.get(id);+ if (existing) {+ return existing;+ }+ const created: MutableAgent = {+ id,+ kind: kindFromPayload(payload, id),+ title: asString(payload.title) ?? asString(payload.detail) ?? id,+ role: asString(payload.role) ?? null,+ model: asString(payload.model) ?? null,+ effort: asString(payload.effort) ?? null,+ status: "pending",+ activationCount: 0,+ usage: null,+ progress: null,+ lastToolName: null,+ result: null,+ error: null,+ outputFile: null,+ parentAgentId: asString(payload.parentAgentId) ?? null,+ agentIndex: asCount(payload.agentIndex) ?? null,+ phaseIndex: asCount(payload.phaseIndex) ?? null,+ phaseTitle: asString(payload.phaseTitle) ?? null,+ attempt: asCount(payload.attempt) ?? null,+ workflowName: asString(payload.workflowName) ?? null,+ phases: [],+ runHandles: null,+ recentActivity: [],+ startedAt: null,+ completedAt: null,+ updatedAt: at,+ };+ agents.set(id, created);+ return created;+}++/** Metadata fill from any payload: never downgrades known values to null. */+function fillMetadata(agent: MutableAgent, payload: Record<string, unknown>): void {+ const title = asString(payload.title);+ if (title) agent.title = title;+ const role = asString(payload.role);+ if (role) agent.role = role;+ const model = asString(payload.model);+ if (model) agent.model = model;+ const effort = asString(payload.effort);+ if (effort) agent.effort = effort;+ const parentAgentId = asString(payload.parentAgentId);+ if (parentAgentId) {+ agent.parentAgentId = parentAgentId;+ if (agent.kind === "subagent") agent.kind = "workflow_agent";+ }+ const workflowName = asString(payload.workflowName);+ if (workflowName) agent.workflowName = workflowName;+ if (asString(payload.taskType) === "local_workflow") agent.kind = "workflow";+ const agentIndex = asCount(payload.agentIndex);+ if (agentIndex !== undefined) agent.agentIndex = agentIndex;+ const phaseIndex = asCount(payload.phaseIndex);+ if (phaseIndex !== undefined) agent.phaseIndex = phaseIndex;+ const phaseTitle = asString(payload.phaseTitle);+ if (phaseTitle) agent.phaseTitle = phaseTitle;+ const attempt = asCount(payload.attempt);+ if (attempt !== undefined) {+ // A new attempt on a workflow slot is a reactivation of the same+ // identity: clear the previous attempt's terminal detail so the status+ // transition (terminal → running, in applyStatus) reads as a fresh run.+ // The activation bump lives ONLY in applyStatus — bumping here too+ // counted every retry twice (review finding: two attempts read "run 3").+ if (agent.attempt !== null && attempt > agent.attempt) {+ agent.result = null;+ agent.error = null;+ agent.completedAt = null;+ }+ agent.attempt = attempt;+ }+ const outputFile = asString(payload.outputFile);+ if (outputFile) agent.outputFile = outputFile;+ if (Array.isArray(payload.phases)) {+ const phases: SubagentWorkflowPhase[] = [];+ for (const entry of payload.phases) {+ if (typeof entry !== "object" || entry === null) continue;+ const record = entry as Record<string, unknown>;+ const index = asCount(record.index);+ const phaseName = asString(record.title);+ if (index !== undefined && phaseName) {+ phases.push({ index, title: phaseName });+ }+ }+ if (phases.length > 0) {+ agent.phases = phases.slice().sort((a, b) => a.index - b.index);+ }+ }+ if (typeof payload.runHandles === "object" && payload.runHandles !== null) {+ const record = payload.runHandles as Record<string, unknown>;+ const runHandles: {+ runId?: string;+ scriptPath?: string;+ transcriptDir?: string;+ sessionUrl?: string;+ } = {};+ const runId = asString(record.runId);+ if (runId) runHandles.runId = runId;+ const scriptPath = asString(record.scriptPath);+ if (scriptPath) runHandles.scriptPath = scriptPath;+ const transcriptDir = asString(record.transcriptDir);+ if (transcriptDir) runHandles.transcriptDir = transcriptDir;+ // Defense-in-depth: the adapter already sanitizes, but payloads are not+ // schema-validated on the read path (shipped XSS lesson).+ const sessionUrl = asString(record.sessionUrl);+ if (sessionUrl && /^https?:\/\//i.test(sessionUrl)) runHandles.sessionUrl = sessionUrl;+ if (Object.keys(runHandles).length > 0) {+ agent.runHandles = { ...agent.runHandles, ...runHandles };+ }+ }+}++function applyStatus(agent: MutableAgent, status: RuntimeSubagentStatus, at: string): void {+ const wasTerminal = isTerminalSubagentStatus(agent.status);+ const isTerminal = isTerminalSubagentStatus(status);+ if (wasTerminal && isTerminal) {+ // Duplicate terminal events are idempotent: first write wins, timestamps+ // don't slide.+ return;+ }+ if ((wasTerminal || agent.status === "idle") && (status === "running" || status === "pending")) {+ // Reactivation: same identity, new run. Clear the previous run's terminal+ // detail so a live card never shows the prior run's output.+ agent.activationCount += 1;+ agent.result = null;+ agent.error = null;+ agent.completedAt = null;+ if (status === "running") {+ agent.startedAt = at;+ }+ }+ if (status === "running" && agent.startedAt === null) {+ agent.startedAt = at;+ }+ if (isTerminal && agent.completedAt === null) {+ agent.completedAt = at;+ }+ agent.status = status;+}++// Map, not object literal: payloads aren't schema-validated on the read+// path, so a status like "toString" must miss instead of resolving an+// inherited Function through the prototype chain.+const TASK_COMPLETED_STATUS: ReadonlyMap<string, RuntimeSubagentStatus> = new Map([+ ["completed", "completed"],+ ["failed", "failed"],+ ["stopped", "interrupted"],+]);++const KNOWN_STATUSES: ReadonlySet<string> = new Set([+ "pending",+ "running",+ "waiting",+ "idle",+ "completed",+ "failed",+ "cancelled",+ "interrupted",+]);++function asRuntimeStatus(value: unknown): RuntimeSubagentStatus | undefined {+ return typeof value === "string" && KNOWN_STATUSES.has(value)+ ? (value as RuntimeSubagentStatus)+ : undefined;+}++/**+ * Folds a thread's persisted activities into subagent state. Tolerant by+ * construction: malformed rows are skipped individually; unknown kinds are+ * ignored. Pure — memoize by activity-list identity at the atom layer.+ *+ * sessionLive=false derives interruption: background tasks die with their+ * provider session, so agents whose terminal rows were lost (server+ * restart, crash) must not read as running forever (review finding: a dead+ * session left a panel full of "Working" agents while the sidebar showed+ * nothing). Idle is preserved — a resumable Codex child stays resumable.+ */+export function foldSubagentActivities(+ activities: ReadonlyArray<OrchestrationThreadActivity>,+ options?: { readonly sessionLive?: boolean },+): ReadonlyArray<RuntimeSubagent> {+ const agents = new Map<string, MutableAgent>();++ for (const activity of activities) {+ if (typeof activity.payload !== "object" || activity.payload === null) {+ continue;+ }+ const payload = activity.payload as Record<string, unknown>;+ const at = activity.createdAt;++ switch (activity.kind) {+ case "task.started": {+ const taskId = asString(payload.taskId);+ if (!taskId) break;+ // Only real agents join the roster. Shells, monitors, and plan-mode+ // tasks are background work — they render in the ordinary work log,+ // not the Agents surface (a "Run 12s stall" shell is not a subagent).+ if (isBackgroundTaskActivity(payload)) break;+ const agent = getOrCreate(agents, taskId, payload, at);+ fillMetadata(agent, payload);+ // Order-robustness: a start row arriving after a terminal state is a+ // late/out-of-order delivery and only fills metadata — it must not+ // reopen the run. Reactivation comes exclusively from explicit+ // status transitions (task.updated / progress status). Guard on the+ // status itself, not activationCount: a task first seen via a+ // terminal task.updated has zero activations but is still settled+ // (review finding: a late start reopened a failed child).+ if (agent.activationCount === 0 && !isTerminalSubagentStatus(agent.status)) {+ agent.activationCount = 1;+ agent.startedAt = agent.startedAt ?? at;+ agent.status = "running";+ } else if (agent.status === "idle") {+ applyStatus(agent, "running", at);+ }+ const detail = asString(payload.detail);+ if (detail && agent.title === agent.id) agent.title = detail;+ agent.updatedAt = at;+ break;+ }+ case "task.progress": {+ const taskId = asString(payload.taskId);+ if (!taskId) break;+ // Membership is sticky per taskId: rows after the first (terminal+ // rows often carry only taskId+status, no marker fields) inherit the+ // first row's classification instead of being re-judged.+ if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;+ const agent = getOrCreate(agents, taskId, payload, at);+ fillMetadata(agent, payload);+ if (agent.activationCount === 0) agent.activationCount = 1;+ const explicitStatus = asRuntimeStatus(payload.status);+ if (explicitStatus) {+ applyStatus(agent, explicitStatus, at);+ } else if (!isTerminalSubagentStatus(agent.status) && agent.status !== "idle") {+ applyStatus(agent, "running", at);+ }+ const summary = asString(payload.summary);+ if (summary) {+ agent.progress = bounded(summary);+ agent.recentActivity = appendActivity(agent.recentActivity, at, summary);+ }+ const lastToolName = asString(payload.lastToolName);+ if (lastToolName) {+ agent.lastToolName = lastToolName;+ if (!summary) {+ agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${lastToolName}`);+ }+ }+ const error = asString(payload.error);+ if (error) agent.error = bounded(error);+ agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));+ agent.updatedAt = at;+ break;+ }+ case "task.updated": {+ const taskId = asString(payload.taskId);+ if (!taskId) break;+ // Membership is sticky per taskId: rows after the first (terminal+ // rows often carry only taskId+status, no marker fields) inherit the+ // first row's classification instead of being re-judged.+ if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;+ const agent = getOrCreate(agents, taskId, payload, at);+ fillMetadata(agent, payload);+ // A task first seen via task.updated (start row aged out) has run at+ // least once — zero activations would misreport "run 0" and let a+ // later start row treat it as never-started (review finding).+ if (agent.activationCount === 0) agent.activationCount = 1;+ const wasTerminal = isTerminalSubagentStatus(agent.status);+ const status = asRuntimeStatus(payload.status);+ if (status) applyStatus(agent, status, at);+ const error = asString(payload.error);+ if (error) agent.error = bounded(error);+ // Provider end time beats ingestion time for the transition that+ // actually settled the run (applyStatus fills completedAt with the+ // activity timestamp first, so check the transition, not null).+ const endedAt = asString(payload.endedAt);+ if (endedAt && !wasTerminal && isTerminalSubagentStatus(agent.status)) {+ agent.completedAt = endedAt;+ }+ agent.updatedAt = at;+ break;+ }+ case "task.completed": {+ const taskId = asString(payload.taskId);+ if (!taskId) break;+ // Membership is sticky per taskId: rows after the first (terminal+ // rows often carry only taskId+status, no marker fields) inherit the+ // first row's classification instead of being re-judged.+ if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;+ const agent = getOrCreate(agents, taskId, payload, at);+ fillMetadata(agent, payload);+ if (agent.activationCount === 0) agent.activationCount = 1;+ // Already-terminal: status and timestamps are frozen (first write+ // wins, duplicates must not slide them) but the completion still+ // ENRICHES — Claude commonly emits terminal task.updated before+ // task.completed, and the completion carries the result summary and+ // final usage the update lacked (review finding: the early return+ // dropped both). Fill-if-missing keeps duplicate completions from+ // replacing the first result.+ const summary = asString(payload.summary) ?? asString(payload.detail);+ if (isTerminalSubagentStatus(agent.status)) {+ if (summary) {+ if (agent.status === "failed") {+ agent.error = agent.error ?? bounded(summary);+ } else {+ agent.result = agent.result ?? bounded(summary);+ }+ }+ agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));+ break;+ }+ const status = TASK_COMPLETED_STATUS.get(asString(payload.status) ?? "") ?? "completed";+ applyStatus(agent, status, at);+ if (summary) {+ if (status === "failed") {+ agent.error = agent.error ?? bounded(summary);+ } else {+ agent.result = bounded(summary);+ }+ }+ agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));+ agent.updatedAt = at;+ break;+ }+ case "tool.progress": {+ // Agent-owned heartbeat: "what it's doing right now".+ const taskId = asString(payload.taskId);+ if (!taskId) break;+ const agent = agents.get(taskId);+ if (!agent) break;+ const toolName = asString(payload.toolName);+ if (toolName) {+ agent.lastToolName = toolName;+ agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${toolName}`);+ }+ agent.updatedAt = at;+ break;+ }+ default:+ break;+ }+ }++ // Consistency pass: when a workflow coordinator has settled, members that+ // never received their own terminal row cannot still be in-flight — the+ // run is over. Cascade the coordinator's outcome so stalled member rows+ // don't read as working forever (live-test finding: statuses drifted+ // whenever member terminal rows were lost or never emitted).+ for (const agent of agents.values()) {+ if (agent.kind !== "workflow" || !isTerminalSubagentStatus(agent.status)) {+ continue;+ }+ for (const member of agents.values()) {+ if (member.parentAgentId !== agent.id) {+ continue;+ }+ if (isTerminalSubagentStatus(member.status) || member.status === "idle") {+ continue;+ }+ member.status = agent.status === "completed" ? "completed" : "interrupted";+ member.completedAt = member.completedAt ?? agent.completedAt ?? agent.updatedAt;+ member.updatedAt = agent.updatedAt;+ }+ }++ // Session death orphans every live agent: no process remains to finish+ // them. Mirrors the server-side liveness registry clearing on+ // session.exited, so panel and sidebar can never disagree.+ if (options?.sessionLive === false) {+ for (const agent of agents.values()) {+ if (isActiveSubagentStatus(agent.status)) {+ agent.status = "interrupted";+ agent.completedAt = agent.completedAt ?? agent.updatedAt;+ }+ }+ }++ let roster = Array.from(agents.values());+ if (roster.length > ROSTER_LIMIT) {+ // Prefer live, then waiting/idle, then newest settled.+ const rank = (agent: MutableAgent): number =>+ isActiveSubagentStatus(agent.status) ? 0 : agent.status === "idle" ? 1 : 2;+ roster = roster+ .slice()+ .sort((a, b) => rank(a) - rank(b) || b.updatedAt.localeCompare(a.updatedAt))+ .slice(0, ROSTER_LIMIT);+ }++ return roster.map((agent) => ({ ...agent }));+}++export interface AgentPanelWorkflowGroup {+ readonly workflow: RuntimeSubagent;+ readonly phases: ReadonlyArray<{+ readonly index: number;+ readonly title: string;+ readonly members: ReadonlyArray<RuntimeSubagent>;+ /** done = every member settled (success or error); running = any active. */+ readonly state: "pending" | "running" | "done";+ readonly activeCount: number;+ readonly settledCount: number;+ }>;+ /** Members with no resolvable phase (orphans render under the workflow). */+ readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;+}++export interface AgentPanelModel {+ readonly workflows: ReadonlyArray<AgentPanelWorkflowGroup>;+ readonly directAgents: ReadonlyArray<RuntimeSubagent>;+ readonly runningCount: number;+ readonly waitingCount: number;+ readonly idleCount: number;+ readonly settledCount: number;+ readonly totalTokens: number;+ readonly hasAgents: boolean;+ readonly liveCount: number;+}++const EMPTY_PANEL_MODEL: AgentPanelModel = {+ workflows: [],+ directAgents: [],+ runningCount: 0,+ waitingCount: 0,+ idleCount: 0,+ settledCount: 0,+ totalTokens: 0,+ hasAgents: false,+ liveCount: 0,+};++export function emptyAgentPanelModel(): AgentPanelModel {+ return EMPTY_PANEL_MODEL;+}++/**+ * Source-neutral view model. When the orchestration-v2 subagent projection+ * exists for the thread, pass it as v2Projection and it wins outright — the+ * two sources are never merged (duplicate-agents failure mode). Until v2+ * lands, callers pass null and the native fold output is used.+ */+export function deriveAgentPanelModel({+ agents,+ v2Projection,+}: {+ readonly agents: ReadonlyArray<RuntimeSubagent>;+ readonly v2Projection?: ReadonlyArray<RuntimeSubagent> | null;+}): AgentPanelModel {+ const source = v2Projection ?? agents;+ if (source.length === 0) {+ return EMPTY_PANEL_MODEL;+ }++ const workflows = source.filter((agent) => agent.kind === "workflow");+ const workflowIds = new Set(workflows.map((workflow) => workflow.id));+ const members = new Map<string, RuntimeSubagent[]>();+ const direct: RuntimeSubagent[] = [];++ for (const agent of source) {+ if (agent.kind === "workflow") {+ continue;+ }+ if (agent.parentAgentId !== null && workflowIds.has(agent.parentAgentId)) {+ const list = members.get(agent.parentAgentId) ?? [];+ list.push(agent);+ members.set(agent.parentAgentId, list);+ } else {+ // Orphaned members (coordinator aged out) fall back to the direct list.+ direct.push(agent);+ }+ }++ const workflowGroups: AgentPanelWorkflowGroup[] = workflows.map((workflow) => {+ const workflowMembers = members.get(workflow.id) ?? [];+ const knownPhases =+ workflow.phases.length > 0+ ? workflow.phases+ : (() => {+ const derived = new Map<number, string>();+ for (const member of workflowMembers) {+ if (member.phaseIndex !== null && !derived.has(member.phaseIndex)) {+ derived.set(+ member.phaseIndex,+ member.phaseTitle ?? `Phase ${member.phaseIndex + 1}`,+ );+ }+ }+ return Array.from(derived.entries())+ .map(([index, title]) => ({ index, title }))+ .slice()+ .sort((a, b) => a.index - b.index);+ })();++ const knownPhaseIndices = new Set(knownPhases.map((phase) => phase.index));+ const phases = knownPhases.map((phase) => {+ const phaseMembers = workflowMembers+ .filter((member) => member.phaseIndex === phase.index)+ .slice()+ .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));+ const activeCount = phaseMembers.filter(+ // Idle members count as active for phase-liveness: a resumable Codex+ // member has not finished the phase.+ (member) => isActiveSubagentStatus(member.status) || member.status === "idle",+ ).length;+ const settledCount = phaseMembers.filter((member) =>+ isTerminalSubagentStatus(member.status),+ ).length;+ const state: "pending" | "running" | "done" =+ phaseMembers.length === 0+ ? "pending"+ : activeCount > 0+ ? "running"+ : settledCount === phaseMembers.length+ ? "done"+ : "pending";+ return {+ index: phase.index,+ title: phase.title,+ members: phaseMembers,+ state,+ activeCount,+ settledCount,+ };+ });++ // Unknown phase indices land here too — a member must never vanish just+ // because its phase row was lost (review finding).+ const unphasedMembers = workflowMembers+ .filter((member) => member.phaseIndex === null || !knownPhaseIndices.has(member.phaseIndex))+ .slice()+ .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));++ return { workflow, phases, unphasedMembers };+ });++ let runningCount = 0;+ let waitingCount = 0;+ let idleCount = 0;+ let settledCount = 0;+ let totalTokens = 0;+ for (const agent of source) {+ if (agent.status === "running" || agent.status === "pending") runningCount += 1;+ else if (agent.status === "waiting") waitingCount += 1;+ else if (agent.status === "idle") idleCount += 1;+ else settledCount += 1;+ // Workflow coordinators aggregate member usage upstream in some providers;+ // avoid double counting by only summing leaf agents when members exist.+ if (agent.kind !== "workflow" || (members.get(agent.id) ?? []).length === 0) {+ totalTokens += agent.usage?.totalTokens ?? 0;+ }+ }++ return {+ workflows: workflowGroups,+ directAgents: direct.slice().sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)),+ runningCount,+ waitingCount,+ idleCount,+ settledCount,+ totalTokens,+ hasAgents: true,+ liveCount: runningCount + waitingCount,+ };+}++/**+ * Members ordered by urgency for the capped inline workflow card: running and+ * failed first, then waiting, then most recently updated.+ */+export function workflowCardMembers(+ group: AgentPanelWorkflowGroup,+ limit: number,+): { readonly visible: ReadonlyArray<RuntimeSubagent>; readonly overflow: number } {+ const all = [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];+ const urgency = (agent: RuntimeSubagent): number => {+ if (agent.status === "failed") return 0;+ if (agent.status === "running") return 1;+ if (agent.status === "waiting") return 2;+ return 3;+ };+ const ordered = all+ .slice()+ .sort((a, b) => urgency(a) - urgency(b) || b.updatedAt.localeCompare(a.updatedAt));+ return {+ visible: ordered.slice(0, limit),+ overflow: Math.max(0, ordered.length - limit),+ };+}++/** Kinds the timeline should not render as generic rows (fold input only). */+export function isSubagentActivityKind(kind: string): boolean {+ return (+ kind === "task.started" ||+ kind === "task.progress" ||+ kind === "task.updated" ||+ kind === "task.completed" ||+ kind === "tool.progress"+ );+}++/**+ * Quiet-timeline guarantee: tool rows attributed to an owning agent belong in+ * the Agents surface, not the parent chat. Unattributed rows must stay.+ */+export function isAgentAttributedToolActivity(activity: OrchestrationThreadActivity): boolean {+ if (typeof activity.payload !== "object" || activity.payload === null) {+ return false;+ }+ const payload = activity.payload as Record<string, unknown>;+ return typeof payload.agentId === "string" && payload.agentId.trim().length > 0;+}++/** Timeline-bypassing synthesized rows (Codex children, workflow members). */+export function isTimelineBypassActivity(activity: OrchestrationThreadActivity): boolean {+ if (typeof activity.payload !== "object" || activity.payload === null) {+ return false;+ }+ return (activity.payload as Record<string, unknown>).timelineBypass === true;+}++/**+ * Compact model chip text: strips vendor prefixes/date-or-context suffixes+ * ("claude-sonnet-5[1m]" → "sonnet-5[1m]", "claude-opus-4-20250514" →+ * "opus-4"). Unknown ids pass through untouched; effort appends as "· high".+ */+export function formatSubagentModelLabel(+ model: string | null,+ effort: string | null,+): string | null {+ if (!model) {+ return null;+ }+ const compact = model+ .replace(/^claude-/, "")+ .replace(/-\d{8}$/, "")+ .replace(/-latest$/, "");+ return effort ? `${compact} · ${effort}` : compact;+}++export function formatSubagentTokenCount(totalTokens: number): string {+ if (totalTokens < 1000) {+ return `${totalTokens}`;+ }+ if (totalTokens < 1_000_000) {+ const value = totalTokens / 1000;+ return `${value >= 100 ? Math.round(value) : value.toFixed(1)}k`;+ }+ return `${(totalTokens / 1_000_000).toFixed(1)}M`;+}diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex d09e63136..c9baa6ac6 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -24,6 +24,7 @@ import { ProviderInstanceId } from "./providerInstance.ts";export const ORCHESTRATION_WS_METHODS = {dispatchCommand: "orchestration.dispatchCommand",+ getWorkflowScript: "orchestration.getWorkflowScript",getTurnDiff: "orchestration.getTurnDiff",getFullThreadDiff: "orchestration.getFullThreadDiff",searchThreads: "orchestration.searchThreads",@@ -438,6 +439,12 @@ export const OrchestrationThreadShell = Schema.Struct({hasPendingApprovals: Schema.Boolean,hasPendingUserInput: Schema.Boolean,hasActionableProposedPlan: Schema.Boolean,+ /**+ * Native background work alive after the turn settles: "working" while+ * subagents/workflows run, "monitoring" when watch loops are the only+ * live work. Optional so old servers/clients interop; absent = none.+ */+ backgroundLiveness: Schema.optional(Schema.NullOr(Schema.Literals(["working", "monitoring"]))),});export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;@@ -1464,11 +1471,63 @@ export const OrchestrationSearchThreadsResult = Schema.Struct({});export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;+export const OrchestrationGetWorkflowScriptInput = Schema.Struct({+ threadId: ThreadId,+ /** Absolute path from the workflow's runHandles.scriptPath. The server+ * re-derives containment; the client value is a hint, never trusted. */+ scriptPath: TrimmedNonEmptyString,+});+export type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;++export const OrchestrationGetWorkflowScriptResult = Schema.Struct({+ scriptPath: TrimmedNonEmptyString,+ contents: Schema.String,+ truncated: Schema.Boolean,+});+export type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;++const WORKFLOW_SCRIPT_ERROR_MESSAGES = {+ "invalid-path": "Workflow scripts must be absolute .js paths.",+ "root-unavailable": "Script root unavailable.",+ "not-found": "Script not found.",+ "outside-root": "Script path is outside the workflow scripts root.",+ "not-js": "Resolved script is not a .js file.",+ "not-regular-file": "Script is not a regular file.",+ "changed-during-read": "Script changed between resolution and open.",+ "read-failed": "Script read failed.",+} as const;++export class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(+ "OrchestrationGetWorkflowScriptError",+ {+ reason: Schema.Literals([+ "invalid-path",+ "root-unavailable",+ "not-found",+ "outside-root",+ "not-js",+ "not-regular-file",+ "changed-during-read",+ "read-failed",+ ]),+ scriptPath: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {+ override get message(): string {+ return WORKFLOW_SCRIPT_ERROR_MESSAGES[this.reason];+ }+}+export const OrchestrationRpcSchemas = {dispatchCommand: {input: ClientOrchestrationCommand,output: DispatchResult,},+ getWorkflowScript: {+ input: OrchestrationGetWorkflowScriptInput,+ output: OrchestrationGetWorkflowScriptResult,+ },getTurnDiff: {input: OrchestrationGetTurnDiffInput,output: OrchestrationGetTurnDiffResult,diff --git a/packages/contracts/src/providerRuntime.test.ts b/packages/contracts/src/providerRuntime.test.tsindex 0e6ced58f..7563ac155 100644--- a/packages/contracts/src/providerRuntime.test.ts+++ b/packages/contracts/src/providerRuntime.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vite-plus/test";import * as Schema from "effect/Schema";-import { ProviderRuntimeEvent } from "./providerRuntime.ts";+import { classifyTaskAgentKind, ProviderRuntimeEvent } from "./providerRuntime.ts";const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);@@ -182,3 +182,22 @@ describe("ProviderRuntimeEvent", () => {expect(parsed.payload.usage.usedTokens).toBe(31251);});});++describe("classifyTaskAgentKind", () => {+ it("classifies agent-flavored, watch-loop, and inert types", () => {+ expect(classifyTaskAgentKind({ taskType: "local_agent" })).toBe("agent");+ expect(classifyTaskAgentKind({ taskType: "local_workflow" })).toBe("agent");+ expect(classifyTaskAgentKind({ taskType: undefined })).toBe("agent");+ expect(classifyTaskAgentKind({ taskType: "brand_new_agent_type" })).toBe("agent");+ expect(classifyTaskAgentKind({ taskType: "local_bash" })).toBe("background");+ expect(classifyTaskAgentKind({ taskType: "monitor" })).toBe("background");+ expect(classifyTaskAgentKind({ taskType: "plan" })).toBe("background");+ });++ it("agent-owned tasks are background unless themselves agent-flavored", () => {+ expect(classifyTaskAgentKind({ taskType: "local_bash", agentId: "owner" })).toBe("background");+ expect(classifyTaskAgentKind({ taskType: undefined, agentId: "owner" })).toBe("background");+ // Nested agent: outlives its parent, stays in the roster.+ expect(classifyTaskAgentKind({ taskType: "local_agent", agentId: "owner" })).toBe("agent");+ });+});diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex eb2563eff..bd525e654 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -176,6 +176,7 @@ const ProviderRuntimeEventType = Schema.Literals(["user-input.resolved","task.started","task.progress",+ "task.updated","task.completed","hook.started","hook.progress",@@ -226,6 +227,7 @@ const UserInputRequestedType = Schema.Literal("user-input.requested");const UserInputResolvedType = Schema.Literal("user-input.resolved");const TaskStartedType = Schema.Literal("task.started");const TaskProgressType = Schema.Literal("task.progress");+const TaskUpdatedType = Schema.Literal("task.updated");const TaskCompletedType = Schema.Literal("task.completed");const HookStartedType = Schema.Literal("hook.started");const HookProgressType = Schema.Literal("hook.progress");@@ -407,6 +409,13 @@ export const ItemLifecyclePayload = Schema.Struct({title: Schema.optional(TrimmedNonEmptyStringSchema),detail: Schema.optional(TrimmedNonEmptyStringSchema),data: Schema.optional(Schema.Unknown),+ /**+ * Owning agent when this item ran inside a subagent (resolved from the+ * SDK's parent_tool_use_id). Clients re-home attributed items out of the+ * main timeline and into the owning agent's Agents-surface row.+ */+ agentId: Schema.optional(TrimmedNonEmptyStringSchema),+ parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),});export type ItemLifecyclePayload = typeof ItemLifecyclePayload.Type;@@ -459,27 +468,180 @@ const UserInputResolvedPayload = Schema.Struct({});export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;+/**+ * Typed per-task usage rollup. Field names match the orchestration-v2 subagent+ * usage vocabulary (#4779) so the eventual migration is a rename, not a remap.+ * Claude reports per-activation deltas; Codex reports cumulative totals — the+ * merge strategy is provider-specific and lives in client-runtime.+ */+export const RuntimeTaskUsage = Schema.Struct({+ totalTokens: NonNegativeInt,+ inputTokens: Schema.optional(NonNegativeInt),+ cachedInputTokens: Schema.optional(NonNegativeInt),+ outputTokens: Schema.optional(NonNegativeInt),+ reasoningOutputTokens: Schema.optional(NonNegativeInt),+ toolUses: Schema.optional(NonNegativeInt),+ durationMs: Schema.optional(NonNegativeInt),+});+export type RuntimeTaskUsage = typeof RuntimeTaskUsage.Type;++export const TaskWorkflowPhase = Schema.Struct({+ index: NonNegativeInt,+ title: TrimmedNonEmptyStringSchema,+});+export type TaskWorkflowPhase = typeof TaskWorkflowPhase.Type;++export const TaskRunHandles = Schema.Struct({+ runId: Schema.optional(TrimmedNonEmptyStringSchema),+ scriptPath: Schema.optional(TrimmedNonEmptyStringSchema),+ transcriptDir: Schema.optional(TrimmedNonEmptyStringSchema),+ /** Only http/https URLs may be stored here — sanitized at the adapter. */+ sessionUrl: Schema.optional(TrimmedNonEmptyStringSchema),+});+export type TaskRunHandles = typeof TaskRunHandles.Type;++/**+ * Watch-loop task types: Monitor-tool tasks plus background shells (a shell+ * that outlives its turn is in practice a watch loop). Canonical single copy —+ * the server liveness registry, ingestion's agentKind stamp, and the client+ * fold's legacy fallback all classify with these sets.+ */+export const MONITOR_TASK_TYPES: ReadonlySet<string> = new Set([+ "monitor",+ "monitor_mcp",+ "local_bash",+ "shell",+]);+/** Task types that are neither agents nor watch loops (plan-mode bookkeeping). */+export const INERT_TASK_TYPES: ReadonlySet<string> = new Set(["plan", "dream"]);++/**+ * Agent-vs-background classification, stamped by ingestion as `agentKind` so+ * persisted rows are self-describing. A deliberate denylist: the SDK's+ * agent-flavored type names drift (subagent, local_agent, local_workflow, …)+ * and an allowlist silently dropped real subagents when "local_agent"+ * appeared. A task launched from inside a subagent (agentId set) is+ * agent-internal background work UNLESS it is itself agent-flavored — a+ * nested agent can outlive its parent and stays in the roster.+ */+export function classifyTaskAgentKind(input: {+ readonly taskType?: string | undefined;+ readonly agentId?: string | undefined;+}): "agent" | "background" {+ const { taskType, agentId } = input;+ const nonAgentType =+ taskType !== undefined && (MONITOR_TASK_TYPES.has(taskType) || INERT_TASK_TYPES.has(taskType));+ if (agentId !== undefined && agentId.trim().length > 0) {+ return taskType === undefined || nonAgentType ? "background" : "agent";+ }+ return nonAgentType ? "background" : "agent";+}++/**+ * Optional agent-identity linkage carried on every task lifecycle payload.+ * Repeated on progress and terminal rows (not just start) so client folds can+ * reconstruct an agent even when its start row aged out of activity retention.+ * All fields optional: old emitters and old rows decode unchanged.+ */+const taskAgentLinkageFields = {+ /** SDK task_type (subagent/shell/monitor/local_workflow/…), repeated on+ * every row so folds can classify without the start row. */+ taskType: Schema.optional(TrimmedNonEmptyStringSchema),+ /**+ * Server-stamped classification (classifyTaskAgentKind at ingestion).+ * Clients trust this stamp outright; rows without it (legacy, pre-stamp)+ * fall back to client-side heuristics.+ */+ agentKind: Schema.optional(Schema.Literals(["agent", "background"])),+ /**+ * Owning agent when the task itself was launched from inside a subagent+ * (e.g. a subagent's background shell). Clients treat such tasks as+ * agent-internal and keep them out of the parent work log.+ */+ agentId: Schema.optional(TrimmedNonEmptyStringSchema),+ title: Schema.optional(TrimmedNonEmptyStringSchema),+ role: Schema.optional(TrimmedNonEmptyStringSchema),+ model: Schema.optional(TrimmedNonEmptyStringSchema),+ /** Reasoning effort when known (e.g. "high"). Open string: provider vocabularies differ. */+ effort: Schema.optional(TrimmedNonEmptyStringSchema),+ toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),+ parentAgentId: Schema.optional(TrimmedNonEmptyStringSchema),+ workflowName: Schema.optional(TrimmedNonEmptyStringSchema),+ agentIndex: Schema.optional(NonNegativeInt),+ phaseIndex: Schema.optional(NonNegativeInt),+ phaseTitle: Schema.optional(TrimmedNonEmptyStringSchema),+ phases: Schema.optional(Schema.Array(TaskWorkflowPhase)),+ attempt: Schema.optional(NonNegativeInt),+ runHandles: Schema.optional(TaskRunHandles),+ outputFile: Schema.optional(TrimmedNonEmptyStringSchema),+ /** Codex agent hierarchy path, e.g. "/root/marlow". */+ agentPath: Schema.optional(TrimmedNonEmptyStringSchema),+ /**+ * Set on provider-synthesized child-agent events (Codex) whose activity+ * belongs in the Agents surface, never the parent timeline.+ */+ timelineBypass: Schema.optional(Schema.Boolean),+} as const;++export const TaskAgentLinkage = Schema.Struct(taskAgentLinkageFields);+export type TaskAgentLinkage = typeof TaskAgentLinkage.Type;+const TaskStartedPayload = Schema.Struct({taskId: RuntimeTaskId,description: Schema.optional(TrimmedNonEmptyStringSchema),- taskType: Schema.optional(TrimmedNonEmptyStringSchema),+ ...taskAgentLinkageFields,});export type TaskStartedPayload = typeof TaskStartedPayload.Type;+export const RuntimeTaskStatus = Schema.Literals([+ "pending",+ "running",+ "waiting",+ "idle",+ "completed",+ "failed",+ "cancelled",+ "interrupted",+]);+export type RuntimeTaskStatus = typeof RuntimeTaskStatus.Type;+const TaskProgressPayload = Schema.Struct({taskId: RuntimeTaskId,description: TrimmedNonEmptyStringSchema,summary: Schema.optional(TrimmedNonEmptyStringSchema),usage: Schema.optional(Schema.Unknown),+ typedUsage: Schema.optional(RuntimeTaskUsage),lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),+ /** Present on synthesized member/child progress rows that carry state. */+ status: Schema.optional(RuntimeTaskStatus),+ error: Schema.optional(TrimmedNonEmptyStringSchema),+ ...taskAgentLinkageFields,});export type TaskProgressPayload = typeof TaskProgressPayload.Type;+/**+ * Non-terminal status patch (from the Claude SDK's task_updated, which main+ * previously dropped). killed→cancelled and paused→idle are mapped at the+ * adapter so the wire only carries the shared vocabulary.+ */+const TaskUpdatedPayload = Schema.Struct({+ taskId: RuntimeTaskId,+ status: Schema.optional(RuntimeTaskStatus),+ description: Schema.optional(TrimmedNonEmptyStringSchema),+ error: Schema.optional(TrimmedNonEmptyStringSchema),+ endedAt: Schema.optional(IsoDateTime),+ isBackgrounded: Schema.optional(Schema.Boolean),+ ...taskAgentLinkageFields,+});+export type TaskUpdatedPayload = typeof TaskUpdatedPayload.Type;+const TaskCompletedPayload = Schema.Struct({taskId: RuntimeTaskId,status: Schema.Literals(["completed", "failed", "stopped"]),summary: Schema.optional(TrimmedNonEmptyStringSchema),usage: Schema.optional(Schema.Unknown),+ typedUsage: Schema.optional(RuntimeTaskUsage),+ ...taskAgentLinkageFields,});export type TaskCompletedPayload = typeof TaskCompletedPayload.Type;@@ -513,6 +675,9 @@ const ToolProgressPayload = Schema.Struct({toolName: Schema.optional(TrimmedNonEmptyStringSchema),summary: Schema.optional(TrimmedNonEmptyStringSchema),elapsedSeconds: Schema.optional(Schema.Number),+ /** Owning task/agent when the tool ran inside a subagent. */+ taskId: Schema.optional(RuntimeTaskId),+ parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),});export type ToolProgressPayload = typeof ToolProgressPayload.Type;@@ -835,6 +1000,13 @@ const ProviderRuntimeTaskProgressEvent = Schema.Struct({});export type ProviderRuntimeTaskProgressEvent = typeof ProviderRuntimeTaskProgressEvent.Type;+const ProviderRuntimeTaskUpdatedEvent = Schema.Struct({+ ...ProviderRuntimeEventBase.fields,+ type: TaskUpdatedType,+ payload: TaskUpdatedPayload,+});+export type ProviderRuntimeTaskUpdatedEvent = typeof ProviderRuntimeTaskUpdatedEvent.Type;+const ProviderRuntimeTaskCompletedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,type: TaskCompletedType,@@ -995,6 +1167,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([ProviderRuntimeUserInputResolvedEvent,ProviderRuntimeTaskStartedEvent,ProviderRuntimeTaskProgressEvent,+ ProviderRuntimeTaskUpdatedEvent,ProviderRuntimeTaskCompletedEvent,ProviderRuntimeHookStartedEvent,ProviderRuntimeHookProgressEvent,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 42cafae31..db40b10fe 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -64,6 +64,7 @@ import {OrchestrationGetTurnDiffError,OrchestrationGetTurnDiffInput,OrchestrationRpcSchemas,+ OrchestrationGetWorkflowScriptError,} from "./orchestration.ts";import { ProviderInstanceId } from "./providerInstance.ts";import {@@ -696,6 +697,15 @@ export const WsOrchestrationDispatchCommandRpc = Rpc.make(},);+export const WsOrchestrationGetWorkflowScriptRpc = Rpc.make(+ ORCHESTRATION_WS_METHODS.getWorkflowScript,+ {+ payload: OrchestrationRpcSchemas.getWorkflowScript.input,+ success: OrchestrationRpcSchemas.getWorkflowScript.output,+ error: Schema.Union([OrchestrationGetWorkflowScriptError, EnvironmentAuthorizationError]),+ },+);+export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, {payload: OrchestrationGetTurnDiffInput,success: OrchestrationRpcSchemas.getTurnDiff.output,@@ -867,6 +877,7 @@ export const WsRpcGroup = RpcGroup.make(WsSubscribeBackgroundPolicyRpc,WsSubscribeResourceTelemetryRpc,WsOrchestrationDispatchCommandRpc,+ WsOrchestrationGetWorkflowScriptRpc,WsOrchestrationGetTurnDiffRpc,WsOrchestrationGetFullThreadDiffRpc,WsOrchestrationSearchThreadsRpc,