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

ChatView.logic.test.ts

1,035 lines30.8 KB

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