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

orchestrationV2Projection.ts

467 lines16.3 KB

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