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} from "@t3tools/contracts";
17import {
18 legacyLinkedPullRequestOf,
19 legacyThreadPullRequestKey,
20 threadPullRequestKeysEqual,
21} from "@t3tools/shared/threadPullRequests";
22import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
23import * as Effect from "effect/Effect";
24import * as Schema from "effect/Schema";
25import * as Predicate from "effect/Predicate";
26
27import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts";
28import {
29 MessageSentPayloadSchema,
30 ProjectCreatedPayload,
31 ProjectDeletedPayload,
32 ProjectMetaUpdatedPayload,
33 ThreadActivityAppendedPayload,
34 ThreadArchivedPayload,
35 ThreadCheckpointRevertRequestedPayload,
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 ThreadTurnStartRequestedPayload,
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) => index >= recentStart || pendingActivities.has(activity),
82 );
83}
84
85function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
86 if (status === "error") return "error" as const;
87 // Match SQL and client projections: a missing git ref is not an interruption.
88 return "completed" as const;
89}
90
91function turnStartRequestIdClearedByActivity(
92 activity: OrchestrationThread["activities"][number],
93): string | null {
94 if (
95 (activity.kind !== "context-compaction" &&
96 activity.kind !== "provider.turn.start.failed" &&
97 activity.kind !== "provider.auth.signed-out") ||
98 !Predicate.isObject(activity.payload)
99 ) {
100 return null;
101 }
102 return typeof activity.payload.requestId === "string" ? activity.payload.requestId : null;
103}
104
105function activityClearsPendingTurnStart(
106 thread: OrchestrationThread,
107 activity: OrchestrationThread["activities"][number],
108): boolean {
109 return (
110 thread.pendingTurnStartMessageId != null &&
111 turnStartRequestIdClearedByActivity(activity) === thread.pendingTurnStartMessageId
112 );
113}
114
115/**
116 * Turn state to settle a still-running latest turn with when its session
117 * leaves the "running" status, or null while the session is (re)starting or
118 * running and the turn must stay unsettled.
119 */
120function settledTurnStateForSessionStatus(
121 status: OrchestrationSession["status"],
122): "completed" | "interrupted" | "error" | null {
123 switch (status) {
124 case "idle":
125 case "ready":
126 return "completed";
127 case "error":
128 return "error";
129 case "interrupted":
130 case "stopped":
131 return "interrupted";
132 case "starting":
133 case "running":
134 return null;
135 }
136}
137
138function updateThread(
139 threads: ReadonlyArray<OrchestrationThread>,
140 threadId: ThreadId,
141 patch: ThreadPatch,
142): OrchestrationThread[] {
143 return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
144}
145
146/** Patch that swaps a thread's links and re-derives the legacy single-PR field from them. */
147function pullRequestsPatch(
148 thread: Pick<OrchestrationThread, "projectId">,
149 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
150 projects: OrchestrationReadModel["projects"],
151): Pick<OrchestrationThread, "pullRequests" | "linkedPullRequest"> {
152 return {
153 pullRequests,
154 linkedPullRequest: legacyLinkedPullRequestOf(
155 pullRequests,
156 thread.projectId,
157 projects.find((project) => project.id === thread.projectId)?.repositoryIdentity,
158 ),
159 };
160}
161
162function upsertPullRequestLink(
163 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
164 link: ThreadPullRequestLink,
165): ReadonlyArray<ThreadPullRequestLink> {
166 const index = pullRequests.findIndex((entry) => threadPullRequestKeysEqual(entry, link));
167 return index === -1
168 ? [...pullRequests, link]
169 : pullRequests.map((entry, entryIndex) => (entryIndex === index ? link : entry));
170}
171
172function removePullRequestLink(
173 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
174 key: ThreadPullRequestKey,
175): ReadonlyArray<ThreadPullRequestLink> {
176 return pullRequests.filter((entry) => !threadPullRequestKeysEqual(entry, key));
177}
178
179/**
180 * Host for a legacy `linkedPullRequest` being replayed into the link array.
181 * Legacy links never carried one; the project's canonical key
182 * (`<host>/<owner>/<name>`) is the best witness, then the link URL.
183 */
184function legacyPullRequestHost(
185 project: OrchestrationProject | undefined,
186 linked: ThreadLinkedPullRequest,
187): string {
188 const canonicalHost = project?.repositoryIdentity?.canonicalKey.split("/")[0];
189 if (canonicalHost) return canonicalHost.toLowerCase();
190 try {
191 return new URL(linked.url).hostname.toLowerCase();
192 } catch {
193 return "unknown";
194 }
195}
196
197function legacyLinkToPullRequests(
198 thread: Pick<OrchestrationThread, "pullRequests">,
199 project: OrchestrationProject | undefined,
200 linked: ThreadLinkedPullRequest | null,
201 linkedAt: string,
202): ReadonlyArray<ThreadPullRequestLink> {
203 // The legacy field held one user-chosen link, so null clears exactly the
204 // manual ones and leaves created/agent/stack links alone.
205 const withoutManual = thread.pullRequests.filter((entry) => entry.source !== "manual");
206 if (linked === null) return withoutManual;
207 return upsertPullRequestLink(withoutManual, {
208 ...legacyThreadPullRequestKey(linked, legacyPullRequestHost(project, linked)),
209 url: linked.url,
210 source: "manual",
211 linkedAt,
212 snapshot: null,
213 stack: null,
214 });
215}
216
217function decodeForEvent<A>(
218 schema: Schema.Decoder<A, never>,
219 value: unknown,
220 eventType: OrchestrationEvent["type"],
221 field: string,
222): Effect.Effect<A, OrchestrationProjectorDecodeError> {
223 return Schema.decodeUnknownEffect(schema)(value).pipe(
224 Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
225 );
226}
227
228function retainThreadMessagesAfterRevert(
229 messages: ReadonlyArray<OrchestrationMessage>,
230 retainedTurnIds: ReadonlySet<string>,
231 turnCount: number,
232 preservedMessageIds: ReadonlySet<string>,
233): ReadonlyArray<OrchestrationMessage> {
234 const retainedMessageIds = new Set(preservedMessageIds);
235 for (const message of messages) {
236 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
237 retainedMessageIds.add(message.id);
238 continue;
239 }
240 if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
241 retainedMessageIds.add(message.id);
242 }
243 }
244
245 // Queued messages preserved across the revert are not part of the retained
246 // turn history, so they must not consume the historical-message quota below.
247 const retainedUserCount = messages.filter(
248 (message) =>
249 message.role === "user" &&
250 !isImportedAgentSessionMessageId(message.id) &&
251 retainedMessageIds.has(message.id) &&
252 !preservedMessageIds.has(message.id),
253 ).length;
254 const missingUserCount = Math.max(0, turnCount - retainedUserCount);
255 if (missingUserCount > 0) {
256 const fallbackUserMessages = messages
257 .filter(
258 (message) =>
259 message.role === "user" &&
260 !retainedMessageIds.has(message.id) &&
261 (message.turnId === null || retainedTurnIds.has(message.turnId)),
262 )
263 .toSorted(
264 (left, right) =>
265 compareDateTimeStrings(left.createdAt, right.createdAt) ||
266 left.id.localeCompare(right.id),
267 )
268 .slice(0, missingUserCount);
269 for (const message of fallbackUserMessages) {
270 retainedMessageIds.add(message.id);
271 }
272 }
273
274 const retainedAssistantCount = messages.filter(
275 (message) =>
276 message.role === "assistant" &&
277 !isImportedAgentSessionMessageId(message.id) &&
278 retainedMessageIds.has(message.id),
279 ).length;
280 const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
281 if (missingAssistantCount > 0) {
282 const fallbackAssistantMessages = messages
283 .filter(
284 (message) =>
285 message.role === "assistant" &&
286 !retainedMessageIds.has(message.id) &&
287 (message.turnId === null || retainedTurnIds.has(message.turnId)),
288 )
289 .toSorted(
290 (left, right) =>
291 compareDateTimeStrings(left.createdAt, right.createdAt) ||
292 left.id.localeCompare(right.id),
293 )
294 .slice(0, missingAssistantCount);
295 for (const message of fallbackAssistantMessages) {
296 retainedMessageIds.add(message.id);
297 }
298 }
299
300 return messages.filter((message) => retainedMessageIds.has(message.id));
301}
302
303function retainThreadActivitiesAfterRevert(
304 activities: ReadonlyArray<OrchestrationThread["activities"][number]>,
305 retainedTurnIds: ReadonlySet<string>,
306): ReadonlyArray<OrchestrationThread["activities"][number]> {
307 return activities.filter(
308 (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
309 );
310}
311
312function retainThreadProposedPlansAfterRevert(
313 proposedPlans: ReadonlyArray<OrchestrationThread["proposedPlans"][number]>,
314 retainedTurnIds: ReadonlySet<string>,
315): ReadonlyArray<OrchestrationThread["proposedPlans"][number]> {
316 return proposedPlans.filter(
317 (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
318 );
319}
320
321function compareThreadActivities(
322 left: OrchestrationThread["activities"][number],
323 right: OrchestrationThread["activities"][number],
324): number {
325 if (left.sequence !== undefined && right.sequence !== undefined) {
326 if (left.sequence !== right.sequence) {
327 return left.sequence - right.sequence;
328 }
329 } else if (left.sequence !== undefined) {
330 return 1;
331 } else if (right.sequence !== undefined) {
332 return -1;
333 }
334
335 return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
336}
337
338export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
339 return {
340 snapshotSequence: 0,
341 projects: [],
342 threads: [],
343 updatedAt: nowIso,
344 };
345}
346
347export function projectEvent(
348 model: OrchestrationReadModel,
349 event: OrchestrationEvent,
350): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {
351 const nextBase: OrchestrationReadModel = {
352 ...model,
353 snapshotSequence: event.sequence,
354 updatedAt: event.occurredAt,
355 };
356
357 switch (event.type) {
358 case "project.created":
359 return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(
360 Effect.map((payload) => {
361 const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);
362 const nextProject = {
363 id: payload.projectId,
364 title: payload.title,
365 workspaceRoot: payload.workspaceRoot,
366 defaultModelSelection: payload.defaultModelSelection,
367 defaultThreadEnvMode: null,
368 autoPull: false,
369 faviconPath: payload.faviconPath ?? null,
370 projectIcon: payload.projectIcon ?? null,
371 scripts: payload.scripts,
372 createdAt: payload.createdAt,
373 updatedAt: payload.updatedAt,
374 deletedAt: null,
375 };
376
377 return {
378 ...nextBase,
379 projects: existing
380 ? nextBase.projects.map((entry) =>
381 entry.id === payload.projectId ? nextProject : entry,
382 )
383 : [...nextBase.projects, nextProject],
384 };
385 }),
386 );
387
388 case "project.meta-updated":
389 return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
390 Effect.map((payload) => ({
391 ...nextBase,
392 projects: nextBase.projects.map((project) =>
393 project.id === payload.projectId
394 ? {
395 ...project,
396 ...(payload.title !== undefined ? { title: payload.title } : {}),
397 ...(payload.workspaceRoot !== undefined
398 ? { workspaceRoot: payload.workspaceRoot }
399 : {}),
400 ...(payload.defaultModelSelection !== undefined
401 ? { defaultModelSelection: payload.defaultModelSelection }
402 : {}),
403 ...(payload.defaultThreadEnvMode !== undefined
404 ? { defaultThreadEnvMode: payload.defaultThreadEnvMode }
405 : {}),
406 ...(payload.autoPull !== undefined ? { autoPull: payload.autoPull } : {}),
407 ...(payload.faviconPath !== undefined
408 ? { faviconPath: payload.faviconPath }
409 : {}),
410 ...(payload.projectIcon !== undefined
411 ? { projectIcon: payload.projectIcon }
412 : {}),
413 ...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
414 updatedAt: payload.updatedAt,
415 }
416 : project,
417 ),
418 })),
419 );
420
421 case "project.deleted":
422 return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe(
423 Effect.map((payload) => ({
424 ...nextBase,
425 projects: nextBase.projects.map((project) =>
426 project.id === payload.projectId
427 ? {
428 ...project,
429 deletedAt: payload.deletedAt,
430 updatedAt: payload.deletedAt,
431 }
432 : project,
433 ),
434 })),
435 );
436
437 case "thread.created":
438 return Effect.gen(function* () {
439 const payload = yield* decodeForEvent(
440 ThreadCreatedPayload,
441 event.payload,
442 event.type,
443 "payload",
444 );
445 const thread: OrchestrationThread = yield* decodeForEvent(
446 OrchestrationThread,
447 {
448 id: payload.threadId,
449 projectId: payload.projectId,
450 title: payload.title,
451 modelSelection: payload.modelSelection,
452 runtimeMode: payload.runtimeMode,
453 interactionMode: payload.interactionMode,
454 branch: payload.branch,
455 worktreePath: payload.worktreePath,
456 pullRequests: [],
457 branchPullRequest: null,
458 latestTurn: null,
459 createdAt: payload.createdAt,
460 updatedAt: payload.updatedAt,
461 archivedAt: null,
462 settledOverride: null,
463 settledAt: null,
464 unsettledAt: null,
465 activeOrderKey: null,
466 snoozedUntil: null,
467 snoozedAt: null,
468 deletedAt: null,
469 messages: [],
470 activities: [],
471 checkpoints: [],
472 session: null,
473 },
474 event.type,
475 "thread",
476 );
477 const existing = nextBase.threads.find((entry) => entry.id === thread.id);
478 return {
479 ...nextBase,
480 threads: existing
481 ? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
482 : [...nextBase.threads, thread],
483 };
484 });
485
486 case "thread.deleted":
487 return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe(
488 Effect.map((payload) => ({
489 ...nextBase,
490 threads: updateThread(nextBase.threads, payload.threadId, {
491 deletedAt: payload.deletedAt,
492 updatedAt: payload.deletedAt,
493 }),
494 })),
495 );
496
497 case "thread.archived":
498 return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(
499 Effect.map((payload) => ({
500 ...nextBase,
501 threads: updateThread(nextBase.threads, payload.threadId, {
502 archivedAt: payload.archivedAt,
503 titleRegeneration: null,
504 updatedAt: payload.updatedAt,
505 }),
506 })),
507 );
508
509 case "thread.unarchived":
510 return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(
511 Effect.map((payload) => ({
512 ...nextBase,
513 threads: updateThread(nextBase.threads, payload.threadId, {
514 archivedAt: null,
515 updatedAt: payload.updatedAt,
516 }),
517 })),
518 );
519
520 case "thread.settled":
521 return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
522 Effect.map((payload) => ({
523 ...nextBase,
524 threads: updateThread(nextBase.threads, payload.threadId, {
525 settledOverride: "settled",
526 settledAt: payload.settledAt,
527 unsettledAt: null,
528 activeOrderKey: null,
529 updatedAt: payload.updatedAt,
530 }),
531 })),
532 );
533
534 case "thread.unsettled":
535 return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, "payload").pipe(
536 Effect.map((payload) => {
537 const existing = nextBase.threads.find((thread) => thread.id === payload.threadId);
538 return {
539 ...nextBase,
540 threads: updateThread(nextBase.threads, payload.threadId, {
541 settledOverride: payload.reason === "user" ? "active" : null,
542 settledAt: null,
543 // Re-entry stamp for active-list ordering. A thread already
544 // pinned active keeps its stamp: the activity reset that clears
545 // the pin is not a re-entry and must not reorder the list.
546 unsettledAt:
547 existing?.settledOverride === "active"
548 ? (existing.unsettledAt ?? null)
549 : payload.updatedAt,
550 updatedAt: payload.updatedAt,
551 }),
552 };
553 }),
554 );
555
556 case "thread.snoozed":
557 return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
558 Effect.map((payload) => ({
559 ...nextBase,
560 threads: updateThread(nextBase.threads, payload.threadId, {
561 snoozedUntil: payload.snoozedUntil,
562 snoozedAt: payload.snoozedAt,
563 updatedAt: payload.updatedAt,
564 }),
565 })),
566 );
567
568 case "thread.unsnoozed":
569 return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
570 Effect.map((payload) => ({
571 ...nextBase,
572 threads: updateThread(nextBase.threads, payload.threadId, {
573 snoozedUntil: null,
574 snoozedAt: null,
575 updatedAt: payload.updatedAt,
576 }),
577 })),
578 );
579
580 case "thread.pinned":
581 return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
582 Effect.map((payload) => ({
583 ...nextBase,
584 threads: updateThread(nextBase.threads, payload.threadId, {
585 pinnedAt: payload.pinnedAt,
586 ...(payload.pinOrderKey !== undefined ? { pinOrderKey: payload.pinOrderKey } : {}),
587 updatedAt: payload.updatedAt,
588 }),
589 })),
590 );
591
592 case "thread.unpinned":
593 return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(
594 Effect.map((payload) => ({
595 ...nextBase,
596 threads: updateThread(nextBase.threads, payload.threadId, {
597 pinnedAt: null,
598 // Unpin clears the slot: re-pinning is "pin again", not "restore
599 // an ancient position".
600 pinOrderKey: null,
601 updatedAt: payload.updatedAt,
602 }),
603 })),
604 );
605
606 case "thread.pin-reordered":
607 return decodeForEvent(ThreadPinReorderedPayload, event.payload, event.type, "payload").pipe(
608 Effect.map((payload) => ({
609 ...nextBase,
610 threads: updateThread(nextBase.threads, payload.threadId, {
611 pinOrderKey: payload.orderKey,
612 updatedAt: payload.updatedAt,
613 }),
614 })),
615 );
616
617 case "thread.meta-updated":
618 return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
619 Effect.map((payload) => {
620 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
621 if (!thread) return nextBase;
622 const acknowledgement = payload.turnStartAcknowledged;
623 const rendezvous = thread.turnStartSubmissionRendezvous ?? null;
624 const acknowledgedRequest =
625 acknowledgement === undefined
626 ? undefined
627 : rendezvous?.requests.find(
628 (request) => request.messageId === acknowledgement.messageId,
629 );
630 const acknowledgedTurnAlreadyRunning =
631 acknowledgement !== undefined &&
632 thread.session?.status === "running" &&
633 thread.session.activeTurnId === acknowledgement.turnId;
634 const acknowledgedTurnAlreadyObserved =
635 acknowledgement !== undefined &&
636 (acknowledgedRequest?.observedTurnIds ?? []).includes(acknowledgement.turnId);
637 // A provider can finish a turn before its start acknowledgement
638 // lands; the settled turn can never consume the submission.
639 const acknowledgedTurnAlreadySettled =
640 acknowledgement !== undefined &&
641 thread.latestTurn !== null &&
642 thread.latestTurn.turnId === acknowledgement.turnId &&
643 thread.latestTurn.state !== "running";
644 // A stopped or interrupted session can never surface the
645 // acknowledged turn, so the submission is resolved rather than
646 // recorded.
647 const acknowledgedSessionDead =
648 acknowledgement !== undefined &&
649 (thread.session?.status === "stopped" || thread.session?.status === "interrupted");
650 const acknowledgementAlreadyAdopted =
651 acknowledgedTurnAlreadyRunning ||
652 acknowledgedTurnAlreadyObserved ||
653 acknowledgedTurnAlreadySettled ||
654 acknowledgedSessionDead;
655 const remainingRequests =
656 acknowledgement === undefined
657 ? (rendezvous?.requests ?? [])
658 : (rendezvous?.requests ?? []).filter(
659 (request) => request.messageId !== acknowledgement.messageId,
660 );
661 // Legacy single-link events replay into the link array so the
662 // derived linkedPullRequest and pullRequests never disagree.
663 const legacyLinkPatch =
664 payload.linkedPullRequest !== undefined
665 ? pullRequestsPatch(
666 thread,
667 legacyLinkToPullRequests(
668 thread,
669 nextBase.projects.find((project) => project.id === thread.projectId),
670 payload.linkedPullRequest,
671 payload.updatedAt,
672 ),
673 nextBase.projects,
674 )
675 : {};
676 return {
677 ...nextBase,
678 threads: updateThread(nextBase.threads, payload.threadId, {
679 ...(payload.title !== undefined ? { title: payload.title } : {}),
680 ...(payload.titleRegeneration !== undefined
681 ? { titleRegeneration: payload.titleRegeneration }
682 : {}),
683 ...(payload.modelSelection !== undefined
684 ? { modelSelection: payload.modelSelection }
685 : {}),
686 ...(payload.branch !== undefined ? { branch: payload.branch } : {}),
687 ...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
688 ...(payload.activeOrderKey !== undefined
689 ? { activeOrderKey: payload.activeOrderKey }
690 : {}),
691 ...(payload.branchPullRequest !== undefined
692 ? { branchPullRequest: payload.branchPullRequest }
693 : {}),
694 ...legacyLinkPatch,
695 ...(acknowledgement !== undefined
696 ? {
697 pendingTurnStartMessageId:
698 acknowledgement.messageId === thread.pendingTurnStartMessageId &&
699 acknowledgementAlreadyAdopted
700 ? null
701 : (thread.pendingTurnStartMessageId ?? null),
702 submittedTurnStarts: acknowledgementAlreadyAdopted
703 ? (thread.submittedTurnStarts ?? []).filter(
704 (entry) => entry.turnId !== acknowledgement.turnId,
705 )
706 : [
707 ...(thread.submittedTurnStarts ?? []).filter(
708 (entry) => entry.messageId !== acknowledgement.messageId,
709 ),
710 acknowledgement,
711 ],
712 turnStartSubmissionRendezvous:
713 remainingRequests.length === 0
714 ? null
715 : {
716 requests: remainingRequests,
717 },
718 }
719 : {}),
720 updatedAt: payload.updatedAt,
721 }),
722 };
723 }),
724 );
725
726 case "thread.pull-request-linked":
727 return decodeForEvent(
728 ThreadPullRequestLinkedPayload,
729 event.payload,
730 event.type,
731 "payload",
732 ).pipe(
733 Effect.map((payload) => {
734 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
735 if (!thread) {
736 return nextBase;
737 }
738 return {
739 ...nextBase,
740 threads: updateThread(nextBase.threads, payload.threadId, {
741 ...pullRequestsPatch(
742 thread,
743 upsertPullRequestLink(thread.pullRequests, payload.link),
744 nextBase.projects,
745 ),
746 updatedAt: payload.updatedAt,
747 }),
748 };
749 }),
750 );
751
752 case "thread.pull-request-unlinked":
753 return decodeForEvent(
754 ThreadPullRequestUnlinkedPayload,
755 event.payload,
756 event.type,
757 "payload",
758 ).pipe(
759 Effect.map((payload) => {
760 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
761 if (!thread) {
762 return nextBase;
763 }
764 return {
765 ...nextBase,
766 threads: updateThread(nextBase.threads, payload.threadId, {
767 ...pullRequestsPatch(
768 thread,
769 removePullRequestLink(thread.pullRequests, payload),
770 nextBase.projects,
771 ),
772 updatedAt: payload.updatedAt,
773 }),
774 };
775 }),
776 );
777
778 case "thread.pull-request-synced":
779 return decodeForEvent(
780 ThreadPullRequestSyncedPayload,
781 event.payload,
782 event.type,
783 "payload",
784 ).pipe(
785 Effect.map((payload) => {
786 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
787 // A sync for a link the user removed in the meantime is stale; drop it.
788 if (
789 !thread ||
790 !thread.pullRequests.some((link) => threadPullRequestKeysEqual(link, payload))
791 ) {
792 return nextBase;
793 }
794 const pullRequests = thread.pullRequests.map((link) =>
795 threadPullRequestKeysEqual(link, payload)
796 ? { ...link, snapshot: payload.snapshot, stack: payload.stack }
797 : link,
798 );
799 return {
800 ...nextBase,
801 threads: updateThread(nextBase.threads, payload.threadId, {
802 ...pullRequestsPatch(thread, pullRequests, nextBase.projects),
803 updatedAt: payload.updatedAt,
804 }),
805 };
806 }),
807 );
808
809 case "thread.runtime-mode-set":
810 return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(
811 Effect.map((payload) => ({
812 ...nextBase,
813 threads: updateThread(nextBase.threads, payload.threadId, {
814 runtimeMode: payload.runtimeMode,
815 updatedAt: payload.updatedAt,
816 }),
817 })),
818 );
819
820 case "thread.interaction-mode-set":
821 return decodeForEvent(
822 ThreadInteractionModeSetPayload,
823 event.payload,
824 event.type,
825 "payload",
826 ).pipe(
827 Effect.map((payload) => ({
828 ...nextBase,
829 threads: updateThread(nextBase.threads, payload.threadId, {
830 interactionMode: payload.interactionMode,
831 updatedAt: payload.updatedAt,
832 }),
833 })),
834 );
835
836 case "thread.turn-start-requested":
837 return decodeForEvent(
838 ThreadTurnStartRequestedPayload,
839 event.payload,
840 event.type,
841 "payload",
842 ).pipe(
843 Effect.map((payload) => {
844 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
845 if (!thread) {
846 return nextBase;
847 }
848 const activeTurnId =
849 thread.session?.status === "running" ? thread.session.activeTurnId : null;
850 return {
851 ...nextBase,
852 threads: updateThread(nextBase.threads, payload.threadId, {
853 ...(payload.modelSelection !== undefined
854 ? { modelSelection: payload.modelSelection }
855 : {}),
856 runtimeMode: payload.runtimeMode,
857 interactionMode: payload.interactionMode,
858 pendingTurnStartMessageId: payload.messageId,
859 ...(payload.expectsTurnStartAcknowledgement === true
860 ? {
861 turnStartSubmissionRendezvous: {
862 requests: [
863 ...(thread.turnStartSubmissionRendezvous?.requests ?? []).filter(
864 (request) => request.messageId !== payload.messageId,
865 ),
866 {
867 messageId: payload.messageId,
868 observedTurnIds: activeTurnId === null ? [] : [activeTurnId],
869 },
870 ],
871 },
872 }
873 : {}),
874 pendingCheckpointRevertMessageIds:
875 thread.pendingCheckpointRevertMessageIds == null
876 ? null
877 : [...thread.pendingCheckpointRevertMessageIds, payload.messageId],
878 updatedAt: event.occurredAt,
879 }),
880 };
881 }),
882 );
883
884 case "thread.checkpoint-revert-requested":
885 return decodeForEvent(
886 ThreadCheckpointRevertRequestedPayload,
887 event.payload,
888 event.type,
889 "payload",
890 ).pipe(
891 Effect.map((payload) => {
892 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
893 if (!thread) return nextBase;
894 return {
895 ...nextBase,
896 threads: updateThread(nextBase.threads, payload.threadId, {
897 pendingCheckpointRevertMessageIds: thread.pendingCheckpointRevertMessageIds ?? [],
898 pendingCheckpointRevertCount: (thread.pendingCheckpointRevertCount ?? 0) + 1,
899 updatedAt: event.occurredAt,
900 }),
901 };
902 }),
903 );
904
905 case "thread.message-sent":
906 return Effect.gen(function* () {
907 const payload = yield* decodeForEvent(
908 MessageSentPayloadSchema,
909 event.payload,
910 event.type,
911 "payload",
912 );
913 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
914 if (!thread) {
915 return nextBase;
916 }
917
918 const message: OrchestrationMessage = yield* decodeForEvent(
919 OrchestrationMessage,
920 {
921 id: payload.messageId,
922 role: payload.role,
923 text: payload.text,
924 ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}),
925 ...(payload.context !== undefined ? { context: payload.context } : {}),
926 turnId: payload.turnId,
927 streaming: payload.streaming,
928 createdAt: payload.createdAt,
929 updatedAt: payload.updatedAt,
930 },
931 event.type,
932 "message",
933 );
934
935 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
936 const messages = existingMessage
937 ? thread.messages.map((entry) =>
938 entry.id === message.id
939 ? {
940 ...entry,
941 text: message.streaming
942 ? `${entry.text}${message.text}`
943 : message.text.length > 0
944 ? message.text
945 : entry.text,
946 streaming: message.streaming,
947 updatedAt: message.updatedAt,
948 turnId: message.turnId,
949 ...(message.attachments !== undefined
950 ? { attachments: message.attachments }
951 : {}),
952 ...(message.context !== undefined ? { context: message.context } : {}),
953 }
954 : entry,
955 )
956 : [...thread.messages, message];
957 const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);
958
959 return {
960 ...nextBase,
961 threads: updateThread(nextBase.threads, payload.threadId, {
962 messages: cappedMessages,
963 updatedAt: event.occurredAt,
964 }),
965 };
966 });
967
968 case "thread.session-set":
969 return Effect.gen(function* () {
970 const payload = yield* decodeForEvent(
971 ThreadSessionSetPayload,
972 event.payload,
973 event.type,
974 "payload",
975 );
976 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
977 if (!thread) {
978 return nextBase;
979 }
980
981 const session: OrchestrationSession = yield* decodeForEvent(
982 OrchestrationSession,
983 payload.session,
984 event.type,
985 "session",
986 );
987
988 // Leaving the "running" session status is the turn-end signal: settle
989 // a still-running latest turn so its duration reflects the whole turn.
990 const settledTurnState = settledTurnStateForSessionStatus(session.status);
991 const activeTurnId = session.status === "running" ? session.activeTurnId : null;
992 const rendezvous = thread.turnStartSubmissionRendezvous ?? null;
993 return {
994 ...nextBase,
995 threads: updateThread(nextBase.threads, payload.threadId, {
996 session,
997 pendingTurnStartMessageId:
998 session.status === "running" && session.activeTurnId !== null
999 ? null
1000 : (thread.pendingTurnStartMessageId ?? null),
1001 submittedTurnStarts:
1002 activeTurnId !== null
1003 ? (thread.submittedTurnStarts ?? []).filter(
1004 (entry) => entry.turnId !== activeTurnId,
1005 )
1006 : // Acknowledged starts die with their session; an idle or
1007 // errored session may still pick them up, since a
1008 // per-request failure does not prove the session is gone.
1009 session.status === "interrupted" || session.status === "stopped"
1010 ? []
1011 : (thread.submittedTurnStarts ?? []),
1012 turnStartSubmissionRendezvous:
1013 activeTurnId === null || rendezvous === null || rendezvous.requests.length === 0
1014 ? rendezvous
1015 : {
1016 requests: rendezvous.requests.map((request) => ({
1017 ...request,
1018 observedTurnIds: [
1019 ...request.observedTurnIds.filter((turnId) => turnId !== activeTurnId),
1020 activeTurnId,
1021 ],
1022 })),
1023 },
1024 latestTurn:
1025 session.status === "running" && session.activeTurnId !== null
1026 ? {
1027 turnId: session.activeTurnId,
1028 state: "running",
1029 requestedAt:
1030 thread.latestTurn?.turnId === session.activeTurnId
1031 ? thread.latestTurn.requestedAt
1032 : session.updatedAt,
1033 startedAt:
1034 thread.latestTurn?.turnId === session.activeTurnId
1035 ? (thread.latestTurn.startedAt ?? session.updatedAt)
1036 : session.updatedAt,
1037 completedAt: null,
1038 assistantMessageId:
1039 thread.latestTurn?.turnId === session.activeTurnId
1040 ? thread.latestTurn.assistantMessageId
1041 : null,
1042 }
1043 : thread.latestTurn !== null &&
1044 thread.latestTurn.state === "running" &&
1045 settledTurnState !== null
1046 ? {
1047 ...thread.latestTurn,
1048 state: settledTurnState,
1049 // A running turn's completedAt can only hold a mid-turn
1050 // placeholder checkpoint timestamp — the session leaving
1051 // "running" is the authoritative turn end.
1052 completedAt: session.updatedAt,
1053 }
1054 : thread.latestTurn,
1055 updatedAt: event.occurredAt,
1056 }),
1057 };
1058 });
1059
1060 case "thread.proposed-plan-upserted":
1061 return Effect.gen(function* () {
1062 const payload = yield* decodeForEvent(
1063 ThreadProposedPlanUpsertedPayload,
1064 event.payload,
1065 event.type,
1066 "payload",
1067 );
1068 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
1069 if (!thread) {
1070 return nextBase;
1071 }
1072
1073 const proposedPlans = [
1074 ...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),
1075 payload.proposedPlan,
1076 ]
1077 .toSorted(
1078 (left, right) =>
1079 left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
1080 )
1081 .slice(-200);
1082
1083 return {
1084 ...nextBase,
1085 threads: updateThread(nextBase.threads, payload.threadId, {
1086 proposedPlans,
1087 updatedAt: event.occurredAt,
1088 }),
1089 };
1090 });
1091
1092 case "thread.turn-diff-completed":
1093 return Effect.gen(function* () {
1094 const payload = yield* decodeForEvent(
1095 ThreadTurnDiffCompletedPayload,
1096 event.payload,
1097 event.type,
1098 "payload",
1099 );
1100 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
1101 if (!thread) {
1102 return nextBase;
1103 }
1104
1105 const checkpoint = yield* decodeForEvent(
1106 OrchestrationCheckpointSummary,
1107 {
1108 turnId: payload.turnId,
1109 checkpointTurnCount: payload.checkpointTurnCount,
1110 checkpointRef: payload.checkpointRef,
1111 status: payload.status,
1112 files: payload.files,
1113 assistantMessageId: payload.assistantMessageId,
1114 completedAt: payload.completedAt,
1115 },
1116 event.type,
1117 "checkpoint",
1118 );
1119
1120 // Do not let a placeholder (status "missing") overwrite a checkpoint
1121 // that has already been captured with a real git ref (status "ready").
1122 // ProviderRuntimeIngestion may fire multiple turn.diff.updated events
1123 // per turn; without this guard later placeholders would clobber the
1124 // real capture dispatched by CheckpointReactor.
1125 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
1126 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
1127 return nextBase;
1128 }
1129
1130 const checkpoints = [
1131 ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
1132 checkpoint,
1133 ]
1134 .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
1135 .slice(-MAX_THREAD_CHECKPOINTS);
1136
1137 // Mid-turn diff updates produce placeholder checkpoints; record the
1138 // checkpoint, but don't settle a turn its session is still running.
1139 const turnStillRunning =
1140 thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
1141
1142 return {
1143 ...nextBase,
1144 threads: updateThread(nextBase.threads, payload.threadId, {
1145 checkpoints,
1146 submittedTurnStarts: turnStillRunning
1147 ? (thread.submittedTurnStarts ?? [])
1148 : (thread.submittedTurnStarts ?? []).filter(
1149 (entry) => entry.turnId !== payload.turnId,
1150 ),
1151 latestTurn: turnStillRunning
1152 ? thread.latestTurn
1153 : {
1154 turnId: payload.turnId,
1155 state:
1156 thread.latestTurn?.turnId === payload.turnId &&
1157 thread.latestTurn.state === "interrupted"
1158 ? "interrupted"
1159 : checkpointStatusToLatestTurnState(payload.status),
1160 requestedAt:
1161 thread.latestTurn?.turnId === payload.turnId
1162 ? thread.latestTurn.requestedAt
1163 : payload.completedAt,
1164 startedAt:
1165 thread.latestTurn?.turnId === payload.turnId
1166 ? (thread.latestTurn.startedAt ?? payload.completedAt)
1167 : payload.completedAt,
1168 completedAt: payload.completedAt,
1169 assistantMessageId: payload.assistantMessageId,
1170 },
1171 updatedAt: event.occurredAt,
1172 }),
1173 };
1174 });
1175
1176 case "thread.reverted":
1177 return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(
1178 Effect.map((payload) => {
1179 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
1180 if (!thread) {
1181 return nextBase;
1182 }
1183
1184 const checkpoints = thread.checkpoints
1185 .filter((entry) => entry.checkpointTurnCount <= payload.turnCount)
1186 .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
1187 .slice(-MAX_THREAD_CHECKPOINTS);
1188 const retainedTurnIds = new Set(checkpoints.map((checkpoint) => checkpoint.turnId));
1189 const messages = retainThreadMessagesAfterRevert(
1190 thread.messages,
1191 retainedTurnIds,
1192 payload.turnCount,
1193 new Set(payload.preservedMessageIds ?? []),
1194 ).slice(-MAX_THREAD_MESSAGES);
1195 const proposedPlans = retainThreadProposedPlansAfterRevert(
1196 thread.proposedPlans,
1197 retainedTurnIds,
1198 ).slice(-200);
1199 const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
1200
1201 const latestCheckpoint = checkpoints.at(-1) ?? null;
1202 const latestTurn =
1203 latestCheckpoint === null
1204 ? null
1205 : {
1206 turnId: latestCheckpoint.turnId,
1207 state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
1208 requestedAt: latestCheckpoint.completedAt,
1209 startedAt: latestCheckpoint.completedAt,
1210 completedAt: latestCheckpoint.completedAt,
1211 assistantMessageId: latestCheckpoint.assistantMessageId,
1212 };
1213
1214 const pendingCheckpointRevertCount = Math.max(
1215 0,
1216 (thread.pendingCheckpointRevertCount ?? 1) - 1,
1217 );
1218 return {
1219 ...nextBase,
1220 threads: updateThread(nextBase.threads, payload.threadId, {
1221 checkpoints,
1222 messages,
1223 proposedPlans,
1224 activities,
1225 latestTurn,
1226 pendingCheckpointRevertMessageIds:
1227 pendingCheckpointRevertCount === 0
1228 ? null
1229 : (thread.pendingCheckpointRevertMessageIds ?? []),
1230 pendingCheckpointRevertCount:
1231 pendingCheckpointRevertCount === 0 ? null : pendingCheckpointRevertCount,
1232 updatedAt: event.occurredAt,
1233 }),
1234 };
1235 }),
1236 );
1237
1238 case "thread.activity-appended":
1239 return decodeForEvent(
1240 ThreadActivityAppendedPayload,
1241 event.payload,
1242 event.type,
1243 "payload",
1244 ).pipe(
1245 Effect.map((payload) => {
1246 const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
1247 if (!thread) {
1248 return nextBase;
1249 }
1250
1251 const activities = retainThreadActivities(
1252 [
1253 ...thread.activities.filter((entry) => entry.id !== payload.activity.id),
1254 payload.activity,
1255 ].toSorted(compareThreadActivities),
1256 );
1257 const pendingTurnStartMessageId = activityClearsPendingTurnStart(thread, payload.activity)
1258 ? null
1259 : (thread.pendingTurnStartMessageId ?? null);
1260 const clearedRequestId = turnStartRequestIdClearedByActivity(payload.activity);
1261 const submittedTurnStarts =
1262 clearedRequestId === null
1263 ? (thread.submittedTurnStarts ?? [])
1264 : (thread.submittedTurnStarts ?? []).filter(
1265 (entry) => entry.messageId !== clearedRequestId,
1266 );
1267 const rendezvous = thread.turnStartSubmissionRendezvous ?? null;
1268 const remainingRequests =
1269 clearedRequestId === null
1270 ? (rendezvous?.requests ?? [])
1271 : (rendezvous?.requests ?? []).filter(
1272 (request) => request.messageId !== clearedRequestId,
1273 );
1274 const turnStartSubmissionRendezvous =
1275 rendezvous === null
1276 ? null
1277 : remainingRequests.length === 0
1278 ? null
1279 : { requests: remainingRequests };
1280 const revertFailed = payload.activity.kind === "checkpoint.revert.failed";
1281 const pendingCheckpointRevertCount = revertFailed
1282 ? Math.max(0, (thread.pendingCheckpointRevertCount ?? 1) - 1)
1283 : (thread.pendingCheckpointRevertCount ?? null);
1284 const pendingCheckpointRevertMessageIds =
1285 revertFailed && pendingCheckpointRevertCount === 0
1286 ? null
1287 : (thread.pendingCheckpointRevertMessageIds ?? null);
1288
1289 return {
1290 ...nextBase,
1291 threads: updateThread(nextBase.threads, payload.threadId, {
1292 activities,
1293 pendingTurnStartMessageId,
1294 submittedTurnStarts,
1295 turnStartSubmissionRendezvous,
1296 pendingCheckpointRevertMessageIds,
1297 pendingCheckpointRevertCount:
1298 pendingCheckpointRevertCount === 0 ? null : pendingCheckpointRevertCount,
1299 updatedAt: event.occurredAt,
1300 }),
1301 };
1302 }),
1303 );
1304
1305 default:
1306 return Effect.succeed(nextBase);
1307 }
1308}