From 37d8ac1077262497900e3151f0a9bf0f2b78c90a Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 04:10:19 +0200 Subject: [PATCH 1/3] fix(server): server-run workflows list every phase up front with each agent's model and time A t3_workflow_run row only showed a phase once an agent in it launched, and its agents carried no provider, model, effort or timestamps, so Lineage and the mobile Agents sheet showed "Not reported" and no run time. The row now lists every stage from the spec when the run is recorded (a repeat's stages labelled round 1), each agent queued. A later round's stages join when the round starts, before the stages after the repeat. Each agent carries the provider, model and effort delegate_task resolves for its target, plus queuedAt, startedAt, completedAt and durationMs. Clients treat a phase of only queued agents as not started and use a member's own provider before it launches. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/ThreadWorkflowGroup.tsx | 11 +- .../threads/threadAgentsPresentation.test.ts | 15 +- .../threads/threadAgentsPresentation.ts | 3 + apps/server/src/mcp/OrchestratorMcpService.ts | 11 +- apps/server/src/mcp/WorkflowRuns.test.ts | 210 ++++++++++++++++++ apps/server/src/mcp/WorkflowRuns.ts | 140 +++++++++--- apps/server/src/mcp/workflowRun.ts | 34 ++- .../chat/SubagentTooltipContent.tsx | 10 +- .../chat/ThreadLineageWorkflowRow.tsx | 1 + .../chat/ThreadRelationshipsControl.tsx | 9 +- .../src/state/subagentRuntime.test.ts | 31 +++ .../src/state/subagentRuntime.ts | 15 +- packages/contracts/src/orchestrationV2.ts | 2 + 13 files changed, 436 insertions(+), 56 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx index df67df16cf58..0f3b54e166dd 100644 --- a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx +++ b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx @@ -49,9 +49,12 @@ export function ThreadWorkflowGroup(props: { readonly onOpen: (threadId: ThreadId) => void; }) { const { group } = props; - const provider = useEnvironmentServerConfig(props.environmentId)?.providers.find( - (candidate) => candidate.instanceId === props.subagent.providerInstanceId, - ); + const providers = useEnvironmentServerConfig(props.environmentId)?.providers; + const providerOf = (member: RuntimeSubagent) => + providers?.find( + (candidate) => + candidate.instanceId === (member.providerInstanceId ?? props.subagent.providerInstanceId), + ); const [selected, setSelected] = useState(null); const rail = workflowRail(group); const open = rail.find((item) => item.key === selected); @@ -129,7 +132,7 @@ export function ThreadWorkflowGroup(props: { key={member.id} environmentId={props.environmentId} member={member} - provider={provider} + provider={providerOf(member)} onOpen={props.onOpen} /> )) diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts index 8514e86a900b..11a14f189f6f 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts @@ -100,7 +100,7 @@ type WorkflowAgent = OrchestrationV2SubagentWorkflow["agents"][number]; const workflowRailOf = ( agents: ReadonlyArray, - status: "running" | "completed" = "running", + status: "running" | "completed" | "cancelled" = "running", ) => workflowRail( deriveWorkflowGroups( @@ -181,6 +181,19 @@ describe("nextWorkflowSelection", () => { expect(nextWorkflowSelection(workflowRailOf([]), null)).toBeNull(); }); + it("opens where a stopped run stopped, not a planned phase it never reached", () => { + const stopped = workflowRailOf( + [ + agent(1, 0, "completed", { startedAt: 1_000 }), + agent(2, 1, "running", { startedAt: 2_000 }), + agent(3, 2, "queued"), + ], + "cancelled", + ); + + expect(nextWorkflowSelection(stopped, null)).toBe("1"); + }); + it("keeps one phase open: another replaces it and the open one collapses the card", () => { expect(nextWorkflowSelection(running, null, "0")).toBe("0"); expect(nextWorkflowSelection(running, "1", "0")).toBe("0"); diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.ts index 7c5bf9b72fd0..997982d614a6 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.ts @@ -158,10 +158,13 @@ export function nextWorkflowSelection( if (tapped !== undefined) return tapped === open ? null : tapped; if (open !== null) return null; const filled = rail.filter((item) => item.members.length > 0); + // Server-run workflows list planned phases up front; a run that stops never starts them. + const reached = filled.filter((item) => item.members.some((member) => member.startedAt !== null)); return ( ( filled.find((item) => item.tone === "working") ?? filled.find((item) => item.tone === "failed") ?? + reached.at(-1) ?? filled.at(-1) )?.key ?? null ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 96433df3b6f2..961f151683b1 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -160,11 +160,11 @@ export interface OrchestratorMcpServiceShape { readonly workflow?: { readonly taskId: NodeId; readonly runId: RunId }; }, ) => Effect.Effect; - /** Fails as `delegateTask` would for this target in the caller's thread, starting nothing. */ + /** Resolves this target as `delegateTask` would in the caller's thread, starting nothing. */ readonly checkTarget: ( scope: McpInvocationScope, target: OrchestratorMcpTarget | undefined, - ) => Effect.Effect; + ) => Effect.Effect; /** Waits, however long, until the task reaches a terminal status. */ readonly awaitTask: ( scope: McpInvocationScope, @@ -2406,7 +2406,12 @@ const make = Effect.gen(function* () { }), checkTarget: Effect.fn("OrchestratorMcpService.checkTarget")(function* (callerScope, target) { const { parent } = yield* loadThreadCaller(callerScope, "delegate_task"); - yield* resolveTargetRechecking({ parent, target, providers: yield* loadProviders }); + const resolved = yield* resolveTargetRechecking({ + parent, + target, + providers: yield* loadProviders, + }); + return resolved.modelSelection; }), awaitTask: Effect.fn("OrchestratorMcpService.awaitTask")(function* (callerScope, taskId) { const scope = yield* requireThreadScope(callerScope, "task_status"); diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index c3a2608724af..f08cf02bf307 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -27,6 +27,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; @@ -200,6 +201,50 @@ const spec = { ], }; +/** A repeat between two stages; agent `a` names its model and effort, the rest inherit the parent's. */ +const planned = { + name: "plan", + stages: [ + { + id: "draft", + agents: [ + { + id: "a", + task: "Draft A.", + target: { + providerInstanceId: claude, + model: "claude-sonnet-5-5", + options: [{ id: "effort", value: "low" }], + }, + }, + { id: "b", task: "Draft B." }, + ], + }, + { + id: "loop", + repeat: { + stages: [ + { id: "revise", agents: [{ id: "writer", task: "Revise {{draft}} {{feedback}}." }] }, + { + id: "review", + agents: [ + { + id: "judge", + task: "Judge {{revise}}.", + resultSchema: { type: "object", required: ["ok"] }, + }, + ], + }, + ], + judge: "judge", + until: { path: "ok", equals: true }, + max: 2, + }, + }, + { id: "ship", agents: [{ id: "p", task: "Ship {{revise}}." }] }, + ], +}; + /** A Codex parent whose turn is live when it calls t3_workflow_run. */ const seedParent = (name: string) => Effect.gen(function* () { @@ -366,6 +411,21 @@ const ended = (threadId: ThreadId, workflowTaskId: NodeId) => ); }); +/** The first workflow row update that matches, in order. */ +const rowWhere = ( + threadId: ThreadId, + workflowTaskId: NodeId, + matches: (row: OrchestrationV2Subagent) => boolean, +) => + Effect.gen(function* () { + const events = yield* parentEvents(threadId); + return yield* events.pipe( + Stream.filter((event) => event.payload.id === workflowTaskId && matches(event.payload)), + Stream.runHead, + Effect.map((event) => Option.getOrThrow(event).payload), + ); + }); + /** Settles a child as its provider would: a final reply, then the run ends. */ const settleChild = (child: OrchestrationV2Subagent, text: string) => Effect.gen(function* () { @@ -489,6 +549,156 @@ it.layer(layerTest)("t3_workflow_run", (it) => { }), ); + it.effect( + "lists every phase and agent, with its model and effort, in the run's first update", + () => + Effect.gen(function* () { + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("plan"); + const { subagentId } = yield* runs.run(parent.scope, planned); + + const first = yield* rowWhere(parent.threadId, subagentId, () => true); + assert.deepEqual( + first.workflow?.phases.map((phase) => phase.title), + ["draft", "revise · round 1", "review · round 1", "ship"], + ); + assert.deepEqual( + first.workflow?.agents.map(({ index, label, phaseIndex, state, ...target }) => ({ + index, + label, + phaseIndex, + state, + target, + })), + [ + { + index: 0, + label: "a", + phaseIndex: 0, + state: "queued", + target: { providerInstanceId: claude, model: "claude-sonnet-5-5", effort: "low" }, + }, + { + index: 1, + label: "b", + phaseIndex: 0, + state: "queued", + target: { providerInstanceId: codex, model: "gpt-5.4" }, + }, + { + index: 2, + label: "writer", + phaseIndex: 1, + state: "queued", + target: { providerInstanceId: codex, model: "gpt-5.4" }, + }, + { + index: 3, + label: "judge", + phaseIndex: 2, + state: "queued", + target: { providerInstanceId: codex, model: "gpt-5.4" }, + }, + { + index: 4, + label: "p", + phaseIndex: 3, + state: "queued", + target: { providerInstanceId: codex, model: "gpt-5.4" }, + }, + ], + ); + }), + ); + + it.effect("times each agent and adds a later round before the stages after it", () => + Effect.gen(function* () { + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("timed"); + const { subagentId } = yield* runs.run(parent.scope, planned); + yield* parent.endTurn; + const settled = new Set(); + /** Lets `ms` pass once the runner has started the next agents, then settles them. */ + const settleNext = (count: number, ms: number, text: string) => + Effect.gen(function* () { + const children = (yield* childrenOf( + parent.threadId, + subagentId, + settled.size + count, + )).filter((child) => !settled.has(child.id)); + yield* rowWhere( + parent.threadId, + subagentId, + (row) => + row.workflow?.agents.filter( + (agent) => + agent.state === "running" && + children.some((child) => child.childThreadId === agent.childThreadId), + ).length === children.length, + ); + yield* TestClock.adjust(ms); + for (const child of children) { + settled.add(child.id); + yield* settleChild(child, text); + } + }); + yield* settleNext(2, 3_000, "Draft."); + yield* settleNext(1, 2_000, "Revised."); + yield* settleNext(1, 1_000, '```json\n{"ok":false}\n```'); + const second = yield* rowWhere(parent.threadId, subagentId, (row) => + (row.workflow?.phases ?? []).some((phase) => phase.title === "revise · round 2"), + ); + assert.deepEqual( + second.workflow?.agents.map((agent) => [agent.label, agent.phaseIndex, agent.state]), + [ + ["a", 0, "completed"], + ["b", 0, "completed"], + ["writer", 1, "completed"], + ["judge", 2, "completed"], + ["writer", 3, "queued"], + ["judge", 4, "queued"], + ["p", 5, "queued"], + ], + ); + yield* settleNext(1, 1_000, "Revised again."); + yield* settleNext(1, 1_000, '```json\n{"ok":true}\n```'); + yield* settleNext(1, 4_000, "Shipped."); + + const row = yield* ended(parent.threadId, subagentId); + assert.equal(row?.status, "completed"); + assert.deepEqual( + row?.workflow?.phases.map((phase) => phase.title), + [ + "draft", + "revise · round 1", + "review · round 1", + "revise · round 2", + "review · round 2", + "ship", + ], + ); + assert.deepEqual( + row?.workflow?.agents.map((agent) => [ + agent.label, + agent.state, + agent.queuedAt, + agent.startedAt, + agent.completedAt, + agent.durationMs, + ]), + [ + ["a", "completed", 0, 0, 3_000, 3_000], + ["b", "completed", 0, 0, 3_000, 3_000], + ["writer", "completed", 3_000, 3_000, 5_000, 2_000], + ["judge", "completed", 5_000, 5_000, 6_000, 1_000], + ["writer", "completed", 6_000, 6_000, 7_000, 1_000], + ["judge", "completed", 7_000, 7_000, 8_000, 1_000], + ["p", "completed", 8_000, 8_000, 12_000, 4_000], + ], + ); + }), + ); + it.effect( "keeps every workflow row update within 2 KB on the wire across a 20-agent stage and 3 rounds", () => diff --git a/apps/server/src/mcp/WorkflowRuns.ts b/apps/server/src/mcp/WorkflowRuns.ts index 8a7a749c3fc1..d97db3c5be44 100644 --- a/apps/server/src/mcp/WorkflowRuns.ts +++ b/apps/server/src/mcp/WorkflowRuns.ts @@ -2,13 +2,16 @@ import { CommandId, isOrchestrationV2WorkActive, type EnvironmentId, + type ModelSelection, NodeId, type OrchestrationV2SubagentWorkflow, + type OrchestrationV2WorkflowAgent, type OrchestrationV2WorkflowRunState, OrchestratorMcpFailure, type OrchestratorMcpDelegateTaskResult, type ThreadId, } from "@t3tools/contracts"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -38,6 +41,7 @@ import { workflowResult, type WorkflowSnapshot, WorkflowSpec, + workflowPhases, } from "./workflowRun.ts"; export class WorkflowRuns extends Context.Service< @@ -86,38 +90,75 @@ const outcomeOf = (result: OrchestratorMcpDelegateTaskResult): WorkflowAgentOutc : { structuredResult: result.structuredResult }), }; -/** The row keeps launches as `workflow.agents` (results stay on the child tasks) and the rest as `workflowRun`. */ +type AgentTarget = Pick; + +const targetOf = (selection: ModelSelection): AgentTarget => { + const effort = + getModelSelectionStringOptionValue(selection, "reasoningEffort") ?? + getModelSelectionStringOptionValue(selection, "effort"); + return { + providerInstanceId: selection.instanceId, + model: selection.model, + ...(effort?.trim() ? { effort: effort.trim() } : {}), + }; +}; + +const targetKey = (stage: string, agent: string) => `${stage}.${agent}`; + +/** + * The row lists every agent of every phase so far, launched or not, in phase order (results stay + * on the child tasks), and keeps the rest of the snapshot as `workflowRun`. + */ function toRow( spec: WorkflowSpec, snapshot: WorkflowSnapshot, childThreads: ReadonlyMap, + targets: ReadonlyMap, ): { readonly workflow: OrchestrationV2SubagentWorkflow; readonly workflowRun: OrchestrationV2WorkflowRunState; } { - const phases = agentStages(spec).map((stage, index) => ({ index, title: stage.id })); const { launches, ...workflowRun } = snapshot; + const phases = workflowPhases(spec, snapshot); + const agents = phases.flatMap(({ stage, round }, phaseIndex) => + stage.agents.map((agent) => ({ stage: stage.id, agent: agent.id, round, phaseIndex })), + ); return { workflow: { name: spec.name, - phases, - agents: launches.map((launch, index) => { + phases: phases.map(({ title }, index) => ({ index, title })), + agents: agents.map(({ stage, agent, round, phaseIndex }, index) => { + const planned = { + index, + label: agent, + phaseIndex, + ...targets.get(targetKey(stage, agent)), + }; + const launch = launches.find( + (l) => l.stage === stage && l.round === round && l.agent === agent, + ); + if (launch === undefined) return { ...planned, state: "queued" as const }; const childThreadId = launch.taskId === null ? undefined : childThreads.get(launch.taskId); + // A launch the run cancels as it ends stays live here; clients show the run's end for it. + const live = launch.outcome === null || launch.cancelRequested; + const { queuedAt, startedAt } = launch; + const completedAt = live ? undefined : launch.completedAt; return { - index, - label: launch.agent, + ...planned, ...(childThreadId === undefined ? {} : { childThreadId }), - // A launch the run cancels as it ends stays live here; clients show the run's end for it. - state: - launch.outcome === null || launch.cancelRequested - ? launch.taskId === null - ? "queued" - : "running" - : launch.outcome.status === "completed" - ? "completed" - : "failed", - phaseIndex: phases.find((phase) => phase.title === launch.stage)?.index ?? 0, - attempt: launch.round, + state: live + ? launch.taskId === null + ? "queued" + : "running" + : launch.outcome?.status === "completed" + ? "completed" + : "failed", + ...(queuedAt === undefined ? {} : { queuedAt }), + ...(startedAt === undefined ? {} : { startedAt }), + ...(completedAt === undefined ? {} : { completedAt }), + ...(startedAt === undefined || completedAt === undefined + ? {} + : { durationMs: Math.max(0, completedAt - startedAt) }), }; }), }, @@ -177,16 +218,34 @@ const make = Effect.gen(function* () { capabilities: new Set(["orchestration"]), issuedAt: 0, }; - return { row, spec, childThreads, live, scope }; + const phases = workflowPhases(spec, row.workflowRun!); + const agents = (row.workflow?.agents ?? []).flatMap((agent) => { + const phase = phases[agent.phaseIndex ?? 0]; + return phase === undefined ? [] : [{ agent, stage: phase.stage.id, round: phase.round }]; + }); + const targets = new Map( + agents.map(({ agent: { providerInstanceId, model, effort, label }, stage }) => [ + targetKey(stage, label), + { + ...(providerInstanceId === undefined ? {} : { providerInstanceId }), + ...(model === undefined ? {} : { model }), + ...(effort === undefined ? {} : { effort }), + }, + ]), + ); + return { row, spec, childThreads, live, scope, agents, targets }; }); /** Rebuilds the runner's snapshot; finished launches read their outcome from their child task. */ const snapshotOf = Effect.fn("WorkflowRuns.snapshotOf")(function* ( run: Effect.Success>, ) { - const stages = agentStages(run.spec); const taskIds = new Map([...run.childThreads].map(([taskId, thread]) => [thread, taskId])); - const launches = yield* Effect.forEach(run.row.workflow?.agents ?? [], (agent) => + // A queued agent with no queue time is one the run has not launched yet. + const launched = run.agents.filter( + ({ agent }) => agent.state !== "queued" || agent.queuedAt !== undefined, + ); + const launches = yield* Effect.forEach(launched, ({ agent, stage, round }) => Effect.gen(function* () { const taskId = agent.childThreadId === undefined ? null : (taskIds.get(agent.childThreadId) ?? null); @@ -198,12 +257,15 @@ const make = Effect.gen(function* () { ? { status: "failed", result: null } : outcomeOf(yield* mcp.taskStatus(run.scope, NodeId.make(taskId))); return { - stage: stages[agent.phaseIndex ?? 0]?.id ?? "", - round: agent.attempt ?? 1, + stage, + round, agent: agent.label, taskId, cancelRequested: false, outcome, + ...(agent.queuedAt === undefined ? {} : { queuedAt: agent.queuedAt }), + ...(agent.startedAt === undefined ? {} : { startedAt: agent.startedAt }), + ...(agent.completedAt === undefined ? {} : { completedAt: agent.completedAt }), }; }), ); @@ -225,7 +287,7 @@ const make = Effect.gen(function* () { ); } if (run.row.runId === null) return; - const { row, spec, childThreads, scope } = run; + const { row, spec, childThreads, scope, targets } = run; const owner = { taskId: row.id, runId: row.runId! }; const port: WorkflowPort = { start: ({ key, agent: { id: _id, task: _template, ...options }, task }) => @@ -258,7 +320,7 @@ const make = Effect.gen(function* () { commandId: id, parentThreadId: threadId, taskId: row.id, - ...toRow(spec, snapshot, childThreads), + ...toRow(spec, snapshot, childThreads, targets), ...(snapshot.status === "running" ? {} : { result: encodeJson(workflowResult(spec, snapshot)) }), @@ -288,18 +350,24 @@ const make = Effect.gen(function* () { ) { const scope = yield* requireThreadScope(callerScope, "t3_workflow_run"); const spec = yield* decodeWorkflowSpec(input); - for (const agent of agentStages(spec).flatMap((stage) => stage.agents)) { - if (agent.target?.environmentId !== undefined) { - return yield* failure( - "invalid_request", - `Agent "${agent.id}": workflow agents run here. Omit target.environmentId.`, - ); + const targets = new Map(); + for (const stage of agentStages(spec)) { + for (const agent of stage.agents) { + if (agent.target?.environmentId !== undefined) { + return yield* failure( + "invalid_request", + `Agent "${agent.id}": workflow agents run here. Omit target.environmentId.`, + ); + } + const selection = yield* mcp + .checkTarget(scope, agent.target) + .pipe( + Effect.mapError((error) => + failure(error.code, `Agent "${agent.id}": ${error.message}`), + ), + ); + targets.set(targetKey(stage.id, agent.id), targetOf(selection)); } - yield* mcp - .checkTarget(scope, agent.target) - .pipe( - Effect.mapError((error) => failure(error.code, `Agent "${agent.id}": ${error.message}`)), - ); } const parent = yield* threads .getThreadRecords(scope.thread.threadId, ["runs", "providerThreads"]) @@ -331,7 +399,7 @@ const make = Effect.gen(function* () { title: spec.name, driver, modelSelection: parentRun.modelSelection, - ...toRow(spec, initialSnapshot(spec, yield* Clock.currentTimeMillis), new Map()), + ...toRow(spec, initialSnapshot(spec, yield* Clock.currentTimeMillis), new Map(), targets), }) .pipe(Effect.mapError(unavailable)); const row = recorded.storedEvents.flatMap(({ event }) => diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 9d9ff832777b..1254e0ba55d1 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -63,6 +63,9 @@ const WorkflowLaunch = Schema.Struct({ taskId: Schema.NullOr(Schema.String), cancelRequested: Schema.Boolean, outcome: Schema.NullOr(WorkflowAgentOutcome), + queuedAt: Schema.optional(Schema.Number), + startedAt: Schema.optional(Schema.Number), + completedAt: Schema.optional(Schema.Number), }); type WorkflowLaunch = typeof WorkflowLaunch.Type; @@ -209,6 +212,27 @@ const asText = (value: unknown) => (typeof value === "string" ? value : JSON.str export const agentStages = (spec: WorkflowSpec) => spec.stages.flatMap((stage) => ("agents" in stage ? [stage] : stage.repeat.stages)); +/** Every stage the run shows, in order: a repeat's stages once per round it reached, round 1 up front. */ +export function workflowPhases( + spec: WorkflowSpec, + state: Pick, +): ReadonlyArray<{ readonly stage: AgentStage; readonly round: number; readonly title: string }> { + return spec.stages.flatMap((stage, position) => { + if ("agents" in stage) return [{ stage, round: 1, title: stage.id }]; + const rounds = + position === state.cursor + ? state.round + : (state.exits.find((exit) => exit.stage === stage.id)?.round ?? 1); + return Array.from({ length: rounds }, (_, index) => + stage.repeat.stages.map((inner) => ({ + stage: inner, + round: index + 1, + title: `${inner.id} · round ${index + 1}`, + })), + ).flat(); + }); +} + function renderTask(spec: WorkflowSpec, state: WorkflowSnapshot, template: string): string { return template.replace(REFERENCE, (match, stageRef: string, agentRef?: string) => { if (stageRef === "feedback") { @@ -339,11 +363,12 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( const started = yield* port .start({ key, stage: launch.stage, round: launch.round, agent, task }) .pipe(Effect.result); + const now = yield* Clock.currentTimeMillis; if (started._tag === "Failure") { const outcome = { status: "failed", result: started.failure.message } as const; - return yield* update(key, { outcome }); + return yield* update(key, { outcome, completedAt: now }); } - yield* update(key, { taskId: started.success }); + yield* update(key, { taskId: started.success, startedAt: now }); yield* watch(key, started.success); }); @@ -365,7 +390,9 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( const launch = state.launches.find((l) => keyOf(l) === event.key); return launch === undefined || launch.outcome !== null ? Effect.void - : update(event.key, { outcome: event.outcome }); + : Effect.flatMap(Clock.currentTimeMillis, (completedAt) => + update(event.key, { outcome: event.outcome, completedAt }), + ); }; while (state.status === "running") { @@ -394,6 +421,7 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( taskId: null, cancelRequested: false, outcome: null, + queuedAt: yield* Clock.currentTimeMillis, }; yield* save({ ...state, launches: [...state.launches, launch] }); yield* startTask(launch); diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index a965e89efd72..126b3cd79e33 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -33,6 +33,8 @@ import { deriveProviderInstanceEntries, shouldShowInstanceBadge } from "../../pr export function SubagentTooltipContent(props: { title: string; model: string | null; + /** Reported with the agent; otherwise read from its model selection. */ + effort?: string | null | undefined; providerInstanceId: ProviderInstanceId; origin: OrchestrationV2Subagent["origin"]; modelSelection?: OrchestrationV2Subagent["modelSelection"]; @@ -72,9 +74,11 @@ export function SubagentTooltipContent(props: { childModel === (modelSlug ?? model) && childSelection?.instanceId === props.providerInstanceId ? childSelection : undefined; - const effort = REASONING_EFFORT_OPTION_IDS.map((id) => - getModelSelectionStringOptionValue(matchingSelection, id), - ).find(Boolean); + const effort = + props.effort || + REASONING_EFFORT_OPTION_IDS.map((id) => + getModelSelectionStringOptionValue(matchingSelection, id), + ).find(Boolean); const speed = provider ? providerModel?.capabilities?.optionDescriptors ?.map((descriptor) => { diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index 8e0ef07c839b..af8cb70600fe 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -95,6 +95,7 @@ function WorkflowMemberRow({ entry.instanceId === task.providerInstanceId, + (entry) => entry.instanceId === providerInstanceId, ); return { - providerInstanceId: task.providerInstanceId, + providerInstanceId, provider: taskProvider, - driver: task.driver, + driver: task?.driver ?? taskProvider?.driver, }; }; return ( diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index 795cfdf80709..4d8f8a3f3b34 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -158,6 +158,37 @@ describe("deriveWorkflowGroups over a dynamic workflow", () => { expect(group?.unphasedMembers).toEqual([]); }); + it("leaves a phase of only queued members not started, and keeps each member's provider", () => { + const codex = ProviderInstanceId.make("codex"); + const groups = groupsOf([ + subagent({ + workflow: { + phases: [ + { index: 0, title: "draft" }, + { index: 1, title: "ship" }, + ], + agents: [ + member({ index: 0, phaseIndex: 0, phaseTitle: undefined }), + member({ + index: 1, + phaseIndex: 1, + phaseTitle: undefined, + state: "queued", + providerInstanceId: codex, + model: "gpt-5.4", + }), + ], + }, + }), + ]); + expect(groups[0]?.phases.map((phase) => [phase.title, phase.state])).toEqual([ + ["draft", "running"], + ["ship", "pending"], + ]); + const queued = groups[0]?.phases[1]?.members[0]; + expect([queued?.providerInstanceId, queued?.model]).toEqual([codex, "gpt-5.4"]); + }); + it.each([false, true])("keeps a reported phase title, missing title first=%s", (missingFirst) => { const agents = [member({ phaseTitle: "Review" }), member({ index: 2, phaseTitle: undefined })]; const groups = groupsOf([ diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index 879deb79716d..e144b5615e46 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -6,6 +6,7 @@ import type { OrchestrationV2Subagent, OrchestrationV2SubagentWorkflow, OrchestrationV2TurnItem, + ProviderInstanceId, } from "@t3tools/contracts"; import { isOrchestrationV2WorkActive, isProviderNativeSubagentThread } from "@t3tools/contracts"; @@ -54,6 +55,8 @@ export interface RuntimeSubagent { readonly model: string | null; readonly effort: string | null; readonly speed?: string | undefined; + /** A workflow member's own provider, when it reports one. */ + readonly providerInstanceId?: ProviderInstanceId | undefined; readonly status: RuntimeSubagentStatus; readonly activationCount: number; readonly usage: SubagentUsage | null; @@ -154,6 +157,9 @@ function workflowMembersToRuntime( model: agent.model ?? null, effort: agent.effort ?? null, ...(agent.speed === undefined ? {} : { speed: agent.speed }), + ...(agent.providerInstanceId === undefined + ? {} + : { providerInstanceId: agent.providerInstanceId }), status, activationCount: agent.attempt ?? 1, usage: workflowUsage(agent), @@ -277,8 +283,13 @@ export function deriveWorkflowGroups( const settledCount = phaseMembers.filter((member) => isTerminalSubagentStatus(member.status), ).length; - const state: "pending" | "running" | "done" = - phaseMembers.length === 0 ? "pending" : hasActiveMember ? "running" : "done"; + const state: "pending" | "running" | "done" = phaseMembers.every( + (member) => member.status === "pending", + ) + ? "pending" + : hasActiveMember + ? "running" + : "done"; return { index: phase.index, title: phase.title, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 91230b96b1f5..17b4ca3137f2 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -786,6 +786,8 @@ export const OrchestrationV2WorkflowAgent = Schema.Struct({ state: Schema.Literals(["queued", "running", "completed", "failed"]), phaseIndex: Schema.optional(NonNegativeInt), phaseTitle: Schema.optional(TrimmedNonEmptyString), + /** Set when the agent may run on another provider than its workflow. */ + providerInstanceId: Schema.optional(ProviderInstanceId), model: Schema.optional(TrimmedNonEmptyString), effort: Schema.optional(TrimmedNonEmptyString), speed: Schema.optional(TrimmedNonEmptyString), From 007a48e5c864f264424399d44772931f0d2bb5ab Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 04:31:36 +0200 Subject: [PATCH 2/3] fix(server): workflow members take times and model from their child, and old rows fail cleanly Review of #18 found four gaps. Times were stamped when the runner noticed a change, so a child that ended during a restart showed the restart time. A member kept its planned model after its child ran another one. A planned agent a run never reached showed as failed with a completion time. Rows from the earlier layout would be expanded with the new one. Each launched member now reads its provider, model, effort, start and end from its child's run records when it starts and when it settles. Clients mark a planned member the run ended before as not started: no completion time, not settled. The row's workflowRun carries version 2; a running row without it fails with a reason and cancels its children instead of resuming, and status reports that reason. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/ThreadWorkflowGroup.tsx | 3 +- .../threads/threadAgentsPresentation.test.ts | 1 + .../threads/threadAgentsPresentation.ts | 2 +- apps/server/src/mcp/WorkflowRuns.test.ts | 174 +++++++++++++++++- apps/server/src/mcp/WorkflowRuns.ts | 172 ++++++++++++----- apps/server/src/mcp/workflowRun.ts | 12 +- .../chat/SubagentTooltipContent.tsx | 3 +- .../chat/ThreadLineageWorkflowRow.tsx | 4 +- .../src/state/subagentRuntime.test.ts | 31 +++- .../src/state/subagentRuntime.ts | 35 ++-- packages/contracts/src/orchestrationV2.ts | 2 + 11 files changed, 358 insertions(+), 81 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx index 0f3b54e166dd..53f733aeb778 100644 --- a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx +++ b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx @@ -154,13 +154,14 @@ function WorkflowMemberRow(props: { threadId === null ? null : scopeThreadRef(props.environmentId, threadId), ); const canOpen = threadId !== null && shell !== null; - const presentation = resolveSubagentRowPresentation({ + const resolved = resolveSubagentRowPresentation({ title: member.title, prompt: "", status: member.status, result: null, childThreadId: threadId, }); + const presentation = member.notStarted ? { ...resolved, statusLabel: "Not started" } : resolved; const { detail, error } = workflowMemberDetail(member); const metadata = workflowMemberMetadata(member, props.provider); const labels = [metadata.model, metadata.effort].filter((value) => value !== null); diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts index 11a14f189f6f..2c155a527599 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts @@ -192,6 +192,7 @@ describe("nextWorkflowSelection", () => { ); expect(nextWorkflowSelection(stopped, null)).toBe("1"); + expect(stopped.map((item) => item.tone)).toEqual(["completed", "stopped", "queued"]); }); it("keeps one phase open: another replaces it and the open one collapses the card", () => { diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.ts index 997982d614a6..34695b9399e4 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.ts @@ -121,7 +121,7 @@ export interface WorkflowRailItem { } function railTone(members: ReadonlyArray): WorkflowRailTone { - if (members.every((member) => member.status === "pending")) return "queued"; + if (members.every((member) => member.notStarted || member.status === "pending")) return "queued"; if (members.some((member) => isActiveSubagentStatus(member.status) || member.status === "idle")) { return "working"; } diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index f08cf02bf307..4f4c2ebc4272 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -4,6 +4,7 @@ import { CommandId, EnvironmentId, EventId, + isOrchestrationV2WorkActive, MessageId, NodeId, OrchestrationV2DomainEvent, @@ -17,6 +18,7 @@ import { ThreadId, } from "@t3tools/contracts"; import { restoreSubagentBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -426,6 +428,9 @@ const rowWhere = ( ); }); +const agentsRunning = (row: OrchestrationV2Subagent) => + row.workflow?.agents.filter((agent) => agent.state === "running").length ?? 0; + /** Settles a child as its provider would: a final reply, then the run ends. */ const settleChild = (child: OrchestrationV2Subagent, text: string) => Effect.gen(function* () { @@ -467,7 +472,36 @@ const settleChild = (child: OrchestrationV2Subagent, text: string) => runId: childRun.id, providerInstanceId: childRun.providerInstanceId, occurredAt: now, - payload: { ...childRun, status: "completed", startedAt: now, completedAt: now }, + payload: { + ...childRun, + status: "completed", + startedAt: childRun.startedAt ?? now, + completedAt: now, + }, + }, + ], + }); + }); + +/** Starts a child's run as its provider would. */ +const startChild = (child: OrchestrationV2Subagent) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const childThreadId = child.childThreadId!; + const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!; + yield* sink.write({ + commandId: CommandId.make(`command:start:${child.id}`), + events: [ + { + id: EventId.make(`event:child-run-start:${child.id}`), + type: "run.updated", + threadId: childThreadId, + runId: childRun.id, + providerInstanceId: childRun.providerInstanceId, + occurredAt: now, + payload: { ...childRun, status: "running", startedAt: now }, }, ], }); @@ -618,7 +652,7 @@ it.layer(layerTest)("t3_workflow_run", (it) => { const { subagentId } = yield* runs.run(parent.scope, planned); yield* parent.endTurn; const settled = new Set(); - /** Lets `ms` pass once the runner has started the next agents, then settles them. */ + /** Once the runner delegates the next agents, their runs start 500 ms later and take `ms`. */ const settleNext = (count: number, ms: number, text: string) => Effect.gen(function* () { const children = (yield* childrenOf( @@ -636,6 +670,8 @@ it.layer(layerTest)("t3_workflow_run", (it) => { children.some((child) => child.childThreadId === agent.childThreadId), ).length === children.length, ); + yield* TestClock.adjust(500); + for (const child of children) yield* startChild(child); yield* TestClock.adjust(ms); for (const child of children) { settled.add(child.id); @@ -687,22 +723,142 @@ it.layer(layerTest)("t3_workflow_run", (it) => { agent.durationMs, ]), [ - ["a", "completed", 0, 0, 3_000, 3_000], - ["b", "completed", 0, 0, 3_000, 3_000], - ["writer", "completed", 3_000, 3_000, 5_000, 2_000], - ["judge", "completed", 5_000, 5_000, 6_000, 1_000], - ["writer", "completed", 6_000, 6_000, 7_000, 1_000], - ["judge", "completed", 7_000, 7_000, 8_000, 1_000], - ["p", "completed", 8_000, 8_000, 12_000, 4_000], + ["a", "completed", 0, 500, 3_500, 3_000], + ["b", "completed", 0, 500, 3_500, 3_000], + ["writer", "completed", 3_500, 4_000, 6_000, 2_000], + ["judge", "completed", 6_000, 6_500, 7_500, 1_000], + ["writer", "completed", 7_500, 8_000, 9_000, 1_000], + ["judge", "completed", 9_000, 9_500, 10_500, 1_000], + ["p", "completed", 10_500, 11_000, 15_000, 4_000], ], ); }), ); + it.effect( + "times an agent from its child's run, even one that ended while the server was down", + () => + Effect.gen(function* () { + const parent = yield* seedParent("downtime"); + const before = yield* Scope.make(); + const { subagentId } = yield* (yield* workflowRunsIn(before)).run(parent.scope, { + name: "one", + stages: [{ id: "one", agents: [{ id: "a", task: "A." }] }], + }); + yield* parent.endTurn; + const [child] = yield* childrenOf(parent.threadId, subagentId, 1); + yield* rowWhere(parent.threadId, subagentId, (row) => agentsRunning(row) === 1); + const startedAt = yield* Clock.currentTimeMillis; + yield* startChild(child!); + yield* TestClock.adjust(1_000); + yield* Scope.close(before, Exit.void); + yield* settleChild(child!, "Done."); + yield* TestClock.adjust(9_000); + + yield* (yield* workflowRunsIn(yield* Effect.scope)).start(); + const [agent] = (yield* ended(parent.threadId, subagentId))?.workflow?.agents ?? []; + assert.deepEqual( + [agent?.state, agent?.startedAt, agent?.completedAt, agent?.durationMs], + ["completed", startedAt, startedAt + 1_000, 1_000], + ); + }), + ); + + it.effect("shows the model a child actually runs once it starts, not the planned one", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("actual-model"); + const { subagentId } = yield* runs.run(parent.scope, { + name: "two", + stages: [ + { id: "one", agents: [{ id: "a", task: "A." }] }, + { id: "two", agents: [{ id: "b", task: "B." }] }, + ], + }); + yield* parent.endTurn; + const [first] = yield* childrenOf(parent.threadId, subagentId, 1); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("command:actual-model:switch"), + threadId: parent.threadId, + modelSelection: { + instanceId: claude, + model: "claude-sonnet-5-5", + options: [{ id: "effort", value: "low" }], + }, + }); + yield* settleChild(first!, "Done."); + const row = yield* rowWhere( + parent.threadId, + subagentId, + (row) => row.workflow?.agents[1]?.state === "running", + ); + const { providerInstanceId, model, effort } = row.workflow!.agents[1]!; + assert.deepEqual( + { providerInstanceId, model, effort }, + { providerInstanceId: claude, model: "claude-sonnet-5-5", effort: "low" }, + ); + }), + ); + + it.effect("fails a running row an older build recorded instead of resuming it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const parent = yield* seedParent("legacy"); + const before = yield* Scope.make(); + const { subagentId } = yield* (yield* workflowRunsIn(before)).run(parent.scope, spec); + yield* parent.endTurn; + const drafts = yield* childrenOf(parent.threadId, subagentId, 2); + yield* Scope.close(before, Exit.void); + const row = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents.find( + (task) => task.id === subagentId, + )!; + const { version: _version, ...legacy } = row.workflowRun!; + const oldLayout = { + name: "review", + phases: [ + { index: 0, title: "draft" }, + { index: 1, title: "judge" }, + ], + agents: drafts.map((draft, index) => ({ + index, + label: draft.title!.split(".")[1]!.split("#")[0]!, + childThreadId: draft.childThreadId!, + state: "running" as const, + phaseIndex: 0, + attempt: 1, + })), + }; + yield* orchestrator.dispatch({ + type: "workflow_run.update", + commandId: CommandId.make("command:legacy:old-layout"), + parentThreadId: parent.threadId, + taskId: subagentId, + workflow: oldLayout, + workflowRun: legacy, + }); + + yield* (yield* workflowRunsIn(yield* Effect.scope)).start(); + const failed = yield* ended(parent.threadId, subagentId); + assert.equal(failed?.status, "failed"); + assert.deepEqual(failed?.workflow, oldLayout); + assert.include(JSON.parse(failed?.result ?? "{}").error, "older T3 build"); + const children = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents.filter( + (task) => task.parentNodeId === subagentId, + ); + assert.lengthOf(children, 2); + assert.isFalse(children.some((task) => isOrchestrationV2WorkActive(task.status))); + assert.lengthOf(yield* wakes(parent.threadId), 1); + }), + ); + it.effect( "keeps every workflow row update within 2 KB on the wire across a 20-agent stage and 3 rounds", () => Effect.gen(function* () { + // Real epoch times, so each timestamp costs its full width on the wire. + yield* TestClock.setTime(1_793_404_800_000); const runs = yield* workflowRunsIn(yield* Effect.scope); const parent = yield* seedParent("bytes"); const wide = { diff --git a/apps/server/src/mcp/WorkflowRuns.ts b/apps/server/src/mcp/WorkflowRuns.ts index d97db3c5be44..0d8c404cda94 100644 --- a/apps/server/src/mcp/WorkflowRuns.ts +++ b/apps/server/src/mcp/WorkflowRuns.ts @@ -4,6 +4,7 @@ import { type EnvironmentId, type ModelSelection, NodeId, + type OrchestrationV2Run, type OrchestrationV2SubagentWorkflow, type OrchestrationV2WorkflowAgent, type OrchestrationV2WorkflowRunState, @@ -15,6 +16,7 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -90,8 +92,49 @@ const outcomeOf = (result: OrchestratorMcpDelegateTaskResult): WorkflowAgentOutc : { structuredResult: result.structuredResult }), }; +/** The row layout this build writes. A row without it is an older build's and is never resumed. */ +const ROW_VERSION = 2; + +const LEGACY_ROW = "This run was recorded by an older T3 build, so it cannot be resumed."; + type AgentTarget = Pick; +/** What a launched agent's child has recorded: where it runs, and when its runs started and ended. */ +type ChildFacts = AgentTarget & Pick; + +interface Child { + readonly threadId: ThreadId; + readonly facts: ChildFacts; +} + +const factsOfAgent = ({ + providerInstanceId, + model, + effort, + startedAt, + completedAt, +}: OrchestrationV2WorkflowAgent): ChildFacts => ({ + ...(providerInstanceId === undefined ? {} : { providerInstanceId }), + ...(model === undefined ? {} : { model }), + ...(effort === undefined ? {} : { effort }), + ...(startedAt === undefined ? {} : { startedAt }), + ...(completedAt === undefined ? {} : { completedAt }), +}); + +/** Read from the child's own run records, never from when the runner noticed a change. */ +const factsOfRuns = (runs: ReadonlyArray): ChildFacts => { + const ordered = runs.toSorted((left, right) => left.ordinal - right.ordinal); + const first = ordered[0]; + const last = ordered.at(-1); + if (first === undefined || last === undefined) return {}; + // Until the child's run starts, its request stands in so a live row can show elapsed time. + return { + ...targetOf(last.modelSelection), + startedAt: DateTime.toEpochMillis(first.startedAt ?? first.requestedAt), + ...(last.completedAt === null ? {} : { completedAt: DateTime.toEpochMillis(last.completedAt) }), + }; +}; + const targetOf = (selection: ModelSelection): AgentTarget => { const effort = getModelSelectionStringOptionValue(selection, "reasoningEffort") ?? @@ -105,6 +148,13 @@ const targetOf = (selection: ModelSelection): AgentTarget => { const targetKey = (stage: string, agent: string) => `${stage}.${agent}`; +const legacyResult = (spec: WorkflowSpec, status: WorkflowResult["status"]): WorkflowResult => ({ + name: spec.name, + status, + error: LEGACY_ROW, + stages: [], +}); + /** * The row lists every agent of every phase so far, launched or not, in phase order (results stay * on the child tasks), and keeps the rest of the snapshot as `workflowRun`. @@ -112,13 +162,13 @@ const targetKey = (stage: string, agent: string) => `${stage}.${agent}`; function toRow( spec: WorkflowSpec, snapshot: WorkflowSnapshot, - childThreads: ReadonlyMap, + children: ReadonlyMap, targets: ReadonlyMap, ): { readonly workflow: OrchestrationV2SubagentWorkflow; readonly workflowRun: OrchestrationV2WorkflowRunState; } { - const { launches, ...workflowRun } = snapshot; + const { launches, ...state } = snapshot; const phases = workflowPhases(spec, snapshot); const agents = phases.flatMap(({ stage, round }, phaseIndex) => stage.agents.map((agent) => ({ stage: stage.id, agent: agent.id, round, phaseIndex })), @@ -138,14 +188,16 @@ function toRow( (l) => l.stage === stage && l.round === round && l.agent === agent, ); if (launch === undefined) return { ...planned, state: "queued" as const }; - const childThreadId = launch.taskId === null ? undefined : childThreads.get(launch.taskId); + const child = launch.taskId === null ? undefined : children.get(launch.taskId); // A launch the run cancels as it ends stays live here; clients show the run's end for it. const live = launch.outcome === null || launch.cancelRequested; - const { queuedAt, startedAt } = launch; - const completedAt = live ? undefined : launch.completedAt; + const { queuedAt } = launch; + const { startedAt, completedAt: endedAt, ...target } = child?.facts ?? {}; + const completedAt = live ? undefined : endedAt; return { ...planned, - ...(childThreadId === undefined ? {} : { childThreadId }), + ...target, + ...(child === undefined ? {} : { childThreadId: child.threadId }), state: live ? launch.taskId === null ? "queued" @@ -162,7 +214,7 @@ function toRow( }; }), }, - workflowRun, + workflowRun: { ...state, version: ROW_VERSION }, }; } @@ -198,12 +250,17 @@ const make = Effect.gen(function* () { const live = subagents.flatMap((child) => child.parentNodeId === row.id && isOrchestrationV2WorkActive(child.status) ? [child.id] : [], ); - const childThreads = new Map( - subagents.flatMap((child): Array<[string, ThreadId]> => - child.parentNodeId === row.id && child.childThreadId !== null - ? [[child.id, child.childThreadId]] - : [], - ), + const workflowRun = row.workflowRun!; + const legacy = workflowRun.version !== ROW_VERSION; + // An older build's agents index another layout; expanding them would misplace every launch. + const recorded = legacy ? [] : (row.workflow?.agents ?? []); + const children = new Map( + subagents.flatMap((child): Array<[string, Child]> => { + if (child.parentNodeId !== row.id || child.childThreadId === null) return []; + const agent = recorded.find((agent) => agent.childThreadId === child.childThreadId); + const facts = agent === undefined ? {} : factsOfAgent(agent); + return [[child.id, { threadId: child.childThreadId, facts }]]; + }), ); // Children act as the run, so their task ids stay stable across restarts. const scope: McpThreadInvocationScope = { @@ -218,29 +275,27 @@ const make = Effect.gen(function* () { capabilities: new Set(["orchestration"]), issuedAt: 0, }; - const phases = workflowPhases(spec, row.workflowRun!); - const agents = (row.workflow?.agents ?? []).flatMap((agent) => { + const phases = workflowPhases(spec, workflowRun); + const agents = recorded.flatMap((agent) => { const phase = phases[agent.phaseIndex ?? 0]; return phase === undefined ? [] : [{ agent, stage: phase.stage.id, round: phase.round }]; }); - const targets = new Map( - agents.map(({ agent: { providerInstanceId, model, effort, label }, stage }) => [ - targetKey(stage, label), - { - ...(providerInstanceId === undefined ? {} : { providerInstanceId }), - ...(model === undefined ? {} : { model }), - ...(effort === undefined ? {} : { effort }), - }, - ]), - ); - return { row, spec, childThreads, live, scope, agents, targets }; + // A later round's agents are planned with what round 1 ran. + const targets = new Map(); + for (const { agent, stage } of agents) { + const key = targetKey(stage, agent.label); + if (targets.has(key)) continue; + const { startedAt: _startedAt, completedAt: _completedAt, ...target } = factsOfAgent(agent); + targets.set(key, target); + } + return { row, spec, workflowRun, legacy, children, live, scope, agents, targets }; }); /** Rebuilds the runner's snapshot; finished launches read their outcome from their child task. */ const snapshotOf = Effect.fn("WorkflowRuns.snapshotOf")(function* ( run: Effect.Success>, ) { - const taskIds = new Map([...run.childThreads].map(([taskId, thread]) => [thread, taskId])); + const taskIds = new Map([...run.children].map(([taskId, child]) => [child.threadId, taskId])); // A queued agent with no queue time is one the run has not launched yet. const launched = run.agents.filter( ({ agent }) => agent.state !== "queued" || agent.queuedAt !== undefined, @@ -264,12 +319,11 @@ const make = Effect.gen(function* () { cancelRequested: false, outcome, ...(agent.queuedAt === undefined ? {} : { queuedAt: agent.queuedAt }), - ...(agent.startedAt === undefined ? {} : { startedAt: agent.startedAt }), - ...(agent.completedAt === undefined ? {} : { completedAt: agent.completedAt }), }; }), ); - return { ...run.row.workflowRun!, launches } satisfies WorkflowSnapshot; + const { version: _version, ...state } = run.workflowRun; + return { ...state, launches } satisfies WorkflowSnapshot; }); const drive = Effect.fn("WorkflowRuns.drive")(function* ( @@ -278,17 +332,34 @@ const make = Effect.gen(function* () { taskId: NodeId, ) { const run = yield* readRun(environmentId, threadId, taskId); + const cancelLive = Effect.forEach( + run.live, + (child) => Effect.ignore(mcp.cancelTask(run.scope, { taskId: child })), + { discard: true }, + ); // A restart can cut off an ended run's cancels; its recorded end and wake stay as they are. - if (run.row.workflowRun?.status !== "running") { - return yield* Effect.forEach( - run.live, - (child) => Effect.ignore(mcp.cancelTask(run.scope, { taskId: child })), - { discard: true }, - ); + if (run.workflowRun.status !== "running") return yield* cancelLive; + const { row, spec, children, scope, targets } = run; + if (run.legacy) { + yield* cancelLive; + return yield* threads + .dispatch({ + type: "workflow_run.update", + commandId: yield* commandId("legacy"), + parentThreadId: threadId, + taskId: row.id, + workflowRun: { ...run.workflowRun, status: "failed" }, + result: encodeJson(legacyResult(spec, "failed")), + }) + .pipe(Effect.asVoid, Effect.mapError(unavailable)); } - if (run.row.runId === null) return; - const { row, spec, childThreads, scope, targets } = run; - const owner = { taskId: row.id, runId: row.runId! }; + if (row.runId === null) return; + const owner = { taskId: row.id, runId: row.runId }; + const learn = (childTaskId: string, threadId: ThreadId) => + threads.getThreadRecords(threadId, ["runs"]).pipe( + Effect.map(({ runs }) => children.set(childTaskId, { threadId, facts: factsOfRuns(runs) })), + Effect.ignore, + ); const port: WorkflowPort = { start: ({ key, agent: { id: _id, task: _template, ...options }, task }) => mcp @@ -301,15 +372,21 @@ const make = Effect.gen(function* () { workflow: owner, }) .pipe( - Effect.map((started) => { - if (started.childThreadId !== null) { - childThreads.set(started.taskId, started.childThreadId); - } - return started.taskId; - }), + Effect.tap((started) => + started.childThreadId === null + ? Effect.void + : learn(started.taskId, started.childThreadId), + ), + Effect.map((started) => started.taskId), ), await: (childTaskId) => - mcp.awaitTask(scope, NodeId.make(childTaskId)).pipe(Effect.map(outcomeOf)), + mcp.awaitTask(scope, NodeId.make(childTaskId)).pipe( + Effect.tap(() => { + const child = children.get(childTaskId); + return child === undefined ? Effect.void : learn(childTaskId, child.threadId); + }), + Effect.map(outcomeOf), + ), cancel: (childTaskId) => mcp.cancelTask(scope, { taskId: NodeId.make(childTaskId) }).pipe(Effect.asVoid), persist: (snapshot) => @@ -320,7 +397,7 @@ const make = Effect.gen(function* () { commandId: id, parentThreadId: threadId, taskId: row.id, - ...toRow(spec, snapshot, childThreads, targets), + ...toRow(spec, snapshot, children, targets), ...(snapshot.status === "running" ? {} : { result: encodeJson(workflowResult(spec, snapshot)) }), @@ -418,6 +495,7 @@ const make = Effect.gen(function* () { ) { const scope = yield* requireThreadScope(callerScope, "t3_workflow_status"); const found = yield* readRun(scope.environmentId, scope.thread.threadId, subagentId); + if (found.legacy) return legacyResult(found.spec, found.workflowRun.status); return workflowResult(found.spec, yield* snapshotOf(found)); }); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 1254e0ba55d1..6c359d838e6f 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -64,8 +64,6 @@ const WorkflowLaunch = Schema.Struct({ cancelRequested: Schema.Boolean, outcome: Schema.NullOr(WorkflowAgentOutcome), queuedAt: Schema.optional(Schema.Number), - startedAt: Schema.optional(Schema.Number), - completedAt: Schema.optional(Schema.Number), }); type WorkflowLaunch = typeof WorkflowLaunch.Type; @@ -120,6 +118,7 @@ type StageResult = { readonly id: string; readonly agents: ReadonlyArray keyOf(l) === event.key); return launch === undefined || launch.outcome !== null ? Effect.void - : Effect.flatMap(Clock.currentTimeMillis, (completedAt) => - update(event.key, { outcome: event.outcome, completedAt }), - ); + : update(event.key, { outcome: event.outcome }); }; while (state.status === "running") { diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index 126b3cd79e33..a43e0871ec6b 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -49,6 +49,7 @@ export function SubagentTooltipContent(props: { parentProject?: Pick | undefined; childProject?: Pick | undefined; status: OrchestrationV2TurnItemStatus; + statusLabel?: string | undefined; result?: string | null | undefined; progress?: string | null | undefined; }) { @@ -168,7 +169,7 @@ export function SubagentTooltipContent(props: { )} > - {props.status.replaceAll("_", " ")} + {props.statusLabel ?? props.status.replaceAll("_", " ")} {props.elapsed} diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index af8cb70600fe..0aebc34ae6eb 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -37,6 +37,7 @@ function phaseElapsed(phase: SubagentWorkflowGroup["phases"][number]) { function phaseStatusLabel(phase: SubagentWorkflowGroup["phases"][number]) { if (phase.state === "running") return "running"; + if (phase.state === "pending") return "not started"; if (phase.members.some((member) => member.status === "failed")) return "failed"; if ( phase.members.some((member) => member.status === "cancelled" || member.status === "interrupted") @@ -84,7 +85,7 @@ function WorkflowMemberRow({ > {member.title} - {member.status} + {member.notStarted ? "not started" : member.status} {member.startedAt ? ( @@ -103,6 +104,7 @@ function WorkflowMemberRow({ driver={driver} elapsed={} status={member.status} + statusLabel={member.notStarted ? "not started" : undefined} result={member.result ?? member.error} progress={member.progress} /> diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index 4d8f8a3f3b34..aebc5cdff6b5 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -97,7 +97,7 @@ describe("projectedSubagentsToRuntime workflow expansion", () => { phases: [], agents: [ member(), - member({ index: 2, state: "queued" }), + member({ index: 2, state: "queued", queuedAt: Date.UTC(2026, 7, 1, 10, 0, 0) }), member({ index: 3, state: "completed", @@ -123,6 +123,35 @@ describe("projectedSubagentsToRuntime workflow expansion", () => { ); }); +describe("planned members a run never launched", () => { + it.each(["failed", "cancelled"] as const)( + "stay not started, unsettled and untimed when the coordinator is %s", + (status) => { + const [group] = groupsOf([ + subagent({ + status, + completedAt: at("2026-08-01T10:00:09.000Z"), + workflow: { + phases: [ + { index: 0, title: "draft" }, + { index: 1, title: "ship" }, + ], + agents: [ + member({ index: 0, phaseIndex: 0, phaseTitle: undefined, state: "failed" }), + member({ index: 1, phaseIndex: 1, phaseTitle: undefined, state: "queued" }), + ], + }, + }), + ]); + const ship = group?.phases[1]; + expect([ship?.state, ship?.settledCount]).toEqual(["pending", 0]); + expect(ship?.members[0]?.notStarted).toBe(true); + expect(ship?.members[0]?.completedAt).toBeNull(); + expect(group?.phases[0]?.members[0]?.notStarted).toBeUndefined(); + }, + ); +}); + describe("deriveWorkflowGroups over a dynamic workflow", () => { it("groups members under their phases and counts the run", () => { const groups = groupsOf([ diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index e144b5615e46..1723a3bae2ae 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -57,6 +57,8 @@ export interface RuntimeSubagent { readonly speed?: string | undefined; /** A workflow member's own provider, when it reports one. */ readonly providerInstanceId?: ProviderInstanceId | undefined; + /** A planned workflow member its run ended before launching; it never settled. */ + readonly notStarted?: true | undefined; readonly status: RuntimeSubagentStatus; readonly activationCount: number; readonly usage: SubagentUsage | null; @@ -134,21 +136,29 @@ function workflowMembersToRuntime( workflow: OrchestrationV2SubagentWorkflow, ): ReadonlyArray { return workflow.agents.map((agent) => { - const status = - (agent.state === "queued" || agent.state === "running") && - isTerminalSubagentStatus(coordinator.status) + // Planned, never queued or started: the run ended before it got there. + const notStarted = + agent.state === "queued" && + agent.queuedAt === undefined && + agent.startedAt === undefined && + isTerminalSubagentStatus(coordinator.status); + const status = notStarted + ? "cancelled" + : (agent.state === "queued" || agent.state === "running") && + isTerminalSubagentStatus(coordinator.status) ? coordinator.status : agent.state === "queued" ? "pending" : agent.state; const failed = status === "failed"; const startedAt = isoFromEpochMillis(agent.startedAt); - const completedAt = isTerminalSubagentStatus(status) - ? (isoFromEpochMillis(agent.completedAt) ?? - (agent.startedAt !== undefined && agent.durationMs !== undefined - ? isoFromEpochMillis(agent.startedAt + agent.durationMs) - : coordinator.completedAt)) - : null; + const completedAt = + !notStarted && isTerminalSubagentStatus(status) + ? (isoFromEpochMillis(agent.completedAt) ?? + (agent.startedAt !== undefined && agent.durationMs !== undefined + ? isoFromEpochMillis(agent.startedAt + agent.durationMs) + : coordinator.completedAt)) + : null; return { ...coordinator, id: `${coordinator.id}:agent:${agent.index}`, @@ -160,6 +170,7 @@ function workflowMembersToRuntime( ...(agent.providerInstanceId === undefined ? {} : { providerInstanceId: agent.providerInstanceId }), + ...(notStarted ? { notStarted } : {}), status, activationCount: agent.attempt ?? 1, usage: workflowUsage(agent), @@ -280,11 +291,11 @@ export function deriveWorkflowGroups( // member has not finished the phase. (member) => isActiveSubagentStatus(member.status) || member.status === "idle", ); - const settledCount = phaseMembers.filter((member) => - isTerminalSubagentStatus(member.status), + const settledCount = phaseMembers.filter( + (member) => !member.notStarted && isTerminalSubagentStatus(member.status), ).length; const state: "pending" | "running" | "done" = phaseMembers.every( - (member) => member.status === "pending", + (member) => member.notStarted || member.status === "pending", ) ? "pending" : hasActiveMember diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 17b4ca3137f2..f81931ee2055 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -857,6 +857,8 @@ export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChi /** Where a server-owned workflow run is; its launches are `workflow.agents`. */ export const OrchestrationV2WorkflowRunState = Schema.Struct({ + /** The row layout; absent on rows an older build recorded, which are never resumed. */ + version: Schema.optional(PositiveInt), status: Schema.Literals(["running", "completed", "failed", "cancelled", "timed_out"]), cursor: NonNegativeInt, round: NonNegativeInt, From 82651a94926ef62f955d4cff99871c1eb91fc59a Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 04:43:47 +0200 Subject: [PATCH 3/3] fix(server): a workflow's final row reads its children's runs again and drops a planned effort Review round 2 of #18 found two gaps. A child whose run started after it was delegated kept its request time as its start when the run ended by timeout or stop, because nothing read its runs again before the final row. And a member kept the planned effort when its child ran a model that has none. Before the run's terminal row, every launched child's runs are read once more. Once a child's facts exist, the member shows the child's whole target, so a missing effort stays missing. The parent-wake test helper now waits for the offer, which follows the row's commit, instead of reading it once. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/WorkflowRuns.test.ts | 99 ++++++++++++++++++++---- apps/server/src/mcp/WorkflowRuns.ts | 27 ++++--- 2 files changed, 103 insertions(+), 23 deletions(-) diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index 4f4c2ebc4272..e59cc2b79f32 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -9,6 +9,7 @@ import { NodeId, OrchestrationV2DomainEvent, type OrchestrationV2Subagent, + type ModelSelection, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -25,7 +26,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Ref from "effect/Ref"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -106,7 +107,9 @@ const provider = (instanceId: ProviderInstanceId, driver: string, model: string) class Offers extends Context.Service< Offers, - Ref.Ref> + SubscriptionRef.SubscriptionRef< + ReadonlyArray + > >()("t3/mcp/WorkflowRuns.test/Offers") {} const layerDatabase = SqlitePersistence.layerMemory; @@ -160,7 +163,7 @@ const layerTest = OrchestratorMcpService.layer.pipe( Offers.pipe( Effect.map((offers) => ({ offer: (request: ProviderContinuationRequests.ProviderContinuationRequest) => - Ref.update(offers, (seen) => [...seen, request]), + SubscriptionRef.update(offers, (seen) => [...seen, request]), take: Effect.never, })), ), @@ -169,7 +172,9 @@ const layerTest = OrchestratorMcpService.layer.pipe( Layer.provideMerge( Layer.effect( Offers, - Ref.make>([]), + SubscriptionRef.make>( + [], + ), ), ), Layer.provideMerge( @@ -248,7 +253,7 @@ const planned = { }; /** A Codex parent whose turn is live when it calls t3_workflow_run. */ -const seedParent = (name: string) => +const seedParent = (name: string, selection: ModelSelection = modelSelection) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const sink = yield* EventSink.EventSinkV2; @@ -265,7 +270,7 @@ const seedParent = (name: string) => threadId, projectId: ProjectId.make("project:workflow-runs"), title: "Parent", - modelSelection, + modelSelection: selection, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -284,7 +289,7 @@ const seedParent = (name: string) => threadId, ordinal: 1, providerInstanceId: codex, - modelSelection, + modelSelection: selection, providerThreadId, userMessageId: MessageId.make(`message:${name}`), rootNodeId, @@ -507,14 +512,20 @@ const startChild = (child: OrchestrationV2Subagent) => }); }); +/** The distinct wakes offered to a parent, once it has had one; the offer follows the row's commit. */ const wakes = (threadId: ThreadId) => - Effect.map(Offers.pipe(Effect.flatMap(Ref.get)), (all) => [ - ...new Set( - all - .filter((offer) => offer.threadId === threadId) - .map((offer) => offer.delegatedCompletion?.messageId), + Offers.pipe( + Effect.flatMap((offers) => + SubscriptionRef.changes(offers).pipe( + Stream.map((all) => all.filter((offer) => offer.threadId === threadId)), + Stream.filter((offered) => offered.length > 0), + Stream.runHead, + ), ), - ]); + Effect.map((offered) => [ + ...new Set(Option.getOrThrow(offered).map((offer) => offer.delegatedCompletion?.messageId)), + ]), + ); /** A WorkflowRuns instance whose runners die with `scope`, as in a server restart. */ const workflowRunsIn = (scope: Scope.Scope) => @@ -802,6 +813,68 @@ it.layer(layerTest)("t3_workflow_run", (it) => { }), ); + it.effect("drops a planned effort once the child runs a model without one", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("dropped-effort", { + ...modelSelection, + options: [{ id: "effort", value: "low" }], + }); + const { subagentId } = yield* runs.run(parent.scope, { + name: "two", + stages: [ + { id: "one", agents: [{ id: "a", task: "A." }] }, + { id: "two", agents: [{ id: "b", task: "B." }] }, + ], + }); + const planned = yield* rowWhere(parent.threadId, subagentId, () => true); + assert.equal(planned.workflow?.agents[1]?.effort, "low"); + yield* parent.endTurn; + const [first] = yield* childrenOf(parent.threadId, subagentId, 1); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("command:dropped-effort:switch"), + threadId: parent.threadId, + modelSelection: { instanceId: claude, model: "claude-sonnet-5-5" }, + }); + yield* settleChild(first!, "Done."); + const row = yield* rowWhere( + parent.threadId, + subagentId, + (row) => row.workflow?.agents[1]?.state === "running", + ); + const { providerInstanceId, model, effort } = row.workflow!.agents[1]!; + assert.deepEqual( + { providerInstanceId, model, effort }, + { providerInstanceId: claude, model: "claude-sonnet-5-5", effort: undefined }, + ); + }), + ); + + it.effect("keeps a child's real start when the run times out after it started", () => + Effect.gen(function* () { + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("timeout-start"); + const { subagentId } = yield* runs.run(parent.scope, { + name: "slow", + timeoutMs: 5_000, + stages: [{ id: "one", agents: [{ id: "a", task: "A." }] }], + }); + yield* parent.endTurn; + const [child] = yield* childrenOf(parent.threadId, subagentId, 1); + yield* rowWhere(parent.threadId, subagentId, (row) => agentsRunning(row) === 1); + const requestedAt = yield* Clock.currentTimeMillis; + yield* TestClock.adjust(500); + yield* startChild(child!); + yield* TestClock.adjust(5_000); + + const row = yield* ended(parent.threadId, subagentId); + assert.equal(row?.workflowRun?.status, "timed_out"); + assert.equal(row?.workflow?.agents[0]?.startedAt, requestedAt + 500); + }), + ); + it.effect("fails a running row an older build recorded instead of resuming it", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/mcp/WorkflowRuns.ts b/apps/server/src/mcp/WorkflowRuns.ts index 0d8c404cda94..43466780b809 100644 --- a/apps/server/src/mcp/WorkflowRuns.ts +++ b/apps/server/src/mcp/WorkflowRuns.ts @@ -178,24 +178,22 @@ function toRow( name: spec.name, phases: phases.map(({ title }, index) => ({ index, title })), agents: agents.map(({ stage, agent, round, phaseIndex }, index) => { - const planned = { - index, - label: agent, - phaseIndex, - ...targets.get(targetKey(stage, agent)), - }; + const base = { index, label: agent, phaseIndex }; + const planned = targets.get(targetKey(stage, agent)); const launch = launches.find( (l) => l.stage === stage && l.round === round && l.agent === agent, ); - if (launch === undefined) return { ...planned, state: "queued" as const }; + if (launch === undefined) return { ...base, ...planned, state: "queued" as const }; const child = launch.taskId === null ? undefined : children.get(launch.taskId); // A launch the run cancels as it ends stays live here; clients show the run's end for it. const live = launch.outcome === null || launch.cancelRequested; const { queuedAt } = launch; - const { startedAt, completedAt: endedAt, ...target } = child?.facts ?? {}; + const { startedAt, completedAt: endedAt, ...ran } = child?.facts ?? {}; const completedAt = live ? undefined : endedAt; + // What the child ran replaces the plan whole: a model without an effort shows none. + const target = ran.providerInstanceId === undefined ? planned : ran; return { - ...planned, + ...base, ...target, ...(child === undefined ? {} : { childThreadId: child.threadId }), state: live @@ -390,7 +388,16 @@ const make = Effect.gen(function* () { cancel: (childTaskId) => mcp.cancelTask(scope, { taskId: NodeId.make(childTaskId) }).pipe(Effect.asVoid), persist: (snapshot) => - commandId("update").pipe( + // The run's last row is final: read every child's runs once more, so none keeps a stand-in. + (snapshot.status === "running" + ? Effect.void + : Effect.forEach( + [...children], + ([childTaskId, child]) => learn(childTaskId, child.threadId), + { discard: true }, + ) + ).pipe( + Effect.andThen(commandId("update")), Effect.flatMap((id) => threads.dispatch({ type: "workflow_run.update",