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

threadReducer.ts

791 lines28.1 KB

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