Open History to see the last commit
1import type {
2 OrchestrationV2DomainEvent,
3 OrchestrationV2ThreadProjection,
4 OrchestrationV2TurnItem,
5} from "@t3tools/contracts";
6import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline";
7
8export type ApplyOrchestrationV2ProjectionEventOptions = {
9 readonly partialTimeline?: boolean;
10 readonly latestLocalTurnOrdinal?: number | null;
11};
12
13function upsertEntity<T extends { readonly id: unknown }>(
14 items: ReadonlyArray<T>,
15 item: T,
16): ReadonlyArray<T> {
17 const index = items.findIndex((candidate) => candidate.id === item.id);
18 if (index === -1) return [...items, item];
19 const next = [...items];
20 next[index] = item;
21 return next;
22}
23
24function removeVisibleItem(
25 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
26 sourceItemId: OrchestrationV2TurnItem["id"],
27): OrchestrationV2ThreadProjection["visibleTurnItems"] {
28 const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
29 if (index === -1) return rows;
30 return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
31}
32
33function renumberVisibleItems(
34 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
35): OrchestrationV2ThreadProjection["visibleTurnItems"] {
36 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
37}
38
39function shouldShowLocalTurnItem(
40 projection: OrchestrationV2ThreadProjection,
41 item: OrchestrationV2TurnItem,
42): boolean {
43 return isOrchestrationV2TurnItemVisible({
44 item,
45 runs: projection.runs,
46 attempts: projection.attempts,
47 items: projection.turnItems,
48 });
49}
50
51function activeVisibleTurnItems(
52 projection: OrchestrationV2ThreadProjection,
53): OrchestrationV2ThreadProjection["visibleTurnItems"] {
54 const rows = projection.visibleTurnItems;
55 let next: Array<(typeof rows)[number]> | null = null;
56 for (let index = 0; index < rows.length; index += 1) {
57 const row = rows[index]!;
58 const keep = row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item);
59 if (!keep) {
60 next ??= rows.slice(0, index);
61 continue;
62 }
63 next?.push(row);
64 }
65 return next === null ? rows : renumberVisibleItems(next);
66}
67
68function oldestLocalTurnOrdinal(
69 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
70): number | null {
71 let oldest: number | null = null;
72 for (const row of rows) {
73 if (row.visibility !== "local") continue;
74 if (oldest === null || row.item.ordinal < oldest) {
75 oldest = row.item.ordinal;
76 }
77 }
78 return oldest;
79}
80
81function shouldDropMissingPartialTurnItem(
82 projection: OrchestrationV2ThreadProjection,
83 item: OrchestrationV2TurnItem,
84 latestLocalTurnOrdinal: number | null | undefined,
85): boolean {
86 if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) {
87 return false;
88 }
89 if (
90 latestLocalTurnOrdinal !== null &&
91 latestLocalTurnOrdinal !== undefined &&
92 item.ordinal <= latestLocalTurnOrdinal
93 ) {
94 return true;
95 }
96 const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems);
97 return oldest !== null && item.ordinal < oldest;
98}
99
100function upsertVisibleTurnItem(
101 projection: OrchestrationV2ThreadProjection,
102 item: OrchestrationV2TurnItem,
103 partialTimeline: boolean,
104 latestLocalTurnOrdinal: number | null | undefined,
105): OrchestrationV2ThreadProjection["visibleTurnItems"] {
106 const rows = projection.visibleTurnItems;
107 const index = rows.findIndex((row) => row.sourceItemId === item.id);
108 const next = {
109 position: 0,
110 visibility: "local" as const,
111 sourceThreadId: item.threadId,
112 sourceItemId: item.id,
113 item,
114 };
115 const previous = index === -1 ? undefined : rows[index]!;
116 if (
117 previous !== undefined &&
118 previous.visibility === next.visibility &&
119 previous.sourceThreadId === next.sourceThreadId &&
120 previous.sourceItemId === next.sourceItemId &&
121 previous.item === item
122 ) {
123 return rows;
124 }
125 if (
126 index === -1 &&
127 partialTimeline &&
128 shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal)
129 ) {
130 return rows;
131 }
132 const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
133 const insertionIndex = updated.findIndex(
134 (row) =>
135 row.visibility === "local" &&
136 (row.item.ordinal > item.ordinal ||
137 (row.item.ordinal === item.ordinal &&
138 String(row.item.id).localeCompare(String(item.id)) > 0)),
139 );
140 updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
141 return renumberVisibleItems(updated);
142}
143
144/** Applies one committed event to a matching thread projection. */
145export function applyOrchestrationV2ProjectionEvent(
146 projection: OrchestrationV2ThreadProjection | null,
147 event: OrchestrationV2DomainEvent,
148 options?: ApplyOrchestrationV2ProjectionEventOptions,
149): OrchestrationV2ThreadProjection | null {
150 if (projection === null || event.threadId !== projection.thread.id) return projection;
151
152 const partialTimeline = options?.partialTimeline === true;
153 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
154 const base = { ...projection, updatedAt: event.occurredAt };
155 switch (event.type) {
156 case "thread.created":
157 case "thread.archived":
158 case "thread.unarchived":
159 case "thread.deleted":
160 case "thread.settled":
161 case "thread.unsettled":
162 case "thread.snoozed":
163 case "thread.unsnoozed":
164 case "thread.pinned":
165 case "thread.unpinned":
166 case "thread.pin-reordered":
167 case "thread.active-reordered":
168 case "thread.metadata-updated":
169 case "thread.pull-request-synced":
170 case "thread.runtime-mode-updated":
171 case "thread.interaction-mode-updated":
172 case "thread.model-selection-updated":
173 case "thread.provider-switched":
174 return { ...base, thread: event.payload };
175 // Visited tracking is read state, not activity: skip the updatedAt bump.
176 case "thread.visited":
177 case "thread.marked-unread":
178 return { ...projection, thread: event.payload };
179 case "run.created":
180 case "run.updated": {
181 const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
182 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
183 }
184 case "run-attempt.created":
185 case "run-attempt.updated": {
186 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
187 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
188 }
189 case "node.updated":
190 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
191 case "subagent.updated":
192 return { ...base, subagents: upsertEntity(base.subagents, event.payload) };
193 case "provider-session.attached":
194 case "provider-session.updated":
195 return {
196 ...base,
197 providerSessions: upsertEntity(base.providerSessions, event.payload),
198 };
199 case "provider-session.detached":
200 return {
201 ...base,
202 providerSessions: base.providerSessions.filter(
203 (session) => session.id !== event.payload.providerSessionId,
204 ),
205 };
206 case "provider-thread.updated":
207 return { ...base, providerThreads: upsertEntity(base.providerThreads, event.payload) };
208 case "provider-turn.updated":
209 return {
210 ...base,
211 providerTurns: upsertEntity(base.providerTurns, {
212 ...event.payload,
213 ...((event.payload.tokenUsage ??
214 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
215 undefined
216 ? {}
217 : {
218 tokenUsage:
219 event.payload.tokenUsage ??
220 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
221 }),
222 }),
223 };
224 case "runtime-request.updated":
225 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
226 case "message.updated":
227 return { ...base, messages: upsertEntity(base.messages, event.payload) };
228 case "plan.updated":
229 return { ...base, plans: upsertEntity(base.plans, event.payload) };
230 case "turn-item.updated": {
231 if (
232 partialTimeline &&
233 !projection.turnItems.some((candidate) => candidate.id === event.payload.id) &&
234 shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
235 ) {
236 return projection;
237 }
238 const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) };
239 const visible = { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
240 return {
241 ...next,
242 visibleTurnItems: shouldShowLocalTurnItem(next, event.payload)
243 ? upsertVisibleTurnItem(visible, event.payload, partialTimeline, latestLocalTurnOrdinal)
244 : removeVisibleItem(visible.visibleTurnItems, event.payload.id),
245 };
246 }
247 case "checkpoint-scope.created":
248 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
249 case "checkpoint.captured":
250 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
251 case "checkpoint.rollback-requested":
252 return base;
253 case "context-handoff.updated":
254 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
255 case "context-transfer.created":
256 case "context-transfer.updated":
257 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
258 }
259}