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