Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projector.ts

1,062 lines36.8 KB

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