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