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

ChatView.logic.test.ts

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