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