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