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