Open History to see the last commit
1import type {
2 OrchestrationEvent,
3 OrchestrationProject,
4 OrchestrationReadModel,
5 ThreadId,
6 ThreadLinkedPullRequest,
7 ThreadPullRequestKey,
8 ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import {
11 isImportedAgentSessionMessageId,
12 OrchestrationCheckpointSummary,
13 OrchestrationMessage,
14 OrchestrationSession,
15 OrchestrationThread,
16 WORKTREE_SETUP_ACTIVITY_KIND,
17} from "@t3tools/contracts";
18import {
19 legacyLinkedPullRequestOf,
20 legacyThreadPullRequestKey,
21 threadPullRequestKeysEqual,
22} from "@t3tools/shared/threadPullRequests";
23import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
24import * as Effect from "effect/Effect";
25import * as Schema from "effect/Schema";
26import * as Predicate from "effect/Predicate";
27
28import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts";
29import {
30 MessageSentPayloadSchema,
31 ProjectCreatedPayload,
32 ProjectDeletedPayload,
33 ProjectMetaUpdatedPayload,
34 ThreadActivityAppendedPayload,
35 ThreadArchivedPayload,
36 ThreadCreatedPayload,
37 ThreadDeletedPayload,
38 ThreadInteractionModeSetPayload,
39 ThreadMetaUpdatedPayload,
40 ThreadProposedPlanUpsertedPayload,
41 ThreadRuntimeModeSetPayload,
42 ThreadSettledPayload,
43 ThreadPinnedPayload,
44 ThreadPinReorderedPayload,
45 ThreadPullRequestLinkedPayload,
46 ThreadPullRequestSyncedPayload,
47 ThreadPullRequestUnlinkedPayload,
48 ThreadSnoozedPayload,
49 ThreadUnpinnedPayload,
50 ThreadUnarchivedPayload,
51 ThreadUnsettledPayload,
52 ThreadUnsnoozedPayload,
53 ThreadRevertedPayload,
54 ThreadSessionSetPayload,
55 ThreadTurnDiffCompletedPayload,
56} from "./Schemas.ts";
57
58type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
59const MAX_THREAD_MESSAGES = 2_000;
60const MAX_THREAD_CHECKPOINTS = 500;
61
62// Async questions can stay open while the agent produces more activity.
63// Match the database snapshot's pending-question retention.
64function retainThreadActivities(activities: OrchestrationThread["activities"]) {
65 const recentStart = activities.length - 500;
66 if (recentStart <= 0) return activities;
67 const pending = new Map<string, OrchestrationThread["activities"][number]>();
68 for (const activity of activities) {
69 if (!Predicate.isObject(activity.payload)) continue;
70 const requestId = activity.payload.requestId;
71 if (typeof requestId !== "string") continue;
72 if (activity.kind === "user-input.requested" && activity.payload.responseMode === "message") {
73 pending.set(requestId, activity);
74 } else if (activity.kind === "user-input.resolved") {
75 pending.delete(requestId);
76 }
77 }
78 const pendingActivities = new Set(pending.values());
79 return activities.filter(
80 (activity, index) =>
81 index >= recentStart ||
82 pendingActivities.has(activity) ||
83 // The worktree setup record is upserted under one id for the thread's
84 // whole life and is the only durable copy of a running setup; an async
85 // setup script can outlast a chatty first turn.
86 activity.kind === WORKTREE_SETUP_ACTIVITY_KIND,
87 );
88}
89
90function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
91 if (status === "error") return "error" as const;
92 // Match SQL and client projections: a missing git ref is not an interruption.
93 return "completed" as const;
94}
95
96/**
97 * Turn state to settle a still-running latest turn with when its session
98 * leaves the "running" status, or null while the session is (re)starting or
99 * running and the turn must stay unsettled.
100 */
101function settledTurnStateForSessionStatus(
102 status: OrchestrationSession["status"],
103): "completed" | "interrupted" | "error" | null {
104 switch (status) {
105 case "idle":
106 case "ready":
107 return "completed";
108 case "error":
109 return "error";
110 case "interrupted":
111 case "stopped":
112 return "interrupted";
113 case "starting":
114 case "running":
115 return null;
116 }
117}
118
119function updateThread(
120 threads: ReadonlyArray<OrchestrationThread>,
121 threadId: ThreadId,
122 patch: ThreadPatch,
123): OrchestrationThread[] {
124 return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
125}
126
127/** Patch that swaps a thread's links and re-derives the legacy single-PR field from them. */
128function pullRequestsPatch(
129 thread: Pick<OrchestrationThread, "projectId">,
130 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
131 projects: OrchestrationReadModel["projects"],
132): Pick<OrchestrationThread, "pullRequests" | "linkedPullRequest"> {
133 return {
134 pullRequests,
135 linkedPullRequest: legacyLinkedPullRequestOf(
136 pullRequests,
137 thread.projectId,
138 projects.find((project) => project.id === thread.projectId)?.repositoryIdentity,
139 ),
140 };
141}
142
143function upsertPullRequestLink(
144 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
145 link: ThreadPullRequestLink,
146): ReadonlyArray<ThreadPullRequestLink> {
147 const index = pullRequests.findIndex((entry) => threadPullRequestKeysEqual(entry, link));
148 return index === -1
149 ? [...pullRequests, link]
150 : pullRequests.map((entry, entryIndex) => (entryIndex === index ? link : entry));
151}
152
153function removePullRequestLink(
154 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
155 key: ThreadPullRequestKey,
156): ReadonlyArray<ThreadPullRequestLink> {
157 return pullRequests.filter((entry) => !threadPullRequestKeysEqual(entry, key));
158}
159
160/**
161 * Host for a legacy `linkedPullRequest` being replayed into the link array.
162 * Legacy links never carried one; the project's canonical key
163 * (`<host>/<owner>/<name>`) is the best witness, then the link URL.
164 */
165function legacyPullRequestHost(
166 project: OrchestrationProject | undefined,
167 linked: ThreadLinkedPullRequest,
168): string {
169 const canonicalHost = project?.repositoryIdentity?.canonicalKey.split("/")[0];
170 if (canonicalHost) return canonicalHost.toLowerCase();
171 try {
172 return new URL(linked.url).hostname.toLowerCase();
173 } catch {
174 return "unknown";
175 }
176}
177
178function legacyLinkToPullRequests(
179 thread: Pick<OrchestrationThread, "pullRequests">,
180 project: OrchestrationProject | undefined,
181 linked: ThreadLinkedPullRequest | null,
182 linkedAt: string,
183): ReadonlyArray<ThreadPullRequestLink> {
184 // The legacy field held one user-chosen link, so null clears exactly the
185 // manual ones and leaves created/agent/stack links alone.
186 const withoutManual = thread.pullRequests.filter((entry) => entry.source !== "manual");
187 if (linked === null) return withoutManual;
188 return upsertPullRequestLink(withoutManual, {
189 ...legacyThreadPullRequestKey(linked, legacyPullRequestHost(project, linked)),
190 url: linked.url,
191 source: "manual",
192 linkedAt,
193 snapshot: null,
194 stack: null,
195 });
196}
197
198function decodeForEvent<A>(
199 schema: Schema.Decoder<A, never>,
200 value: unknown,
201 eventType: OrchestrationEvent["type"],
202 field: string,
203): Effect.Effect<A, OrchestrationProjectorDecodeError> {
204 return Schema.decodeUnknownEffect(schema)(value).pipe(
205 Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
206 );
207}
208
209function retainThreadMessagesAfterRevert(
210 messages: ReadonlyArray<OrchestrationMessage>,
211 retainedTurnIds: ReadonlySet<string>,
212 turnCount: number,
213): ReadonlyArray<OrchestrationMessage> {
214 const retainedMessageIds = new Set<string>();
215 for (const message of messages) {
216 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
217 retainedMessageIds.add(message.id);
218 continue;
219 }
220 if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
221 retainedMessageIds.add(message.id);
222 }
223 }
224
225 const retainedUserCount = messages.filter(
226 (message) =>
227 message.role === "user" &&
228 !isImportedAgentSessionMessageId(message.id) &&
229 retainedMessageIds.has(message.id),
230 ).length;
231 const missingUserCount = Math.max(0, turnCount - retainedUserCount);
232 if (missingUserCount > 0) {
233 const fallbackUserMessages = messages
234 .filter(
235 (message) =>
236 message.role === "user" &&
237 !retainedMessageIds.has(message.id) &&
238 (message.turnId === null || retainedTurnIds.has(message.turnId)),
239 )
240 .toSorted(
241 (left, right) =>
242 compareDateTimeStrings(left.createdAt, right.createdAt) ||
243 left.id.localeCompare(right.id),
244 )
245 .slice(0, missingUserCount);
246 for (const message of fallbackUserMessages) {
247 retainedMessageIds.add(message.id);
248 }
249 }
250
251 const retainedAssistantCount = messages.filter(
252 (message) =>
253 message.role === "assistant" &&
254 !isImportedAgentSessionMessageId(message.id) &&
255 retainedMessageIds.has(message.id),
256 ).length;
257 const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
258 if (missingAssistantCount > 0) {
259 const fallbackAssistantMessages = messages
260 .filter(
261 (message) =>
262 message.role === "assistant" &&
263 !retainedMessageIds.has(message.id) &&
264 (message.turnId === null || retainedTurnIds.has(message.turnId)),
265 )
266 .toSorted(
267 (left, right) =>
268 compareDateTimeStrings(left.createdAt, right.createdAt) ||
269 left.id.localeCompare(right.id),
270 )
271 .slice(0, missingAssistantCount);
272 for (const message of fallbackAssistantMessages) {
273 retainedMessageIds.add(message.id);
274 }
275 }
276
277 return messages.filter((message) => retainedMessageIds.has(message.id));
278}
279
280function retainThreadActivitiesAfterRevert(
281 activities: ReadonlyArray<OrchestrationThread["activities"][number]>,
282 retainedTurnIds: ReadonlySet<string>,
283): ReadonlyArray<OrchestrationThread["activities"][number]> {
284 return activities.filter(
285 (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
286 );
287}
288
289function retainThreadProposedPlansAfterRevert(
290 proposedPlans: ReadonlyArray<OrchestrationThread["proposedPlans"][number]>,
291 retainedTurnIds: ReadonlySet<string>,
292): ReadonlyArray<OrchestrationThread["proposedPlans"][number]> {
293 return proposedPlans.filter(
294 (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
295 );
296}
297
298function compareThreadActivities(
299 left: OrchestrationThread["activities"][number],
300 right: OrchestrationThread["activities"][number],
301): number {
302 if (left.sequence !== undefined && right.sequence !== undefined) {
303 if (left.sequence !== right.sequence) {
304 return left.sequence - right.sequence;
305 }
306 } else if (left.sequence !== undefined) {
307 return 1;
308 } else if (right.sequence !== undefined) {
309 return -1;
310 }
311
312 return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
313}
314
315export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
316 return {
317 snapshotSequence: 0,
318 projects: [],
319 threads: [],
320 updatedAt: nowIso,
321 };
322}
323
324export function projectEvent(
325 model: OrchestrationReadModel,
326 event: OrchestrationEvent,
327): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {
328 const nextBase: OrchestrationReadModel = {
329 ...model,
330 snapshotSequence: event.sequence,
331 updatedAt: event.occurredAt,
332 };
333
334 switch (event.type) {
335 case "project.created":
336 return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(
337 Effect.map((payload) => {
338 const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);
339 const nextProject = {
340 id: payload.projectId,
341 title: payload.title,
342 workspaceRoot: payload.workspaceRoot,
343 defaultModelSelection: payload.defaultModelSelection,
344 defaultThreadEnvMode: null,
345 autoPull: false,
346 faviconPath: payload.faviconPath ?? null,
347 projectIcon: payload.projectIcon ?? null,
348 scripts: payload.scripts,
349 createdAt: payload.createdAt,
350 updatedAt: payload.updatedAt,
351 deletedAt: null,
352 };
353
354 return {
355 ...nextBase,
356 projects: existing
357 ? nextBase.projects.map((entry) =>
358 entry.id === payload.projectId ? nextProject : entry,
359 )
360 : [...nextBase.projects, nextProject],
361 };
362 }),
363 );
364
365 case "project.meta-updated":
366 return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
367 Effect.map((payload) => ({
368 ...nextBase,
369 projects: nextBase.projects.map((project) =>
370 project.id === payload.projectId
371 ? {
372 ...project,
373 ...(payload.title !== undefined ? { title: payload.title } : {}),
374 ...(payload.workspaceRoot !== undefined
375 ? { workspaceRoot: payload.workspaceRoot }
376 : {}),
377 ...(payload.defaultModelSelection !== undefined
378 ? { defaultModelSelection: payload.defaultModelSelection }
379 : {}),
380 ...(payload.defaultThreadEnvMode !== undefined
381 ? { defaultThreadEnvMode: payload.defaultThreadEnvMode }
382 : {}),
383 ...(payload.autoPull !== undefined ? { autoPull: payload.autoPull } : {}),
384 ...(payload.faviconPath !== undefined
385 ? { faviconPath: payload.faviconPath }
386 : {}),
387 ...(payload.projectIcon !== undefined
388 ? { projectIcon: payload.projectIcon }
389 : {}),
390 ...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
391 updatedAt: payload.updatedAt,
392 }
393 : project,
394 ),
395 })),
396 );
397
398 case "project.deleted":
399 return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe(
400 Effect.map((payload) => ({
401 ...nextBase,
402 projects: nextBase.projects.map((project) =>
403 project.id === payload.projectId
404 ? {
405 ...project,
406 deletedAt: payload.deletedAt,
407 updatedAt: payload.deletedAt,
408 }
409 : project,
410 ),
411 })),
412 );
413
414 case "thread.created":
415 return Effect.gen(function* () {
416 const payload = yield* decodeForEvent(
417 ThreadCreatedPayload,
418 event.payload,
419 event.type,
420 "payload",
421 );
422 const thread: OrchestrationThread = yield* decodeForEvent(
423 OrchestrationThread,
424 {
425 id: payload.threadId,
426 projectId: payload.projectId,
427 title: payload.title,
428 modelSelection: payload.modelSelection,
429 runtimeMode: payload.runtimeMode,
430 interactionMode: payload.interactionMode,
431 branch: payload.branch,
432 worktreePath: payload.worktreePath,
433 pullRequests: [],
434 branchPullRequest: null,
435 latestTurn: null,
436 createdAt: payload.createdAt,
437 updatedAt: payload.updatedAt,
438 archivedAt: null,
439 settledOverride: null,
440 settledAt: null,
441 unsettledAt: null,
442 activeOrderKey: null,
443 snoozedUntil: null,
444 snoozedAt: null,
445 deletedAt: null,
446 messages: [],
447 activities: [],
448 checkpoints: [],
449 session: null,
450 },
451 event.type,
452 "thread",
453 );
454 const existing = nextBase.threads.find((entry) => entry.id === thread.id);
455 return {
456 ...nextBase,
457 threads: existing
458 ? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
459 : [...nextBase.threads, thread],
460 };
461 });
462
463 case "thread.deleted":
464 return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe(
465 Effect.map((payload) => ({
466 ...nextBase,
467 threads: updateThread(nextBase.threads, payload.threadId, {
468 deletedAt: payload.deletedAt,
469 updatedAt: payload.deletedAt,
470 }),
471 })),
472 );
473
474 case "thread.archived":
475 return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(
476 Effect.map((payload) => ({
477 ...nextBase,
478 threads: updateThread(nextBase.threads, payload.threadId, {
479 archivedAt: payload.archivedAt,
480 titleRegeneration: null,
481 updatedAt: payload.updatedAt,
482 }),
483 })),
484 );
485
486 case "thread.unarchived":
487 return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(
488 Effect.map((payload) => ({
489 ...nextBase,
490 threads: updateThread(nextBase.threads, payload.threadId, {
491 archivedAt: null,
492 updatedAt: payload.updatedAt,
493 }),
494 })),
495 );
496
497 case "thread.settled":
498 return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
499 Effect.map((payload) => ({
500 ...nextBase,
501 threads: updateThread(nextBase.threads, payload.threadId, {
502 settledOverride: "settled",
503 settledAt: payload.settledAt,
504 unsettledAt: null,
505 activeOrderKey: null,
506 updatedAt: payload.updatedAt,
507 }),
508 })),
509 );
510
511 case "thread.unsettled":
512 return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, "payload").pipe(
513 Effect.map((payload) => {
514 const existing = nextBase.threads.find((thread) => thread.id === payload.threadId);
515 return {
516 ...nextBase,
517 threads: updateThread(nextBase.threads, payload.threadId, {
518 settledOverride: payload.reason === "user" ? "active" : null,
519 settledAt: null,
520 // Re-entry stamp for active-list ordering. A thread already
521 // pinned active keeps its stamp: the activity reset that clears
522 // the pin is not a re-entry and must not reorder the list.
523 unsettledAt:
524 existing?.settledOverride === "active"
525 ? (existing.unsettledAt ?? null)
526 : payload.updatedAt,
527 updatedAt: payload.updatedAt,
528 }),
529 };
530 }),
531 );
532
533 case "thread.snoozed":
534 return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
535 Effect.map((payload) => ({
536 ...nextBase,
537 threads: updateThread(nextBase.threads, payload.threadId, {
538 snoozedUntil: payload.snoozedUntil,
539 snoozedAt: payload.snoozedAt,
540 updatedAt: payload.updatedAt,
541 }),
542 })),
543 );
544
545 case "thread.unsnoozed":
546 return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
547 Effect.map((payload) => ({
548 ...nextBase,
549 threads: updateThread(nextBase.threads, payload.threadId, {
550 snoozedUntil: null,
551 snoozedAt: null,
552 updatedAt: payload.updatedAt,
553 }),
554 })),
555 );
556
557 case "thread.pinned":
558 return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
559 Effect.map((payload) => ({
560 ...nextBase,
561 threads: updateThread(nextBase.threads, payload.threadId, {
562 pinnedAt: payload.pinnedAt,
563 ...(payload.pinOrderKey !== undefined ? { pinOrderKey: payload.pinOrderKey } : {}),
564 updatedAt: payload.updatedAt,
565 }),
566 })),
567 );
568
569 case "thread.unpinned":
570 return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(
571 Effect.map((payload) => ({
572 ...nextBase,
573 threads: updateThread(nextBase.threads, payload.threadId, {
574 pinnedAt: null,
575 // Unpin clears the slot: re-pinning is "pin again", not "restore
576 // an ancient position".
577 pinOrderKey: null,
578 updatedAt: payload.updatedAt,
579 }),
580 })),
581 );
582
583 case "thread.pin-reordered":
584 return decodeForEvent(ThreadPinReorderedPayload, event.payload, event.type, "payload").pipe(
585 Effect.map((payload) => ({
586 ...nextBase,
587 threads: updateThread(nextBase.threads, payload.threadId, {
588 pinOrderKey: payload.orderKey,
589 updatedAt: payload.updatedAt,
590 }),
591 })),
592 );
593
594 case "thread.meta-updated":
595 return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
596 Effect.map((payload) => {
597 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
598 // Legacy single-link events replay into the link array so the
599 // derived linkedPullRequest and pullRequests never disagree.
600 const legacyLinkPatch =
601 thread !== undefined && payload.linkedPullRequest !== undefined
602 ? pullRequestsPatch(
603 thread,
604 legacyLinkToPullRequests(
605 thread,
606 nextBase.projects.find((project) => project.id === thread.projectId),
607 payload.linkedPullRequest,
608 payload.updatedAt,
609 ),
610 nextBase.projects,
611 )
612 : {};
613 return {
614 ...nextBase,
615 threads: updateThread(nextBase.threads, payload.threadId, {
616 ...(payload.title !== undefined ? { title: payload.title } : {}),
617 ...(payload.titleState !== undefined ? { titleState: payload.titleState } : {}),
618 ...(payload.titleRegeneration !== undefined
619 ? { titleRegeneration: payload.titleRegeneration }
620 : {}),
621 ...(payload.modelSelection !== undefined
622 ? { modelSelection: payload.modelSelection }
623 : {}),
624 ...(payload.branch !== undefined ? { branch: payload.branch } : {}),
625 ...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
626 ...(payload.activeOrderKey !== undefined
627 ? { activeOrderKey: payload.activeOrderKey }
628 : {}),
629 ...(payload.branchPullRequest !== undefined
630 ? { branchPullRequest: payload.branchPullRequest }
631 : {}),
632 ...legacyLinkPatch,
633 updatedAt: payload.updatedAt,
634 }),
635 };
636 }),
637 );
638
639 case "thread.pull-request-linked":
640 return decodeForEvent(
641 ThreadPullRequestLinkedPayload,
642 event.payload,
643 event.type,
644 "payload",
645 ).pipe(
646 Effect.map((payload) => {
647 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
648 if (!thread) {
649 return nextBase;
650 }
651 return {
652 ...nextBase,
653 threads: updateThread(nextBase.threads, payload.threadId, {
654 ...pullRequestsPatch(
655 thread,
656 upsertPullRequestLink(thread.pullRequests, payload.link),
657 nextBase.projects,
658 ),
659 updatedAt: payload.updatedAt,
660 }),
661 };
662 }),
663 );
664
665 case "thread.pull-request-unlinked":
666 return decodeForEvent(
667 ThreadPullRequestUnlinkedPayload,
668 event.payload,
669 event.type,
670 "payload",
671 ).pipe(
672 Effect.map((payload) => {
673 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
674 if (!thread) {
675 return nextBase;
676 }
677 return {
678 ...nextBase,
679 threads: updateThread(nextBase.threads, payload.threadId, {
680 ...pullRequestsPatch(
681 thread,
682 removePullRequestLink(thread.pullRequests, payload),
683 nextBase.projects,
684 ),
685 updatedAt: payload.updatedAt,
686 }),
687 };
688 }),
689 );
690
691 case "thread.pull-request-synced":
692 return decodeForEvent(
693 ThreadPullRequestSyncedPayload,
694 event.payload,
695 event.type,
696 "payload",
697 ).pipe(
698 Effect.map((payload) => {
699 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
700 // A sync for a link the user removed in the meantime is stale; drop it.
701 if (
702 !thread ||
703 !thread.pullRequests.some((link) => threadPullRequestKeysEqual(link, payload))
704 ) {
705 return nextBase;
706 }
707 const pullRequests = thread.pullRequests.map((link) =>
708 threadPullRequestKeysEqual(link, payload)
709 ? { ...link, snapshot: payload.snapshot, stack: payload.stack }
710 : link,
711 );
712 return {
713 ...nextBase,
714 threads: updateThread(nextBase.threads, payload.threadId, {
715 ...pullRequestsPatch(thread, pullRequests, nextBase.projects),
716 updatedAt: payload.updatedAt,
717 }),
718 };
719 }),
720 );
721
722 case "thread.runtime-mode-set":
723 return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(
724 Effect.map((payload) => ({
725 ...nextBase,
726 threads: updateThread(nextBase.threads, payload.threadId, {
727 runtimeMode: payload.runtimeMode,
728 updatedAt: payload.updatedAt,
729 }),
730 })),
731 );
732
733 case "thread.interaction-mode-set":
734 return decodeForEvent(
735 ThreadInteractionModeSetPayload,
736 event.payload,
737 event.type,
738 "payload",
739 ).pipe(
740 Effect.map((payload) => ({
741 ...nextBase,
742 threads: updateThread(nextBase.threads, payload.threadId, {
743 interactionMode: payload.interactionMode,
744 updatedAt: payload.updatedAt,
745 }),
746 })),
747 );
748
749 case "thread.message-sent":
750 return Effect.gen(function* () {
751 const payload = yield* decodeForEvent(
752 MessageSentPayloadSchema,
753 event.payload,
754 event.type,
755 "payload",
756 );
757 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
758 if (!thread) {
759 return nextBase;
760 }
761
762 const message: OrchestrationMessage = yield* decodeForEvent(
763 OrchestrationMessage,
764 {
765 id: payload.messageId,
766 role: payload.role,
767 text: payload.text,
768 ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}),
769 ...(payload.context !== undefined ? { context: payload.context } : {}),
770 turnId: payload.turnId,
771 streaming: payload.streaming,
772 createdAt: payload.createdAt,
773 updatedAt: payload.updatedAt,
774 },
775 event.type,
776 "message",
777 );
778
779 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
780 const messages = existingMessage
781 ? thread.messages.map((entry) =>
782 entry.id === message.id
783 ? {
784 ...entry,
785 text: message.streaming
786 ? `${entry.text}${message.text}`
787 : message.text.length > 0
788 ? message.text
789 : entry.text,
790 streaming: message.streaming,
791 updatedAt: message.updatedAt,
792 turnId: message.turnId,
793 ...(message.attachments !== undefined
794 ? { attachments: message.attachments }
795 : {}),
796 ...(message.context !== undefined ? { context: message.context } : {}),
797 }
798 : entry,
799 )
800 : [...thread.messages, message];
801 const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);
802
803 return {
804 ...nextBase,
805 threads: updateThread(nextBase.threads, payload.threadId, {
806 messages: cappedMessages,
807 updatedAt: event.occurredAt,
808 }),
809 };
810 });
811
812 case "thread.session-set":
813 return Effect.gen(function* () {
814 const payload = yield* decodeForEvent(
815 ThreadSessionSetPayload,
816 event.payload,
817 event.type,
818 "payload",
819 );
820 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
821 if (!thread) {
822 return nextBase;
823 }
824
825 const session: OrchestrationSession = yield* decodeForEvent(
826 OrchestrationSession,
827 payload.session,
828 event.type,
829 "session",
830 );
831
832 // Leaving the "running" session status is the turn-end signal: settle
833 // a still-running latest turn so its duration reflects the whole turn.
834 const settledTurnState = settledTurnStateForSessionStatus(session.status);
835 return {
836 ...nextBase,
837 threads: updateThread(nextBase.threads, payload.threadId, {
838 session,
839 latestTurn:
840 session.status === "running" && session.activeTurnId !== null
841 ? {
842 turnId: session.activeTurnId,
843 state: "running",
844 requestedAt:
845 thread.latestTurn?.turnId === session.activeTurnId
846 ? thread.latestTurn.requestedAt
847 : session.updatedAt,
848 startedAt:
849 thread.latestTurn?.turnId === session.activeTurnId
850 ? (thread.latestTurn.startedAt ?? session.updatedAt)
851 : session.updatedAt,
852 completedAt: null,
853 assistantMessageId:
854 thread.latestTurn?.turnId === session.activeTurnId
855 ? thread.latestTurn.assistantMessageId
856 : null,
857 }
858 : thread.latestTurn !== null &&
859 thread.latestTurn.state === "running" &&
860 settledTurnState !== null
861 ? {
862 ...thread.latestTurn,
863 state: settledTurnState,
864 // A running turn's completedAt can only hold a mid-turn
865 // placeholder checkpoint timestamp — the session leaving
866 // "running" is the authoritative turn end.
867 completedAt: session.updatedAt,
868 }
869 : thread.latestTurn,
870 updatedAt: event.occurredAt,
871 }),
872 };
873 });
874
875 case "thread.proposed-plan-upserted":
876 return Effect.gen(function* () {
877 const payload = yield* decodeForEvent(
878 ThreadProposedPlanUpsertedPayload,
879 event.payload,
880 event.type,
881 "payload",
882 );
883 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
884 if (!thread) {
885 return nextBase;
886 }
887
888 const proposedPlans = [
889 ...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),
890 payload.proposedPlan,
891 ]
892 .toSorted(
893 (left, right) =>
894 left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
895 )
896 .slice(-200);
897
898 return {
899 ...nextBase,
900 threads: updateThread(nextBase.threads, payload.threadId, {
901 proposedPlans,
902 updatedAt: event.occurredAt,
903 }),
904 };
905 });
906
907 case "thread.turn-diff-completed":
908 return Effect.gen(function* () {
909 const payload = yield* decodeForEvent(
910 ThreadTurnDiffCompletedPayload,
911 event.payload,
912 event.type,
913 "payload",
914 );
915 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
916 if (!thread) {
917 return nextBase;
918 }
919
920 const checkpoint = yield* decodeForEvent(
921 OrchestrationCheckpointSummary,
922 {
923 turnId: payload.turnId,
924 checkpointTurnCount: payload.checkpointTurnCount,
925 checkpointRef: payload.checkpointRef,
926 status: payload.status,
927 files: payload.files,
928 assistantMessageId: payload.assistantMessageId,
929 completedAt: payload.completedAt,
930 },
931 event.type,
932 "checkpoint",
933 );
934
935 // Do not let a placeholder (status "missing") overwrite a checkpoint
936 // that has already been captured with a real git ref (status "ready").
937 // ProviderRuntimeIngestion may fire multiple turn.diff.updated events
938 // per turn; without this guard later placeholders would clobber the
939 // real capture dispatched by CheckpointReactor.
940 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
941 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
942 return nextBase;
943 }
944
945 const checkpoints = [
946 ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
947 checkpoint,
948 ]
949 .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
950 .slice(-MAX_THREAD_CHECKPOINTS);
951
952 // Mid-turn diff updates produce placeholder checkpoints; record the
953 // checkpoint, but don't settle a turn its session is still running.
954 const turnStillRunning =
955 thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
956
957 return {
958 ...nextBase,
959 threads: updateThread(nextBase.threads, payload.threadId, {
960 checkpoints,
961 latestTurn: turnStillRunning
962 ? thread.latestTurn
963 : {
964 turnId: payload.turnId,
965 state:
966 thread.latestTurn?.turnId === payload.turnId &&
967 thread.latestTurn.state === "interrupted"
968 ? "interrupted"
969 : checkpointStatusToLatestTurnState(payload.status),
970 requestedAt:
971 thread.latestTurn?.turnId === payload.turnId
972 ? thread.latestTurn.requestedAt
973 : payload.completedAt,
974 startedAt:
975 thread.latestTurn?.turnId === payload.turnId
976 ? (thread.latestTurn.startedAt ?? payload.completedAt)
977 : payload.completedAt,
978 completedAt: payload.completedAt,
979 assistantMessageId: payload.assistantMessageId,
980 },
981 updatedAt: event.occurredAt,
982 }),
983 };
984 });
985
986 case "thread.reverted":
987 return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(
988 Effect.map((payload) => {
989 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
990 if (!thread) {
991 return nextBase;
992 }
993
994 const checkpoints = thread.checkpoints
995 .filter((entry) => entry.checkpointTurnCount <= payload.turnCount)
996 .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
997 .slice(-MAX_THREAD_CHECKPOINTS);
998 const retainedTurnIds = new Set(checkpoints.map((checkpoint) => checkpoint.turnId));
999 const messages = retainThreadMessagesAfterRevert(
1000 thread.messages,
1001 retainedTurnIds,
1002 payload.turnCount,
1003 ).slice(-MAX_THREAD_MESSAGES);
1004 const proposedPlans = retainThreadProposedPlansAfterRevert(
1005 thread.proposedPlans,
1006 retainedTurnIds,
1007 ).slice(-200);
1008 const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
1009
1010 const latestCheckpoint = checkpoints.at(-1) ?? null;
1011 const latestTurn =
1012 latestCheckpoint === null
1013 ? null
1014 : {
1015 turnId: latestCheckpoint.turnId,
1016 state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
1017 requestedAt: latestCheckpoint.completedAt,
1018 startedAt: latestCheckpoint.completedAt,
1019 completedAt: latestCheckpoint.completedAt,
1020 assistantMessageId: latestCheckpoint.assistantMessageId,
1021 };
1022
1023 return {
1024 ...nextBase,
1025 threads: updateThread(nextBase.threads, payload.threadId, {
1026 checkpoints,
1027 messages,
1028 proposedPlans,
1029 activities,
1030 latestTurn,
1031 updatedAt: event.occurredAt,
1032 }),
1033 };
1034 }),
1035 );
1036
1037 case "thread.activity-appended":
1038 return decodeForEvent(
1039 ThreadActivityAppendedPayload,
1040 event.payload,
1041 event.type,
1042 "payload",
1043 ).pipe(
1044 Effect.map((payload) => {
1045 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
1046 if (!thread) {
1047 return nextBase;
1048 }
1049
1050 const activities = retainThreadActivities(
1051 [
1052 ...thread.activities.filter((entry) => entry.id !== payload.activity.id),
1053 payload.activity,
1054 ].toSorted(compareThreadActivities),
1055 );
1056
1057 return {
1058 ...nextBase,
1059 threads: updateThread(nextBase.threads, payload.threadId, {
1060 activities,
1061 updatedAt: event.occurredAt,
1062 }),
1063 };
1064 }),
1065 );
1066
1067 default:
1068 return Effect.succeed(nextBase);
1069 }
1070}