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

ChatView.logic.test.ts

975 lines29.1 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 serverThreadStarted: true,
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("buildLoadingThreadFromShell", () => {
320 it("preserves shell metadata and supplies empty detail collections", () => {
321 const shell = {
322 environmentId,
323 id: threadId,
324 projectId,
325 title: "Loading thread",
326 modelSelection: {
327 instanceId: ProviderInstanceId.make("codex"),
328 model: "gpt-5.4",
329 },
330 runtimeMode: "full-access",
331 interactionMode: "default",
332 branch: "main",
333 worktreePath: null,
334 latestTurn: null,
335 createdAt: now,
336 updatedAt: now,
337 archivedAt: null,
338 settledOverride: null,
339 settledAt: null,
340 snoozedUntil: null,
341 snoozedAt: null,
342 session: null,
343 latestUserMessageAt: now,
344 hasPendingApprovals: false,
345 hasPendingUserInput: false,
346 hasActionableProposedPlan: false,
347 } satisfies ThreadShell;
348​
349 expect(buildLoadingThreadFromShell(shell)).toMatchObject({
350 environmentId,
351 id: threadId,
352 projectId,
353 title: "Loading thread",
354 branch: "main",
355 deletedAt: null,
356 messages: [],
357 proposedPlans: [],
358 activities: [],
359 checkpoints: [],
360 });
361 });
362});
363​
364describe("resolveThreadMetadataUpdateForNextTurn", () => {
365 const modelSelection = {
366 instanceId: ProviderInstanceId.make("codex"),
367 model: "gpt-5.4",
368 };
369​
370 it("updates a stale local thread branch to the active checkout", () => {
371 expect(
372 resolveThreadMetadataUpdateForNextTurn({
373 currentModelSelection: modelSelection,
374 currentBranch: "feature/thread",
375 nextBranch: "feature/checkout",
376 }),
377 ).toEqual({ branch: "feature/checkout", worktreePath: null });
378 });
379​
380 it("does not write metadata when the model and branch are unchanged", () => {
381 expect(
382 resolveThreadMetadataUpdateForNextTurn({
383 currentModelSelection: modelSelection,
384 nextModelSelection: modelSelection,
385 currentBranch: "feature/current",
386 nextBranch: "feature/current",
387 }),
388 ).toBeNull();
389 });
390});
391​
392describe("buildThreadTurnInterruptInput", () => {
393 it("targets the session's active running turn", () => {
394 const activeTurnId = TurnId.make("turn-running");
395​
396 expect(
397 buildThreadTurnInterruptInput(
398 makeThread({
399 session: {
400 ...readySession,
401 status: "running",
402 activeTurnId,
403 },
404 }),
405 ),
406 ).toEqual({ threadId, turnId: activeTurnId });
407 });
408​
409 it("omits a turn id when the session is not running", () => {
410 expect(buildThreadTurnInterruptInput(makeThread({ session: readySession }))).toEqual({
411 threadId,
412 });
413 });
414});
415​
416describe("deriveComposerSendState", () => {
417 it("treats expired terminal pills as non-sendable content", () => {
418 const state = deriveComposerSendState({
419 prompt: "\uFFFC",
420 imageCount: 0,
421 terminalContexts: [
422 {
423 id: "ctx-expired",
424 threadId,
425 terminalId: "default",
426 terminalLabel: "Terminal 1",
427 lineStart: 4,
428 lineEnd: 4,
429 text: "",
430 createdAt: now,
431 },
432 ],
433 });
434​
435 expect(state.trimmedPrompt).toBe("");
436 expect(state.sendableTerminalContexts).toEqual([]);
437 expect(state.expiredTerminalContextCount).toBe(1);
438 expect(state.hasSendableContent).toBe(false);
439 });
440​
441 it("keeps text sendable while excluding expired terminal pills", () => {
442 const state = deriveComposerSendState({
443 prompt: `yoo \uFFFC waddup`,
444 imageCount: 0,
445 terminalContexts: [
446 {
447 id: "ctx-expired",
448 threadId,
449 terminalId: "default",
450 terminalLabel: "Terminal 1",
451 lineStart: 4,
452 lineEnd: 4,
453 text: "",
454 createdAt: now,
455 },
456 ],
457 });
458​
459 expect(state.trimmedPrompt).toBe("yoo waddup");
460 expect(state.expiredTerminalContextCount).toBe(1);
461 expect(state.hasSendableContent).toBe(true);
462 });
463​
464 it("treats element contexts as sendable content (no text, no images, no terminals)", () => {
465 const state = deriveComposerSendState({
466 prompt: "",
467 imageCount: 0,
468 terminalContexts: [],
469 elementContextCount: 1,
470 });
471​
472 expect(state.trimmedPrompt).toBe("");
473 expect(state.expiredTerminalContextCount).toBe(0);
474 expect(state.hasSendableContent).toBe(true);
475 });
476​
477 it("does NOT treat zero element contexts as sendable", () => {
478 expect(
479 deriveComposerSendState({
480 prompt: "",
481 imageCount: 0,
482 terminalContexts: [],
483 elementContextCount: 0,
484 }).hasSendableContent,
485 ).toBe(false);
486 });
487});
488​
489describe("buildExpiredTerminalContextToastCopy", () => {
490 it("formats empty and omission guidance", () => {
491 expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
492 title: "Expired terminal context won't be sent",
493 description: "Remove it or re-add it to include terminal output.",
494 });
495 expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
496 title: "Expired terminal contexts omitted from message",
497 description: "Re-add it if you want that terminal output included.",
498 });
499 });
500});
501​
502describe("getStartedThreadModelChangeBlockReason", () => {
503 const providers = [
504 {
505 instanceId: ProviderInstanceId.make("codex"),
506 },
507 {
508 instanceId: ProviderInstanceId.make("grok"),
509 requiresNewThreadForModelChange: true,
510 },
511 ];
512​
513 it("allows model changes before a provider session has started", () => {
514 expect(
515 getStartedThreadModelChangeBlockReason({
516 providers,
517 hasStartedSession: false,
518 currentModelSelection: {
519 instanceId: ProviderInstanceId.make("grok"),
520 model: "grok-build",
521 },
522 nextModelSelection: {
523 instanceId: ProviderInstanceId.make("grok"),
524 model: "grok-other",
525 },
526 }),
527 ).toBeNull();
528 });
529​
530 it("allows unchanged model selections for restricted providers", () => {
531 expect(
532 getStartedThreadModelChangeBlockReason({
533 providers,
534 hasStartedSession: true,
535 currentModelSelection: {
536 instanceId: ProviderInstanceId.make("grok"),
537 model: "grok-build",
538 },
539 nextModelSelection: {
540 instanceId: ProviderInstanceId.make("grok"),
541 model: "grok-build",
542 },
543 }),
544 ).toBeNull();
545 });
546​
547 it("blocks started-session model changes when either provider requires a new thread", () => {
548 expect(
549 getStartedThreadModelChangeBlockReason({
550 providers,
551 hasStartedSession: true,
552 currentModelSelection: {
553 instanceId: ProviderInstanceId.make("codex"),
554 model: "gpt-5.4",
555 },
556 nextModelSelection: {
557 instanceId: ProviderInstanceId.make("grok"),
558 model: "grok-build",
559 },
560 }),
561 ).toEqual({
562 title: "Start a new chat to change models",
563 description:
564 "This provider does not allow switching models after a conversation has started.",
565 });
566 });
567});
568​
569describe("resolveSendEnvMode", () => {
570 it("keeps worktree mode only for git repositories", () => {
571 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
572 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
573 });
574});
575​
576describe("resolveBackgroundDraftWorkspaceOptions", () => {
577 it("keeps New worktree selected without reusing the launched worktree", () => {
578 expect(
579 resolveBackgroundDraftWorkspaceOptions({
580 envMode: "worktree",
581 branch: "main",
582 startFromOrigin: true,
583 }),
584 ).toEqual({
585 envMode: "worktree",
586 branch: "main",
587 worktreePath: null,
588 startFromOrigin: true,
589 });
590 });
591});
592​
593describe("branchMismatchKey", () => {
594 it("builds a key from thread id and both branches", () => {
595 expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
596 "thread-1:feat/a:feat/b",
597 );
598 });
599​
600 it("returns null without a thread or mismatch", () => {
601 expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
602 expect(branchMismatchKey("thread-1", null)).toBeNull();
603 });
604});
605​
606describe("shouldShowBranchMismatchBanner", () => {
607 const base = {
608 hasMismatch: true,
609 isDismissed: false,
610 composerHasContent: false,
611 wasShownForCurrentMismatch: false,
612 };
613​
614 it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
615 expect(shouldShowBranchMismatchBanner(base)).toBe(false);
616 });
617​
618 it("shows once the composer has draft content", () => {
619 expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
620 });
621​
622 it("stays mounted after the draft clears once shown for the current mismatch", () => {
623 expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
624 true,
625 );
626 });
627​
628 it("never shows when dismissed or without a mismatch", () => {
629 expect(
630 shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
631 ).toBe(false);
632 expect(
633 shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
634 ).toBe(false);
635 });
636});
637​
638describe("shouldShowPlanFollowUpPrompt", () => {
639 const base = {
640 pendingUserInputCount: 0,
641 interactionMode: "plan" as const,
642 latestTurnSettled: true,
643 hasActionableProposedPlan: true,
644 hasComposerAttachments: false,
645 };
646​
647 it("shows plan actions for a settled actionable plan without attachments", () => {
648 expect(shouldShowPlanFollowUpPrompt(base)).toBe(true);
649 });
650​
651 it("hides plan actions while the composer has staged attachments", () => {
652 expect(shouldShowPlanFollowUpPrompt({ ...base, hasComposerAttachments: true })).toBe(false);
653 });
654​
655 it("preserves the existing plan follow-up gates", () => {
656 expect(shouldShowPlanFollowUpPrompt({ ...base, pendingUserInputCount: 1 })).toBe(false);
657 expect(shouldShowPlanFollowUpPrompt({ ...base, interactionMode: "default" })).toBe(false);
658 expect(shouldShowPlanFollowUpPrompt({ ...base, latestTurnSettled: false })).toBe(false);
659 expect(shouldShowPlanFollowUpPrompt({ ...base, hasActionableProposedPlan: false })).toBe(false);
660 });
661});
662​
663describe("session branch mismatch dismissal", () => {
664 it("tracks dismissed keys and treats other keys as active", () => {
665 expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
666 dismissBranchMismatchForSession("t1:a:b");
667 expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
668 expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
669 expect(isBranchMismatchDismissedForSession(null)).toBe(false);
670 });
671});
672​
673describe("reconcileMountedTerminalThreadIds", () => {
674 it("keeps open threads and makes the active thread most recent", () => {
675 expect(
676 reconcileMountedTerminalThreadIds({
677 currentThreadIds: ["thread-a", "thread-b", "thread-c"],
678 openThreadIds: ["thread-a", "thread-b", "thread-c"],
679 activeThreadId: "thread-a",
680 activeThreadTerminalOpen: true,
681 maxHiddenThreadCount: 2,
682 }),
683 ).toEqual(["thread-b", "thread-c", "thread-a"]);
684 });
685​
686 it("drops closed threads and enforces the hidden mounted cap", () => {
687 const ids = Array.from(
688 { length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
689 (_, index) => `thread-${index}`,
690 );
691 expect(
692 reconcileMountedTerminalThreadIds({
693 currentThreadIds: ids,
694 openThreadIds: ids.slice(1),
695 activeThreadId: null,
696 activeThreadTerminalOpen: false,
697 }),
698 ).toEqual(ids.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
699 });
700});
701​
702describe("reconcileRetainedMountedThreadIds", () => {
703 it("retains hidden open threads and adds the active open thread", () => {
704 expect(
705 reconcileRetainedMountedThreadIds({
706 currentThreadIds: [ThreadId.make("thread-hidden")],
707 openThreadIds: [ThreadId.make("thread-hidden")],
708 activeThreadId: ThreadId.make("thread-active"),
709 activeThreadOpen: true,
710 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
711 }),
712 ).toEqual([ThreadId.make("thread-hidden"), ThreadId.make("thread-active")]);
713 });
714​
715 it("can retain the active thread as hidden when it is inactive", () => {
716 expect(
717 reconcileRetainedMountedThreadIds({
718 currentThreadIds: [ThreadId.make("thread-active")],
719 openThreadIds: [ThreadId.make("thread-active")],
720 activeThreadId: ThreadId.make("thread-active"),
721 activeThreadOpen: false,
722 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
723 retainInactiveActiveThread: true,
724 }),
725 ).toEqual([ThreadId.make("thread-active")]);
726 });
727​
728 it("evicts the oldest hidden threads beyond the configured cap", () => {
729 const currentThreadIds = Array.from(
730 { length: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS + 2 },
731 (_, index) => ThreadId.make(`thread-${index + 1}`),
732 );
733​
734 expect(
735 reconcileRetainedMountedThreadIds({
736 currentThreadIds,
737 openThreadIds: currentThreadIds,
738 activeThreadId: null,
739 activeThreadOpen: false,
740 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
741 }),
742 ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_PREVIEW_THREADS));
743 });
744});
745​
746describe("shouldWriteThreadErrorToCurrentServerThread", () => {
747 it("writes errors for a shell-derived active server thread", () => {
748 const routeThreadRef = { environmentId, threadId };
749​
750 expect(
751 shouldWriteThreadErrorToCurrentServerThread({
752 activeServerThread: { environmentId, id: threadId },
753 routeThreadRef,
754 targetThreadId: threadId,
755 }),
756 ).toBe(true);
757 });
758​
759 it("requires an active server thread matching the environment, route, and target", () => {
760 const routeThreadRef = { environmentId, threadId };
761​
762 expect(
763 shouldWriteThreadErrorToCurrentServerThread({
764 activeServerThread: null,
765 routeThreadRef,
766 targetThreadId: threadId,
767 }),
768 ).toBe(false);
769 });
770});
771​
772describe("startNewThreadForProject", () => {
773 it("starts a thread through the supplied shared handler for the active project", () => {
774 const calls: Array<{ environmentId: EnvironmentId; projectId: ProjectId }> = [];
775 const projectRef = { environmentId, projectId };
776​
777 expect(
778 startNewThreadForProject(projectRef, (nextProjectRef) => {
779 calls.push(nextProjectRef);
780 return Promise.resolve();
781 }),
782 ).toBe(true);
783 expect(calls).toEqual([projectRef]);
784 });
785​
786 it("does nothing when the active project is unavailable", () => {
787 let called = false;
788​
789 expect(
790 startNewThreadForProject(null, () => {
791 called = true;
792 return Promise.resolve();
793 }),
794 ).toBe(false);
795 expect(called).toBe(false);
796 });
797});
798​
799describe("hasServerAcknowledgedLocalDispatch", () => {
800 it("does not acknowledge unchanged server state", () => {
801 const localDispatch = createLocalDispatchSnapshot(
802 makeThread({ latestTurn: completedTurn, session: readySession }),
803 );
804​
805 expect(
806 hasServerAcknowledgedLocalDispatch({
807 localDispatch,
808 phase: "ready",
809 latestTurn: completedTurn,
810 latestUserMessageId: localDispatch.latestUserMessageId,
811 session: readySession,
812 hasPendingApproval: false,
813 hasPendingUserInput: false,
814 threadError: null,
815 }),
816 ).toBe(false);
817 });
818​
819 it("keeps a follow-up active while its provider session is starting", () => {
820 const localDispatch = createLocalDispatchSnapshot(
821 makeThread({ latestTurn: completedTurn, session: readySession }),
822 );
823​
824 expect(
825 hasServerAcknowledgedLocalDispatch({
826 localDispatch,
827 phase: "connecting",
828 latestTurn: completedTurn,
829 latestUserMessageId: MessageId.make("message-followup"),
830 session: {
831 ...readySession,
832 status: "starting",
833 updatedAt: "2026-03-29T00:01:00.000Z",
834 },
835 hasPendingApproval: false,
836 hasPendingUserInput: false,
837 threadError: null,
838 }),
839 ).toBe(false);
840 });
841​
842 it("acknowledges a settled newer turn", () => {
843 const localDispatch = createLocalDispatchSnapshot(
844 makeThread({ latestTurn: completedTurn, session: readySession }),
845 );
846 const newerTurn = {
847 ...completedTurn,
848 turnId: TurnId.make("turn-2"),
849 requestedAt: "2026-03-29T00:01:00.000Z",
850 startedAt: "2026-03-29T00:01:01.000Z",
851 completedAt: "2026-03-29T00:01:30.000Z",
852 };
853​
854 expect(
855 hasServerAcknowledgedLocalDispatch({
856 localDispatch,
857 phase: "ready",
858 latestTurn: newerTurn,
859 latestUserMessageId: localDispatch.latestUserMessageId,
860 session: { ...readySession, updatedAt: newerTurn.completedAt },
861 hasPendingApproval: false,
862 hasPendingUserInput: false,
863 threadError: null,
864 }),
865 ).toBe(true);
866 });
867​
868 it("waits for the matching running turn before acknowledging", () => {
869 const localDispatch = createLocalDispatchSnapshot(
870 makeThread({ latestTurn: completedTurn, session: readySession }),
871 );
872 const runningTurn = {
873 ...completedTurn,
874 turnId: TurnId.make("turn-2"),
875 state: "running" as const,
876 requestedAt: "2026-03-29T00:01:00.000Z",
877 startedAt: "2026-03-29T00:01:01.000Z",
878 completedAt: null,
879 };
880​
881 expect(
882 hasServerAcknowledgedLocalDispatch({
883 localDispatch,
884 phase: "running",
885 latestTurn: runningTurn,
886 latestUserMessageId: localDispatch.latestUserMessageId,
887 session: {
888 ...readySession,
889 status: "running",
890 activeTurnId: TurnId.make("turn-other"),
891 },
892 hasPendingApproval: false,
893 hasPendingUserInput: false,
894 threadError: null,
895 }),
896 ).toBe(false);
897 expect(
898 hasServerAcknowledgedLocalDispatch({
899 localDispatch,
900 phase: "running",
901 latestTurn: runningTurn,
902 latestUserMessageId: localDispatch.latestUserMessageId,
903 session: {
904 ...readySession,
905 status: "running",
906 activeTurnId: runningTurn.turnId,
907 },
908 hasPendingApproval: false,
909 hasPendingUserInput: false,
910 threadError: null,
911 }),
912 ).toBe(true);
913 });
914​
915 it("acknowledges a steering message projected onto the current running turn", () => {
916 const runningTurn = {
917 ...completedTurn,
918 state: "running" as const,
919 completedAt: null,
920 };
921 const runningSession = {
922 ...readySession,
923 status: "running" as const,
924 activeTurnId: runningTurn.turnId,
925 };
926 const localDispatch = createLocalDispatchSnapshot(
927 makeThread({
928 latestTurn: runningTurn,
929 session: runningSession,
930 messages: [
931 {
932 id: MessageId.make("message-before-steer"),
933 role: "user",
934 text: "Initial prompt",
935 turnId: runningTurn.turnId,
936 createdAt: runningTurn.requestedAt,
937 updatedAt: runningTurn.requestedAt,
938 streaming: false,
939 },
940 ],
941 }),
942 );
943​
944 expect(
945 hasServerAcknowledgedLocalDispatch({
946 localDispatch,
947 phase: "running",
948 latestTurn: runningTurn,
949 latestUserMessageId: MessageId.make("message-steer"),
950 session: runningSession,
951 hasPendingApproval: false,
952 hasPendingUserInput: false,
953 threadError: null,
954 }),
955 ).toBe(true);
956 });
957​
958 it("acknowledges pending user interaction and errors immediately", () => {
959 const localDispatch = createLocalDispatchSnapshot(makeThread());
960 const common = {
961 localDispatch,
962 phase: "ready" as const,
963 latestTurn: null,
964 latestUserMessageId: localDispatch.latestUserMessageId,
965 session: null,
966 hasPendingApproval: false,
967 hasPendingUserInput: false,
968 threadError: null,
969 };
970​
971 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingApproval: true })).toBe(true);
972 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingUserInput: true })).toBe(true);
973 expect(hasServerAcknowledgedLocalDispatch({ ...common, threadError: "failed" })).toBe(true);
974 });
975});