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

threadReducer.ts

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