Open History to see the last commit
1import { applyThreadPullRequestLinkUpdate } from "@t3tools/shared/threadPullRequests";
2import type {
3 OrchestrationV2DomainEvent,
4 OrchestrationV2Run,
5 OrchestrationV2ThreadProjection,
6 OrchestrationV2TurnItem,
7} from "@t3tools/contracts";
8import {
9 createOrchestrationV2TurnItemVisibility,
10 isOrchestrationV2TurnItemVisible,
11} from "@t3tools/shared/orchestrationV2Timeline";
12
13export type ApplyOrchestrationV2ProjectionEventOptions = {
14 readonly partialTimeline?: boolean;
15 readonly latestLocalTurnOrdinal?: number | null;
16};
17
18function upsertEntity<T extends { readonly id: unknown }>(
19 items: ReadonlyArray<T>,
20 item: T,
21): ReadonlyArray<T> {
22 const index = items.findIndex((candidate) => candidate.id === item.id);
23 if (index === -1) return [...items, item];
24 const next = [...items];
25 next[index] = item;
26 return next;
27}
28
29function removeVisibleItem(
30 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
31 sourceItemId: OrchestrationV2TurnItem["id"],
32): OrchestrationV2ThreadProjection["visibleTurnItems"] {
33 const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
34 if (index === -1) return rows;
35 return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
36}
37
38function renumberVisibleItems(
39 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
40): OrchestrationV2ThreadProjection["visibleTurnItems"] {
41 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
42}
43
44function shouldShowLocalTurnItem(
45 projection: OrchestrationV2ThreadProjection,
46 item: OrchestrationV2TurnItem,
47): boolean {
48 return isOrchestrationV2TurnItemVisible({
49 item,
50 runs: projection.runs,
51 attempts: projection.attempts,
52 items: projection.turnItems,
53 });
54}
55
56function activeVisibleTurnItems(
57 projection: OrchestrationV2ThreadProjection,
58): OrchestrationV2ThreadProjection["visibleTurnItems"] {
59 const rows = projection.visibleTurnItems;
60 const isVisible = createOrchestrationV2TurnItemVisibility({
61 runs: projection.runs,
62 attempts: projection.attempts,
63 items: projection.turnItems,
64 });
65 let next: Array<(typeof rows)[number]> | null = null;
66 for (let index = 0; index < rows.length; index += 1) {
67 const row = rows[index]!;
68 const keep = row.visibility !== "local" || isVisible(row.item);
69 if (!keep) {
70 next ??= rows.slice(0, index);
71 continue;
72 }
73 next?.push(row);
74 }
75 return next === null ? rows : renumberVisibleItems(next);
76}
77
78function oldestLocalTurnOrdinal(
79 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
80): number | null {
81 let oldest: number | null = null;
82 for (const row of rows) {
83 if (row.visibility !== "local") continue;
84 if (oldest === null || row.item.ordinal < oldest) {
85 oldest = row.item.ordinal;
86 }
87 }
88 return oldest;
89}
90
91const UNFINISHED_RUN_STATUSES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([
92 "preparing",
93 "queued",
94 "starting",
95 "running",
96 "waiting",
97]);
98
99function shouldDropMissingPartialTurnItem(
100 projection: OrchestrationV2ThreadProjection,
101 item: OrchestrationV2TurnItem,
102 latestLocalTurnOrdinal: number | null | undefined,
103): boolean {
104 if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) {
105 return false;
106 }
107 if (item.runId === null) {
108 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
109 }
110 // A queued run keeps the ordinal it got when queued, so a steer sent later
111 // can raise the watermark past it. Items of a run that has not finished are
112 // new, not unloaded history: the first lands while the run is still queued,
113 // and a bounded window can start after the ones before it.
114 if (
115 projection.runs.some((run) => run.id === item.runId && UNFINISHED_RUN_STATUSES.has(run.status))
116 ) {
117 return false;
118 }
119 if (
120 projection.visibleTurnItems.some(
121 (row) =>
122 row.visibility === "local" &&
123 row.item.runId === item.runId &&
124 row.item.ordinal <= item.ordinal,
125 )
126 ) {
127 return false;
128 }
129 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
130}
131
132function isBelowPartialWindow(
133 projection: OrchestrationV2ThreadProjection,
134 item: OrchestrationV2TurnItem,
135 latestLocalTurnOrdinal: number | null | undefined,
136): boolean {
137 if (
138 latestLocalTurnOrdinal !== null &&
139 latestLocalTurnOrdinal !== undefined &&
140 item.ordinal <= latestLocalTurnOrdinal
141 ) {
142 return true;
143 }
144 const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems);
145 return oldest !== null && item.ordinal < oldest;
146}
147
148function upsertVisibleTurnItem(
149 projection: OrchestrationV2ThreadProjection,
150 item: OrchestrationV2TurnItem,
151 partialTimeline: boolean,
152 latestLocalTurnOrdinal: number | null | undefined,
153): OrchestrationV2ThreadProjection["visibleTurnItems"] {
154 const rows = projection.visibleTurnItems;
155 // Streamed updates land on the newest rows. Item ids are unique, so the
156 // search can start there.
157 let index = rows.length - 1;
158 while (index >= 0 && rows[index]!.sourceItemId !== item.id) index -= 1;
159 const next = {
160 position: 0,
161 visibility: "local" as const,
162 sourceThreadId: item.threadId,
163 sourceItemId: item.id,
164 item,
165 };
166 const previous = index === -1 ? undefined : rows[index]!;
167 if (
168 previous !== undefined &&
169 previous.visibility === next.visibility &&
170 previous.sourceThreadId === next.sourceThreadId &&
171 previous.sourceItemId === next.sourceItemId &&
172 previous.item === item
173 ) {
174 return rows;
175 }
176 if (
177 index === -1 &&
178 partialTimeline &&
179 shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal)
180 ) {
181 return rows;
182 }
183 // The item goes before the first later local row, as if its old row were
184 // removed first. One pass builds and renumbers the result: this runs for
185 // every streamed chunk of a thread that can hold thousands of rows.
186 let insertion = rows.length;
187 for (let candidate = 0; candidate < rows.length; candidate += 1) {
188 const row = rows[candidate]!;
189 if (
190 candidate !== index &&
191 row.visibility === "local" &&
192 (row.item.ordinal > item.ordinal ||
193 (row.item.ordinal === item.ordinal &&
194 String(row.item.id).localeCompare(String(item.id)) > 0))
195 ) {
196 insertion = candidate;
197 break;
198 }
199 }
200 const updated: Array<(typeof rows)[number]> = [];
201 for (let source = 0; source < rows.length; source += 1) {
202 if (source === insertion) updated.push(next);
203 if (source !== index) updated.push(rows[source]!);
204 }
205 if (insertion === rows.length) updated.push(next);
206 for (let position = 0; position < updated.length; position += 1) {
207 const row = updated[position]!;
208 if (row.position !== position) updated[position] = { ...row, position };
209 }
210 return updated;
211}
212
213export function applyOrchestrationV2ProjectionEvent(
214 projection: OrchestrationV2ThreadProjection | null,
215 event: OrchestrationV2DomainEvent,
216 options?: ApplyOrchestrationV2ProjectionEventOptions,
217): OrchestrationV2ThreadProjection | null {
218 if (projection === null || event.threadId !== projection.thread.id) return projection;
219
220 const partialTimeline = options?.partialTimeline === true;
221 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
222 const base = { ...projection, updatedAt: event.occurredAt };
223 switch (event.type) {
224 case "thread.pull-request-link-updated":
225 return {
226 ...base,
227 thread: applyThreadPullRequestLinkUpdate(projection.thread, event.payload),
228 };
229 case "thread.created":
230 case "thread.archived":
231 case "thread.unarchived":
232 case "thread.deleted":
233 case "thread.settled":
234 case "thread.unsettled":
235 case "thread.snoozed":
236 case "thread.unsnoozed":
237 case "thread.auto-settle-set":
238 case "thread.pinned":
239 case "thread.unpinned":
240 case "thread.pin-reordered":
241 case "thread.active-reordered":
242 case "thread.metadata-updated":
243 case "thread.pull-request-synced":
244 case "thread.runtime-mode-updated":
245 case "thread.interaction-mode-updated":
246 case "thread.model-selection-updated":
247 case "thread.provider-switched":
248 return { ...base, thread: event.payload };
249 // Visited tracking is read state, not activity: skip the updatedAt bump.
250 case "thread.visited":
251 case "thread.marked-unread":
252 return { ...projection, thread: event.payload };
253 case "run.created":
254 case "run.updated": {
255 const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
256 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
257 }
258 case "run.background-work-cancelled":
259 return {
260 ...base,
261 runs: base.runs.map((run) =>
262 run.id === event.payload.runId
263 ? {
264 ...run,
265 restartCancelledBackgroundWork: event.payload.restartCancelledBackgroundWork,
266 }
267 : run,
268 ),
269 };
270 case "run-attempt.created":
271 case "run-attempt.updated": {
272 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
273 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
274 }
275 case "node.updated":
276 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
277 case "subagent.updated":
278 return { ...base, subagents: upsertEntity(base.subagents, event.payload) };
279 case "provider-session.attached":
280 case "provider-session.updated":
281 return {
282 ...base,
283 providerSessions: upsertEntity(base.providerSessions, event.payload),
284 };
285 case "provider-session.detached":
286 return {
287 ...base,
288 providerSessions: base.providerSessions.filter(
289 (session) => session.id !== event.payload.providerSessionId,
290 ),
291 };
292 case "provider-thread.updated":
293 return { ...base, providerThreads: upsertEntity(base.providerThreads, event.payload) };
294 case "provider-turn.updated":
295 return {
296 ...base,
297 providerTurns: upsertEntity(base.providerTurns, {
298 ...event.payload,
299 ...((event.payload.tokenUsage ??
300 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
301 undefined
302 ? {}
303 : {
304 tokenUsage:
305 event.payload.tokenUsage ??
306 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
307 }),
308 }),
309 };
310 case "runtime-request.updated":
311 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
312 case "message.updated":
313 return { ...base, messages: upsertEntity(base.messages, event.payload) };
314 case "plan.updated":
315 return { ...base, plans: upsertEntity(base.plans, event.payload) };
316 case "turn-item.updated": {
317 // Streamed updates land on the newest items, so search from the end.
318 let itemIndex = projection.turnItems.length - 1;
319 while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== event.payload.id) {
320 itemIndex -= 1;
321 }
322 if (
323 partialTimeline &&
324 itemIndex === -1 &&
325 shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
326 ) {
327 return projection;
328 }
329 const turnItems = [...projection.turnItems];
330 if (itemIndex === -1) turnItems.push(event.payload);
331 else turnItems[itemIndex] = event.payload;
332 const next = { ...base, turnItems };
333 // Only interrupt requests can change another item's visibility. Streaming
334 // text/tool updates must not recheck every row against every run.
335 const previous = itemIndex === -1 ? undefined : projection.turnItems[itemIndex];
336 const visible =
337 event.payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
338 ? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }
339 : next;
340 return {
341 ...next,
342 visibleTurnItems: shouldShowLocalTurnItem(next, event.payload)
343 ? upsertVisibleTurnItem(visible, event.payload, partialTimeline, latestLocalTurnOrdinal)
344 : removeVisibleItem(visible.visibleTurnItems, event.payload.id),
345 };
346 }
347 case "checkpoint-scope.created":
348 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
349 case "checkpoint.captured":
350 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
351 case "checkpoint.rollback-requested":
352 return base;
353 case "context-handoff.updated":
354 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
355 case "context-transfer.created":
356 case "context-transfer.updated":
357 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
358 }
359}