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