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.actualModel !== undefined ? { actualModel: payload.actualModel } : {}),
769 ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}),
770 ...(payload.context !== undefined ? { context: payload.context } : {}),
771 turnId: payload.turnId,
772 streaming: payload.streaming,
773 createdAt: payload.createdAt,
774 updatedAt: payload.updatedAt,
775 },
776 event.type,
777 "message",
778 );
779
780 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
781 const messages = existingMessage
782 ? thread.messages.map((entry) =>
783 entry.id === message.id
784 ? {
785 ...entry,
786 text: message.streaming
787 ? `${entry.text}${message.text}`
788 : message.text.length > 0
789 ? message.text
790 : entry.text,
791 streaming: message.streaming,
792 updatedAt: message.updatedAt,
793 turnId: message.turnId,
794 ...(message.actualModel !== undefined
795 ? { actualModel: message.actualModel }
796 : {}),
797 ...(message.attachments !== undefined
798 ? { attachments: message.attachments }
799 : {}),
800 ...(message.context !== undefined ? { context: message.context } : {}),
801 }
802 : entry,
803 )
804 : [...thread.messages, message];
805 const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);
806
807 return {
808 ...nextBase,
809 threads: updateThread(nextBase.threads, payload.threadId, {
810 messages: cappedMessages,
811 updatedAt: event.occurredAt,
812 }),
813 };
814 });
815
816 case "thread.session-set":
817 return Effect.gen(function* () {
818 const payload = yield* decodeForEvent(
819 ThreadSessionSetPayload,
820 event.payload,
821 event.type,
822 "payload",
823 );
824 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
825 if (!thread) {
826 return nextBase;
827 }
828
829 const session: OrchestrationSession = yield* decodeForEvent(
830 OrchestrationSession,
831 payload.session,
832 event.type,
833 "session",
834 );
835
836 // Leaving the "running" session status is the turn-end signal: settle
837 // a still-running latest turn so its duration reflects the whole turn.
838 const settledTurnState = settledTurnStateForSessionStatus(session.status);
839 return {
840 ...nextBase,
841 threads: updateThread(nextBase.threads, payload.threadId, {
842 session,
843 latestTurn:
844 session.status === "running" && session.activeTurnId !== null
845 ? {
846 turnId: session.activeTurnId,
847 state: "running",
848 requestedAt:
849 thread.latestTurn?.turnId === session.activeTurnId
850 ? thread.latestTurn.requestedAt
851 : session.updatedAt,
852 startedAt:
853 thread.latestTurn?.turnId === session.activeTurnId
854 ? (thread.latestTurn.startedAt ?? session.updatedAt)
855 : session.updatedAt,
856 completedAt: null,
857 assistantMessageId:
858 thread.latestTurn?.turnId === session.activeTurnId
859 ? thread.latestTurn.assistantMessageId
860 : null,
861 }
862 : thread.latestTurn !== null &&
863 thread.latestTurn.state === "running" &&
864 settledTurnState !== null
865 ? {
866 ...thread.latestTurn,
867 state: settledTurnState,
868 // A running turn's completedAt can only hold a mid-turn
869 // placeholder checkpoint timestamp — the session leaving
870 // "running" is the authoritative turn end.
871 completedAt: session.updatedAt,
872 }
873 : thread.latestTurn,
874 updatedAt: event.occurredAt,
875 }),
876 };
877 });
878
879 case "thread.proposed-plan-upserted":
880 return Effect.gen(function* () {
881 const payload = yield* decodeForEvent(
882 ThreadProposedPlanUpsertedPayload,
883 event.payload,
884 event.type,
885 "payload",
886 );
887 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
888 if (!thread) {
889 return nextBase;
890 }
891
892 const proposedPlans = [
893 ...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),
894 payload.proposedPlan,
895 ]
896 .toSorted(
897 (left, right) =>
898 left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
899 )
900 .slice(-200);
901
902 return {
903 ...nextBase,
904 threads: updateThread(nextBase.threads, payload.threadId, {
905 proposedPlans,
906 updatedAt: event.occurredAt,
907 }),
908 };
909 });
910
911 case "thread.turn-diff-completed":
912 return Effect.gen(function* () {
913 const payload = yield* decodeForEvent(
914 ThreadTurnDiffCompletedPayload,
915 event.payload,
916 event.type,
917 "payload",
918 );
919 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
920 if (!thread) {
921 return nextBase;
922 }
923
924 const checkpoint = yield* decodeForEvent(
925 OrchestrationCheckpointSummary,
926 {
927 turnId: payload.turnId,
928 checkpointTurnCount: payload.checkpointTurnCount,
929 checkpointRef: payload.checkpointRef,
930 status: payload.status,
931 files: payload.files,
932 assistantMessageId: payload.assistantMessageId,
933 completedAt: payload.completedAt,
934 },
935 event.type,
936 "checkpoint",
937 );
938
939 // Do not let a placeholder (status "missing") overwrite a checkpoint
940 // that has already been captured with a real git ref (status "ready").
941 // ProviderRuntimeIngestion may fire multiple turn.diff.updated events
942 // per turn; without this guard later placeholders would clobber the
943 // real capture dispatched by CheckpointReactor.
944 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
945 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
946 return nextBase;
947 }
948
949 const checkpoints = [
950 ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
951 checkpoint,
952 ]
953 .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
954 .slice(-MAX_THREAD_CHECKPOINTS);
955
956 // Mid-turn diff updates produce placeholder checkpoints; record the
957 // checkpoint, but don't settle a turn its session is still running.
958 const turnStillRunning =
959 thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
960
961 return {
962 ...nextBase,
963 threads: updateThread(nextBase.threads, payload.threadId, {
964 checkpoints,
965 latestTurn: turnStillRunning
966 ? thread.latestTurn
967 : {
968 turnId: payload.turnId,
969 state:
970 thread.latestTurn?.turnId === payload.turnId &&
971 thread.latestTurn.state === "interrupted"
972 ? "interrupted"
973 : checkpointStatusToLatestTurnState(payload.status),
974 requestedAt:
975 thread.latestTurn?.turnId === payload.turnId
976 ? thread.latestTurn.requestedAt
977 : payload.completedAt,
978 startedAt:
979 thread.latestTurn?.turnId === payload.turnId
980 ? (thread.latestTurn.startedAt ?? payload.completedAt)
981 : payload.completedAt,
982 completedAt: payload.completedAt,
983 assistantMessageId: payload.assistantMessageId,
984 },
985 updatedAt: event.occurredAt,
986 }),
987 };
988 });
989
990 case "thread.reverted":
991 return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(
992 Effect.map((payload) => {
993 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
994 if (!thread) {
995 return nextBase;
996 }
997
998 const checkpoints = thread.checkpoints
999 .filter((entry) => entry.checkpointTurnCount <= payload.turnCount)
1000 .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
1001 .slice(-MAX_THREAD_CHECKPOINTS);
1002 const retainedTurnIds = new Set(checkpoints.map((checkpoint) => checkpoint.turnId));
1003 const messages = retainThreadMessagesAfterRevert(
1004 thread.messages,
1005 retainedTurnIds,
1006 payload.turnCount,
1007 ).slice(-MAX_THREAD_MESSAGES);
1008 const proposedPlans = retainThreadProposedPlansAfterRevert(
1009 thread.proposedPlans,
1010 retainedTurnIds,
1011 ).slice(-200);
1012 const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
1013
1014 const latestCheckpoint = checkpoints.at(-1) ?? null;
1015 const latestTurn =
1016 latestCheckpoint === null
1017 ? null
1018 : {
1019 turnId: latestCheckpoint.turnId,
1020 state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
1021 requestedAt: latestCheckpoint.completedAt,
1022 startedAt: latestCheckpoint.completedAt,
1023 completedAt: latestCheckpoint.completedAt,
1024 assistantMessageId: latestCheckpoint.assistantMessageId,
1025 };
1026
1027 return {
1028 ...nextBase,
1029 threads: updateThread(nextBase.threads, payload.threadId, {
1030 checkpoints,
1031 messages,
1032 proposedPlans,
1033 activities,
1034 latestTurn,
1035 updatedAt: event.occurredAt,
1036 }),
1037 };
1038 }),
1039 );
1040
1041 case "thread.activity-appended":
1042 return decodeForEvent(
1043 ThreadActivityAppendedPayload,
1044 event.payload,
1045 event.type,
1046 "payload",
1047 ).pipe(
1048 Effect.map((payload) => {
1049 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
1050 if (!thread) {
1051 return nextBase;
1052 }
1053
1054 const activities = retainThreadActivities(
1055 [
1056 ...thread.activities.filter((entry) => entry.id !== payload.activity.id),
1057 payload.activity,
1058 ].toSorted(compareThreadActivities),
1059 );
1060
1061 return {
1062 ...nextBase,
1063 threads: updateThread(nextBase.threads, payload.threadId, {
1064 activities,
1065 updatedAt: event.occurredAt,
1066 }),
1067 };
1068 }),
1069 );
1070
1071 default:
1072 return Effect.succeed(nextBase);
1073 }
1074}