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

orchestrationV2PendingBackgroundWork.ts

268 lines9.4 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 * The turn items the pending-work list names, without its settled-run gate.
176 * Stop ends exactly these, so the list and Stop cannot disagree.
177 */
178export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
179 readonly turnItems: ReadonlyArray<Item>;
180 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
181}): ReadonlyArray<Item> {
182 const rolledBackRunIds = new Set(
183 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
184 );
185 return input.turnItems.filter(
186 (item) =>
187 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
188 isOrchestrationV2WorkActive(item.status) &&
189 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
190 // Null/absent run id stays eligible; only known rolled_back runs drop.
191 (item.runId === undefined ||
192 item.runId === null ||
193 !rolledBackRunIds.has(String(item.runId))),
194 );
196​
197/**
198 * Derive one normalized pending-background-work list for post-settlement UI.
199 *
200 * Sources:
201 * - Provider-thread roster (Claude SDK background tasks)
202 * - Active command_execution / dynamic_tool / subagent turn items
203 *
204 * Gated on latest root run settlement. Dedupes by native task ID. Excludes
205 * the roster while any interruptible foreground run remains active. Excludes
206 * Grok persistent monitors (`dynamic_tool` input with `persistent: true`).
207 * Excludes turn items whose run resolves to `rolled_back` (abandoned work);
208 * items with a null or absent run id stay eligible (matches SQL shell path).
209 * Does not consult subagent entities (those double-count turn items).
210 */
211export function derivePendingBackgroundWork(input: {
212 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
213 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
214 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
215 readonly activeProviderThreadId?: string | null;
216 readonly hasActiveRun?: boolean;
217 /**
218 * Run rows used to exclude items owned by rolled_back runs. Optional for
219 * callers that already filtered (SQL shell path); in-memory callers should
220 * pass projection runs so policy cannot drift.
221 */
222 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
223}): ReadonlyArray<PendingBackgroundWorkTask> {
224 const hasActiveRun =
225 input.hasActiveRun ??
226 input.runs?.some(
227 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
228 ) ??
229 false;
230 if (hasActiveRun) {
231 return [];
232 }
233 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
234 return [];
235 }
236​
237 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
238​
239 const providerThreads =
240 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
241 ? input.providerThreads
242 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
243​
244 for (const providerThread of providerThreads) {
245 for (const task of providerThread.pendingBackgroundTasks ?? []) {
246 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
247 continue;
248 }
249 const { description: rawDescription, ...named } = task;
250 const description = rawDescription?.trim();
251 byTaskId.set(task.taskId, {
252 ...named,
253 ...(description === undefined || description.length === 0 ? {} : { description }),
254 });
255 }
256 }
257​
258 for (const item of pendingBackgroundTurnItems(input)) {
259 const taskId = nativeTaskIdFromTurnItem(item);
260 if (byTaskId.has(taskId)) {
261 continue;
262 }
263​
264 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
265 }
266​
267 return Array.from(byTaskId.values());