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

ChatView.logic.test.ts

1,223 lines36.5 KB

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