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

ChatView.logic.test.ts

1,160 lines36.3 KB

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