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

ChatView.logic.test.ts

1,180 lines37.2 KB

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