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: checkpointStatusToTurnState(event.payload.status),
525 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
526 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
527 completedAt: event.payload.completedAt,
528 assistantMessageId: event.payload.assistantMessageId,
529 }
530 : thread.latestTurn;
531
532 return {
533 kind: "updated",
534 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
535 };
536 }
537
538 // ── Revert ──────────────────────────────────────────────────────
539 case "thread.reverted": {
540 const checkpoints = pipe(
541 thread.checkpoints,
542 Arr.filter(
543 (entry) =>
544 entry.checkpointTurnCount !== undefined &&
545 entry.checkpointTurnCount <= event.payload.turnCount,
546 ),
547 Arr.sort(checkpointOrder),
548 );
549
550 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
551 const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds);
552 const proposedPlans = pipe(
553 thread.proposedPlans,
554 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
555 );
556 const activities = pipe(
557 thread.activities,
558 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
559 );
560 const latestCheckpoint = checkpoints.at(-1) ?? null;
561
562 return {
563 kind: "updated",
564 thread: {
565 ...thread,
566 checkpoints,
567 messages,
568 proposedPlans,
569 activities,
570 latestTurn:
571 latestCheckpoint === null
572 ? null
573 : {
574 turnId: latestCheckpoint.turnId,
575 state: checkpointStatusToTurnState(
576 latestCheckpoint.status as "ready" | "missing" | "error",
577 ),
578 requestedAt: latestCheckpoint.completedAt,
579 startedAt: latestCheckpoint.completedAt,
580 completedAt: latestCheckpoint.completedAt,
581 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
582 },
583 updatedAt: event.occurredAt,
584 },
585 };
586 }
587
588 // ── Activities ──────────────────────────────────────────────────
589 case "thread.activity-appended": {
590 const activity = event.payload.activity;
591 // A resolvable context-window update supersedes earlier resolvable ones
592 // for the same turn: consumers only read the latest value (walking the
593 // array backwards), and providers stream these updates continuously, so
594 // retaining the history grows the thread by thousands of rows over a
595 // long session. Mirrors the server-side snapshot rule in
596 // dropStaleContextWindowActivities; retention stays per turn so a
597 // thread.reverted that discards turns can still resolve a value from
598 // the turns that survive.
599 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
600 // Live streams append in order: an unseen id sorting at/after the tail
601 // of a known-sorted array appends without re-filtering and re-sorting
602 // the whole history on every event. The id set moves forward to the new
603 // array; a superseded array falls back to the sorting path.
604 const ids = activityIdIndex.get(thread.activities);
605 const lastActivity = thread.activities.at(-1);
606 if (
607 !supersedesContextWindow &&
608 ids !== undefined &&
609 (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
610 !ids.has(activity.id)
611 ) {
612 const activities = Arr.append(thread.activities, activity);
613 activityIdIndex.delete(thread.activities);
614 ids.add(activity.id);
615 activityIdIndex.set(activities, ids);
616 return {
617 kind: "updated",
618 thread: {
619 ...thread,
620 activities,
621 updatedAt: event.occurredAt,
622 },
623 };
624 }
625 const activities = pipe(
626 thread.activities,
627 Arr.filter(
628 (entry) =>
629 entry.id !== activity.id &&
630 !(
631 supersedesContextWindow &&
632 entry.turnId === activity.turnId &&
633 isResolvableContextWindowActivity(entry)
634 ),
635 ),
636 Arr.append(activity),
637 Arr.sort(activityOrder),
638 );
639 activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));
640
641 return {
642 kind: "updated",
643 thread: { ...thread, activities, updatedAt: event.occurredAt },
644 };
645 }
646
647 // ── Events that don't mutate thread state directly ──────────────
648 case "thread.approval-response-requested":
649 case "thread.user-input-response-requested":
650 case "thread.checkpoint-revert-requested":
651 return { kind: "unchanged" };
652 }
653
654 // Forward-compatible: ignore unrecognized event types.
655 return { kind: "unchanged" };
656}
657
658// ── Helpers ──────────────────────────────────────────────────────────
659
660/**
661 * Turn state to settle a still-running latest turn with when its session
662 * leaves the "running" status, or null while the session is (re)starting or
663 * running and the turn must stay unsettled.
664 */
665function settledTurnStateForSessionStatus(
666 status: OrchestrationSession["status"],
667): "completed" | "interrupted" | "error" | null {
668 switch (status) {
669 case "idle":
670 case "ready":
671 return "completed";
672 case "error":
673 return "error";
674 case "interrupted":
675 case "stopped":
676 return "interrupted";
677 case "starting":
678 case "running":
679 return null;
680 }
681}
682
683function checkpointStatusToTurnState(
684 status: "ready" | "missing" | "error",
685): OrchestrationLatestTurn["state"] {
686 switch (status) {
687 case "ready":
688 return "completed";
689 case "error":
690 return "error";
691 case "missing":
692 return "completed";
693 }
694}
695
696/**
697 * Returns `previous` when `next` matches it field for field, otherwise `next`.
698 * Streaming cases recompute the latest turn on every delta, and keeping the
699 * old reference lets selectors and memos keyed on `latestTurn` skip work.
700 */
701function reuseLatestTurn(
702 previous: OrchestrationLatestTurn | null,
703 next: OrchestrationLatestTurn | null,
704): OrchestrationLatestTurn | null {
705 if (previous === null || next === null) {
706 return next;
707 }
708 return previous.turnId === next.turnId &&
709 previous.state === next.state &&
710 previous.requestedAt === next.requestedAt &&
711 previous.startedAt === next.startedAt &&
712 previous.completedAt === next.completedAt &&
713 previous.assistantMessageId === next.assistantMessageId &&
714 previous.sourceProposedPlan?.threadId === next.sourceProposedPlan?.threadId &&
715 previous.sourceProposedPlan?.planId === next.sourceProposedPlan?.planId
716 ? previous
717 : next;
718}
719
720/**
721 * Points the checkpoint for `turnId` at `messageId`. Returns the input array
722 * untouched when no checkpoint needs rebinding, so streaming deltas for an
723 * already-bound message do not allocate a new `checkpoints` reference.
724 */
725function rebindCheckpointAssistantMessage(
726 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
727 turnId: TurnId,
728 messageId: MessageId,
729): ReadonlyArray<OrchestrationCheckpointSummary> {
730 const needsRebind = checkpoints.some(
731 (entry) => entry.turnId === turnId && entry.assistantMessageId !== messageId,
732 );
733 if (!needsRebind) {
734 return checkpoints;
735 }
736 return Arr.map(checkpoints, (entry) =>
737 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
738 );
739}
740
741function retainMessagesAfterRevert(
742 messages: ReadonlyArray<OrchestrationMessage>,
743 retainedTurnIds: ReadonlySet<string>,
744): OrchestrationMessage[] {
745 // Keep messages that belong to a retained turn, plus system messages and
746 // messages without a turn binding (pre-turn-0 user messages).
747 return Arr.filter(messages, (message) => {
748 if (message.role === "system") {
749 return true;
750 }
751 if (message.turnId === null) {
752 return true;
753 }
754 return retainedTurnIds.has(message.turnId);
755 });
756}