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