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

orchestrationV2Projection.ts

501 lines17.7 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 (
274 (runId !== undefined && item.runId !== runId) ||
275 item.type !== "user_message" ||
276 item.inputIntent !== "queued_turn"
277 )
278 continue;
279 if (!shouldShowLocalTurnItem(projection, item)) continue;
280 visibleTurnItems = upsertVisibleTurnItem(
281 { ...projection, visibleTurnItems },
282 item,
283 false,
284 null,
285 );
286 }
287 return visibleTurnItems;
289​
290// Older caches can retain delivered queued input hidden by the former visibility rule.
291// Request cards retained outside the window must not be pulled into the timeline.
292export function restoreCachedProjectionVisibility(
293 projection: OrchestrationV2ThreadProjection,
294): OrchestrationV2ThreadProjection {
295 const visibleTurnItems = restoreQueuedUserItems({
296 ...projection,
297 visibleTurnItems: activeVisibleTurnItems(projection),
298 });
299 return visibleTurnItems === projection.visibleTurnItems
300 ? projection
301 : { ...projection, visibleTurnItems };
303​
304export function applyOrchestrationV2ProjectionEvent(
305 projection: OrchestrationV2ThreadProjection | null,
306 event: OrchestrationV2DomainEvent,
307 options?: ApplyOrchestrationV2ProjectionEventOptions,
308): OrchestrationV2ThreadProjection | null {
309 if (projection === null || event.threadId !== projection.thread.id) return projection;
310​
311 const partialTimeline = options?.partialTimeline === true;
312 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
313 const base = { ...projection, updatedAt: event.occurredAt };
314 switch (event.type) {
315 case "thread.pull-request-link-updated":
316 return {
317 ...projection,
318 thread: applyThreadPullRequestLinkUpdate(projection.thread, event.payload),
319 };
320 case "thread.created":
321 case "thread.archived":
322 case "thread.unarchived":
323 case "thread.deleted":
324 case "thread.settled":
325 case "thread.unsettled":
326 case "thread.snoozed":
327 case "thread.unsnoozed":
328 case "thread.auto-settle-set":
329 case "thread.pinned":
330 case "thread.unpinned":
331 case "thread.pin-reordered":
332 case "thread.metadata-updated":
333 case "thread.runtime-mode-updated":
334 case "thread.interaction-mode-updated":
335 case "thread.model-selection-updated":
336 case "thread.provider-switched":
337 case "thread.guest-share-updated":
338 return { ...base, thread: event.payload };
339 // Reordering and PR refreshes keep the orchestrator's activity time, as the server does.
340 case "thread.active-reordered":
341 case "thread.pull-request-synced":
342 case "thread.issue-synced":
343 return { ...base, thread: event.payload, updatedAt: event.payload.updatedAt };
344 // Visited tracking, tags and tool overrides are not activity: skip the updatedAt bump.
345 case "thread.visited":
346 case "thread.tags-updated":
347 case "thread.tool-overrides-updated":
348 case "thread.marked-unread":
349 return { ...projection, thread: event.payload };
350 case "thread.visit-recorded":
351 return {
352 ...projection,
353 thread: applyOrchestrationV2ThreadVisit(projection.thread, event.payload),
354 };
355 case "run.created":
356 case "run.updated": {
357 // Lifecycle updates carry the run as it was when the turn started. What the run returned
358 // is written by its own event, and an update without it must not take it away.
359 const known = base.runs.find((run) => run.id === event.payload.id);
360 const run =
361 event.payload.output === undefined && known?.output !== undefined
362 ? { ...event.payload, output: known.output }
363 : event.payload;
364 const next = { ...base, runs: upsertEntity(base.runs, run) };
365 const visible = { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
366 const wasQueued = known?.status === "queued";
367 return wasQueued && event.payload.status !== "queued"
368 ? { ...visible, visibleTurnItems: restoreQueuedUserItems(visible, event.payload.id) }
369 : visible;
370 }
371 case "run.background-work-cancelled":
372 return {
373 ...base,
374 runs: base.runs.map((run) =>
375 run.id === event.payload.runId
376 ? {
377 ...run,
378 restartCancelledBackgroundWork: event.payload.restartCancelledBackgroundWork,
379 }
380 : run,
381 ),
382 };
383 case "run.output-submitted":
384 return {
385 ...base,
386 runs: base.runs.map((run) =>
387 run.id === event.payload.runId ? { ...run, output: event.payload.output } : run,
388 ),
389 };
390 case "run-attempt.created":
391 case "run-attempt.updated": {
392 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
393 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
394 }
395 case "node.updated":
396 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
397 case "subagent.updated":
398 return {
399 ...base,
400 subagents: upsertEntity(
401 base.subagents,
402 restoreSubagentBodies(
403 event.payload,
404 base.subagents.find((subagent) => subagent.id === event.payload.id),
405 ),
406 ),
407 };
408 case "provider-session.attached":
409 case "provider-session.updated":
410 return {
411 ...base,
412 providerSessions: upsertEntity(base.providerSessions, event.payload),
413 };
414 case "provider-session.detached":
415 return {
416 ...base,
417 providerSessions: base.providerSessions.filter(
418 (session) => session.id !== event.payload.providerSessionId,
419 ),
420 };
421 case "provider-thread.updated":
422 return {
423 ...base,
424 thread:
425 event.payload.appThreadId === base.thread.id &&
426 !isQueuedProviderThreadPlaceholder(event.payload)
427 ? { ...base.thread, activeProviderThreadId: event.payload.id }
428 : base.thread,
429 providerThreads: upsertEntity(base.providerThreads, event.payload),
430 };
431 case "provider-turn.updated":
432 return {
433 ...base,
434 providerTurns: upsertEntity(base.providerTurns, {
435 ...event.payload,
436 ...((event.payload.tokenUsage ??
437 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
438 undefined
439 ? {}
440 : {
441 tokenUsage:
442 event.payload.tokenUsage ??
443 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
444 }),
445 }),
446 };
447 case "runtime-request.updated":
448 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
449 case "message.updated":
450 return { ...base, messages: upsertEntity(base.messages, event.payload) };
451 case "plan.updated":
452 return { ...base, plans: upsertEntity(base.plans, event.payload) };
453 case "turn-item.updated": {
454 let payload = restoreTurnItemBodies(event.payload, latestBodies(projection));
455 // Streamed updates land on the newest items, so search from the end.
456 let itemIndex = projection.turnItems.length - 1;
457 while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== payload.id) {
458 itemIndex -= 1;
459 }
460 const deferredWork =
461 itemIndex === -1 ? undefined : projection.turnItems[itemIndex]?.deferredWork;
462 if (deferredWork !== undefined) payload = { ...payload, deferredWork };
463 if (
464 partialTimeline &&
465 itemIndex === -1 &&
466 shouldDropMissingPartialTurnItem(projection, payload, latestLocalTurnOrdinal)
467 ) {
468 return projection;
469 }
470 const turnItems =
471 itemIndex === -1
472 ? [...projection.turnItems, payload]
473 : replaceProjectionArrayItem(projection.turnItems, itemIndex, payload);
474 const next = { ...base, turnItems };
475 // Only interrupt requests can change another item's visibility. Streaming
476 // text/tool updates must not recheck every row against every run.
477 const previous = itemIndex === -1 ? undefined : projection.turnItems[itemIndex];
478 const visible =
479 payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
480 ? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }
481 : next;
482 return {
483 ...next,
484 visibleTurnItems: shouldShowLocalTurnItem(next, payload)
485 ? upsertVisibleTurnItem(visible, payload, partialTimeline, latestLocalTurnOrdinal)
486 : removeVisibleItem(visible.visibleTurnItems, payload.id),
487 };
488 }
489 case "checkpoint-scope.created":
490 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
491 case "checkpoint.captured":
492 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
493 case "checkpoint.rollback-requested":
494 return base;
495 case "context-handoff.updated":
496 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
497 case "context-transfer.created":
498 case "context-transfer.updated":
499 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
500 }