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