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