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