Open History to see the last commit
1import {
2 latestRootProviderFailure,
3 latestUnheldRun,
4 threadErrorSummary,
5 usageLimitRunPresentedAsLatest,
6} from "@t3tools/shared/orchestrationV2ThreadError";
7import {
8 isOrchestrationV2WorkActive,
9 isProviderNativeSubagentThread,
10 type ModelSelection,
11 type OrchestrationV2NotificationSource,
12 type OrchestrationV2PendingBackgroundTask,
13 type ServerProviderModel,
14 type OrchestrationV2ExecutionNode,
15 type OrchestrationV2ThreadProjection,
16 type ThreadId,
17} from "@t3tools/contracts";
18import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
19import { getProviderOptionCurrentLabel, getProviderOptionDescriptors } from "@t3tools/shared/model";
20import { formatDuration } from "@t3tools/shared/orchestrationTiming";
21import * as DateTime from "effect/DateTime";
22
23import {
24 threadRuntimeIsActive,
25 type ThreadRunSummary,
26 type ThreadRuntimeSummary,
27} from "./models.ts";
28
29const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
30const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
31
32function latestMatchingRun(
33 projection: OrchestrationV2ThreadProjection,
34 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
35): OrchestrationV2ThreadProjection["runs"][number] | null {
36 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
37 (latest, candidate) =>
38 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
39 ? candidate
40 : latest,
41 null,
42 );
43}
44
45function summarizeThreadRun(
46 projection: OrchestrationV2ThreadProjection,
47 run: OrchestrationV2ThreadProjection["runs"][number],
48): ThreadRunSummary {
49 return {
50 runId: run.id,
51 status: run.status,
52 requestedAt: DateTime.formatIso(run.requestedAt),
53 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
54 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
55 assistantMessageId:
56 projection.messages.findLast(
57 (message) => message.runId === run.id && message.role === "assistant",
58 )?.id ?? null,
59 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
60 };
61}
62
63function presentedUsageLimitRun(
64 projection: OrchestrationV2ThreadProjection,
65): OrchestrationV2ThreadProjection["runs"][number] | null {
66 const providerSession = projection.providerSessions.findLast(
67 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
68 );
69 return usageLimitRunPresentedAsLatest(
70 projection.runs,
71 projection.turnItems,
72 providerSession?.lastError ?? null,
73 );
74}
75
76/** The run that stands for the thread's outcome when no run is executing. */
77function presentedLatestRun(
78 projection: OrchestrationV2ThreadProjection,
79): OrchestrationV2ThreadProjection["runs"][number] | null {
80 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
81}
82
83export function deriveLatestThreadRun(
84 projection: OrchestrationV2ThreadProjection,
85): ThreadRunSummary | null {
86 const run = presentedLatestRun(projection);
87 return run === null ? null : summarizeThreadRun(projection, run);
88}
89
90/**
91 * Returns the run that owns live provider work, falling back to the newest run
92 * once the thread is idle. A newer queued run must not make an older executing
93 * run look settled in clients that render per-run activity.
94 */
95export function deriveThreadActivityRun(
96 projection: OrchestrationV2ThreadProjection,
97): ThreadRunSummary | null {
98 const run =
99 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
100 presentedLatestRun(projection);
101 return run === null ? null : summarizeThreadRun(projection, run);
102}
103
104/**
105 * Provider-native subagent threads never get app runs: their work is a runless
106 * root turn whose status follows the subagent. Returns when that work started
107 * while it is still active, so clients can show the same working state (and
108 * timer) as a run. Stop, queue, and steer stay run-only.
109 */
110export function deriveRunlessWorkStartedAt(
111 projection: OrchestrationV2ThreadProjection,
112): string | null {
113 const status = deriveProviderSubagentStatus(projection);
114 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
115}
116
117export interface ProviderSubagentStatus {
118 readonly status: OrchestrationV2ExecutionNode["status"];
119 readonly startedAt: string | null;
120 readonly completedAt: string | null;
121}
122
123/**
124 * Status of a provider-native subagent thread (see
125 * isProviderNativeSubagentThread), read from its runless root turn. Null
126 * until that root turn arrives, and for every other thread.
127 */
128export function deriveProviderSubagentStatus(
129 projection: OrchestrationV2ThreadProjection,
130): ProviderSubagentStatus | null {
131 if (!isProviderNativeSubagentThread(projection.thread)) return null;
132 const node = projection.nodes.findLast(
133 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
134 );
135 if (node === undefined) return null;
136 return {
137 status: node.status,
138 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
139 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
140 };
141}
142
143// Option ids providers use for reasoning effort (Codex, Claude, Grok/ACP, OpenCode).
144const REASONING_EFFORT_OPTION_IDS = ["reasoningEffort", "effort", "reasoning", "variant"] as const;
145
146/**
147 * The reasoning effort a thread's model runs at, resolved and named the way
148 * the composer's effort picker does: the stored choice when valid, else the
149 * descriptor's current value, else the model's default. Null when the
150 * provider catalog has no effort option for this model (a subagent on a
151 * model the catalog does not describe), rather than guessing.
152 */
153export function formatModelSelectionEffort(
154 selection: ModelSelection,
155 models: ReadonlyArray<ServerProviderModel> = [],
156): string | null {
157 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
158 if (!caps) return null;
159 const descriptors = getProviderOptionDescriptors({ caps, selections: selection.options });
160 for (const id of REASONING_EFFORT_OPTION_IDS) {
161 const descriptor = descriptors.find((candidate) => candidate.id === id);
162 if (descriptor?.type !== "select") continue;
163 const label = getProviderOptionCurrentLabel(descriptor);
164 if (label) return label;
165 }
166 return null;
167}
168
169const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
170 idle: "Idle",
171 pending: "Working",
172 running: "Working",
173 waiting: "Waiting",
174 completed: "Completed",
175 interrupted: "Interrupted",
176 failed: "Failed",
177 cancelled: "Cancelled",
178 rolled_back: "Cancelled",
179};
180
181/**
182 * One line for the read-only subagent bar: "Working 12s", "Completed in 34s",
183 * or just the status when no duration is known.
184 */
185export function formatProviderSubagentStatus(
186 status: ProviderSubagentStatus | null,
187 nowMs: number,
188): string {
189 if (status === null) return "Starting";
190 const label = SUBAGENT_STATUS_LABELS[status.status];
191 const live = isOrchestrationV2WorkActive(status.status);
192 if (!live && status.status !== "completed") return label;
193 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
194 const end = live
195 ? nowMs
196 : status.completedAt === null
197 ? Number.NaN
198 : Date.parse(status.completedAt);
199 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
200 // Whole seconds: a ticking label must not flicker through tenths.
201 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
202 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
203}
204
205export function deriveThreadRuntime(
206 projection: OrchestrationV2ThreadProjection,
207): ThreadRuntimeSummary | null {
208 const latestRun = deriveLatestThreadRun(projection);
209 const providerSession = projection.providerSessions.findLast(
210 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
211 );
212 const usageLimitedRun = presentedUsageLimitRun(projection);
213 const latestRunProjection = presentedLatestRun(projection);
214 const activityRun = deriveThreadActivityRun(projection);
215 if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
216 const activeRunId =
217 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
218 const hasPendingBackgroundTasks =
219 derivePendingBackgroundWork({
220 latestRun: latestRunProjection,
221 providerThreads: projection.providerThreads,
222 turnItems: projection.turnItems,
223 activeProviderThreadId: projection.thread.activeProviderThreadId,
224 runs: projection.runs,
225 }).length > 0;
226 return {
227 status: usageLimitedRun
228 ? "failed"
229 : hasPendingBackgroundTasks && latestRunProjection?.status !== "failed"
230 ? "idle"
231 : (activityRun?.status ?? "idle"),
232 activeRunId,
233 activityStartedAt:
234 activityRun !== null && ACTIVITY_RUN_STATUSES.has(activityRun.status)
235 ? (activityRun.startedAt ?? activityRun.requestedAt)
236 : null,
237 providerInstanceId: projection.thread.providerInstanceId,
238 providerName: providerSession?.driver ?? null,
239 ...threadErrorSummary(
240 latestRootProviderFailure(latestRunProjection, projection.turnItems),
241 providerSession?.lastError ?? null,
242 ),
243 updatedAt: DateTime.formatIso(projection.updatedAt),
244 };
245}
246
247export function threadRuntimeHasInterruptibleRun(
248 runtime: ThreadRuntimeSummary | null | undefined,
249): boolean {
250 return (
251 threadRuntimeIsActive(runtime) &&
252 runtime?.activeRunId !== null &&
253 runtime?.activeRunId !== undefined
254 );
255}
256
257type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
258
259// `order` groups work the way a reader thinks about it: agents first, loose tasks last.
260const BACKGROUND_WORK_KINDS: Record<
261 BackgroundWorkKind,
262 { readonly order: number; readonly singular: string; readonly plural: string }
263> = {
264 subagent: { order: 0, singular: "subagent", plural: "subagents" },
265 command: { order: 1, singular: "command", plural: "commands" },
266 monitor: { order: 2, singular: "monitor", plural: "monitors" },
267 background_task: { order: 3, singular: "background task", plural: "background tasks" },
268};
269
270export interface PendingBackgroundWorkItem {
271 readonly taskId: string;
272 readonly kind: BackgroundWorkKind;
273 /** The work's name, or its noun when the provider gave none. */
274 readonly label: string;
275 /** A subagent's own thread, when it has one. */
276 readonly childThreadId: ThreadId | undefined;
277}
278
279export interface PendingBackgroundWorkPresentation {
280 /** "Waiting on subagent Review src/math.ts", "Waiting on 2 subagents and 1 command". */
281 readonly title: string;
282 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
283}
284
285function joinWithAnd(parts: ReadonlyArray<string>): string {
286 if (parts.length <= 1) return parts.join("");
287 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
288}
289
290/** Names what a settled thread is still waiting on, grouped by kind, for the composer strip. */
291export function presentPendingBackgroundWork(
292 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
293): PendingBackgroundWorkPresentation | null {
294 if (tasks.length === 0) return null;
295 const items = tasks
296 .map((task): PendingBackgroundWorkItem => {
297 const description = task.description?.trim();
298 return {
299 taskId: task.taskId,
300 kind: task.kind,
301 label:
302 description === undefined || description.length === 0
303 ? BACKGROUND_WORK_KINDS[task.kind].singular
304 : description,
305 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
306 };
307 })
308 // `map` returned a new array; Hermes has no `toSorted`.
309 .sort(
310 (left, right) =>
311 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
312 );
313 const [only] = items;
314 if (items.length === 1 && only !== undefined) {
315 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
316 return {
317 title: only.label === noun ? `Waiting on a ${noun}` : `Waiting on ${noun} ${only.label}`,
318 items,
319 };
320 }
321 const counts = new Map<BackgroundWorkKind, number>();
322 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
323 const groups = Array.from(counts, ([kind, count]) => {
324 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
325 return `${count} ${count === 1 ? singular : plural}`;
326 });
327 return { title: `Waiting on ${joinWithAnd(groups)}`, items };
328}
329
330/** The thread a notification row opens: that of the one subagent or delegated task it reports. */
331export function notificationChildThreadId(
332 source: OrchestrationV2NotificationSource,
333): ThreadId | undefined {
334 switch (source.kind) {
335 case "subagent":
336 case "delegated_task":
337 return source.childThreadId;
338 case "command":
339 case "monitor":
340 case "background_task":
341 return undefined;
342 default:
343 source satisfies never;
344 return undefined;
345 }
346}