Open History to see the last commit
1import {
2 boundAttachmentIds,
3 buildExpiredTerminalContextToastCopy,
4 mergeDirectPreviewAnnotation,
5 planComposerTurn,
6 snapshotComposerSend,
7 withMessageContext,
8 deriveAvailableRevertTurnCounts,
9} from "./ChatView.logic";
10import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
11import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
12import { deriveProviderInstanceEntries } from "../providerInstances";
13import { ensureInlineContextReferences } from "../lib/composerContextReferences";
14import { terminalContextReference } from "../lib/composerContextRecords";
15import {
16 CommandId,
17 EnvironmentId,
18 MessageId,
19 ProjectId,
20 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
21 ProviderInstanceId,
22 ProviderSessionId,
23 ProviderThreadId,
24 ThreadId,
25 RunId,
26 TurnItemId,
27 type OrchestrationV2ProjectedTurnItem,
28 type WorktreeSetupSnapshot,
29} from "@t3tools/contracts";
30import * as DateTime from "effect/DateTime";
31import * as Option from "effect/Option";
32import { afterEach, describe, expect, it, vi } from "vite-plus/test";
33import { Atom } from "effect/reactivity";
34import { appAtomRegistry } from "../rpc/atomRegistry";
35import { environmentThreadDetails } from "../state/threads";
36
37import type { Thread } from "../types";
38import { makeThreadFixture, makeThreadProjectionFixture } from "../test-fixtures";
39import {
40 getAntigravitySendBlockReason,
41 resolveComposerProviderSelection,
42 resolveWorktreeSetupProgress,
43 peekRememberedThreadTimeline,
44 rememberReadyThreadTimeline,
45 resetHeldThreadTimeline,
46 resolveThreadSwitchTimeline,
47 timelineHasEphemeralPreviewUrls,
48 createLocalDispatchSnapshot,
49 deriveCommittedServerUserMessageIds,
50 deriveComposerSendState,
51 deriveLockedProvider,
52 hasServerAcknowledgedLocalDispatch,
53 waitForRevertedMessage,
54} from "./ChatView.logic";
55
56const environmentId = EnvironmentId.make("environment-local");
57const projectId = ProjectId.make("project-1");
58const threadId = ThreadId.make("thread-1");
59const now = "2026-03-29T00:00:00.000Z";
60
61function makeThread(overrides: Partial<Thread> = {}): Thread {
62 return makeThreadFixture({
63 id: threadId,
64 environmentId,
65 projectId,
66 title: "Thread",
67 modelSelection: {
68 instanceId: ProviderInstanceId.make("codex"),
69 model: "gpt-5.4",
70 },
71 runtimeMode: "full-access",
72 interactionMode: "default",
73 runtime: null,
74 createdAt: now,
75 updatedAt: now,
76 archivedAt: null,
77 settledOverride: null,
78 settledAt: null,
79 deletedAt: null,
80 latestRun: null,
81 branch: null,
82 worktreePath: null,
83 ...overrides,
84 });
85}
86
87const completedTurn = {
88 runId: RunId.make("turn-1"),
89 status: "completed" as const,
90 requestedAt: now,
91 startedAt: "2026-03-29T00:00:01.000Z",
92 completedAt: "2026-03-29T00:00:10.000Z",
93 assistantMessageId: null,
94};
95
96const readySession = {
97 status: "completed" as const,
98 providerName: "codex",
99 providerInstanceId: ProviderInstanceId.make("codex"),
100 activeRunId: null,
101 lastError: null,
102 updatedAt: "2026-03-29T00:00:10.000Z",
103};
104
105describe("deriveComposerSendState", () => {
106 it("keeps text sendable while excluding expired terminal pills", () => {
107 const state = deriveComposerSendState({
108 prompt: `yoo [Terminal 1](t3-context://v1/terminal/ctx-expired) waddup`,
109 imageCount: 0,
110 terminalContexts: [
111 {
112 id: "ctx-expired",
113 threadId,
114 terminalId: "default",
115 terminalLabel: "Terminal 1",
116 lineStart: 4,
117 lineEnd: 4,
118 text: "",
119 createdAt: now,
120 },
121 ],
122 });
123
124 expect(state.trimmedPrompt).toBe("yoo waddup");
125 expect(state.expiredTerminalContextCount).toBe(1);
126 expect(state.hasSendableContent).toBe(true);
127 });
128});
129
130describe("buildExpiredTerminalContextToastCopy", () => {
131 it("refers to several expired contexts as them", () => {
132 expect(buildExpiredTerminalContextToastCopy(2, "empty")).toEqual({
133 title: "Expired terminal contexts won't be sent",
134 description: "Remove them or re-add them to include terminal output.",
135 });
136 expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
137 title: "Expired terminal contexts omitted from message",
138 description: "Re-add them if you want that terminal output included.",
139 });
140 expect(buildExpiredTerminalContextToastCopy(1, "omitted").description).toBe(
141 "Re-add it if you want that terminal output included.",
142 );
143 });
144});
145
146describe("hasServerAcknowledgedLocalDispatch", () => {
147 it("acknowledges a settled newer background turn", () => {
148 const localDispatch = createLocalDispatchSnapshot(
149 makeThread({ latestRun: completedTurn, runtime: readySession }),
150 { submissionIntent: "background" },
151 );
152 const newerTurn = {
153 ...completedTurn,
154 runId: RunId.make("turn-2"),
155 requestedAt: "2026-03-29T00:01:00.000Z",
156 startedAt: "2026-03-29T00:01:01.000Z",
157 completedAt: "2026-03-29T00:01:30.000Z",
158 };
159
160 expect(
161 hasServerAcknowledgedLocalDispatch({
162 localDispatch,
163 phase: "ready",
164 latestRun: newerTurn,
165 runtime: { ...readySession, updatedAt: newerTurn.completedAt },
166 hasPendingApproval: false,
167 hasPendingUserInput: false,
168 threadError: null,
169 }),
170 ).toBe(true);
171 });
172
173 it("holds a first send while the thread shell still reports a preparing run", () => {
174 const localDispatch = createLocalDispatchSnapshot(makeThread());
175 const preparingRun = {
176 ...completedTurn,
177 status: "preparing" as const,
178 startedAt: null,
179 completedAt: null,
180 };
181
182 expect(
183 hasServerAcknowledgedLocalDispatch({
184 localDispatch,
185 phase: "disconnected",
186 latestRun: preparingRun,
187 runtime: { ...readySession, status: "preparing", activeRunId: preparingRun.runId },
188 hasPendingApproval: false,
189 hasPendingUserInput: false,
190 threadError: null,
191 }),
192 ).toBe(false);
193 });
194
195 it.each([
196 ["queued", "message-queued", true],
197 ["queued", "message-before-send", false],
198 ["preparing", "message-queued", false],
199 ["starting", "message-queued", false],
200 ] as const)("acknowledges %s with latest message %s: %s", (status, messageId, acknowledged) => {
201 const localDispatch = createLocalDispatchSnapshot(
202 makeThread({ latestRun: completedTurn, runtime: readySession }),
203 { latestUserMessageId: MessageId.make("message-before-send") },
204 );
205 // The shell hides the silent compaction run, so its runtime reports the queued message's run.
206 const queuedRun = {
207 ...completedTurn,
208 runId: RunId.make("turn-queued"),
209 status: "queued" as const,
210 requestedAt: "2026-03-29T00:01:00.000Z",
211 startedAt: null,
212 completedAt: null,
213 };
214
215 expect(
216 hasServerAcknowledgedLocalDispatch({
217 localDispatch,
218 phase: "running",
219 latestRun: queuedRun,
220 latestUserMessageId: MessageId.make(messageId),
221 runtime: { ...readySession, status },
222 hasPendingApproval: false,
223 hasPendingUserInput: false,
224 threadError: null,
225 }),
226 ).toBe(acknowledged);
227 });
228
229 it("waits for the matching running turn before acknowledging", () => {
230 const localDispatch = createLocalDispatchSnapshot(
231 makeThread({ latestRun: completedTurn, runtime: readySession }),
232 );
233 const runningTurn = {
234 ...completedTurn,
235 runId: RunId.make("turn-2"),
236 status: "running" as const,
237 requestedAt: "2026-03-29T00:01:00.000Z",
238 startedAt: "2026-03-29T00:01:01.000Z",
239 completedAt: null,
240 };
241
242 expect(
243 hasServerAcknowledgedLocalDispatch({
244 localDispatch,
245 phase: "running",
246 latestRun: runningTurn,
247 runtime: {
248 ...readySession,
249 status: "running",
250 activeRunId: RunId.make("turn-other"),
251 },
252 hasPendingApproval: false,
253 hasPendingUserInput: false,
254 threadError: null,
255 }),
256 ).toBe(false);
257 expect(
258 hasServerAcknowledgedLocalDispatch({
259 localDispatch,
260 phase: "running",
261 latestRun: runningTurn,
262 runtime: {
263 ...readySession,
264 status: "running",
265 activeRunId: runningTurn.runId,
266 },
267 hasPendingApproval: false,
268 hasPendingUserInput: false,
269 threadError: null,
270 }),
271 ).toBe(true);
272 });
273
274 it("acknowledges a steering message projected onto the current running run", () => {
275 const runningRun = {
276 ...completedTurn,
277 status: "running" as const,
278 completedAt: null,
279 };
280 const runningRuntime = {
281 ...readySession,
282 status: "running" as const,
283 activeRunId: runningRun.runId,
284 };
285 const localDispatch = createLocalDispatchSnapshot(
286 makeThread({ latestRun: runningRun, runtime: runningRuntime }),
287 { latestUserMessageId: MessageId.make("message-before-steer") },
288 );
289
290 expect(
291 hasServerAcknowledgedLocalDispatch({
292 localDispatch,
293 phase: "running",
294 latestRun: runningRun,
295 latestUserMessageId: MessageId.make("message-steer"),
296 runtime: runningRuntime,
297 hasPendingApproval: false,
298 hasPendingUserInput: false,
299 threadError: null,
300 }),
301 ).toBe(true);
302 });
303});
304
305describe("deriveCommittedServerUserMessageIds", () => {
306 it("tracks only committed user turn items, not assistant rows or projection-only messages", () => {
307 const turnStartId = MessageId.make("message-turn-start");
308 const steerId = MessageId.make("message-steer");
309 const assistantId = MessageId.make("message-assistant");
310 const committedAt = DateTime.makeUnsafe("2026-06-26T17:50:15.180Z");
311 const runId = RunId.make("run:thread:thread-1:ordinal:1");
312 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
313 {
314 position: 0,
315 visibility: "local",
316 sourceThreadId: threadId,
317 sourceItemId: TurnItemId.make("turn-item:message-turn-start"),
318 item: {
319 id: TurnItemId.make("turn-item:message-turn-start"),
320 threadId,
321 runId,
322 nodeId: null,
323 providerThreadId: null,
324 providerTurnId: null,
325 nativeItemRef: null,
326 parentItemId: null,
327 ordinal: 1,
328 status: "completed",
329 title: null,
330 startedAt: committedAt,
331 completedAt: committedAt,
332 updatedAt: committedAt,
333 createdBy: "user",
334 creationSource: "web",
335 type: "user_message",
336 messageId: turnStartId,
337 inputIntent: "turn_start",
338 text: "start",
339 attachments: [],
340 },
341 },
342 {
343 position: 1,
344 visibility: "local",
345 sourceThreadId: threadId,
346 sourceItemId: TurnItemId.make("turn-item:message-assistant"),
347 item: {
348 id: TurnItemId.make("turn-item:message-assistant"),
349 threadId,
350 runId,
351 nodeId: null,
352 providerThreadId: null,
353 providerTurnId: null,
354 nativeItemRef: null,
355 parentItemId: null,
356 ordinal: 2,
357 status: "completed",
358 title: null,
359 startedAt: committedAt,
360 completedAt: committedAt,
361 updatedAt: committedAt,
362 type: "assistant_message",
363 messageId: assistantId,
364 text: "working",
365 streaming: false,
366 },
367 },
368 {
369 position: 2,
370 visibility: "local",
371 sourceThreadId: threadId,
372 sourceItemId: TurnItemId.make("turn-item:message-steer"),
373 item: {
374 id: TurnItemId.make("turn-item:message-steer"),
375 threadId,
376 runId,
377 nodeId: null,
378 providerThreadId: null,
379 providerTurnId: null,
380 nativeItemRef: null,
381 parentItemId: null,
382 ordinal: 3,
383 status: "completed",
384 title: null,
385 startedAt: committedAt,
386 completedAt: committedAt,
387 updatedAt: committedAt,
388 createdBy: "user",
389 creationSource: "web",
390 type: "user_message",
391 messageId: steerId,
392 inputIntent: "steer",
393 text: "continue",
394 attachments: [],
395 },
396 },
397 ];
398
399 expect(deriveCommittedServerUserMessageIds(visibleTurnItems)).toEqual(
400 new Set([turnStartId, steerId]),
401 );
402 });
403});
404
405describe("resolveThreadSwitchTimeline", () => {
406 afterEach(() => {
407 resetHeldThreadTimeline();
408 });
409
410 const held = { threadKey: "env-1:thread-a", entries: ["a1", "a2"] };
411
412 it("paints a remembered destination instead of the last-viewed thread", () => {
413 rememberReadyThreadTimeline(held);
414 rememberReadyThreadTimeline({ threadKey: "env-1:thread-b", entries: ["b1", "b2"] });
415 expect(peekRememberedThreadTimeline<string[]>("env-1:thread-a")).toEqual(["a1", "a2"]);
416 expect(
417 resolveThreadSwitchTimeline({
418 loading: true,
419 activeThreadKey: "env-1:thread-a",
420 nextEntries: [],
421 }),
422 ).toEqual(["a1", "a2"]);
423 });
424
425 it("does not paint the last-viewed thread for a destination with nothing remembered", () => {
426 rememberReadyThreadTimeline(held);
427 expect(
428 resolveThreadSwitchTimeline({
429 loading: true,
430 activeThreadKey: "env-2:thread-b",
431 nextEntries: [],
432 }),
433 ).toEqual([]);
434 });
435
436 it("does not remember a timeline that still has handoff blob previews", () => {
437 expect(
438 timelineHasEphemeralPreviewUrls([
439 {
440 kind: "message",
441 message: {
442 id: MessageId.make("preview-message"),
443 role: "user",
444 text: "Preview",
445 runId: null,
446 streaming: false,
447 createdAt: "2026-09-10T12:00:00.000Z",
448 updatedAt: "2026-09-10T12:00:00.000Z",
449 attachments: [
450 {
451 type: "image",
452 id: "preview",
453 name: "preview.png",
454 mimeType: "image/png",
455 sizeBytes: 1,
456 previewUrl: "blob:handoff",
457 },
458 ],
459 },
460 },
461 ]),
462 ).toBe(true);
463 expect(
464 timelineHasEphemeralPreviewUrls([
465 {
466 kind: "message",
467 message: {
468 id: MessageId.make("preview-message"),
469 role: "user",
470 text: "Preview",
471 runId: null,
472 streaming: false,
473 createdAt: "2026-09-10T12:00:00.000Z",
474 updatedAt: "2026-09-10T12:00:00.000Z",
475 attachments: [
476 {
477 type: "image",
478 id: "preview",
479 name: "preview.png",
480 mimeType: "image/png",
481 sizeBytes: 1,
482 previewUrl: "https://cdn.example/a.png",
483 },
484 ],
485 },
486 },
487 ]),
488 ).toBe(false);
489 });
490});
491
492describe("resolveComposerProviderSelection", () => {
493 const catalogModels: ServerProvider["models"] = [
494 { slug: "gemini-pro", name: "Gemini Pro", isCustom: false, capabilities: null },
495 ];
496
497 function entry(driver: string, instanceId = driver, overrides: Partial<ServerProvider> = {}) {
498 return deriveProviderInstanceEntries([
499 {
500 driver: ProviderDriverKind.make(driver),
501 instanceId: ProviderInstanceId.make(instanceId),
502 enabled: true,
503 installed: true,
504 status: "ready",
505 auth: { status: "authenticated" },
506 version: null,
507 checkedAt: now,
508 models: [],
509 slashCommands: [],
510 skills: [],
511 ...overrides,
512 },
513 ])[0]!;
514 }
515
516 function importedThread(instanceId: ProviderInstanceId) {
517 return makeThread({
518 modelSelection: { instanceId, model: "default" },
519 itemCount: 1,
520 });
521 }
522
523 it.each([
524 ["claudeAgent", "claude_work"],
525 ["codex", "codex_work"],
526 ["ollama", "local_models"],
527 ])("keeps imported %s history selectable through its custom instance", (driver, instanceId) => {
528 const importedEntry = entry(driver, instanceId);
529 const entries = [entry(driver === "codex" ? "claudeAgent" : "codex"), importedEntry];
530 const thread = importedThread(importedEntry.instanceId);
531 const lockedProvider = deriveLockedProvider({
532 thread,
533 selectedProvider: entries[0]!.instanceId,
534 threadProvider: thread.modelSelection.instanceId,
535 providers: entries.map((entry) => entry.snapshot),
536 });
537
538 expect(thread.runtime).toBeNull();
539 expect(lockedProvider).toBe(driver);
540 expect(
541 resolveComposerProviderSelection({
542 entries,
543 candidateInstanceIds: [thread.modelSelection.instanceId],
544 lockedProvider,
545 lockedInstanceId: thread.modelSelection.instanceId,
546 }).selectedProviderEntry?.instanceId,
547 ).toBe(importedEntry.instanceId);
548 });
549
550 it("keeps the session driver authoritative over instance and draft selections", () => {
551 const selected = entry("claudeAgent", "claude_work");
552 const sessionEntry = entry("ollama", "local_models");
553 const thread = importedThread(selected.instanceId);
554
555 expect(
556 deriveLockedProvider({
557 thread: {
558 ...thread,
559 runtime: {
560 ...readySession,
561 providerName: sessionEntry.driverKind,
562 providerInstanceId: sessionEntry.instanceId,
563 },
564 },
565 selectedProvider: selected.instanceId,
566 threadProvider: thread.modelSelection.instanceId,
567 providers: [selected.snapshot, sessionEntry.snapshot],
568 }),
569 ).toBe(sessionEntry.driverKind);
570 });
571
572 it.each(["missing", "disabled"] as const)(
573 "does not move imported history to another driver when its instance is %s",
574 (state) => {
575 const imported = entry("claudeAgent", "claude_work", { enabled: false });
576 const other = entry("codex");
577 const entries = state === "missing" ? [other] : [other, imported];
578 const thread = importedThread(imported.instanceId);
579 const lockedProvider = deriveLockedProvider({
580 thread,
581 selectedProvider: other.instanceId,
582 threadProvider: thread.modelSelection.instanceId,
583 providers: entries.map((entry) => entry.snapshot),
584 });
585
586 expect(lockedProvider).not.toBeNull();
587 expect(
588 resolveComposerProviderSelection({
589 entries,
590 candidateInstanceIds: [other.instanceId, imported.instanceId],
591 lockedProvider,
592 lockedInstanceId: imported.instanceId,
593 }).selectedProviderEntry,
594 ).toBeUndefined();
595 },
596 );
597
598 it("keeps a signed-out selection instead of silently switching providers", () => {
599 const signedOutEntry = entry("antigravity", "google_work", {
600 status: "error",
601 auth: { status: "unauthenticated" },
602 models: catalogModels,
603 });
604 const selection = resolveComposerProviderSelection({
605 entries: [entry("codex"), signedOutEntry],
606 candidateInstanceIds: [signedOutEntry.instanceId],
607 lockedProvider: null,
608 lockedInstanceId: null,
609 });
610
611 expect(selection.selectedProviderEntry?.instanceId).toBe(signedOutEntry.instanceId);
612 expect(
613 getAntigravitySendBlockReason(selection.selectedProviderEntry?.snapshot, "gemini-pro"),
614 ).toBe("Sign in to Antigravity in provider settings before sending.");
615 });
616
617 it("blocks a saved model that a ready catalog no longer lists", () => {
618 const provider = entry("antigravity", "google_work", {
619 status: "ready",
620 models: catalogModels,
621 }).snapshot;
622
623 expect(getAntigravitySendBlockReason(provider, "saved-model-not-in-current-catalog")).toBe(
624 "That Antigravity model is no longer available. Choose another model.",
625 );
626 expect(getAntigravitySendBlockReason(provider, "gemini-pro")).toBeNull();
627 });
628
629 it("allows a saved native model to retry after a provider error without changing it", () => {
630 const provider = entry("antigravity", "google_work", {
631 status: "error",
632 models: catalogModels,
633 }).snapshot;
634
635 expect(
636 getAntigravitySendBlockReason(provider, "saved-model-not-in-current-catalog"),
637 ).toBeNull();
638 });
639
640 it("does not continue an existing Antigravity thread in another profile after deletion", () => {
641 const missingInstanceId = ProviderInstanceId.make("google_work");
642 const selection = resolveComposerProviderSelection({
643 entries: [entry("antigravity")],
644 candidateInstanceIds: [missingInstanceId],
645 lockedProvider: ProviderDriverKind.make("antigravity"),
646 lockedInstanceId: missingInstanceId,
647 });
648
649 expect(selection.selectedProviderEntry).toBeUndefined();
650 expect(selection.unavailableProviderInstanceId).toBe(missingInstanceId);
651 });
652
653 it("keeps the session's continuation group when another instance was selected", () => {
654 const sessionEntry = entry("antigravity", "google_work", {
655 enabled: false,
656 continuation: { groupKey: "work-profile" },
657 });
658 const anotherEntry = entry("antigravity", "google_personal", {
659 continuation: { groupKey: "personal-profile" },
660 });
661 const selection = resolveComposerProviderSelection({
662 entries: [sessionEntry, anotherEntry],
663 candidateInstanceIds: [anotherEntry.instanceId, sessionEntry.instanceId],
664 lockedProvider: ProviderDriverKind.make("antigravity"),
665 lockedInstanceId: sessionEntry.instanceId,
666 });
667
668 expect(selection.selectedProviderEntry).toBeUndefined();
669 });
670});
671
672describe("checkout Git memory", () => {
673 it("does not confuse an environment id containing the separator with a path", () => {
674 rememberCheckoutIsRepo(EnvironmentId.make("env"), "a:b", false);
675 expect(recallCheckoutIsRepo(EnvironmentId.make("env:a"), "b")).toBeUndefined();
676 });
677});
678
679describe("worktree setup visibility", () => {
680 const stage = (
681 id: "fetch" | "checkout" | "submodules" | "setup-script" | "agent",
682 status: "done" | "running" | "failed" | "pending",
683 ) => ({
684 id,
685 status,
686 startedAt: now,
687 endedAt: status === "running" || status === "pending" ? null : now,
688 percent: null,
689 detail: null,
690 tail: [],
691 });
692 const base = {
693 threadId,
694 phase: "running" as const,
695 startedAt: now,
696 endedAt: null,
697 branch: "feature",
698 baseRef: "main",
699 worktreePath: null,
700 setupScript: null,
701 stages: [stage("checkout", "running"), stage("agent", "pending")],
702 error: null,
703 sequence: 1,
704 };
705 const settledDone = {
706 ...base,
707 phase: "done" as const,
708 endedAt: now,
709 stages: [stage("checkout", "done"), stage("setup-script", "done"), stage("agent", "done")],
710 };
711
712 it("uses streamed setup progress immediately without reverting to an older held snapshot", () => {
713 const newest = { ...settledDone, sequence: 9 };
714 const resolve = (latest: WorktreeSetupSnapshot | null, held: WorktreeSetupSnapshot | null) =>
715 resolveWorktreeSetupProgress({
716 threadId,
717 localPreparing: false,
718 runStatus: "running",
719 latest,
720 held,
721 });
722 expect(resolve(newest, base)).toEqual({ snapshot: newest, isPreparingWorktree: false });
723 expect(resolve(base, newest)).toEqual({ snapshot: newest, isPreparingWorktree: false });
724 const other = { ...base, threadId: ThreadId.make("another-thread") };
725 expect(resolve(other, other)).toEqual({ snapshot: null, isPreparingWorktree: false });
726 });
727});
728
729describe("waitForRevertedMessage", () => {
730 const threadRef = { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("t") };
731 const messageId = MessageId.make("message-2");
732 const requestId = CommandId.make("rollback-1");
733
734 function projectionAtom() {
735 const base = makeThreadProjectionFixture();
736 const providerThreadId = ProviderThreadId.make("provider-thread");
737 const projection = {
738 ...base,
739 thread: { ...base.thread, activeProviderThreadId: providerThreadId },
740 providerThreads: [
741 {
742 id: providerThreadId,
743 driver: "codex",
744 providerInstanceId: base.thread.providerInstanceId,
745 providerSessionId: ProviderSessionId.make("provider-session"),
746 appThreadId: base.thread.id,
747 ownerNodeId: null,
748 nativeThreadRef: null,
749 nativeConversationHeadRef: null,
750 status: "idle",
751 firstRunOrdinal: 1,
752 lastRunOrdinal: 4,
753 handoffIds: [],
754 forkedFrom: null,
755 createdAt: base.updatedAt,
756 updatedAt: base.updatedAt,
757 },
758 ],
759 runs: [1, 2, 3, 4].map((ordinal) => ({
760 id: RunId.make(`run-${ordinal}`),
761 threadId: base.thread.id,
762 ordinal,
763 providerInstanceId: base.thread.providerInstanceId,
764 modelSelection: base.thread.modelSelection,
765 providerThreadId,
766 userMessageId: MessageId.make(`message-${ordinal}`),
767 rootNodeId: null,
768 activeAttemptId: null,
769 status: "completed",
770 requestedAt: base.updatedAt,
771 startedAt: base.updatedAt,
772 completedAt: base.updatedAt,
773 checkpointId: null,
774 contextHandoffId: null,
775 })),
776 messages: [
777 {
778 id: messageId,
779 threadId: base.thread.id,
780 runId: RunId.make("run-2"),
781 nodeId: null,
782 role: "user",
783 text: "second",
784 attachments: [],
785 streaming: false,
786 createdAt: base.updatedAt,
787 updatedAt: base.updatedAt,
788 },
789 ],
790 } as unknown as ReturnType<typeof makeThreadProjectionFixture>;
791 const state = Atom.make({ data: Option.some(projection) });
792 vi.spyOn(environmentThreadDetails, "stateAtom").mockReturnValue(state as never);
793 return { state, projection };
794 }
795
796 afterEach(() => vi.restoreAllMocks());
797
798 it("rejects with the projected reason when the rollback fails for good", async () => {
799 const { state, projection } = projectionAtom();
800 const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {});
801 await Promise.resolve();
802 appAtomRegistry.set(state, {
803 data: Option.some({
804 ...projection,
805 thread: {
806 ...projection.thread,
807 rollbackFailure: { requestId, message: "The provider could not roll back." },
808 },
809 }),
810 });
811
812 await expect(waiting).rejects.toThrow("The provider could not roll back.");
813 });
814
815 it.each([
816 ["same", "streamed"],
817 ["replacement", "streamed"],
818 ["replacement", "refetched"],
819 ] as const)(
820 "waits for the retained rollback suffix when the edited message and run are paged out (%s provider, %s)",
821 async (providerIdentity, projectionSource) => {
822 vi.useFakeTimers();
823 const { state, projection } = projectionAtom();
824 const latestRunId = RunId.make("latest-run-9");
825 const latestRun = {
826 ...projection.runs[3]!,
827 id: latestRunId,
828 ordinal: 9,
829 userMessageId: MessageId.make("latest-message-9"),
830 status: "cancelled" as const,
831 };
832 const bounded = {
833 ...projection,
834 messages: [],
835 providerThreads: projection.providerThreads.map((thread) => ({
836 ...thread,
837 lastRunOrdinal: 9,
838 })),
839 runs: [
840 {
841 ...latestRun,
842 id: RunId.make("old-rewound-run-3"),
843 userMessageId: MessageId.make("old-rewound-message-3"),
844 ordinal: 3,
845 status: "rolled_back" as const,
846 },
847 latestRun,
848 ],
849 };
850 const oldProviderThread = bounded.providerThreads[0]!;
851 const completedProviderThread = {
852 ...oldProviderThread,
853 ...(providerIdentity === "replacement"
854 ? { id: ProviderThreadId.make("replacement-provider-thread"), firstRunOrdinal: null }
855 : {}),
856 lastRunOrdinal: null,
857 };
858 appAtomRegistry.set(state, { data: Option.some(bounded) });
859 let outcome = "pending";
860 const waiting = waitForRevertedMessage(threadRef, 0, requestId, async () => {}).then(
861 () => {
862 outcome = "reverted";
863 },
864 (error: Error) => {
865 outcome = error.message;
866 },
867 );
868
869 try {
870 await vi.advanceTimersByTimeAsync(0);
871 expect(outcome).toBe("pending");
872
873 appAtomRegistry.set(state, {
874 data: Option.some({
875 ...bounded,
876 thread: {
877 ...bounded.thread,
878 activeProviderThreadId:
879 projectionSource === "refetched"
880 ? completedProviderThread.id
881 : oldProviderThread.id,
882 },
883 providerThreads:
884 providerIdentity === "replacement"
885 ? [oldProviderThread, completedProviderThread]
886 : [completedProviderThread],
887 runs: bounded.runs.map((run) =>
888 run.id === latestRunId ? { ...run, status: "rolled_back" as const } : run,
889 ),
890 }),
891 });
892 await vi.advanceTimersByTimeAsync(0);
893 expect(outcome).toBe("reverted");
894 await waiting;
895 } finally {
896 vi.clearAllTimers();
897 vi.useRealTimers();
898 }
899 },
900 );
901
902 it("waits for the requested target when another client finishes a shallower rewind", async () => {
903 vi.useFakeTimers();
904 const { state, projection } = projectionAtom();
905 let outcome = "pending";
906 const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {}).then(
907 () => {
908 outcome = "reverted";
909 },
910 (error: Error) => {
911 outcome = error.message;
912 },
913 );
914
915 try {
916 await vi.advanceTimersByTimeAsync(0);
917 expect(outcome).toBe("pending");
918
919 // Our command is accepted while the earlier target-3 effect is still running.
920 const shallowerRewind = {
921 ...projection,
922 thread: { ...projection.thread, rollbackRequestId: requestId, rollbackFailure: null },
923 providerThreads: projection.providerThreads.map((thread) => ({
924 ...thread,
925 lastRunOrdinal: 3,
926 })),
927 runs: projection.runs.map((run) =>
928 run.ordinal > 3 ? { ...run, status: "rolled_back" as const } : run,
929 ),
930 };
931 appAtomRegistry.set(state, { data: Option.some(shallowerRewind) });
932 await vi.advanceTimersByTimeAsync(0);
933 expect(outcome).toBe("pending");
934
935 appAtomRegistry.set(state, {
936 data: Option.some({
937 ...shallowerRewind,
938 providerThreads: shallowerRewind.providerThreads.map((thread) => ({
939 ...thread,
940 lastRunOrdinal: 1,
941 })),
942 runs: shallowerRewind.runs.map((run) =>
943 run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run,
944 ),
945 }),
946 });
947 await vi.advanceTimersByTimeAsync(0);
948 expect(outcome).toBe("reverted");
949 await waiting;
950 } finally {
951 vi.clearAllTimers();
952 vi.useRealTimers();
953 }
954 });
955
956 it("rejects a stale edit already rewound by another client during attachment preparation", async () => {
957 vi.useFakeTimers();
958 const { state, projection } = projectionAtom();
959 appAtomRegistry.set(state, {
960 data: Option.some({
961 ...projection,
962 thread: { ...projection.thread, rollbackRequestId: CommandId.make("other-client-rewind") },
963 messages: [],
964 providerThreads: projection.providerThreads.map((thread) => ({
965 ...thread,
966 lastRunOrdinal: 1,
967 })),
968 runs: projection.runs.map((run) =>
969 run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run,
970 ),
971 }),
972 });
973 const revert = vi.fn(async () => {});
974 let outcome = "pending";
975 const waiting = waitForRevertedMessage(threadRef, 1, requestId, revert).then(
976 () => {
977 outcome = "reverted";
978 },
979 () => {
980 outcome = "rejected";
981 },
982 );
983
984 try {
985 await vi.advanceTimersByTimeAsync(0);
986 expect(outcome).toBe("rejected");
987 expect(revert).not.toHaveBeenCalled();
988 await waiting;
989 } finally {
990 vi.clearAllTimers();
991 vi.useRealTimers();
992 }
993 });
994});
995
996describe("mergeDirectPreviewAnnotation", () => {
997 const annotation = (id: string) =>
998 ({
999 id,
1000 pageUrl: "http://localhost:5173/",
1001 pageTitle: null,
1002 comment: "tighten this",
1003 elements: [],
1004 regions: [],
1005 strokes: [],
1006 styleChanges: [],
1007 screenshot: {
1008 dataUrl: "data:image/png;base64,AAAA",
1009 width: 10,
1010 height: 10,
1011 cropRect: { x: 0, y: 0, width: 10, height: 10 },
1012 },
1013 createdAt: "2026-10-16T00:00:00.000Z",
1014 }) as const;
1015 const image = (id: string) =>
1016 ({ id, type: "image", name: `${id}.png`, mimeType: "image/png", sizeBytes: 1 }) as never;
1017
1018 it("drops the screenshot claim when the attachment cap is full", () => {
1019 const result = mergeDirectPreviewAnnotation({
1020 images: [],
1021 fileCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1022 previewAnnotations: [],
1023 direct: { annotation: annotation("a"), image: image("crop") },
1024 });
1025 expect(result.images).toEqual([]);
1026 expect(result.previewAnnotations[0]?.screenshot).toBeNull();
1027 });
1028});
1029
1030describe("snapshotComposerSend", () => {
1031 const expired = {
1032 id: "ctx-expired",
1033 threadId,
1034 terminalId: "default",
1035 terminalLabel: "Terminal 1",
1036 lineStart: 4,
1037 lineEnd: 4,
1038 text: "",
1039 createdAt: now,
1040 };
1041 const live = { ...expired, id: "ctx-live", text: "pnpm test", lineStart: 9, lineEnd: 9 };
1042
1043 it("drops expired terminal contexts from the contexts and from the prompt", () => {
1044 const snapshot = snapshotComposerSend({
1045 prompt: ensureInlineContextReferences("run", [
1046 terminalContextReference(expired),
1047 terminalContextReference(live),
1048 ]),
1049 images: [],
1050 files: [],
1051 terminalContexts: [expired, live],
1052 sendableTerminalContexts: [live],
1053 previewAnnotations: [],
1054 reviewComments: [],
1055 threadContexts: [],
1056 environmentContexts: [],
1057 });
1058
1059 expect(snapshot.terminalContexts).toEqual([live]);
1060 expect(snapshot.messageText).toBe(
1061 ensureInlineContextReferences("run", [terminalContextReference(live)]).trim(),
1062 );
1063 });
1064});
1065
1066describe("planComposerTurn", () => {
1067 const base = {
1068 messageText: "hello",
1069 sendQueuesBehindSetup: false,
1070 isServerThread: false,
1071 activeMessageCount: 0,
1072 sendEnvMode: "worktree" as const,
1073 worktreePath: null,
1074 activeThreadBranch: "main",
1075 resumeCompactionTokens: null,
1076 keepFullHistory: false,
1077 phase: "ready" as const,
1078 dispatchMode: "auto" as const,
1079 freshContext: false,
1080 };
1081
1082 it("prepares a worktree from the selected branch on a new thread", () => {
1083 expect(planComposerTurn(base)).toMatchObject({
1084 missingWorktreeBaseBranch: false,
1085 baseBranchForWorktree: "main",
1086 shouldQueueBehindActiveRun: false,
1087 });
1088 });
1089
1090 it("refuses a new worktree without a base branch", () => {
1091 expect(planComposerTurn({ ...base, activeThreadBranch: null })).toMatchObject({
1092 missingWorktreeBaseBranch: true,
1093 baseBranchForWorktree: null,
1094 });
1095 });
1096
1097 it("queues behind a compaction of a stale session, except for /compact itself", () => {
1098 const stale = { ...base, resumeCompactionTokens: 120_000 };
1099 for (const messageText of ["hello", "/compactfoo"]) {
1100 expect(planComposerTurn({ ...stale, messageText })).toMatchObject({
1101 compactBeforeSend: true,
1102 turnDispatchMode: "queue",
1103 shouldQueueBehindActiveRun: true,
1104 });
1105 }
1106 for (const messageText of ["/COMPACT", "/compact keep the API notes", "/compact\n tests"]) {
1107 expect(planComposerTurn({ ...stale, messageText })).toMatchObject({
1108 compactBeforeSend: false,
1109 turnDispatchMode: "auto",
1110 shouldQueueBehindActiveRun: false,
1111 });
1112 }
1113 });
1114
1115 it("queues behind a running turn only when asked to", () => {
1116 const running = {
1117 ...base,
1118 isServerThread: true,
1119 activeMessageCount: 3,
1120 phase: "running" as const,
1121 };
1122 expect(planComposerTurn({ ...running, dispatchMode: "queue" }).shouldQueueBehindActiveRun).toBe(
1123 true,
1124 );
1125 expect(planComposerTurn({ ...running, dispatchMode: "steer" })).toMatchObject({
1126 shouldQueueBehindActiveRun: false,
1127 baseBranchForWorktree: null,
1128 });
1129 // A fresh session cannot join the running turn, and a stale one is not compacted first.
1130 expect(
1131 planComposerTurn({
1132 ...running,
1133 dispatchMode: "steer",
1134 freshContext: true,
1135 resumeCompactionTokens: 120_000,
1136 }),
1137 ).toMatchObject({
1138 compactBeforeSend: false,
1139 turnDispatchMode: "queue",
1140 shouldQueueBehindActiveRun: true,
1141 });
1142 });
1143});
1144
1145describe("withMessageContext", () => {
1146 const context = { records: [] } as unknown as NonNullable<
1147 Parameters<typeof withMessageContext>[0]["context"]
1148 >;
1149
1150 it("sends the context inline", () => {
1151 expect(withMessageContext({ text: "hi", context })).toEqual({ text: "hi", context });
1152 });
1153
1154 it("sends the text alone without context", () => {
1155 expect(withMessageContext({ text: "hi", context: undefined })).toEqual({ text: "hi" });
1156 });
1157});
1158
1159describe("boundAttachmentIds", () => {
1160 it("prefers the uploaded id and falls back to the local one", () => {
1161 expect(
1162 boundAttachmentIds([{ id: "upload-1" }, {}], [{ id: "local-1" }, { id: "local-2" }]),
1163 ).toEqual(["upload-1", "local-2"]);
1164 });
1165});
1166
1167describe("deriveAvailableRevertTurnCounts", () => {
1168 const providerThreadId = ProviderThreadId.make("provider-thread");
1169 const otherProviderThreadId = ProviderThreadId.make("other-provider-thread");
1170
1171 function projection(input: { readonly providerSessionId: ProviderSessionId | null }) {
1172 const base = makeThreadProjectionFixture();
1173 const run = (ordinal: number) => ({
1174 id: RunId.make(`run-${ordinal}`),
1175 ordinal,
1176 activeAttemptId: `attempt-${ordinal}`,
1177 });
1178 const turn = (ordinal: number, attempt: number, threadId: ProviderThreadId) => ({
1179 id: `turn-${attempt}-${ordinal}`,
1180 runAttemptId: `attempt-${attempt}`,
1181 ordinal,
1182 providerThreadId: threadId,
1183 });
1184 return {
1185 ...base,
1186 thread: { ...base.thread, activeProviderThreadId: providerThreadId },
1187 providerThreads: [
1188 {
1189 id: providerThreadId,
1190 providerInstanceId: base.thread.modelSelection.instanceId,
1191 providerSessionId: input.providerSessionId,
1192 },
1193 ],
1194 runs: [run(1), run(2), run(3)],
1195 attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, providerTurnId: null })),
1196 // Run 2's latest turn moved to another provider thread, so its checkpoint cannot restore
1197 // this conversation.
1198 providerTurns: [
1199 turn(1, 1, providerThreadId),
1200 turn(1, 2, providerThreadId),
1201 turn(2, 2, otherProviderThreadId),
1202 turn(1, 3, providerThreadId),
1203 ],
1204 } as unknown as ReturnType<typeof makeThreadProjectionFixture>;
1205 }
1206
1207 it("offers the thread start and runs whose latest turn is on the active provider thread", () => {
1208 const available = deriveAvailableRevertTurnCounts(
1209 projection({ providerSessionId: ProviderSessionId.make("session") }),
1210 );
1211 expect([...available].toSorted()).toEqual([0, 1, 3]);
1212 });
1213
1214 it("offers nothing without a provider session to rewind", () => {
1215 expect(deriveAvailableRevertTurnCounts(projection({ providerSessionId: null })).size).toBe(0);
1216 expect(deriveAvailableRevertTurnCounts(null).size).toBe(0);
1217 });
1218});