diff --git a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx index df67df16cf58..53f733aeb778 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} /> )) @@ -151,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 8514e86a900b..2c155a527599 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,20 @@ 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"); + 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", () => { 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..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"; } @@ -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..e59cc2b79f32 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -4,10 +4,12 @@ import { CommandId, EnvironmentId, EventId, + isOrchestrationV2WorkActive, MessageId, NodeId, OrchestrationV2DomainEvent, type OrchestrationV2Subagent, + type ModelSelection, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -17,16 +19,18 @@ 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"; 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"; +import * as TestClock from "effect/testing/TestClock"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; @@ -103,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; @@ -157,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, })), ), @@ -166,7 +172,9 @@ const layerTest = OrchestratorMcpService.layer.pipe( Layer.provideMerge( Layer.effect( Offers, - Ref.make>([]), + SubscriptionRef.make>( + [], + ), ), ), Layer.provideMerge( @@ -200,8 +208,52 @@ 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) => +const seedParent = (name: string, selection: ModelSelection = modelSelection) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const sink = yield* EventSink.EventSinkV2; @@ -218,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, @@ -237,7 +289,7 @@ const seedParent = (name: string) => threadId, ordinal: 1, providerInstanceId: codex, - modelSelection, + modelSelection: selection, providerThreadId, userMessageId: MessageId.make(`message:${name}`), rootNodeId, @@ -366,6 +418,24 @@ 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), + ); + }); + +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* () { @@ -407,20 +477,55 @@ 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 }, }, ], }); }); +/** 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) => @@ -489,10 +594,344 @@ 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(); + /** 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( + 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(500); + for (const child of children) yield* startChild(child); + 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, 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("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; + 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 8a7a749c3fc1..43466780b809 100644 --- a/apps/server/src/mcp/WorkflowRuns.ts +++ b/apps/server/src/mcp/WorkflowRuns.ts @@ -2,16 +2,21 @@ import { CommandId, isOrchestrationV2WorkActive, type EnvironmentId, + type ModelSelection, NodeId, + type OrchestrationV2Run, 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"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -38,6 +43,7 @@ import { workflowResult, type WorkflowSnapshot, WorkflowSpec, + workflowPhases, } from "./workflowRun.ts"; export class WorkflowRuns extends Context.Service< @@ -86,42 +92,127 @@ 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`. */ +/** 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") ?? + getModelSelectionStringOptionValue(selection, "effort"); + return { + providerInstanceId: selection.instanceId, + model: selection.model, + ...(effort?.trim() ? { effort: effort.trim() } : {}), + }; +}; + +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`. + */ function toRow( spec: WorkflowSpec, snapshot: WorkflowSnapshot, - childThreads: ReadonlyMap, + children: 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 { 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 })), + ); return { workflow: { name: spec.name, - phases, - agents: launches.map((launch, index) => { - const childThreadId = launch.taskId === null ? undefined : childThreads.get(launch.taskId); + phases: phases.map(({ title }, index) => ({ index, title })), + agents: agents.map(({ stage, agent, round, phaseIndex }, index) => { + 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 { ...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, ...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 { - index, - label: launch.agent, - ...(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, + ...base, + ...target, + ...(child === undefined ? {} : { childThreadId: child.threadId }), + 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) }), }; }), }, - workflowRun, + workflowRun: { ...state, version: ROW_VERSION }, }; } @@ -157,12 +248,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 = { @@ -177,16 +273,32 @@ const make = Effect.gen(function* () { capabilities: new Set(["orchestration"]), issuedAt: 0, }; - return { row, spec, childThreads, live, scope }; + 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 }]; + }); + // 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 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) => + 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, + ); + const launches = yield* Effect.forEach(launched, ({ agent, stage, round }) => Effect.gen(function* () { const taskId = agent.childThreadId === undefined ? null : (taskIds.get(agent.childThreadId) ?? null); @@ -198,16 +310,18 @@ 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 }), }; }), ); - 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* ( @@ -216,17 +330,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 } = 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 @@ -239,26 +370,41 @@ 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) => - 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", commandId: id, parentThreadId: threadId, taskId: row.id, - ...toRow(spec, snapshot, childThreads), + ...toRow(spec, snapshot, children, targets), ...(snapshot.status === "running" ? {} : { result: encodeJson(workflowResult(spec, snapshot)) }), @@ -288,18 +434,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 +483,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 }) => @@ -350,6 +502,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 9d9ff832777b..6c359d838e6f 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -63,6 +63,7 @@ const WorkflowLaunch = Schema.Struct({ taskId: Schema.NullOr(Schema.String), cancelRequested: Schema.Boolean, outcome: Schema.NullOr(WorkflowAgentOutcome), + queuedAt: Schema.optional(Schema.Number), }); type WorkflowLaunch = typeof WorkflowLaunch.Type; @@ -117,6 +118,7 @@ type StageResult = { readonly id: string; readonly agents: ReadonlyArray (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") { @@ -394,6 +417,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..a43e0871ec6b 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"]; @@ -47,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; }) { @@ -72,9 +75,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) => { @@ -164,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 8e0ef07c839b..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 ? ( @@ -95,6 +96,7 @@ function WorkflowMemberRow({ } status={member.status} + statusLabel={member.notStarted ? "not started" : undefined} result={member.result ?? member.error} progress={member.progress} /> diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index d8aecbd16bba..1634ac3e0ce8 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -887,14 +887,15 @@ export function ThreadRelationshipsPanel(props: { member.childThreadId === null ? undefined : subagentsByThreadId.get(member.childThreadId as ThreadId); - if (task === undefined) return undefined; + const providerInstanceId = task?.providerInstanceId ?? member.providerInstanceId; + if (providerInstanceId === undefined) return undefined; const taskProvider = providers?.find( - (entry) => 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..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([ @@ -158,6 +187,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..1723a3bae2ae 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,10 @@ 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; + /** 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; @@ -131,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}`, @@ -154,6 +167,10 @@ function workflowMembersToRuntime( model: agent.model ?? null, effort: agent.effort ?? null, ...(agent.speed === undefined ? {} : { speed: agent.speed }), + ...(agent.providerInstanceId === undefined + ? {} + : { providerInstanceId: agent.providerInstanceId }), + ...(notStarted ? { notStarted } : {}), status, activationCount: agent.attempt ?? 1, usage: workflowUsage(agent), @@ -274,11 +291,16 @@ 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.length === 0 ? "pending" : hasActiveMember ? "running" : "done"; + const state: "pending" | "running" | "done" = phaseMembers.every( + (member) => member.notStarted || 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..f81931ee2055 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), @@ -855,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,