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

ChatView.logic.test.ts

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