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

threadReducer.ts

1,043 lines38.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 ThreadPullRequestLink,
14 TurnId,
15} from "@t3tools/contracts";
16import { threadPullRequestKeysEqual } from "@t3tools/shared/threadPullRequests";
17import { isImportedAgentSessionMessageId } from "@t3tools/contracts";
18import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
19import * as Predicate from "effect/Predicate";
20​
21export type ThreadDetailReducerResult =
22 | { readonly kind: "updated"; readonly thread: OrchestrationThread }
23 | { readonly kind: "deleted" }
24 | { readonly kind: "unchanged" };
25​
26/** Keep only a legacy route supplied by the server; detail events cannot resolve project hosts. */
27function withPullRequests(
28 thread: OrchestrationThread,
29 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
30 updatedAt: string,
31): ThreadDetailReducerResult {
32 return {
33 kind: "updated",
34 thread: {
35 ...thread,
36 pullRequests,
37 linkedPullRequest:
38 thread.linkedPullRequest &&
39 pullRequests.some(
40 (link) => link.source !== "stack-dismissed" && link.url === thread.linkedPullRequest?.url,
41 )
42 ? thread.linkedPullRequest
43 : null,
44 updatedAt,
45 },
46 };
48​
49const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
50 O.mapInput(O.String, (p) => p.createdAt),
51 O.mapInput(O.String, (p) => p.id),
52);
53​
54const checkpointOrder = O.mapInput(
55 O.Number,
56 (cp: OrchestrationThread["checkpoints"][number]) =>
57 cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
58);
59​
60const activityOrder = O.combineAll<OrchestrationThreadActivity>([
61 O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
62 O.mapInput(O.String, (a) => a.createdAt),
63 O.mapInput(O.String, (a) => a.id),
64]);
65​
66// Per-array id index so the streaming append path can reject a re-delivered
67// id without rescanning the history. Only arrays this reducer produced are
68// indexed: presence also proves the array is activityOrder-sorted, which
69// snapshot-loaded arrays (DB order, null sequences first) are not.
70const activityIdIndex = new WeakMap<
71 ReadonlyArray<OrchestrationThreadActivity>,
72 Set<OrchestrationThreadActivity["id"]>
73>();
74​
75function turnStartRequestIdClearedByActivity(activity: OrchestrationThreadActivity): string | null {
76 if (
77 (activity.kind !== "context-compaction" &&
78 activity.kind !== "provider.turn.start.failed" &&
79 activity.kind !== "provider.auth.signed-out") ||
80 !Predicate.isObject(activity.payload)
81 ) {
82 return null;
83 }
84 return typeof activity.payload.requestId === "string" ? activity.payload.requestId : null;
86​
87function activityClearsPendingTurnStart(
88 thread: OrchestrationThread,
89 activity: OrchestrationThreadActivity,
90): boolean {
91 return (
92 thread.pendingTurnStartMessageId != null &&
93 turnStartRequestIdClearedByActivity(activity) === thread.pendingTurnStartMessageId
94 );
96​
97/**
98 * Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the
99 * server's snapshot-side `dropStaleContextWindowActivities`): rows without a
100 * finite, non-negative `usedTokens` are skipped during the consumer's backward
101 * walk, so they must not replace an earlier resolvable row here.
102 */
103function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
104 if (activity.kind !== "context-window.updated") {
105 return false;
106 }
107 const payload =
108 activity.payload && typeof activity.payload === "object"
109 ? (activity.payload as Record<string, unknown>)
110 : null;
111 const usedTokens = payload?.usedTokens;
112 return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
114​
115/**
116 * Apply a single orchestration event to an `OrchestrationThread`, returning
117 * the updated thread, a deletion signal, or an "unchanged" marker when the
118 * event doesn't affect this thread.
119 *
120 * This is a pure reducer operating on contract types. UI-specific mapping
121 * (e.g. resolving attachment preview URLs, normalising model slugs, adding
122 * scoped fields like `environmentId`) is the caller's responsibility.
123 */
124export function applyThreadDetailEvent(
125 thread: OrchestrationThread,
126 event: OrchestrationEvent,
127): ThreadDetailReducerResult {
128 switch (event.type) {
129 // ── Project events (irrelevant to thread detail) ────────────────
130 case "project.created":
131 case "project.meta-updated":
132 case "project.deleted":
133 return { kind: "unchanged" };
134​
135 // ── Thread lifecycle ────────────────────────────────────────────
136 case "thread.created":
137 return {
138 kind: "updated",
139 thread: {
140 id: event.payload.threadId,
141 projectId: event.payload.projectId,
142 title: event.payload.title,
143 modelSelection: event.payload.modelSelection,
144 runtimeMode: event.payload.runtimeMode,
145 interactionMode: event.payload.interactionMode,
146 branch: event.payload.branch,
147 worktreePath: event.payload.worktreePath,
148 branchPullRequest: null,
149 latestTurn: null,
150 createdAt: event.payload.createdAt,
151 updatedAt: event.payload.updatedAt,
152 archivedAt: null,
153 settledOverride: null,
154 settledAt: null,
155 unsettledAt: null,
156 activeOrderKey: null,
157 snoozedUntil: null,
158 snoozedAt: null,
159 deletedAt: null,
160 pullRequests: [],
161 messages: [],
162 proposedPlans: [],
163 activities: [],
164 checkpoints: [],
165 session: null,
166 },
167 };
168​
169 case "thread.deleted":
170 return { kind: "deleted" };
171​
172 case "thread.archived":
173 return {
174 kind: "updated",
175 thread: {
176 ...thread,
177 archivedAt: event.payload.archivedAt,
178 titleRegeneration: null,
179 updatedAt: event.payload.updatedAt,
180 },
181 };
182​
183 case "thread.unarchived":
184 return {
185 kind: "updated",
186 thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
187 };
188​
189 case "thread.settled":
190 return {
191 kind: "updated",
192 thread: {
193 ...thread,
194 settledOverride: "settled",
195 settledAt: event.payload.settledAt,
196 unsettledAt: null,
197 activeOrderKey: null,
198 updatedAt: event.payload.updatedAt,
199 },
200 };
201​
202 case "thread.unsettled":
203 return {
204 kind: "updated",
205 thread: {
206 ...thread,
207 settledOverride: event.payload.reason === "user" ? "active" : null,
208 settledAt: null,
209 // A thread already pinned active keeps its re-entry stamp: the
210 // activity reset that clears the pin must not reorder the list.
211 unsettledAt:
212 thread.settledOverride === "active"
213 ? (thread.unsettledAt ?? null)
214 : event.payload.updatedAt,
215 updatedAt: event.payload.updatedAt,
216 },
217 };
218​
219 case "thread.snoozed":
220 return {
221 kind: "updated",
222 thread: {
223 ...thread,
224 snoozedUntil: event.payload.snoozedUntil,
225 snoozedAt: event.payload.snoozedAt,
226 updatedAt: event.payload.updatedAt,
227 },
228 };
229​
230 case "thread.unsnoozed":
231 return {
232 kind: "updated",
233 thread: {
234 ...thread,
235 snoozedUntil: null,
236 snoozedAt: null,
237 updatedAt: event.payload.updatedAt,
238 },
239 };
240​
241 case "thread.pinned":
242 return {
243 kind: "updated",
244 thread: {
245 ...thread,
246 pinnedAt: event.payload.pinnedAt,
247 ...(event.payload.pinOrderKey !== undefined
248 ? { pinOrderKey: event.payload.pinOrderKey }
249 : {}),
250 updatedAt: event.payload.updatedAt,
251 },
252 };
253​
254 case "thread.unpinned":
255 return {
256 kind: "updated",
257 thread: {
258 ...thread,
259 pinnedAt: null,
260 pinOrderKey: null,
261 updatedAt: event.payload.updatedAt,
262 },
263 };
264​
265 case "thread.pin-reordered":
266 return {
267 kind: "updated",
268 thread: {
269 ...thread,
270 pinOrderKey: event.payload.orderKey,
271 updatedAt: event.payload.updatedAt,
272 },
273 };
274​
275 // ── Thread metadata ─────────────────────────────────────────────
276 case "thread.meta-updated": {
277 const acknowledgement = event.payload.turnStartAcknowledged;
278 const rendezvous = thread.turnStartSubmissionRendezvous ?? null;
279 const acknowledgedRequest =
280 acknowledgement === undefined
281 ? undefined
282 : rendezvous?.requests.find((request) => request.messageId === acknowledgement.messageId);
283 const acknowledgedTurnAlreadyRunning =
284 acknowledgement !== undefined &&
285 thread.session?.status === "running" &&
286 thread.session.activeTurnId === acknowledgement.turnId;
287 const acknowledgedTurnAlreadyObserved =
288 acknowledgement !== undefined &&
289 (acknowledgedRequest?.observedTurnIds ?? []).includes(acknowledgement.turnId);
290 // A provider can finish a turn before its start acknowledgement
291 // lands; the settled turn can never consume the submission.
292 const acknowledgedTurnAlreadySettled =
293 acknowledgement !== undefined &&
294 thread.latestTurn !== null &&
295 thread.latestTurn.turnId === acknowledgement.turnId &&
296 thread.latestTurn.state !== "running";
297 // A stopped or interrupted session can never surface the acknowledged
298 // turn, so the submission is resolved rather than recorded.
299 const acknowledgedSessionDead =
300 acknowledgement !== undefined &&
301 (thread.session?.status === "stopped" || thread.session?.status === "interrupted");
302 const acknowledgementAlreadyAdopted =
303 acknowledgedTurnAlreadyRunning ||
304 acknowledgedTurnAlreadyObserved ||
305 acknowledgedTurnAlreadySettled ||
306 acknowledgedSessionDead;
307 const remainingRequests =
308 acknowledgement === undefined
309 ? (rendezvous?.requests ?? [])
310 : (rendezvous?.requests ?? []).filter(
311 (request) => request.messageId !== acknowledgement.messageId,
312 );
313 return {
314 kind: "updated",
315 thread: {
316 ...thread,
317 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
318 ...(event.payload.titleRegeneration !== undefined
319 ? { titleRegeneration: event.payload.titleRegeneration }
320 : {}),
321 ...(event.payload.modelSelection !== undefined
322 ? { modelSelection: event.payload.modelSelection }
323 : {}),
324 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
325 ...(event.payload.worktreePath !== undefined
326 ? { worktreePath: event.payload.worktreePath }
327 : {}),
328 ...(event.payload.linkedPullRequest !== undefined
329 ? { linkedPullRequest: event.payload.linkedPullRequest }
330 : {}),
331 ...(event.payload.branchPullRequest !== undefined
332 ? { branchPullRequest: event.payload.branchPullRequest }
333 : {}),
334 ...(event.payload.activeOrderKey !== undefined
335 ? { activeOrderKey: event.payload.activeOrderKey }
336 : {}),
337 ...(acknowledgement !== undefined
338 ? {
339 pendingTurnStartMessageId:
340 acknowledgement.messageId === thread.pendingTurnStartMessageId &&
341 acknowledgementAlreadyAdopted
342 ? null
343 : (thread.pendingTurnStartMessageId ?? null),
344 submittedTurnStarts: acknowledgementAlreadyAdopted
345 ? (thread.submittedTurnStarts ?? []).filter(
346 (entry) => entry.turnId !== acknowledgement.turnId,
347 )
348 : [
349 ...(thread.submittedTurnStarts ?? []).filter(
350 (entry) => entry.messageId !== acknowledgement.messageId,
351 ),
352 acknowledgement,
353 ],
354 turnStartSubmissionRendezvous:
355 remainingRequests.length === 0
356 ? null
357 : {
358 requests: remainingRequests,
359 },
360 }
361 : {}),
362 updatedAt: event.payload.updatedAt,
363 },
364 };
365 }
366​
367 case "thread.pull-request-linked": {
368 const link = event.payload.link;
369 const others = thread.pullRequests.filter(
370 (existing) => !threadPullRequestKeysEqual(existing, link),
371 );
372 return withPullRequests(thread, [...others, link], event.payload.updatedAt);
373 }
374​
375 case "thread.pull-request-unlinked":
376 return withPullRequests(
377 thread,
378 thread.pullRequests.filter(
379 (existing) => !threadPullRequestKeysEqual(existing, event.payload),
380 ),
381 event.payload.updatedAt,
382 );
383​
384 case "thread.pull-request-synced": {
385 if (
386 !thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, event.payload))
387 ) {
388 return { kind: "unchanged" };
389 }
390 return withPullRequests(
391 thread,
392 thread.pullRequests.map((existing) =>
393 threadPullRequestKeysEqual(existing, event.payload)
394 ? { ...existing, snapshot: event.payload.snapshot, stack: event.payload.stack }
395 : existing,
396 ),
397 event.payload.updatedAt,
398 );
399 }
400​
401 case "thread.runtime-mode-set":
402 return {
403 kind: "updated",
404 thread: {
405 ...thread,
406 runtimeMode: event.payload.runtimeMode,
407 updatedAt: event.payload.updatedAt,
408 },
409 };
410​
411 case "thread.interaction-mode-set":
412 return {
413 kind: "updated",
414 thread: {
415 ...thread,
416 interactionMode: event.payload.interactionMode,
417 updatedAt: event.payload.updatedAt,
418 },
419 };
420​
421 // ── Turn lifecycle ──────────────────────────────────────────────
422 case "thread.turn-start-requested": {
423 const activeTurnId =
424 thread.session?.status === "running" ? thread.session.activeTurnId : null;
425 return {
426 kind: "updated",
427 thread: {
428 ...thread,
429 ...(event.payload.modelSelection !== undefined
430 ? { modelSelection: event.payload.modelSelection }
431 : {}),
432 runtimeMode: event.payload.runtimeMode,
433 interactionMode: event.payload.interactionMode,
434 pendingTurnStartMessageId: event.payload.messageId,
435 ...(event.payload.expectsTurnStartAcknowledgement === true
436 ? {
437 turnStartSubmissionRendezvous: {
438 requests: [
439 ...(thread.turnStartSubmissionRendezvous?.requests ?? []).filter(
440 (request) => request.messageId !== event.payload.messageId,
441 ),
442 {
443 messageId: event.payload.messageId,
444 observedTurnIds: activeTurnId === null ? [] : [activeTurnId],
445 },
446 ],
447 },
448 }
449 : {}),
450 updatedAt: event.occurredAt,
451 },
452 };
453 }
454​
455 case "thread.turn-interrupt-requested": {
456 if (event.payload.turnId === undefined) {
457 return { kind: "unchanged" };
458 }
459 const latestTurn = thread.latestTurn;
460 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
461 return { kind: "unchanged" };
462 }
463 return {
464 kind: "updated",
465 thread: {
466 ...thread,
467 latestTurn: {
468 ...latestTurn,
469 state: "interrupted",
470 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
471 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
472 },
473 updatedAt: event.occurredAt,
474 },
475 };
476 }
477​
478 // ── Messages ────────────────────────────────────────────────────
479 case "thread.message-sent": {
480 const message: OrchestrationMessage = {
481 id: event.payload.messageId,
482 role: event.payload.role,
483 text: event.payload.text,
484 ...(event.payload.attachments !== undefined
485 ? { attachments: event.payload.attachments }
486 : {}),
487 ...(event.payload.context !== undefined ? { context: event.payload.context } : {}),
488 turnId: event.payload.turnId,
489 streaming: event.payload.streaming,
490 createdAt: event.payload.createdAt,
491 updatedAt: event.payload.updatedAt,
492 };
493​
494 let found = false;
495 const messages = thread.messages.map((entry) => {
496 if (entry.id !== message.id) return entry;
497 found = true;
498 return {
499 ...entry,
500 text: message.streaming
501 ? `${entry.text}${message.text}`
502 : message.text.length > 0
503 ? message.text
504 : entry.text,
505 streaming: message.streaming,
506 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
507 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
508 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
509 ...(message.context !== undefined ? { context: message.context } : {}),
510 };
511 });
512 if (!found) messages.push(message);
513 // Update latestTurn for assistant messages bound to a turn. A completed
514 // assistant message only settles the turn once the session is no longer
515 // running it — providers may emit several assistant messages per turn
516 // (commentary between tool calls), and the turn must stay unsettled
517 // until the provider reports turn end. Streaming deltas recompute the
518 // same record, so the previous reference is kept when nothing changed.
519 const turnStillRunning =
520 event.payload.turnId !== null &&
521 thread.session?.status === "running" &&
522 thread.session.activeTurnId === event.payload.turnId;
523 const settlesTurn = !event.payload.streaming && !turnStillRunning;
524 const latestTurn = reuseLatestTurn(
525 thread.latestTurn,
526 event.payload.role === "assistant" &&
527 event.payload.turnId !== null &&
528 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
529 ? {
530 turnId: event.payload.turnId,
531 state: settlesTurn
532 ? thread.latestTurn?.state === "interrupted"
533 ? "interrupted"
534 : thread.latestTurn?.state === "error"
535 ? "error"
536 : "completed"
537 : "running",
538 requestedAt:
539 thread.latestTurn?.turnId === event.payload.turnId
540 ? thread.latestTurn.requestedAt
541 : event.payload.createdAt,
542 startedAt:
543 thread.latestTurn?.turnId === event.payload.turnId
544 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
545 : event.payload.createdAt,
546 completedAt: settlesTurn
547 ? event.payload.updatedAt
548 : thread.latestTurn?.turnId === event.payload.turnId
549 ? (thread.latestTurn.completedAt ?? null)
550 : null,
551 assistantMessageId: event.payload.messageId,
552 }
553 : thread.latestTurn,
554 );
555​
556 // Rebind checkpoint assistant message IDs for assistant messages. The
557 // helper hands back the same array when the entry is already bound.
558 const checkpoints =
559 event.payload.role === "assistant" && event.payload.turnId !== null
560 ? rebindCheckpointAssistantMessage(
561 thread.checkpoints,
562 event.payload.turnId,
563 event.payload.messageId,
564 )
565 : thread.checkpoints;
566​
567 return {
568 kind: "updated",
569 thread: {
570 ...thread,
571 messages,
572 checkpoints,
573 latestTurn,
574 updatedAt: event.occurredAt,
575 },
576 };
577 }
578​
579 // ── Session ─────────────────────────────────────────────────────
580 case "thread.session-set": {
581 // Leaving the "running" session status is the turn-end signal: settle a
582 // still-running latest turn so its duration reflects the whole turn.
583 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
584 const activeTurnId =
585 event.payload.session.status === "running" ? event.payload.session.activeTurnId : null;
586 const rendezvous = thread.turnStartSubmissionRendezvous ?? null;
587 const latestTurn = reuseLatestTurn(
588 thread.latestTurn,
589 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
590 ? {
591 turnId: event.payload.session.activeTurnId,
592 state: "running",
593 requestedAt:
594 thread.latestTurn?.turnId === event.payload.session.activeTurnId
595 ? thread.latestTurn.requestedAt
596 : event.payload.session.updatedAt,
597 startedAt:
598 thread.latestTurn?.turnId === event.payload.session.activeTurnId
599 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
600 : event.payload.session.updatedAt,
601 completedAt: null,
602 assistantMessageId:
603 thread.latestTurn?.turnId === event.payload.session.activeTurnId
604 ? thread.latestTurn.assistantMessageId
605 : null,
606 }
607 : thread.latestTurn !== null &&
608 thread.latestTurn.state === "running" &&
609 settledTurnState !== null
610 ? {
611 ...thread.latestTurn,
612 state: settledTurnState,
613 // A running turn's completedAt can only hold a mid-turn
614 // placeholder checkpoint timestamp — the session leaving
615 // "running" is the authoritative turn end.
616 completedAt: event.payload.session.updatedAt,
617 }
618 : thread.latestTurn,
619 );
620​
621 return {
622 kind: "updated",
623 thread: {
624 ...thread,
625 session: event.payload.session,
626 pendingTurnStartMessageId:
627 event.payload.session.status === "running" &&
628 event.payload.session.activeTurnId !== null
629 ? null
630 : (thread.pendingTurnStartMessageId ?? null),
631 submittedTurnStarts:
632 activeTurnId !== null
633 ? (thread.submittedTurnStarts ?? []).filter((entry) => entry.turnId !== activeTurnId)
634 : // Acknowledged starts die with their session; an idle or
635 // errored session may still pick them up, since a per-request
636 // failure does not prove the session is gone.
637 event.payload.session.status === "interrupted" ||
638 event.payload.session.status === "stopped"
639 ? []
640 : (thread.submittedTurnStarts ?? []),
641 turnStartSubmissionRendezvous:
642 activeTurnId === null || rendezvous === null || rendezvous.requests.length === 0
643 ? rendezvous
644 : {
645 requests: rendezvous.requests.map((request) => ({
646 ...request,
647 observedTurnIds: [
648 ...request.observedTurnIds.filter((turnId) => turnId !== activeTurnId),
649 activeTurnId,
650 ],
651 })),
652 },
653 latestTurn,
654 updatedAt: event.occurredAt,
655 },
656 };
657 }
658​
659 case "thread.session-stop-requested":
660 return thread.session === null
661 ? { kind: "unchanged" }
662 : {
663 kind: "updated",
664 thread: {
665 ...thread,
666 session: {
667 ...thread.session,
668 status: "stopped",
669 activeTurnId: null,
670 updatedAt: event.payload.createdAt,
671 },
672 updatedAt: event.occurredAt,
673 },
674 };
675​
676 // ── Proposed plans ──────────────────────────────────────────────
677 case "thread.proposed-plan-upserted": {
678 const proposedPlan = event.payload.proposedPlan;
679​
680 const proposedPlans = pipe(
681 thread.proposedPlans,
682 Arr.filter((entry) => entry.id !== proposedPlan.id),
683 Arr.append(proposedPlan),
684 Arr.sort(proposedPlanOrder),
685 );
686​
687 return {
688 kind: "updated",
689 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
690 };
691 }
692​
693 // ── Checkpoints / turn diffs ────────────────────────────────────
694 case "thread.turn-diff-completed": {
695 const checkpoint: OrchestrationCheckpointSummary = {
696 turnId: event.payload.turnId,
697 checkpointTurnCount: event.payload.checkpointTurnCount,
698 checkpointRef: event.payload.checkpointRef,
699 status: event.payload.status,
700 files: event.payload.files,
701 assistantMessageId: event.payload.assistantMessageId,
702 completedAt: event.payload.completedAt,
703 };
704​
705 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
706 // Don't overwrite a non-missing checkpoint with a missing one.
707 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
708 return { kind: "unchanged" };
709 }
710​
711 const checkpoints = pipe(
712 thread.checkpoints,
713 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
714 Arr.append(checkpoint),
715 Arr.sort(checkpointOrder),
716 );
717​
718 // Mid-turn diff updates produce placeholder checkpoints; record the
719 // checkpoint, but don't settle a turn its session is still running.
720 const diffTurnStillRunning =
721 thread.session?.status === "running" &&
722 thread.session.activeTurnId === event.payload.turnId;
723 const latestTurn =
724 !diffTurnStillRunning &&
725 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
726 ? {
727 turnId: event.payload.turnId,
728 state:
729 thread.latestTurn?.state === "interrupted"
730 ? "interrupted"
731 : checkpointStatusToTurnState(event.payload.status),
732 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
733 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
734 completedAt: event.payload.completedAt,
735 assistantMessageId: event.payload.assistantMessageId,
736 }
737 : thread.latestTurn;
738​
739 return {
740 kind: "updated",
741 thread: {
742 ...thread,
743 checkpoints,
744 submittedTurnStarts: diffTurnStillRunning
745 ? (thread.submittedTurnStarts ?? [])
746 : (thread.submittedTurnStarts ?? []).filter(
747 (entry) => entry.turnId !== event.payload.turnId,
748 ),
749 latestTurn,
750 updatedAt: event.occurredAt,
751 },
752 };
753 }
754​
755 // ── Revert ──────────────────────────────────────────────────────
756 case "thread.reverted": {
757 const checkpoints = pipe(
758 thread.checkpoints,
759 Arr.filter(
760 (entry) =>
761 entry.checkpointTurnCount !== undefined &&
762 entry.checkpointTurnCount <= event.payload.turnCount,
763 ),
764 Arr.sort(checkpointOrder),
765 );
766​
767 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
768 const messages = retainMessagesAfterRevert(
769 thread.messages,
770 retainedTurnIds,
771 event.payload.turnCount,
772 new Set(event.payload.preservedMessageIds ?? []),
773 );
774 const proposedPlans = pipe(
775 thread.proposedPlans,
776 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
777 );
778 const activities = pipe(
779 thread.activities,
780 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
781 );
782 const latestCheckpoint = checkpoints.at(-1) ?? null;
783​
784 return {
785 kind: "updated",
786 thread: {
787 ...thread,
788 checkpoints,
789 messages,
790 proposedPlans,
791 activities,
792 latestTurn:
793 latestCheckpoint === null
794 ? null
795 : {
796 turnId: latestCheckpoint.turnId,
797 state: checkpointStatusToTurnState(
798 latestCheckpoint.status as "ready" | "missing" | "error",
799 ),
800 requestedAt: latestCheckpoint.completedAt,
801 startedAt: latestCheckpoint.completedAt,
802 completedAt: latestCheckpoint.completedAt,
803 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
804 },
805 updatedAt: event.occurredAt,
806 },
807 };
808 }
809​
810 // ── Activities ──────────────────────────────────────────────────
811 case "thread.activity-appended": {
812 const activity = event.payload.activity;
813 // A resolvable context-window update supersedes earlier resolvable ones
814 // for the same turn: consumers only read the latest value (walking the
815 // array backwards), and providers stream these updates continuously, so
816 // retaining the history grows the thread by thousands of rows over a
817 // long session. Mirrors the server-side snapshot rule in
818 // dropStaleContextWindowActivities; retention stays per turn so a
819 // thread.reverted that discards turns can still resolve a value from
820 // the turns that survive.
821 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
822 const pendingTurnStartMessageId = activityClearsPendingTurnStart(thread, activity)
823 ? null
824 : (thread.pendingTurnStartMessageId ?? null);
825 const clearedRequestId = turnStartRequestIdClearedByActivity(activity);
826 const submittedTurnStarts =
827 clearedRequestId === null
828 ? (thread.submittedTurnStarts ?? [])
829 : (thread.submittedTurnStarts ?? []).filter(
830 (entry) => entry.messageId !== clearedRequestId,
831 );
832 const rendezvous = thread.turnStartSubmissionRendezvous ?? null;
833 const remainingRequests =
834 clearedRequestId === null
835 ? (rendezvous?.requests ?? [])
836 : (rendezvous?.requests ?? []).filter(
837 (request) => request.messageId !== clearedRequestId,
838 );
839 const turnStartSubmissionRendezvous =
840 rendezvous === null
841 ? null
842 : remainingRequests.length === 0
843 ? null
844 : { requests: remainingRequests };
845 // Live streams append in order: an unseen id sorting at/after the tail
846 // of a known-sorted array appends without re-filtering and re-sorting
847 // the whole history on every event. The id set moves forward to the new
848 // array; a superseded array falls back to the sorting path.
849 const ids = activityIdIndex.get(thread.activities);
850 const lastActivity = thread.activities.at(-1);
851 if (
852 !supersedesContextWindow &&
853 ids !== undefined &&
854 (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
855 !ids.has(activity.id)
856 ) {
857 const activities = Arr.append(thread.activities, activity);
858 activityIdIndex.delete(thread.activities);
859 ids.add(activity.id);
860 activityIdIndex.set(activities, ids);
861 return {
862 kind: "updated",
863 thread: {
864 ...thread,
865 activities,
866 pendingTurnStartMessageId,
867 submittedTurnStarts,
868 turnStartSubmissionRendezvous,
869 updatedAt: event.occurredAt,
870 },
871 };
872 }
873 const activities = pipe(
874 thread.activities,
875 Arr.filter(
876 (entry) =>
877 entry.id !== activity.id &&
878 !(
879 supersedesContextWindow &&
880 entry.turnId === activity.turnId &&
881 isResolvableContextWindowActivity(entry)
882 ),
883 ),
884 Arr.append(activity),
885 Arr.sort(activityOrder),
886 );
887 activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));
888​
889 return {
890 kind: "updated",
891 thread: {
892 ...thread,
893 activities,
894 pendingTurnStartMessageId,
895 submittedTurnStarts,
896 turnStartSubmissionRendezvous,
897 updatedAt: event.occurredAt,
898 },
899 };
900 }
901​
902 // ── Events that don't mutate thread state directly ──────────────
903 case "thread.approval-response-requested":
904 case "thread.user-input-response-requested":
905 case "thread.checkpoint-revert-requested":
906 return { kind: "unchanged" };
907 }
908​
909 // Forward-compatible: ignore unrecognized event types.
910 return { kind: "unchanged" };
912​
913// ── Helpers ──────────────────────────────────────────────────────────
914​
915/**
916 * Turn state to settle a still-running latest turn with when its session
917 * leaves the "running" status, or null while the session is (re)starting or
918 * running and the turn must stay unsettled.
919 */
920function settledTurnStateForSessionStatus(
921 status: OrchestrationSession["status"],
922): "completed" | "interrupted" | "error" | null {
923 switch (status) {
924 case "idle":
925 case "ready":
926 return "completed";
927 case "error":
928 return "error";
929 case "interrupted":
930 case "stopped":
931 return "interrupted";
932 case "starting":
933 case "running":
934 return null;
935 }
937​
938function checkpointStatusToTurnState(
939 status: "ready" | "missing" | "error",
940): OrchestrationLatestTurn["state"] {
941 switch (status) {
942 case "ready":
943 return "completed";
944 case "error":
945 return "error";
946 case "missing":
947 return "completed";
948 }
950​
951/**
952 * Returns `previous` when `next` matches it field for field, otherwise `next`.
953 * Streaming cases recompute the latest turn on every delta, and keeping the
954 * old reference lets selectors and memos keyed on `latestTurn` skip work.
955 */
956function reuseLatestTurn(
957 previous: OrchestrationLatestTurn | null,
958 next: OrchestrationLatestTurn | null,
959): OrchestrationLatestTurn | null {
960 if (previous === null || next === null) {
961 return next;
962 }
963 return previous.turnId === next.turnId &&
964 previous.state === next.state &&
965 previous.requestedAt === next.requestedAt &&
966 previous.startedAt === next.startedAt &&
967 previous.completedAt === next.completedAt &&
968 previous.assistantMessageId === next.assistantMessageId &&
969 previous.sourceProposedPlan?.threadId === next.sourceProposedPlan?.threadId &&
970 previous.sourceProposedPlan?.planId === next.sourceProposedPlan?.planId
971 ? previous
972 : next;
974​
975/**
976 * Points the checkpoint for `turnId` at `messageId`. Returns the input array
977 * untouched when no checkpoint needs rebinding, so streaming deltas for an
978 * already-bound message do not allocate a new `checkpoints` reference.
979 */
980function rebindCheckpointAssistantMessage(
981 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
982 turnId: TurnId,
983 messageId: MessageId,
984): ReadonlyArray<OrchestrationCheckpointSummary> {
985 const needsRebind = checkpoints.some(
986 (entry) => entry.turnId === turnId && entry.assistantMessageId !== messageId,
987 );
988 if (!needsRebind) {
989 return checkpoints;
990 }
991 return Arr.map(checkpoints, (entry) =>
992 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
993 );
995​
996function retainMessagesAfterRevert(
997 messages: ReadonlyArray<OrchestrationMessage>,
998 retainedTurnIds: ReadonlySet<string>,
999 turnCount: number,
1000 preservedMessageIds: ReadonlySet<string>,
1001): OrchestrationMessage[] {
1002 const retainedMessageIds = new Set(preservedMessageIds);
1003 for (const message of messages) {
1004 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
1005 retainedMessageIds.add(message.id);
1006 } else if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
1007 retainedMessageIds.add(message.id);
1010​
1011 for (const role of ["user", "assistant"] as const) {
1012 // Queued messages preserved across the revert are not part of the retained
1013 // turn history, so they must not consume the historical-message quota below.
1014 const retainedCount = messages.filter(
1015 (message) =>
1016 message.role === role &&
1017 !isImportedAgentSessionMessageId(message.id) &&
1018 retainedMessageIds.has(message.id) &&
1019 !preservedMessageIds.has(message.id),
1020 ).length;
1021 const missingCount = Math.max(0, turnCount - retainedCount);
1022 const fallbackMessages = messages
1023 .filter(
1024 (message) =>
1025 message.role === role &&
1026 !retainedMessageIds.has(message.id) &&
1027 (message.turnId === null || retainedTurnIds.has(message.turnId)),
1029 // `.sort()`, not `.toSorted()`: `.filter()` above already returned a fresh array, and
1030 // this is shared with mobile, which runs on Hermes and has no ES2023 array methods.
1031 .sort(
1032 (left, right) =>
1033 compareDateTimeStrings(left.createdAt, right.createdAt) ||
1034 left.id.localeCompare(right.id),
1036 .slice(0, missingCount);
1037 for (const message of fallbackMessages) {
1038 retainedMessageIds.add(message.id);
1041​
1042 return Arr.filter(messages, (message) => retainedMessageIds.has(message.id));