@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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