Open History to see the last commit
1import {
2 EnvironmentId,
3 MessageId,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 TurnId,
8} from "@t3tools/contracts";
9import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10
11import type { Thread, ThreadShell } from "../types";
12import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";
13import {
14 MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
15 MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
16 branchMismatchKey,
17 buildExpiredTerminalContextToastCopy,
18 buildLoadingThreadFromShell,
19 buildThreadTurnInterruptInput,
20 createLocalDispatchSnapshot,
21 deriveComposerSendState,
22 dismissBranchMismatchForSession,
23 ENVIRONMENT_RECONNECT_WARNING_GRACE_MS,
24 getStartedThreadModelChangeBlockReason,
25 isVideoPreviewRequestCurrent,
26 hasEnvironmentReconnectWarningGraceElapsed,
27 hasServerAcknowledgedLocalDispatch,
28 isBranchMismatchDismissedForSession,
29 reconcileMountedTerminalThreadIds,
30 reconcileRetainedMountedThreadIds,
31 resolveBackgroundDraftWorkspaceOptions,
32 resolveDraftPromotionNavigationTarget,
33 resolveThreadMetadataUpdateForNextTurn,
34 resolveSendEnvMode,
35 resolveDraftHeroState,
36 scheduleEnvironmentReconnectWarning,
37 startNewThreadForProject,
38 codexArtifactTemplatePromptToAppend,
39 shouldDockDraftHeroForSubmission,
40 shouldReleaseTimelineAnchorForToolActivity,
41 shouldShowBranchMismatchBanner,
42 shouldShowPlanFollowUpPrompt,
43 shouldWriteThreadErrorToCurrentServerThread,
44 toolGroupConsumesUpwardNavigation,
45} from "./ChatView.logic";
46
47describe("isVideoPreviewRequestCurrent", () => {
48 it("rejects changed threads and replaced previews", () => {
49 expect(isVideoPreviewRequestCurrent("thread-1", "thread-2", 1, 1)).toBe(false);
50 expect(isVideoPreviewRequestCurrent("thread-1", "thread-1", 1, 2)).toBe(false);
51 expect(isVideoPreviewRequestCurrent("thread-1", "thread-1", 2, 2)).toBe(true);
52 });
53});
54
55describe("toolGroupConsumesUpwardNavigation", () => {
56 class ScrollElement extends EventTarget {
57 scrollTop = 0;
58 scrollHeight = 100;
59 clientHeight = 100;
60 overflowY = "visible";
61
62 constructor(
63 readonly parentElement: ScrollElement | null = null,
64 readonly isToolGroup = false,
65 ) {
66 super();
67 }
68
69 closest(selector: string): ScrollElement | null {
70 if (selector !== "[data-tool-group-scroll]") return null;
71 return this.isToolGroup ? this : (this.parentElement?.closest(selector) ?? null);
72 }
73 }
74
75 beforeEach(() => {
76 vi.stubGlobal("Element", ScrollElement);
77 vi.stubGlobal("getComputedStyle", (element: ScrollElement) => ({
78 overflowY: element.overflowY,
79 }));
80 });
81 afterEach(() => vi.unstubAllGlobals());
82
83 it("releases upward navigation when an overflowing group is at the top", () => {
84 const group = Object.assign(new ScrollElement(null, true), {
85 overflowY: "auto",
86 scrollHeight: 300,
87 });
88
89 expect(toolGroupConsumesUpwardNavigation(new ScrollElement(group))).toBe(false);
90 });
91
92 it.each([
93 { overflowY: "auto", scrollTop: 1 },
94 { overflowY: "auto", scrollTop: 0.25 },
95 { overflowY: "scroll", scrollTop: 80 },
96 ])("consumes upward navigation within a scrolled group: %j", (scroll) => {
97 const group = Object.assign(new ScrollElement(null, true), {
98 scrollHeight: 300,
99 ...scroll,
100 });
101
102 expect(toolGroupConsumesUpwardNavigation(group)).toBe(true);
103 });
104
105 it.each([100, 300])(
106 "consumes scrolling in a nested result with a group content height of %i",
107 (scrollHeight) => {
108 const group = Object.assign(new ScrollElement(null, true), {
109 overflowY: "auto",
110 scrollHeight,
111 });
112 const result = Object.assign(new ScrollElement(group), {
113 overflowY: "auto",
114 scrollHeight: 300,
115 scrollTop: 0.25,
116 });
117
118 expect(toolGroupConsumesUpwardNavigation(new ScrollElement(result))).toBe(true);
119 },
120 );
121
122 it("releases upward navigation when the group and nested result are both at the top", () => {
123 const group = Object.assign(new ScrollElement(null, true), {
124 overflowY: "auto",
125 scrollHeight: 300,
126 });
127 const result = Object.assign(new ScrollElement(group), {
128 overflowY: "scroll",
129 scrollHeight: 300,
130 });
131
132 expect(toolGroupConsumesUpwardNavigation(new ScrollElement(result))).toBe(false);
133 });
134
135 it("ignores targets outside a tool group and non-element targets", () => {
136 const outside = Object.assign(new ScrollElement(), {
137 overflowY: "auto",
138 scrollHeight: 300,
139 scrollTop: 40,
140 });
141
142 expect(toolGroupConsumesUpwardNavigation(outside)).toBe(false);
143 expect(toolGroupConsumesUpwardNavigation(new EventTarget())).toBe(false);
144 expect(toolGroupConsumesUpwardNavigation(null)).toBe(false);
145 });
146
147 it("does not consume scrolling from an ancestor beyond the tool group", () => {
148 const timeline = Object.assign(new ScrollElement(), {
149 overflowY: "auto",
150 scrollHeight: 300,
151 scrollTop: 40,
152 });
153 const group = new ScrollElement(timeline, true);
154
155 expect(toolGroupConsumesUpwardNavigation(new ScrollElement(group))).toBe(false);
156 });
157
158 it.each(["hidden", "clip", "visible"])(
159 "ignores a non-scrollable child with overflow-y %s",
160 (overflowY) => {
161 const group = new ScrollElement(null, true);
162 const result = Object.assign(new ScrollElement(group), {
163 overflowY,
164 scrollHeight: 300,
165 scrollTop: 40,
166 });
167
168 expect(toolGroupConsumesUpwardNavigation(new ScrollElement(result))).toBe(false);
169 },
170 );
171
172 it("does not consume programmatic scrolling on an overflow-hidden group", () => {
173 const group = Object.assign(new ScrollElement(null, true), {
174 overflowY: "hidden",
175 scrollHeight: 300,
176 scrollTop: 40,
177 });
178
179 expect(toolGroupConsumesUpwardNavigation(group)).toBe(false);
180 });
181});
182
183const environmentId = EnvironmentId.make("environment-local");
184const projectId = ProjectId.make("project-1");
185const threadId = ThreadId.make("thread-1");
186const now = "2026-03-29T00:00:00.000Z";
187const helloWorldTemplate: CodexArtifactTemplate = {
188 artifactKind: "document",
189 displayName: "Hello World",
190 skillDirectory: "/Users/test/.codex/skills/artifact-template-hello-world",
191 skillName: "artifact-template-hello-world",
192};
193
194describe("artifact template composer insertion", () => {
195 it("does not insert an already-present prompt", () => {
196 const prompt = "Create a document using this $artifact-template-hello-world about…";
197
198 expect(codexArtifactTemplatePromptToAppend(prompt, helloWorldTemplate)).toBeNull();
199 });
200});
201
202describe("draft hero submission transition", () => {
203 it("does not dock the composer before a background submission", () => {
204 expect(
205 shouldDockDraftHeroForSubmission({
206 isDraftHeroState: true,
207 activeThreadKey: "environment-local:thread-1",
208 submissionIntent: "background",
209 }),
210 ).toBe(false);
211 });
212
213 it("keeps the composer in the hero layout until navigation after server promotion", () => {
214 expect(
215 resolveDraftHeroState({
216 isLocalDraftThread: false,
217 hasTimelineEntries: true,
218 isWorking: true,
219 draftHeroDockRequested: false,
220 backgroundSubmissionPending: true,
221 }),
222 ).toBe(true);
223 });
224
225 it("does not auto-navigate a background submission after server promotion", () => {
226 expect(
227 resolveDraftPromotionNavigationTarget({
228 serverThreadRef: { environmentId, threadId },
229 serverThread: makeThread({ latestTurn: completedTurn }),
230 backgroundSubmissionPending: true,
231 }),
232 ).toBeNull();
233 });
234});
235
236describe("shouldReleaseTimelineAnchorForToolActivity", () => {
237 const activeTurnId = TurnId.make("active-turn");
238 const anchorMessageId = MessageId.make("anchored-message");
239 const activeToolEntry = {
240 id: "tool-entry",
241 kind: "work" as const,
242 createdAt: now,
243 entry: {
244 id: "active-tool",
245 createdAt: now,
246 turnId: activeTurnId,
247 label: "Run command",
248 tone: "tool" as const,
249 command: "git status",
250 },
251 };
252
253 it("releases the send anchor for tool activity in the active turn", () => {
254 expect(
255 shouldReleaseTimelineAnchorForToolActivity({
256 anchorMessageId,
257 liveFollowEnabled: true,
258 runningTurnId: activeTurnId,
259 timelineEntries: [activeToolEntry],
260 }),
261 ).toBe(true);
262 });
263
264 it("keeps the anchor while the user reads history", () => {
265 expect(
266 shouldReleaseTimelineAnchorForToolActivity({
267 anchorMessageId,
268 liveFollowEnabled: false,
269 runningTurnId: activeTurnId,
270 timelineEntries: [activeToolEntry],
271 }),
272 ).toBe(false);
273 });
274
275 it("ignores tool activity from earlier turns", () => {
276 expect(
277 shouldReleaseTimelineAnchorForToolActivity({
278 anchorMessageId,
279 liveFollowEnabled: true,
280 runningTurnId: activeTurnId,
281 timelineEntries: [
282 {
283 ...activeToolEntry,
284 entry: {
285 ...activeToolEntry.entry,
286 turnId: TurnId.make("previous-turn"),
287 },
288 },
289 ],
290 }),
291 ).toBe(false);
292 });
293
294 it("ignores thinking and error rows without tool activity", () => {
295 expect(
296 shouldReleaseTimelineAnchorForToolActivity({
297 anchorMessageId,
298 liveFollowEnabled: true,
299 runningTurnId: activeTurnId,
300 timelineEntries: [
301 {
302 ...activeToolEntry,
303 entry: {
304 id: "thinking-entry",
305 createdAt: now,
306 turnId: activeTurnId,
307 label: "Thinking",
308 tone: "thinking",
309 },
310 },
311 {
312 ...activeToolEntry,
313 id: "error-entry",
314 entry: {
315 id: "error-entry",
316 createdAt: now,
317 turnId: activeTurnId,
318 label: "Provider error",
319 tone: "error",
320 },
321 },
322 ],
323 }),
324 ).toBe(false);
325 });
326
327 it("does nothing without an anchor or running turn", () => {
328 const input = {
329 anchorMessageId,
330 liveFollowEnabled: true,
331 runningTurnId: activeTurnId,
332 timelineEntries: [activeToolEntry],
333 };
334
335 expect(shouldReleaseTimelineAnchorForToolActivity({ ...input, anchorMessageId: null })).toBe(
336 false,
337 );
338 expect(shouldReleaseTimelineAnchorForToolActivity({ ...input, runningTurnId: null })).toBe(
339 false,
340 );
341 });
342});
343
344describe("environment reconnect warning grace", () => {
345 afterEach(() => vi.useRealTimers());
346
347 it("shows a persistent reconnect after the grace period", () => {
348 vi.useFakeTimers();
349 const showWarning = vi.fn();
350
351 scheduleEnvironmentReconnectWarning(showWarning);
352 vi.advanceTimersByTime(ENVIRONMENT_RECONNECT_WARNING_GRACE_MS - 1);
353 expect(showWarning).not.toHaveBeenCalled();
354
355 vi.advanceTimersByTime(1);
356 expect(showWarning).toHaveBeenCalledOnce();
357 });
358
359 it("cancels the warning when the connection recovers during the grace period", () => {
360 vi.useFakeTimers();
361 const showWarning = vi.fn();
362
363 const cancel = scheduleEnvironmentReconnectWarning(showWarning);
364 cancel();
365 vi.advanceTimersByTime(ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
366
367 expect(showWarning).not.toHaveBeenCalled();
368 });
369
370 it("does not reuse elapsed grace from another environment", () => {
371 const anotherEnvironmentId = EnvironmentId.make("environment-remote");
372
373 expect(hasEnvironmentReconnectWarningGraceElapsed(environmentId, environmentId)).toBe(true);
374 expect(hasEnvironmentReconnectWarningGraceElapsed(anotherEnvironmentId, environmentId)).toBe(
375 false,
376 );
377 });
378});
379
380function makeThread(overrides: Partial<Thread> = {}): Thread {
381 return {
382 id: threadId,
383 environmentId,
384 projectId,
385 title: "Thread",
386 modelSelection: {
387 instanceId: ProviderInstanceId.make("codex"),
388 model: "gpt-5.4",
389 },
390 runtimeMode: "full-access",
391 interactionMode: "default",
392 session: null,
393 messages: [],
394 proposedPlans: [],
395 activities: [],
396 checkpoints: [],
397 createdAt: now,
398 updatedAt: now,
399 archivedAt: null,
400 settledOverride: null,
401 settledAt: null,
402 deletedAt: null,
403 latestTurn: null,
404 branch: null,
405 worktreePath: null,
406 ...overrides,
407 };
408}
409
410const completedTurn = {
411 turnId: TurnId.make("turn-1"),
412 state: "completed" as const,
413 requestedAt: now,
414 startedAt: "2026-03-29T00:00:01.000Z",
415 completedAt: "2026-03-29T00:00:10.000Z",
416 assistantMessageId: null,
417};
418
419const readySession = {
420 threadId,
421 status: "ready" as const,
422 providerName: "codex",
423 providerInstanceId: ProviderInstanceId.make("codex"),
424 runtimeMode: "full-access" as const,
425 activeTurnId: null,
426 lastError: null,
427 updatedAt: "2026-03-29T00:00:10.000Z",
428};
429
430describe("draft promotion during worktree setup", () => {
431 const serverThreadRef = { environmentId, threadId };
432
433 it.each([null, "idle", "starting", "ready"] as const)(
434 "keeps the draft mounted while the first turn waits with session %s",
435 (status) => {
436 const serverThread = makeThread({
437 messages: [
438 {
439 id: MessageId.make("submitted-message"),
440 role: "user",
441 text: "Start in a new worktree",
442 turnId: null,
443 createdAt: now,
444 updatedAt: now,
445 streaming: false,
446 },
447 ],
448 session: status ? { ...readySession, status } : null,
449 });
450
451 expect(
452 resolveDraftPromotionNavigationTarget({
453 serverThreadRef,
454 serverThread,
455 backgroundSubmissionPending: false,
456 }),
457 ).toBeNull();
458 },
459 );
460
461 it("promotes when the provider starts the first turn", () => {
462 const latestTurn = { ...completedTurn, state: "running" as const, completedAt: null };
463
464 expect(
465 resolveDraftPromotionNavigationTarget({
466 serverThreadRef,
467 serverThread: makeThread({
468 latestTurn,
469 session: { ...readySession, status: "running", activeTurnId: latestTurn.turnId },
470 }),
471 backgroundSubmissionPending: false,
472 }),
473 ).toEqual(serverThreadRef);
474 });
475
476 it.each(["error", "stopped", "interrupted"] as const)(
477 "promotes a startup that ends as %s before a turn starts",
478 (status) => {
479 expect(
480 resolveDraftPromotionNavigationTarget({
481 serverThreadRef,
482 serverThread: makeThread({ session: { ...readySession, status } }),
483 backgroundSubmissionPending: false,
484 }),
485 ).toEqual(serverThreadRef);
486 },
487 );
488});
489
490describe("buildLoadingThreadFromShell", () => {
491 it("preserves shell metadata and supplies empty detail collections", () => {
492 const shell = {
493 environmentId,
494 id: threadId,
495 projectId,
496 title: "Loading thread",
497 modelSelection: {
498 instanceId: ProviderInstanceId.make("codex"),
499 model: "gpt-5.4",
500 },
501 runtimeMode: "full-access",
502 interactionMode: "default",
503 branch: "main",
504 worktreePath: null,
505 latestTurn: null,
506 createdAt: now,
507 updatedAt: now,
508 archivedAt: null,
509 settledOverride: null,
510 settledAt: null,
511 snoozedUntil: null,
512 snoozedAt: null,
513 session: null,
514 latestUserMessageAt: now,
515 hasPendingApprovals: false,
516 hasPendingUserInput: false,
517 hasActionableProposedPlan: false,
518 } satisfies ThreadShell;
519
520 expect(buildLoadingThreadFromShell(shell)).toMatchObject({
521 environmentId,
522 id: threadId,
523 projectId,
524 title: "Loading thread",
525 branch: "main",
526 deletedAt: null,
527 messages: [],
528 proposedPlans: [],
529 activities: [],
530 checkpoints: [],
531 });
532 });
533});
534
535describe("resolveThreadMetadataUpdateForNextTurn", () => {
536 const modelSelection = {
537 instanceId: ProviderInstanceId.make("codex"),
538 model: "gpt-5.4",
539 };
540
541 it("updates a stale local thread branch to the active checkout", () => {
542 expect(
543 resolveThreadMetadataUpdateForNextTurn({
544 currentModelSelection: modelSelection,
545 currentBranch: "feature/thread",
546 nextBranch: "feature/checkout",
547 }),
548 ).toEqual({ branch: "feature/checkout", worktreePath: null });
549 });
550
551 it("does not write metadata when the model and branch are unchanged", () => {
552 expect(
553 resolveThreadMetadataUpdateForNextTurn({
554 currentModelSelection: modelSelection,
555 nextModelSelection: modelSelection,
556 currentBranch: "feature/current",
557 nextBranch: "feature/current",
558 }),
559 ).toBeNull();
560 });
561});
562
563describe("buildThreadTurnInterruptInput", () => {
564 it("targets the session's active running turn", () => {
565 const activeTurnId = TurnId.make("turn-running");
566
567 expect(
568 buildThreadTurnInterruptInput(
569 makeThread({
570 session: {
571 ...readySession,
572 status: "running",
573 activeTurnId,
574 },
575 }),
576 ),
577 ).toEqual({ threadId, turnId: activeTurnId });
578 });
579
580 it("omits a turn id when the session is not running", () => {
581 expect(buildThreadTurnInterruptInput(makeThread({ session: readySession }))).toEqual({
582 threadId,
583 });
584 });
585});
586
587describe("deriveComposerSendState", () => {
588 it("treats expired terminal pills as non-sendable content", () => {
589 const state = deriveComposerSendState({
590 prompt: "\uFFFC",
591 imageCount: 0,
592 terminalContexts: [
593 {
594 id: "ctx-expired",
595 threadId,
596 terminalId: "default",
597 terminalLabel: "Terminal 1",
598 lineStart: 4,
599 lineEnd: 4,
600 text: "",
601 createdAt: now,
602 },
603 ],
604 });
605
606 expect(state.trimmedPrompt).toBe("");
607 expect(state.sendableTerminalContexts).toEqual([]);
608 expect(state.expiredTerminalContextCount).toBe(1);
609 expect(state.hasSendableContent).toBe(false);
610 });
611
612 it("keeps text sendable while excluding expired terminal pills", () => {
613 const state = deriveComposerSendState({
614 prompt: `yoo \uFFFC waddup`,
615 imageCount: 0,
616 terminalContexts: [
617 {
618 id: "ctx-expired",
619 threadId,
620 terminalId: "default",
621 terminalLabel: "Terminal 1",
622 lineStart: 4,
623 lineEnd: 4,
624 text: "",
625 createdAt: now,
626 },
627 ],
628 });
629
630 expect(state.trimmedPrompt).toBe("yoo waddup");
631 expect(state.expiredTerminalContextCount).toBe(1);
632 expect(state.hasSendableContent).toBe(true);
633 });
634
635 it("treats element contexts as sendable content (no text, no images, no terminals)", () => {
636 const state = deriveComposerSendState({
637 prompt: "",
638 imageCount: 0,
639 terminalContexts: [],
640 elementContextCount: 1,
641 });
642
643 expect(state.trimmedPrompt).toBe("");
644 expect(state.expiredTerminalContextCount).toBe(0);
645 expect(state.hasSendableContent).toBe(true);
646 });
647
648 it("does NOT treat zero element contexts as sendable", () => {
649 expect(
650 deriveComposerSendState({
651 prompt: "",
652 imageCount: 0,
653 terminalContexts: [],
654 elementContextCount: 0,
655 }).hasSendableContent,
656 ).toBe(false);
657 });
658});
659
660describe("buildExpiredTerminalContextToastCopy", () => {
661 it("formats empty and omission guidance", () => {
662 expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
663 title: "Expired terminal context won't be sent",
664 description: "Remove it or re-add it to include terminal output.",
665 });
666 expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
667 title: "Expired terminal contexts omitted from message",
668 description: "Re-add it if you want that terminal output included.",
669 });
670 });
671});
672
673describe("getStartedThreadModelChangeBlockReason", () => {
674 const providers = [
675 {
676 instanceId: ProviderInstanceId.make("codex"),
677 },
678 {
679 instanceId: ProviderInstanceId.make("grok"),
680 requiresNewThreadForModelChange: true,
681 },
682 ];
683
684 it("allows model changes before a provider session has started", () => {
685 expect(
686 getStartedThreadModelChangeBlockReason({
687 providers,
688 hasStartedSession: false,
689 currentModelSelection: {
690 instanceId: ProviderInstanceId.make("grok"),
691 model: "grok-build",
692 },
693 nextModelSelection: {
694 instanceId: ProviderInstanceId.make("grok"),
695 model: "grok-other",
696 },
697 }),
698 ).toBeNull();
699 });
700
701 it("allows unchanged model selections for restricted providers", () => {
702 expect(
703 getStartedThreadModelChangeBlockReason({
704 providers,
705 hasStartedSession: true,
706 currentModelSelection: {
707 instanceId: ProviderInstanceId.make("grok"),
708 model: "grok-build",
709 },
710 nextModelSelection: {
711 instanceId: ProviderInstanceId.make("grok"),
712 model: "grok-build",
713 },
714 }),
715 ).toBeNull();
716 });
717
718 it("blocks started-session model changes when either provider requires a new thread", () => {
719 expect(
720 getStartedThreadModelChangeBlockReason({
721 providers,
722 hasStartedSession: true,
723 currentModelSelection: {
724 instanceId: ProviderInstanceId.make("codex"),
725 model: "gpt-5.4",
726 },
727 nextModelSelection: {
728 instanceId: ProviderInstanceId.make("grok"),
729 model: "grok-build",
730 },
731 }),
732 ).toEqual({
733 title: "Start a new chat to change models",
734 description:
735 "This provider does not allow switching models after a conversation has started.",
736 });
737 });
738});
739
740describe("resolveSendEnvMode", () => {
741 it("keeps worktree mode only for git repositories", () => {
742 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
743 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
744 });
745});
746
747describe("resolveBackgroundDraftWorkspaceOptions", () => {
748 it("keeps New worktree selected without reusing the launched worktree", () => {
749 expect(
750 resolveBackgroundDraftWorkspaceOptions({
751 envMode: "worktree",
752 branch: "main",
753 startFromOrigin: true,
754 }),
755 ).toEqual({
756 envMode: "worktree",
757 branch: "main",
758 worktreePath: null,
759 startFromOrigin: true,
760 });
761 });
762});
763
764describe("branchMismatchKey", () => {
765 it("builds a key from thread id and both branches", () => {
766 expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
767 "thread-1:feat/a:feat/b",
768 );
769 });
770
771 it("returns null without a thread or mismatch", () => {
772 expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
773 expect(branchMismatchKey("thread-1", null)).toBeNull();
774 });
775});
776
777describe("shouldShowBranchMismatchBanner", () => {
778 const base = {
779 hasMismatch: true,
780 isDismissed: false,
781 composerHasContent: false,
782 wasShownForCurrentMismatch: false,
783 };
784
785 it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
786 expect(shouldShowBranchMismatchBanner(base)).toBe(false);
787 });
788
789 it("shows once the composer has draft content", () => {
790 expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
791 });
792
793 it("stays mounted after the draft clears once shown for the current mismatch", () => {
794 expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
795 true,
796 );
797 });
798
799 it("never shows when dismissed or without a mismatch", () => {
800 expect(
801 shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
802 ).toBe(false);
803 expect(
804 shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
805 ).toBe(false);
806 });
807});
808
809describe("shouldShowPlanFollowUpPrompt", () => {
810 const base = {
811 pendingUserInputCount: 0,
812 interactionMode: "plan" as const,
813 latestTurnSettled: true,
814 hasActionableProposedPlan: true,
815 hasComposerAttachments: false,
816 };
817
818 it("shows plan actions for a settled actionable plan without attachments", () => {
819 expect(shouldShowPlanFollowUpPrompt(base)).toBe(true);
820 });
821
822 it("hides plan actions while the composer has staged attachments", () => {
823 expect(shouldShowPlanFollowUpPrompt({ ...base, hasComposerAttachments: true })).toBe(false);
824 });
825
826 it("preserves the existing plan follow-up gates", () => {
827 expect(shouldShowPlanFollowUpPrompt({ ...base, pendingUserInputCount: 1 })).toBe(false);
828 expect(shouldShowPlanFollowUpPrompt({ ...base, interactionMode: "default" })).toBe(false);
829 expect(shouldShowPlanFollowUpPrompt({ ...base, latestTurnSettled: false })).toBe(false);
830 expect(shouldShowPlanFollowUpPrompt({ ...base, hasActionableProposedPlan: false })).toBe(false);
831 });
832});
833
834describe("session branch mismatch dismissal", () => {
835 it("tracks dismissed keys and treats other keys as active", () => {
836 expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
837 dismissBranchMismatchForSession("t1:a:b");
838 expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
839 expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
840 expect(isBranchMismatchDismissedForSession(null)).toBe(false);
841 });
842});
843
844describe("reconcileMountedTerminalThreadIds", () => {
845 it("keeps open threads and makes the active thread most recent", () => {
846 expect(
847 reconcileMountedTerminalThreadIds({
848 currentThreadIds: ["thread-a", "thread-b", "thread-c"],
849 openThreadIds: ["thread-a", "thread-b", "thread-c"],
850 activeThreadId: "thread-a",
851 activeThreadTerminalOpen: true,
852 maxHiddenThreadCount: 2,
853 }),
854 ).toEqual(["thread-b", "thread-c", "thread-a"]);
855 });
856
857 it("drops closed threads and enforces the hidden mounted cap", () => {
858 const ids = Array.from(
859 { length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
860 (_, index) => `thread-${index}`,
861 );
862 expect(
863 reconcileMountedTerminalThreadIds({
864 currentThreadIds: ids,
865 openThreadIds: ids.slice(1),
866 activeThreadId: null,
867 activeThreadTerminalOpen: false,
868 }),
869 ).toEqual(ids.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
870 });
871});
872
873describe("reconcileRetainedMountedThreadIds", () => {
874 it("retains hidden open threads and adds the active open thread", () => {
875 expect(
876 reconcileRetainedMountedThreadIds({
877 currentThreadIds: [ThreadId.make("thread-hidden")],
878 openThreadIds: [ThreadId.make("thread-hidden")],
879 activeThreadId: ThreadId.make("thread-active"),
880 activeThreadOpen: true,
881 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
882 }),
883 ).toEqual([ThreadId.make("thread-hidden"), ThreadId.make("thread-active")]);
884 });
885
886 it("can retain the active thread as hidden when it is inactive", () => {
887 expect(
888 reconcileRetainedMountedThreadIds({
889 currentThreadIds: [ThreadId.make("thread-active")],
890 openThreadIds: [ThreadId.make("thread-active")],
891 activeThreadId: ThreadId.make("thread-active"),
892 activeThreadOpen: false,
893 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
894 retainInactiveActiveThread: true,
895 }),
896 ).toEqual([ThreadId.make("thread-active")]);
897 });
898
899 it("evicts the oldest hidden threads beyond the configured cap", () => {
900 const currentThreadIds = Array.from(
901 { length: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS + 2 },
902 (_, index) => ThreadId.make(`thread-${index + 1}`),
903 );
904
905 expect(
906 reconcileRetainedMountedThreadIds({
907 currentThreadIds,
908 openThreadIds: currentThreadIds,
909 activeThreadId: null,
910 activeThreadOpen: false,
911 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
912 }),
913 ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_PREVIEW_THREADS));
914 });
915});
916
917describe("shouldWriteThreadErrorToCurrentServerThread", () => {
918 it("writes errors for a shell-derived active server thread", () => {
919 const routeThreadRef = { environmentId, threadId };
920
921 expect(
922 shouldWriteThreadErrorToCurrentServerThread({
923 activeServerThread: { environmentId, id: threadId },
924 routeThreadRef,
925 targetThreadId: threadId,
926 }),
927 ).toBe(true);
928 });
929
930 it("requires an active server thread matching the environment, route, and target", () => {
931 const routeThreadRef = { environmentId, threadId };
932
933 expect(
934 shouldWriteThreadErrorToCurrentServerThread({
935 activeServerThread: null,
936 routeThreadRef,
937 targetThreadId: threadId,
938 }),
939 ).toBe(false);
940 });
941});
942
943describe("startNewThreadForProject", () => {
944 it("starts a thread through the supplied shared handler for the active project", () => {
945 const calls: Array<{ environmentId: EnvironmentId; projectId: ProjectId }> = [];
946 const projectRef = { environmentId, projectId };
947
948 expect(
949 startNewThreadForProject(projectRef, (nextProjectRef) => {
950 calls.push(nextProjectRef);
951 return Promise.resolve();
952 }),
953 ).toBe(true);
954 expect(calls).toEqual([projectRef]);
955 });
956
957 it("does nothing when the active project is unavailable", () => {
958 let called = false;
959
960 expect(
961 startNewThreadForProject(null, () => {
962 called = true;
963 return Promise.resolve();
964 }),
965 ).toBe(false);
966 expect(called).toBe(false);
967 });
968});
969
970describe("hasServerAcknowledgedLocalDispatch", () => {
971 it("does not acknowledge unchanged server state", () => {
972 const localDispatch = createLocalDispatchSnapshot(
973 makeThread({ latestTurn: completedTurn, session: readySession }),
974 );
975
976 expect(
977 hasServerAcknowledgedLocalDispatch({
978 localDispatch,
979 phase: "ready",
980 latestTurn: completedTurn,
981 latestUserMessageId: localDispatch.latestUserMessageId,
982 session: readySession,
983 hasPendingApproval: false,
984 hasPendingUserInput: false,
985 threadError: null,
986 }),
987 ).toBe(false);
988 });
989
990 it("keeps a follow-up active while its provider session is starting", () => {
991 const localDispatch = createLocalDispatchSnapshot(
992 makeThread({ latestTurn: completedTurn, session: readySession }),
993 );
994
995 expect(
996 hasServerAcknowledgedLocalDispatch({
997 localDispatch,
998 phase: "connecting",
999 latestTurn: completedTurn,
1000 latestUserMessageId: MessageId.make("message-followup"),
1001 session: {
1002 ...readySession,
1003 status: "starting",
1004 updatedAt: "2026-03-29T00:01:00.000Z",
1005 },
1006 hasPendingApproval: false,
1007 hasPendingUserInput: false,
1008 threadError: null,
1009 }),
1010 ).toBe(false);
1011 });
1012
1013 it("acknowledges a settled newer turn", () => {
1014 const localDispatch = createLocalDispatchSnapshot(
1015 makeThread({ latestTurn: completedTurn, session: readySession }),
1016 );
1017 const newerTurn = {
1018 ...completedTurn,
1019 turnId: TurnId.make("turn-2"),
1020 requestedAt: "2026-03-29T00:01:00.000Z",
1021 startedAt: "2026-03-29T00:01:01.000Z",
1022 completedAt: "2026-03-29T00:01:30.000Z",
1023 };
1024
1025 expect(
1026 hasServerAcknowledgedLocalDispatch({
1027 localDispatch,
1028 phase: "ready",
1029 latestTurn: newerTurn,
1030 latestUserMessageId: localDispatch.latestUserMessageId,
1031 session: { ...readySession, updatedAt: newerTurn.completedAt },
1032 hasPendingApproval: false,
1033 hasPendingUserInput: false,
1034 threadError: null,
1035 }),
1036 ).toBe(true);
1037 });
1038
1039 it("waits for the matching running turn before acknowledging", () => {
1040 const localDispatch = createLocalDispatchSnapshot(
1041 makeThread({ latestTurn: completedTurn, session: readySession }),
1042 );
1043 const runningTurn = {
1044 ...completedTurn,
1045 turnId: TurnId.make("turn-2"),
1046 state: "running" as const,
1047 requestedAt: "2026-03-29T00:01:00.000Z",
1048 startedAt: "2026-03-29T00:01:01.000Z",
1049 completedAt: null,
1050 };
1051
1052 expect(
1053 hasServerAcknowledgedLocalDispatch({
1054 localDispatch,
1055 phase: "running",
1056 latestTurn: runningTurn,
1057 latestUserMessageId: localDispatch.latestUserMessageId,
1058 session: {
1059 ...readySession,
1060 status: "running",
1061 activeTurnId: TurnId.make("turn-other"),
1062 },
1063 hasPendingApproval: false,
1064 hasPendingUserInput: false,
1065 threadError: null,
1066 }),
1067 ).toBe(false);
1068 expect(
1069 hasServerAcknowledgedLocalDispatch({
1070 localDispatch,
1071 phase: "running",
1072 latestTurn: runningTurn,
1073 latestUserMessageId: localDispatch.latestUserMessageId,
1074 session: {
1075 ...readySession,
1076 status: "running",
1077 activeTurnId: runningTurn.turnId,
1078 },
1079 hasPendingApproval: false,
1080 hasPendingUserInput: false,
1081 threadError: null,
1082 }),
1083 ).toBe(true);
1084 });
1085
1086 it("acknowledges a steering message projected onto the current running turn", () => {
1087 const runningTurn = {
1088 ...completedTurn,
1089 state: "running" as const,
1090 completedAt: null,
1091 };
1092 const runningSession = {
1093 ...readySession,
1094 status: "running" as const,
1095 activeTurnId: runningTurn.turnId,
1096 };
1097 const localDispatch = createLocalDispatchSnapshot(
1098 makeThread({
1099 latestTurn: runningTurn,
1100 session: runningSession,
1101 messages: [
1102 {
1103 id: MessageId.make("message-before-steer"),
1104 role: "user",
1105 text: "Initial prompt",
1106 turnId: runningTurn.turnId,
1107 createdAt: runningTurn.requestedAt,
1108 updatedAt: runningTurn.requestedAt,
1109 streaming: false,
1110 },
1111 ],
1112 }),
1113 );
1114
1115 expect(
1116 hasServerAcknowledgedLocalDispatch({
1117 localDispatch,
1118 phase: "running",
1119 latestTurn: runningTurn,
1120 latestUserMessageId: MessageId.make("message-steer"),
1121 session: runningSession,
1122 hasPendingApproval: false,
1123 hasPendingUserInput: false,
1124 threadError: null,
1125 }),
1126 ).toBe(true);
1127 });
1128
1129 it("acknowledges pending user interaction and errors immediately", () => {
1130 const localDispatch = createLocalDispatchSnapshot(makeThread());
1131 const common = {
1132 localDispatch,
1133 phase: "ready" as const,
1134 latestTurn: null,
1135 latestUserMessageId: localDispatch.latestUserMessageId,
1136 session: null,
1137 hasPendingApproval: false,
1138 hasPendingUserInput: false,
1139 threadError: null,
1140 };
1141
1142 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingApproval: true })).toBe(true);
1143 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingUserInput: true })).toBe(true);
1144 expect(hasServerAcknowledgedLocalDispatch({ ...common, threadError: "failed" })).toBe(true);
1145 });
1146});