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