Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatView.logic.test.ts

1,241 lines39.4 KB

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