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

ChatView.logic.test.ts

1,248 lines39.5 KB

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