Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

orchestrationV2PendingBackgroundWork.ts

263 lines9.1 KB

1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderThread,
4 OrchestrationV2Run,
5 OrchestrationV2TurnItem,
6 ThreadId,
7} from "@t3tools/contracts";
8import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
9​
10const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
11 "command_execution",
12 "dynamic_tool",
13 "subagent",
14]);
15​
16/**
17 * True terminal run statuses (includes `rolled_back`). Retained as the
18 * canonical terminal set for this module; do not widen or reuse it as the
19 * background-wait gate — that gate intentionally excludes `rolled_back`.
20 */
21const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
22 "cancelled",
23 "completed",
24 "failed",
25 "interrupted",
26 "rolled_back",
27]);
28​
29/**
30 * Run statuses that allow a pending-background roster to surface.
31 * Includes `waiting`: a successful turn persists as waiting until checkpoint
32 * capture flips it to completed, and waiting is only set from completed.
33 * Excludes `rolled_back`: the provider-thread roster is not run-tied, so a
34 * rolled-back latest run must fail the gate entirely (not only item filter).
35 * Built explicitly rather than spreading or deleting from TERMINAL_RUN_STATUSES.
36 */
37const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
38 "cancelled",
39 "completed",
40 "failed",
41 "interrupted",
42 "waiting",
43]);
44​
45// Keep TERMINAL_RUN_STATUSES referenced so the true-terminal set stays defined
46// next to the background-wait subset (rolled_back is terminal, not wait-settled).
47void TERMINAL_RUN_STATUSES;
48​
49export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
50​
51/**
52 * Whether a turn-item update can end background work that a settled run is
53 * still waiting on: an item of a background type that is no longer active.
54 * Streaming output on a running item, and every other item type, cannot.
55 */
56export function turnItemUpdateCanEndBackgroundWork(
57 item: Pick<OrchestrationV2TurnItem, "type" | "status">,
58): boolean {
59 return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
61​
62/**
63 * Whether background work left behind by a completed root run holds back its
64 * completion alert (desktop/web notification and the mobile push). Commands,
65 * such as dev servers and other long-lived shells, do not: the agent is done
66 * and may leave them running for hours. Subagents and monitors do, because
67 * they wake the agent and it continues (#13625). Work the adapter cannot name,
68 * including kinds this build does not know, holds as the conservative choice.
69 */
70export function backgroundWorkHoldsCompletion(
71 tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
72): boolean {
73 return tasks.some((task) => backgroundWorkKindHoldsCompletion(task.kind));
75​
76function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean {
77 switch (kind) {
78 case "command":
79 return false;
80 case "subagent":
81 case "monitor":
82 case "background_task":
83 return true;
84 }
86​
87type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
88​
89type PendingBackgroundWorkProviderThread = Pick<
90 OrchestrationV2ProviderThread,
91 "id" | "pendingBackgroundTasks"
92>;
93​
94type PendingBackgroundWorkTurnItem = {
95 readonly id: OrchestrationV2TurnItem["id"] | string;
96 readonly type: OrchestrationV2TurnItem["type"];
97 readonly status: OrchestrationV2TurnItem["status"];
98 readonly title: string | null;
99 /** When present and the run is rolled_back, the item is abandoned, not pending. */
100 readonly runId?: OrchestrationV2Run["id"] | string | null;
101 readonly nativeItemRef?: {
102 readonly nativeId: string | null;
103 } | null;
104 readonly input?: unknown;
105 readonly prompt?: string | undefined;
106 readonly childThreadId?: ThreadId | null;
107};
108​
109function isLatestRunSettledForBackgroundWait(
110 latestRun: PendingBackgroundWorkRun | null | undefined,
111): boolean {
112 if (latestRun === undefined || latestRun === null) {
113 return false;
114 }
115 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
117​
118function isPersistentDynamicToolInput(input: unknown): boolean {
119 if (input === null || typeof input !== "object" || Array.isArray(input)) {
120 return false;
121 }
122 return Reflect.get(input, "persistent") === true;
124​
125function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
126 if (typeof item.title === "string" && item.title.trim().length > 0) {
127 return item.title.trim();
128 }
129 if (item.type === "command_execution" && typeof item.input === "string") {
130 const command = item.input.trim();
131 return command.length > 0 ? command : undefined;
132 }
133 if (item.type === "dynamic_tool") {
134 const toolName = Reflect.get(item, "toolName");
135 if (typeof toolName === "string" && toolName.trim().length > 0) {
136 return toolName.trim();
137 }
138 }
139 if (item.type === "subagent" && typeof item.prompt === "string") {
140 const prompt = item.prompt.trim();
141 return prompt.length > 0 ? prompt : undefined;
142 }
143 return undefined;
145​
146function pendingTaskFromTurnItem(
147 taskId: string,
148 item: PendingBackgroundWorkTurnItem,
149): PendingBackgroundWorkTask {
150 const description = descriptionFromTurnItem(item);
151 const named = { taskId, ...(description === undefined ? {} : { description }) };
152 switch (item.type) {
153 case "subagent":
154 return {
155 ...named,
156 kind: "subagent",
157 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
158 };
159 case "command_execution":
160 return { ...named, kind: "command" };
161 default:
162 return { ...named, kind: "background_task" };
163 }
165​
166function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
167 const nativeId = item.nativeItemRef?.nativeId;
168 if (typeof nativeId === "string" && nativeId.length > 0) {
169 return nativeId;
170 }
171 return String(item.id);
173​
174/**
175 * Derive one normalized pending-background-work list for post-settlement UI.
176 *
177 * Sources:
178 * - Provider-thread roster (Claude SDK background tasks)
179 * - Active command_execution / dynamic_tool / subagent turn items
180 *
181 * Gated on latest root run settlement. Dedupes by native task ID. Excludes
182 * the roster while any interruptible foreground run remains active. Excludes
183 * Grok persistent monitors (`dynamic_tool` input with `persistent: true`).
184 * Excludes turn items whose run resolves to `rolled_back` (abandoned work);
185 * items with a null or absent run id stay eligible (matches SQL shell path).
186 * Does not consult subagent entities (those double-count turn items).
187 */
188export function derivePendingBackgroundWork(input: {
189 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
190 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
191 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
192 readonly activeProviderThreadId?: string | null;
193 readonly hasActiveRun?: boolean;
194 /**
195 * Run rows used to exclude items owned by rolled_back runs. Optional for
196 * callers that already filtered (SQL shell path); in-memory callers should
197 * pass projection runs so policy cannot drift.
198 */
199 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
200}): ReadonlyArray<PendingBackgroundWorkTask> {
201 const hasActiveRun =
202 input.hasActiveRun ??
203 input.runs?.some(
204 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
205 ) ??
206 false;
207 if (hasActiveRun) {
208 return [];
209 }
210 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
211 return [];
212 }
213​
214 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
215 const rolledBackRunIds = new Set(
216 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
217 );
218​
219 const providerThreads =
220 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
221 ? input.providerThreads
222 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
223​
224 for (const providerThread of providerThreads) {
225 for (const task of providerThread.pendingBackgroundTasks ?? []) {
226 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
227 continue;
228 }
229 const { description: rawDescription, ...named } = task;
230 const description = rawDescription?.trim();
231 byTaskId.set(task.taskId, {
232 ...named,
233 ...(description === undefined || description.length === 0 ? {} : { description }),
234 });
235 }
236 }
237​
238 for (const item of input.turnItems) {
239 if (!BACKGROUND_TURN_ITEM_TYPES.has(item.type)) {
240 continue;
241 }
242 if (!isOrchestrationV2WorkActive(item.status)) {
243 continue;
244 }
245 if (item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) {
246 continue;
247 }
248 // Null/absent run id stays eligible; only known rolled_back runs drop.
249 const itemRunId = item.runId;
250 if (itemRunId !== undefined && itemRunId !== null && rolledBackRunIds.has(String(itemRunId))) {
251 continue;
252 }
253​
254 const taskId = nativeTaskIdFromTurnItem(item);
255 if (byTaskId.has(taskId)) {
256 continue;
257 }
258​
259 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
260 }
261​
262 return Array.from(byTaskId.values());