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

ChatView.logic.test.ts

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