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