Open History to see the last commit
1import {
2 latestRootProviderFailure,
3 threadErrorSummary,
4} from "@t3tools/shared/orchestrationV2ThreadError";
5import {
6 isOrchestrationV2WorkActive,
7 isProviderNativeSubagentThread,
8 type ModelSelection,
9 type ServerProviderModel,
10 type OrchestrationV2ExecutionNode,
11 type OrchestrationV2ThreadProjection,
12} from "@t3tools/contracts";
13import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
14import { getProviderOptionCurrentLabel, getProviderOptionDescriptors } from "@t3tools/shared/model";
15import { formatDuration } from "@t3tools/shared/orchestrationTiming";
16import * as DateTime from "effect/DateTime";
17
18import {
19 threadRuntimeIsActive,
20 type ThreadRunSummary,
21 type ThreadRuntimeSummary,
22} from "./models.ts";
23
24const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
25const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
26
27function latestMatchingRun(
28 projection: OrchestrationV2ThreadProjection,
29 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
30): OrchestrationV2ThreadProjection["runs"][number] | null {
31 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
32 (latest, candidate) =>
33 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
34 ? candidate
35 : latest,
36 null,
37 );
38}
39
40function summarizeThreadRun(
41 projection: OrchestrationV2ThreadProjection,
42 run: OrchestrationV2ThreadProjection["runs"][number],
43): ThreadRunSummary {
44 return {
45 runId: run.id,
46 status: run.status,
47 requestedAt: DateTime.formatIso(run.requestedAt),
48 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
49 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
50 assistantMessageId:
51 projection.messages.findLast(
52 (message) => message.runId === run.id && message.role === "assistant",
53 )?.id ?? null,
54 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
55 };
56}
57
58export function deriveLatestThreadRun(
59 projection: OrchestrationV2ThreadProjection,
60): ThreadRunSummary | null {
61 const run = latestMatchingRun(projection, () => true);
62 return run === null ? null : summarizeThreadRun(projection, run);
63}
64
65/**
66 * Returns the run that owns live provider work, falling back to the newest run
67 * once the thread is idle. A newer queued run must not make an older executing
68 * run look settled in clients that render per-run activity.
69 */
70export function deriveThreadActivityRun(
71 projection: OrchestrationV2ThreadProjection,
72): ThreadRunSummary | null {
73 const run =
74 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
75 latestMatchingRun(projection, () => true);
76 return run === null ? null : summarizeThreadRun(projection, run);
77}
78
79/**
80 * Provider-native subagent threads never get app runs: their work is a runless
81 * root turn whose status follows the subagent. Returns when that work started
82 * while it is still active, so clients can show the same working state (and
83 * timer) as a run. Stop, queue, and steer stay run-only.
84 */
85export function deriveRunlessWorkStartedAt(
86 projection: OrchestrationV2ThreadProjection,
87): string | null {
88 const status = deriveProviderSubagentStatus(projection);
89 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
90}
91
92export interface ProviderSubagentStatus {
93 readonly status: OrchestrationV2ExecutionNode["status"];
94 readonly startedAt: string | null;
95 readonly completedAt: string | null;
96}
97
98/**
99 * Status of a provider-native subagent thread (see
100 * isProviderNativeSubagentThread), read from its runless root turn. Null
101 * until that root turn arrives, and for every other thread.
102 */
103export function deriveProviderSubagentStatus(
104 projection: OrchestrationV2ThreadProjection,
105): ProviderSubagentStatus | null {
106 if (!isProviderNativeSubagentThread(projection.thread)) return null;
107 const node = projection.nodes.findLast(
108 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
109 );
110 if (node === undefined) return null;
111 return {
112 status: node.status,
113 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
114 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
115 };
116}
117
118// Option ids providers use for reasoning effort (Codex, Claude, Grok/ACP, OpenCode).
119const REASONING_EFFORT_OPTION_IDS = ["reasoningEffort", "effort", "reasoning", "variant"] as const;
120
121/**
122 * The reasoning effort a thread's model runs at, resolved and named the way
123 * the composer's effort picker does: the stored choice when valid, else the
124 * descriptor's current value, else the model's default. Null when the
125 * provider catalog has no effort option for this model (a subagent on a
126 * model the catalog does not describe), rather than guessing.
127 */
128export function formatModelSelectionEffort(
129 selection: ModelSelection,
130 models: ReadonlyArray<ServerProviderModel> = [],
131): string | null {
132 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
133 if (!caps) return null;
134 const descriptors = getProviderOptionDescriptors({ caps, selections: selection.options });
135 for (const id of REASONING_EFFORT_OPTION_IDS) {
136 const descriptor = descriptors.find((candidate) => candidate.id === id);
137 if (descriptor?.type !== "select") continue;
138 const label = getProviderOptionCurrentLabel(descriptor);
139 if (label) return label;
140 }
141 return null;
142}
143
144const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
145 idle: "Idle",
146 pending: "Working",
147 running: "Working",
148 waiting: "Waiting",
149 completed: "Completed",
150 interrupted: "Interrupted",
151 failed: "Failed",
152 cancelled: "Cancelled",
153 rolled_back: "Cancelled",
154};
155
156/**
157 * One line for the read-only subagent bar: "Working 12s", "Completed in 34s",
158 * or just the status when no duration is known.
159 */
160export function formatProviderSubagentStatus(
161 status: ProviderSubagentStatus | null,
162 nowMs: number,
163): string {
164 if (status === null) return "Starting";
165 const label = SUBAGENT_STATUS_LABELS[status.status];
166 const live = isOrchestrationV2WorkActive(status.status);
167 if (!live && status.status !== "completed") return label;
168 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
169 const end = live
170 ? nowMs
171 : status.completedAt === null
172 ? Number.NaN
173 : Date.parse(status.completedAt);
174 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
175 // Whole seconds: a ticking label must not flicker through tenths.
176 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
177 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
178}
179
180export function deriveThreadRuntime(
181 projection: OrchestrationV2ThreadProjection,
182): ThreadRuntimeSummary | null {
183 const latestRun = deriveLatestThreadRun(projection);
184 const latestRunProjection = latestMatchingRun(projection, () => true);
185 const activityRun = deriveThreadActivityRun(projection);
186 const providerSession = projection.providerSessions.findLast(
187 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
188 );
189 if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
190 const activeRunId =
191 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
192 const hasPendingBackgroundTasks =
193 derivePendingBackgroundWork({
194 latestRun: latestRunProjection,
195 providerThreads: projection.providerThreads,
196 turnItems: projection.turnItems,
197 activeProviderThreadId: projection.thread.activeProviderThreadId,
198 runs: projection.runs,
199 }).length > 0;
200 return {
201 status: hasPendingBackgroundTasks ? "idle" : (activityRun?.status ?? "idle"),
202 activeRunId,
203 activityStartedAt:
204 activityRun !== null && ACTIVITY_RUN_STATUSES.has(activityRun.status)
205 ? (activityRun.startedAt ?? activityRun.requestedAt)
206 : null,
207 providerInstanceId: projection.thread.providerInstanceId,
208 providerName: providerSession?.driver ?? null,
209 ...threadErrorSummary(
210 latestRootProviderFailure(latestRunProjection, projection.turnItems),
211 providerSession?.lastError ?? null,
212 ),
213 updatedAt: DateTime.formatIso(projection.updatedAt),
214 };
215}
216
217export function threadRuntimeHasInterruptibleRun(
218 runtime: ThreadRuntimeSummary | null | undefined,
219): boolean {
220 return (
221 threadRuntimeIsActive(runtime) &&
222 runtime?.activeRunId !== null &&
223 runtime?.activeRunId !== undefined
224 );
225}