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