Open History to see the last commit
1import { pipe } from "effect/Function";
2import * as Arr from "effect/Array";
3import * as O from "effect/Order";
4import type {
5 MessageId,
6 OrchestrationCheckpointSummary,
7 OrchestrationEvent,
8 OrchestrationLatestTurn,
9 OrchestrationMessage,
10 OrchestrationSession,
11 OrchestrationThread,
12 OrchestrationThreadActivity,
13 TurnId,
14} from "@t3tools/contracts";
15import { isImportedAgentSessionMessageId } from "@t3tools/contracts";
16import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
17
18export type ThreadDetailReducerResult =
19 | { readonly kind: "updated"; readonly thread: OrchestrationThread }
20 | { readonly kind: "deleted" }
21 | { readonly kind: "unchanged" };
22
23const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
24 O.mapInput(O.String, (p) => p.createdAt),
25 O.mapInput(O.String, (p) => p.id),
26);
27
28const checkpointOrder = O.mapInput(
29 O.Number,
30 (cp: OrchestrationThread["checkpoints"][number]) =>
31 cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
32);
33
34const activityOrder = O.combineAll<OrchestrationThreadActivity>([
35 O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
36 O.mapInput(O.String, (a) => a.createdAt),
37 O.mapInput(O.String, (a) => a.id),
38]);
39
40// Per-array id index so the streaming append path can reject a re-delivered
41// id without rescanning the history. Only arrays this reducer produced are
42// indexed: presence also proves the array is activityOrder-sorted, which
43// snapshot-loaded arrays (DB order, null sequences first) are not.
44const activityIdIndex = new WeakMap<
45 ReadonlyArray<OrchestrationThreadActivity>,
46 Set<OrchestrationThreadActivity["id"]>
47>();
48
49/**
50 * Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the
51 * server's snapshot-side `dropStaleContextWindowActivities`): rows without a
52 * finite, non-negative `usedTokens` are skipped during the consumer's backward
53 * walk, so they must not replace an earlier resolvable row here.
54 */
55function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
56 if (activity.kind !== "context-window.updated") {
57 return false;
58 }
59 const payload =
60 activity.payload && typeof activity.payload === "object"
61 ? (activity.payload as Record<string, unknown>)
62 : null;
63 const usedTokens = payload?.usedTokens;
64 return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
65}
66
67/**
68 * Apply a single orchestration event to an `OrchestrationThread`, returning
69 * the updated thread, a deletion signal, or an "unchanged" marker when the
70 * event doesn't affect this thread.
71 *
72 * This is a pure reducer operating on contract types. UI-specific mapping
73 * (e.g. resolving attachment preview URLs, normalising model slugs, adding
74 * scoped fields like `environmentId`) is the caller's responsibility.
75 */
76export function applyThreadDetailEvent(
77 thread: OrchestrationThread,
78 event: OrchestrationEvent,
79): ThreadDetailReducerResult {
80 switch (event.type) {
81 // ── Project events (irrelevant to thread detail) ────────────────
82 case "project.created":
83 case "project.meta-updated":
84 case "project.deleted":
85 return { kind: "unchanged" };
86
87 // ── Thread lifecycle ────────────────────────────────────────────
88 case "thread.created":
89 return {
90 kind: "updated",
91 thread: {
92 id: event.payload.threadId,
93 projectId: event.payload.projectId,
94 title: event.payload.title,
95 modelSelection: event.payload.modelSelection,
96 runtimeMode: event.payload.runtimeMode,
97 interactionMode: event.payload.interactionMode,
98 branch: event.payload.branch,
99 worktreePath: event.payload.worktreePath,
100 branchPullRequest: null,
101 latestTurn: null,
102 createdAt: event.payload.createdAt,
103 updatedAt: event.payload.updatedAt,
104 archivedAt: null,
105 settledOverride: null,
106 settledAt: null,
107 unsettledAt: null,
108 snoozedUntil: null,
109 snoozedAt: null,
110 deletedAt: null,
111 messages: [],
112 proposedPlans: [],
113 activities: [],
114 checkpoints: [],
115 session: null,
116 },
117 };
118
119 case "thread.deleted":
120 return { kind: "deleted" };
121
122 case "thread.archived":
123 return {
124 kind: "updated",
125 thread: {
126 ...thread,
127 archivedAt: event.payload.archivedAt,
128 titleRegeneration: null,
129 updatedAt: event.payload.updatedAt,
130 },
131 };
132
133 case "thread.unarchived":
134 return {
135 kind: "updated",
136 thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
137 };
138
139 case "thread.settled":
140 return {
141 kind: "updated",
142 thread: {
143 ...thread,
144 settledOverride: "settled",
145 settledAt: event.payload.settledAt,
146 unsettledAt: null,
147 updatedAt: event.payload.updatedAt,
148 },
149 };
150
151 case "thread.unsettled":
152 return {
153 kind: "updated",
154 thread: {
155 ...thread,
156 settledOverride: event.payload.reason === "user" ? "active" : null,
157 settledAt: null,
158 // A thread already pinned active keeps its re-entry stamp: the
159 // activity reset that clears the pin must not reorder the list.
160 unsettledAt:
161 thread.settledOverride === "active"
162 ? (thread.unsettledAt ?? null)
163 : event.payload.updatedAt,
164 updatedAt: event.payload.updatedAt,
165 },
166 };
167
168 case "thread.snoozed":
169 return {
170 kind: "updated",
171 thread: {
172 ...thread,
173 snoozedUntil: event.payload.snoozedUntil,
174 snoozedAt: event.payload.snoozedAt,
175 updatedAt: event.payload.updatedAt,
176 },
177 };
178
179 case "thread.unsnoozed":
180 return {
181 kind: "updated",
182 thread: {
183 ...thread,
184 snoozedUntil: null,
185 snoozedAt: null,
186 updatedAt: event.payload.updatedAt,
187 },
188 };
189
190 case "thread.pinned":
191 return {
192 kind: "updated",
193 thread: {
194 ...thread,
195 pinnedAt: event.payload.pinnedAt,
196 ...(event.payload.pinOrderKey !== undefined
197 ? { pinOrderKey: event.payload.pinOrderKey }
198 : {}),
199 updatedAt: event.payload.updatedAt,
200 },
201 };
202
203 case "thread.unpinned":
204 return {
205 kind: "updated",
206 thread: {
207 ...thread,
208 pinnedAt: null,
209 pinOrderKey: null,
210 updatedAt: event.payload.updatedAt,
211 },
212 };
213
214 case "thread.pin-reordered":
215 return {
216 kind: "updated",
217 thread: {
218 ...thread,
219 pinOrderKey: event.payload.orderKey,
220 updatedAt: event.payload.updatedAt,
221 },
222 };
223
224 // ── Thread metadata ─────────────────────────────────────────────
225 case "thread.meta-updated":
226 return {
227 kind: "updated",
228 thread: {
229 ...thread,
230 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
231 ...(event.payload.titleRegeneration !== undefined
232 ? { titleRegeneration: event.payload.titleRegeneration }
233 : {}),
234 ...(event.payload.modelSelection !== undefined
235 ? { modelSelection: event.payload.modelSelection }
236 : {}),
237 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
238 ...(event.payload.worktreePath !== undefined
239 ? { worktreePath: event.payload.worktreePath }
240 : {}),
241 ...(event.payload.linkedPullRequest !== undefined
242 ? { linkedPullRequest: event.payload.linkedPullRequest }
243 : {}),
244 ...(event.payload.branchPullRequest !== undefined
245 ? { branchPullRequest: event.payload.branchPullRequest }
246 : {}),
247 updatedAt: event.payload.updatedAt,
248 },
249 };
250
251 case "thread.runtime-mode-set":
252 return {
253 kind: "updated",
254 thread: {
255 ...thread,
256 runtimeMode: event.payload.runtimeMode,
257 updatedAt: event.payload.updatedAt,
258 },
259 };
260
261 case "thread.interaction-mode-set":
262 return {
263 kind: "updated",
264 thread: {
265 ...thread,
266 interactionMode: event.payload.interactionMode,
267 updatedAt: event.payload.updatedAt,
268 },
269 };
270
271 // ── Turn lifecycle ──────────────────────────────────────────────
272 case "thread.turn-start-requested":
273 return {
274 kind: "updated",
275 thread: {
276 ...thread,
277 ...(event.payload.modelSelection !== undefined
278 ? { modelSelection: event.payload.modelSelection }
279 : {}),
280 runtimeMode: event.payload.runtimeMode,
281 interactionMode: event.payload.interactionMode,
282 updatedAt: event.occurredAt,
283 },
284 };
285
286 case "thread.turn-interrupt-requested": {
287 if (event.payload.turnId === undefined) {
288 return { kind: "unchanged" };
289 }
290 const latestTurn = thread.latestTurn;
291 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
292 return { kind: "unchanged" };
293 }
294 return {
295 kind: "updated",
296 thread: {
297 ...thread,
298 latestTurn: {
299 ...latestTurn,
300 state: "interrupted",
301 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
302 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
303 },
304 updatedAt: event.occurredAt,
305 },
306 };
307 }
308
309 // ── Messages ────────────────────────────────────────────────────
310 case "thread.message-sent": {
311 const message: OrchestrationMessage = {
312 id: event.payload.messageId,
313 role: event.payload.role,
314 text: event.payload.text,
315 ...(event.payload.attachments !== undefined
316 ? { attachments: event.payload.attachments }
317 : {}),
318 turnId: event.payload.turnId,
319 streaming: event.payload.streaming,
320 createdAt: event.payload.createdAt,
321 updatedAt: event.payload.updatedAt,
322 };
323
324 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
325 const messages = existingMessage
326 ? Arr.map(thread.messages, (entry) =>
327 entry.id !== message.id
328 ? entry
329 : {
330 ...entry,
331 text: message.streaming
332 ? `${entry.text}${message.text}`
333 : message.text.length > 0
334 ? message.text
335 : entry.text,
336 streaming: message.streaming,
337 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
338 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
339 ...(message.attachments !== undefined
340 ? { attachments: message.attachments }
341 : {}),
342 },
343 )
344 : Arr.append(thread.messages, message);
345 // Update latestTurn for assistant messages bound to a turn. A completed
346 // assistant message only settles the turn once the session is no longer
347 // running it — providers may emit several assistant messages per turn
348 // (commentary between tool calls), and the turn must stay unsettled
349 // until the provider reports turn end. Streaming deltas recompute the
350 // same record, so the previous reference is kept when nothing changed.
351 const turnStillRunning =
352 event.payload.turnId !== null &&
353 thread.session?.status === "running" &&
354 thread.session.activeTurnId === event.payload.turnId;
355 const settlesTurn = !event.payload.streaming && !turnStillRunning;
356 const latestTurn = reuseLatestTurn(
357 thread.latestTurn,
358 event.payload.role === "assistant" &&
359 event.payload.turnId !== null &&
360 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
361 ? {
362 turnId: event.payload.turnId,
363 state: settlesTurn
364 ? thread.latestTurn?.state === "interrupted"
365 ? "interrupted"
366 : thread.latestTurn?.state === "error"
367 ? "error"
368 : "completed"
369 : "running",
370 requestedAt:
371 thread.latestTurn?.turnId === event.payload.turnId
372 ? thread.latestTurn.requestedAt
373 : event.payload.createdAt,
374 startedAt:
375 thread.latestTurn?.turnId === event.payload.turnId
376 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
377 : event.payload.createdAt,
378 completedAt: settlesTurn
379 ? event.payload.updatedAt
380 : thread.latestTurn?.turnId === event.payload.turnId
381 ? (thread.latestTurn.completedAt ?? null)
382 : null,
383 assistantMessageId: event.payload.messageId,
384 }
385 : thread.latestTurn,
386 );
387
388 // Rebind checkpoint assistant message IDs for assistant messages. The
389 // helper hands back the same array when the entry is already bound.
390 const checkpoints =
391 event.payload.role === "assistant" && event.payload.turnId !== null
392 ? rebindCheckpointAssistantMessage(
393 thread.checkpoints,
394 event.payload.turnId,
395 event.payload.messageId,
396 )
397 : thread.checkpoints;
398
399 return {
400 kind: "updated",
401 thread: {
402 ...thread,
403 messages,
404 checkpoints,
405 latestTurn,
406 updatedAt: event.occurredAt,
407 },
408 };
409 }
410
411 // ── Session ─────────────────────────────────────────────────────
412 case "thread.session-set": {
413 // Leaving the "running" session status is the turn-end signal: settle a
414 // still-running latest turn so its duration reflects the whole turn.
415 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
416 const latestTurn = reuseLatestTurn(
417 thread.latestTurn,
418 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
419 ? {
420 turnId: event.payload.session.activeTurnId,
421 state: "running",
422 requestedAt:
423 thread.latestTurn?.turnId === event.payload.session.activeTurnId
424 ? thread.latestTurn.requestedAt
425 : event.payload.session.updatedAt,
426 startedAt:
427 thread.latestTurn?.turnId === event.payload.session.activeTurnId
428 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
429 : event.payload.session.updatedAt,
430 completedAt: null,
431 assistantMessageId:
432 thread.latestTurn?.turnId === event.payload.session.activeTurnId
433 ? thread.latestTurn.assistantMessageId
434 : null,
435 }
436 : thread.latestTurn !== null &&
437 thread.latestTurn.state === "running" &&
438 settledTurnState !== null
439 ? {
440 ...thread.latestTurn,
441 state: settledTurnState,
442 // A running turn's completedAt can only hold a mid-turn
443 // placeholder checkpoint timestamp — the session leaving
444 // "running" is the authoritative turn end.
445 completedAt: event.payload.session.updatedAt,
446 }
447 : thread.latestTurn,
448 );
449
450 return {
451 kind: "updated",
452 thread: {
453 ...thread,
454 session: event.payload.session,
455 latestTurn,
456 updatedAt: event.occurredAt,
457 },
458 };
459 }
460
461 case "thread.session-stop-requested":
462 return thread.session === null
463 ? { kind: "unchanged" }
464 : {
465 kind: "updated",
466 thread: {
467 ...thread,
468 session: {
469 ...thread.session,
470 status: "stopped",
471 activeTurnId: null,
472 updatedAt: event.payload.createdAt,
473 },
474 updatedAt: event.occurredAt,
475 },
476 };
477
478 // ── Proposed plans ──────────────────────────────────────────────
479 case "thread.proposed-plan-upserted": {
480 const proposedPlan = event.payload.proposedPlan;
481
482 const proposedPlans = pipe(
483 thread.proposedPlans,
484 Arr.filter((entry) => entry.id !== proposedPlan.id),
485 Arr.append(proposedPlan),
486 Arr.sort(proposedPlanOrder),
487 );
488
489 return {
490 kind: "updated",
491 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
492 };
493 }
494
495 // ── Checkpoints / turn diffs ────────────────────────────────────
496 case "thread.turn-diff-completed": {
497 const checkpoint: OrchestrationCheckpointSummary = {
498 turnId: event.payload.turnId,
499 checkpointTurnCount: event.payload.checkpointTurnCount,
500 checkpointRef: event.payload.checkpointRef,
501 status: event.payload.status,
502 files: event.payload.files,
503 assistantMessageId: event.payload.assistantMessageId,
504 completedAt: event.payload.completedAt,
505 };
506
507 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
508 // Don't overwrite a non-missing checkpoint with a missing one.
509 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
510 return { kind: "unchanged" };
511 }
512
513 const checkpoints = pipe(
514 thread.checkpoints,
515 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
516 Arr.append(checkpoint),
517 Arr.sort(checkpointOrder),
518 );
519
520 // Mid-turn diff updates produce placeholder checkpoints; record the
521 // checkpoint, but don't settle a turn its session is still running.
522 const diffTurnStillRunning =
523 thread.session?.status === "running" &&
524 thread.session.activeTurnId === event.payload.turnId;
525 const latestTurn =
526 !diffTurnStillRunning &&
527 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
528 ? {
529 turnId: event.payload.turnId,
530 state:
531 thread.latestTurn?.state === "interrupted"
532 ? "interrupted"
533 : checkpointStatusToTurnState(event.payload.status),
534 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
535 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
536 completedAt: event.payload.completedAt,
537 assistantMessageId: event.payload.assistantMessageId,
538 }
539 : thread.latestTurn;
540
541 return {
542 kind: "updated",
543 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
544 };
545 }
546
547 // ── Revert ──────────────────────────────────────────────────────
548 case "thread.reverted": {
549 const checkpoints = pipe(
550 thread.checkpoints,
551 Arr.filter(
552 (entry) =>
553 entry.checkpointTurnCount !== undefined &&
554 entry.checkpointTurnCount <= event.payload.turnCount,
555 ),
556 Arr.sort(checkpointOrder),
557 );
558
559 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
560 const messages = retainMessagesAfterRevert(
561 thread.messages,
562 retainedTurnIds,
563 event.payload.turnCount,
564 );
565 const proposedPlans = pipe(
566 thread.proposedPlans,
567 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
568 );
569 const activities = pipe(
570 thread.activities,
571 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
572 );
573 const latestCheckpoint = checkpoints.at(-1) ?? null;
574
575 return {
576 kind: "updated",
577 thread: {
578 ...thread,
579 checkpoints,
580 messages,
581 proposedPlans,
582 activities,
583 latestTurn:
584 latestCheckpoint === null
585 ? null
586 : {
587 turnId: latestCheckpoint.turnId,
588 state: checkpointStatusToTurnState(
589 latestCheckpoint.status as "ready" | "missing" | "error",
590 ),
591 requestedAt: latestCheckpoint.completedAt,
592 startedAt: latestCheckpoint.completedAt,
593 completedAt: latestCheckpoint.completedAt,
594 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
595 },
596 updatedAt: event.occurredAt,
597 },
598 };
599 }
600
601 // ── Activities ──────────────────────────────────────────────────
602 case "thread.activity-appended": {
603 const activity = event.payload.activity;
604 // A resolvable context-window update supersedes earlier resolvable ones
605 // for the same turn: consumers only read the latest value (walking the
606 // array backwards), and providers stream these updates continuously, so
607 // retaining the history grows the thread by thousands of rows over a
608 // long session. Mirrors the server-side snapshot rule in
609 // dropStaleContextWindowActivities; retention stays per turn so a
610 // thread.reverted that discards turns can still resolve a value from
611 // the turns that survive.
612 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
613 // Live streams append in order: an unseen id sorting at/after the tail
614 // of a known-sorted array appends without re-filtering and re-sorting
615 // the whole history on every event. The id set moves forward to the new
616 // array; a superseded array falls back to the sorting path.
617 const ids = activityIdIndex.get(thread.activities);
618 const lastActivity = thread.activities.at(-1);
619 if (
620 !supersedesContextWindow &&
621 ids !== undefined &&
622 (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
623 !ids.has(activity.id)
624 ) {
625 const activities = Arr.append(thread.activities, activity);
626 activityIdIndex.delete(thread.activities);
627 ids.add(activity.id);
628 activityIdIndex.set(activities, ids);
629 return {
630 kind: "updated",
631 thread: {
632 ...thread,
633 activities,
634 updatedAt: event.occurredAt,
635 },
636 };
637 }
638 const activities = pipe(
639 thread.activities,
640 Arr.filter(
641 (entry) =>
642 entry.id !== activity.id &&
643 !(
644 supersedesContextWindow &&
645 entry.turnId === activity.turnId &&
646 isResolvableContextWindowActivity(entry)
647 ),
648 ),
649 Arr.append(activity),
650 Arr.sort(activityOrder),
651 );
652 activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));
653
654 return {
655 kind: "updated",
656 thread: { ...thread, activities, updatedAt: event.occurredAt },
657 };
658 }
659
660 // ── Events that don't mutate thread state directly ──────────────
661 case "thread.approval-response-requested":
662 case "thread.user-input-response-requested":
663 case "thread.checkpoint-revert-requested":
664 return { kind: "unchanged" };
665 }
666
667 // Forward-compatible: ignore unrecognized event types.
668 return { kind: "unchanged" };
669}
670
671// ── Helpers ──────────────────────────────────────────────────────────
672
673/**
674 * Turn state to settle a still-running latest turn with when its session
675 * leaves the "running" status, or null while the session is (re)starting or
676 * running and the turn must stay unsettled.
677 */
678function settledTurnStateForSessionStatus(
679 status: OrchestrationSession["status"],
680): "completed" | "interrupted" | "error" | null {
681 switch (status) {
682 case "idle":
683 case "ready":
684 return "completed";
685 case "error":
686 return "error";
687 case "interrupted":
688 case "stopped":
689 return "interrupted";
690 case "starting":
691 case "running":
692 return null;
693 }
694}
695
696function checkpointStatusToTurnState(
697 status: "ready" | "missing" | "error",
698): OrchestrationLatestTurn["state"] {
699 switch (status) {
700 case "ready":
701 return "completed";
702 case "error":
703 return "error";
704 case "missing":
705 return "completed";
706 }
707}
708
709/**
710 * Returns `previous` when `next` matches it field for field, otherwise `next`.
711 * Streaming cases recompute the latest turn on every delta, and keeping the
712 * old reference lets selectors and memos keyed on `latestTurn` skip work.
713 */
714function reuseLatestTurn(
715 previous: OrchestrationLatestTurn | null,
716 next: OrchestrationLatestTurn | null,
717): OrchestrationLatestTurn | null {
718 if (previous === null || next === null) {
719 return next;
720 }
721 return previous.turnId === next.turnId &&
722 previous.state === next.state &&
723 previous.requestedAt === next.requestedAt &&
724 previous.startedAt === next.startedAt &&
725 previous.completedAt === next.completedAt &&
726 previous.assistantMessageId === next.assistantMessageId &&
727 previous.sourceProposedPlan?.threadId === next.sourceProposedPlan?.threadId &&
728 previous.sourceProposedPlan?.planId === next.sourceProposedPlan?.planId
729 ? previous
730 : next;
731}
732
733/**
734 * Points the checkpoint for `turnId` at `messageId`. Returns the input array
735 * untouched when no checkpoint needs rebinding, so streaming deltas for an
736 * already-bound message do not allocate a new `checkpoints` reference.
737 */
738function rebindCheckpointAssistantMessage(
739 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
740 turnId: TurnId,
741 messageId: MessageId,
742): ReadonlyArray<OrchestrationCheckpointSummary> {
743 const needsRebind = checkpoints.some(
744 (entry) => entry.turnId === turnId && entry.assistantMessageId !== messageId,
745 );
746 if (!needsRebind) {
747 return checkpoints;
748 }
749 return Arr.map(checkpoints, (entry) =>
750 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
751 );
752}
753
754function retainMessagesAfterRevert(
755 messages: ReadonlyArray<OrchestrationMessage>,
756 retainedTurnIds: ReadonlySet<string>,
757 turnCount: number,
758): OrchestrationMessage[] {
759 const retainedMessageIds = new Set<string>();
760 for (const message of messages) {
761 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
762 retainedMessageIds.add(message.id);
763 } else if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
764 retainedMessageIds.add(message.id);
765 }
766 }
767
768 for (const role of ["user", "assistant"] as const) {
769 const retainedCount = messages.filter(
770 (message) =>
771 message.role === role &&
772 !isImportedAgentSessionMessageId(message.id) &&
773 retainedMessageIds.has(message.id),
774 ).length;
775 const missingCount = Math.max(0, turnCount - retainedCount);
776 const fallbackMessages = messages
777 .filter(
778 (message) =>
779 message.role === role &&
780 !retainedMessageIds.has(message.id) &&
781 (message.turnId === null || retainedTurnIds.has(message.turnId)),
782 )
783 .toSorted(
784 (left, right) =>
785 compareDateTimeStrings(left.createdAt, right.createdAt) ||
786 left.id.localeCompare(right.id),
787 )
788 .slice(0, missingCount);
789 for (const message of fallbackMessages) {
790 retainedMessageIds.add(message.id);
791 }
792 }
793
794 return Arr.filter(messages, (message) => retainedMessageIds.has(message.id));
795}