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

ChatView.logic.test.ts

878 lines26.5 KB

1import {
2 EnvironmentId,
3 MessageId,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 RunId,
8 TurnItemId,
9 type OrchestrationV2ProjectedTurnItem,
10} from "@t3tools/contracts";
11import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";
12import * as DateTime from "effect/DateTime";
13import { describe, expect, it } from "vite-plus/test";
14​
15import type { Thread } from "../types";
16import { makeThreadFixture } from "../test-fixtures";
17import {
18 MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
19 MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
20 branchMismatchKey,
21 buildExpiredTerminalContextToastCopy,
22 createLocalDispatchSnapshot,
23 deriveCommittedServerUserMessageIds,
24 deriveComposerSendState,
25 dismissBranchMismatchForSession,
26 getStartedThreadModelChangeBlockReason,
27 hasServerAcknowledgedLocalDispatch,
28 isBranchMismatchDismissedForSession,
29 isVideoPreviewRequestCurrent,
30 loadVideoPreviewUrl,
31 reconcileMountedTerminalThreadIds,
32 reconcileRetainedMountedThreadIds,
33 resolveDraftPromotionNavigationTarget,
34 resolveEffectiveInteractionMode,
35 resolveThreadMetadataUpdateForNextTurn,
36 resolveSendEnvMode,
37 startNewThreadForProject,
38 shouldShowBranchMismatchBanner,
39 shouldShowComposerContextStrip,
40 shouldShowPlanFollowUpPrompt,
41 shouldWriteThreadErrorToCurrentServerThread,
42} from "./ChatView.logic";
43​
44describe("loadVideoPreviewUrl", () => {
45 it("loads video bytes into an object URL", async () => {
46 const objectUrl = await loadVideoPreviewUrl("data:video/mp4;base64,AA==");
47 expect(objectUrl).toMatch(/^blob:/);
48 URL.revokeObjectURL(objectUrl);
49 });
50​
51 it("stops loading when the preview request is cancelled", async () => {
52 const controller = new AbortController();
53 controller.abort();
54​
55 await expect(
56 loadVideoPreviewUrl("data:video/mp4;base64,AA==", controller.signal),
57 ).rejects.toMatchObject({ name: "AbortError" });
58 });
59});
60​
61describe("isVideoPreviewRequestCurrent", () => {
62 it("rejects changed threads and replaced previews", () => {
63 expect(isVideoPreviewRequestCurrent("thread-1", "thread-2", 1, 1)).toBe(false);
64 expect(isVideoPreviewRequestCurrent("thread-1", "thread-1", 1, 2)).toBe(false);
65 expect(isVideoPreviewRequestCurrent("thread-1", "thread-1", 2, 2)).toBe(true);
66 });
67});
68​
69const environmentId = EnvironmentId.make("environment-local");
70const projectId = ProjectId.make("project-1");
71const threadId = ThreadId.make("thread-1");
72const now = "2026-03-29T00:00:00.000Z";
73const helloWorldTemplate: CodexArtifactTemplate = {
74 artifactKind: "document",
75 displayName: "Hello World",
76 skillDirectory: "/Users/test/.codex/skills/artifact-template-hello-world",
77 skillName: "artifact-template-hello-world",
78};
79​
80function makeThread(overrides: Partial<Thread> = {}): Thread {
81 return makeThreadFixture({
82 id: threadId,
83 environmentId,
84 projectId,
85 title: "Thread",
86 modelSelection: {
87 instanceId: ProviderInstanceId.make("codex"),
88 model: "gpt-5.4",
89 },
90 runtimeMode: "full-access",
91 interactionMode: "default",
92 runtime: null,
93 messages: [],
94 proposedPlans: [],
95 createdAt: now,
96 updatedAt: now,
97 archivedAt: null,
98 settledOverride: null,
99 settledAt: null,
100 deletedAt: null,
101 latestRun: null,
102 branch: null,
103 worktreePath: null,
104 ...overrides,
105 });
107​
108const completedTurn = {
109 runId: RunId.make("turn-1"),
110 status: "completed" as const,
111 requestedAt: now,
112 startedAt: "2026-03-29T00:00:01.000Z",
113 completedAt: "2026-03-29T00:00:10.000Z",
114 assistantMessageId: null,
115};
116​
117const readySession = {
118 status: "completed" as const,
119 providerName: "codex",
120 providerInstanceId: ProviderInstanceId.make("codex"),
121 activeRunId: null,
122 lastError: null,
123 updatedAt: "2026-03-29T00:00:10.000Z",
124};
125​
126describe("resolveDraftPromotionNavigationTarget", () => {
127 const serverThreadRef = { environmentId, threadId };
128 const preparingRun = {
129 ...completedTurn,
130 status: "preparing" as const,
131 startedAt: null,
132 completedAt: null,
133 };
134​
135 it("stays on the draft while the workspace is still preparing", () => {
136 expect(
137 resolveDraftPromotionNavigationTarget({
138 serverThreadRef,
139 serverThread: makeThread({ latestRun: preparingRun }),
140 backgroundSubmissionPending: false,
141 }),
142 ).toBeNull();
143 expect(
144 resolveDraftPromotionNavigationTarget({
145 serverThreadRef,
146 serverThread: makeThread(),
147 backgroundSubmissionPending: false,
148 }),
149 ).toBeNull();
150 });
151​
152 it("navigates once the run starts or startup stops", () => {
153 expect(
154 resolveDraftPromotionNavigationTarget({
155 serverThreadRef,
156 serverThread: makeThread({ latestRun: completedTurn }),
157 backgroundSubmissionPending: false,
158 }),
159 ).toBe(serverThreadRef);
160 expect(
161 resolveDraftPromotionNavigationTarget({
162 serverThreadRef,
163 serverThread: makeThread({
164 latestRun: { ...preparingRun, status: "failed" as const },
165 }),
166 backgroundSubmissionPending: false,
167 }),
168 ).toBe(serverThreadRef);
169 });
170​
171 it("defers while a background submission is pending", () => {
172 expect(
173 resolveDraftPromotionNavigationTarget({
174 serverThreadRef,
175 serverThread: makeThread({ latestRun: completedTurn }),
176 backgroundSubmissionPending: true,
177 }),
178 ).toBeNull();
179 });
180});
181​
182describe("resolveEffectiveInteractionMode", () => {
183 it("forces build mode when legacy plan mode is disabled", () => {
184 expect(
185 resolveEffectiveInteractionMode({
186 planModeEnabled: false,
187 composerInteractionMode: "plan",
188 threadInteractionMode: "plan",
189 }),
190 ).toBe("default");
191 });
192​
193 it("uses the saved mode while legacy plan mode is enabled", () => {
194 expect(
195 resolveEffectiveInteractionMode({
196 planModeEnabled: true,
197 composerInteractionMode: null,
198 threadInteractionMode: "plan",
199 }),
200 ).toBe("plan");
201 });
202});
203​
204describe("resolveThreadMetadataUpdateForNextTurn", () => {
205 const modelSelection = {
206 instanceId: ProviderInstanceId.make("codex"),
207 model: "gpt-5.4",
208 };
209​
210 it("updates a stale local thread branch to the active checkout", () => {
211 expect(
212 resolveThreadMetadataUpdateForNextTurn({
213 currentModelSelection: modelSelection,
214 currentBranch: "feature/thread",
215 nextBranch: "feature/checkout",
216 }),
217 ).toEqual({ branch: "feature/checkout", worktreePath: null });
218 });
219​
220 it("does not write metadata when the model and branch are unchanged", () => {
221 expect(
222 resolveThreadMetadataUpdateForNextTurn({
223 currentModelSelection: modelSelection,
224 nextModelSelection: modelSelection,
225 currentBranch: "feature/current",
226 nextBranch: "feature/current",
227 }),
228 ).toBeNull();
229 });
230});
231​
232describe("shouldShowComposerContextStrip", () => {
233 it("shows git context while composing a new thread", () => {
234 expect(
235 shouldShowComposerContextStrip({
236 isDraftHeroState: true,
237 isGitRepo: true,
238 hasActiveProject: true,
239 persistInActiveThreads: false,
240 }),
241 ).toBe(true);
242 });
243​
244 it("keeps git context in an active thread only when requested", () => {
245 expect(
246 shouldShowComposerContextStrip({
247 isDraftHeroState: false,
248 isGitRepo: true,
249 hasActiveProject: true,
250 persistInActiveThreads: true,
251 }),
252 ).toBe(true);
253 expect(
254 shouldShowComposerContextStrip({
255 isDraftHeroState: false,
256 isGitRepo: true,
257 hasActiveProject: true,
258 persistInActiveThreads: false,
259 }),
260 ).toBe(false);
261 });
262​
263 it("hides git context without a git-backed project", () => {
264 expect(
265 shouldShowComposerContextStrip({
266 isDraftHeroState: true,
267 isGitRepo: false,
268 hasActiveProject: true,
269 persistInActiveThreads: true,
270 }),
271 ).toBe(false);
272 expect(
273 shouldShowComposerContextStrip({
274 isDraftHeroState: true,
275 isGitRepo: true,
276 hasActiveProject: false,
277 persistInActiveThreads: true,
278 }),
279 ).toBe(false);
280 });
281});
282describe("deriveComposerSendState", () => {
283 it("treats expired terminal pills as non-sendable content", () => {
284 const state = deriveComposerSendState({
285 prompt: "\uFFFC",
286 imageCount: 0,
287 terminalContexts: [
288 {
289 id: "ctx-expired",
290 threadId,
291 terminalId: "default",
292 terminalLabel: "Terminal 1",
293 lineStart: 4,
294 lineEnd: 4,
295 text: "",
296 createdAt: now,
297 },
298 ],
299 });
300​
301 expect(state.trimmedPrompt).toBe("");
302 expect(state.sendableTerminalContexts).toEqual([]);
303 expect(state.expiredTerminalContextCount).toBe(1);
304 expect(state.hasSendableContent).toBe(false);
305 });
306​
307 it("keeps text sendable while excluding expired terminal pills", () => {
308 const state = deriveComposerSendState({
309 prompt: `yoo \uFFFC waddup`,
310 imageCount: 0,
311 terminalContexts: [
312 {
313 id: "ctx-expired",
314 threadId,
315 terminalId: "default",
316 terminalLabel: "Terminal 1",
317 lineStart: 4,
318 lineEnd: 4,
319 text: "",
320 createdAt: now,
321 },
322 ],
323 });
324​
325 expect(state.trimmedPrompt).toBe("yoo waddup");
326 expect(state.expiredTerminalContextCount).toBe(1);
327 expect(state.hasSendableContent).toBe(true);
328 });
329​
330 it("treats element contexts as sendable content (no text, no images, no terminals)", () => {
331 const state = deriveComposerSendState({
332 prompt: "",
333 imageCount: 0,
334 terminalContexts: [],
335 elementContextCount: 1,
336 });
337​
338 expect(state.trimmedPrompt).toBe("");
339 expect(state.expiredTerminalContextCount).toBe(0);
340 expect(state.hasSendableContent).toBe(true);
341 });
342​
343 it("does NOT treat zero element contexts as sendable", () => {
344 expect(
345 deriveComposerSendState({
346 prompt: "",
347 imageCount: 0,
348 terminalContexts: [],
349 elementContextCount: 0,
350 }).hasSendableContent,
351 ).toBe(false);
352 });
353});
354​
355describe("buildExpiredTerminalContextToastCopy", () => {
356 it("formats empty and omission guidance", () => {
357 expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
358 title: "Expired terminal context won't be sent",
359 description: "Remove it or re-add it to include terminal output.",
360 });
361 expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
362 title: "Expired terminal contexts omitted from message",
363 description: "Re-add it if you want that terminal output included.",
364 });
365 });
366});
367​
368describe("getStartedThreadModelChangeBlockReason", () => {
369 const providers = [
370 {
371 instanceId: ProviderInstanceId.make("codex"),
372 },
373 {
374 instanceId: ProviderInstanceId.make("grok"),
375 requiresNewThreadForModelChange: true,
376 },
377 ];
378​
379 it("allows model changes before a provider session has started", () => {
380 expect(
381 getStartedThreadModelChangeBlockReason({
382 providers,
383 hasStartedSession: false,
384 currentModelSelection: {
385 instanceId: ProviderInstanceId.make("grok"),
386 model: "grok-build",
387 },
388 nextModelSelection: {
389 instanceId: ProviderInstanceId.make("grok"),
390 model: "grok-other",
391 },
392 }),
393 ).toBeNull();
394 });
395​
396 it("allows unchanged model selections for restricted providers", () => {
397 expect(
398 getStartedThreadModelChangeBlockReason({
399 providers,
400 hasStartedSession: true,
401 currentModelSelection: {
402 instanceId: ProviderInstanceId.make("grok"),
403 model: "grok-build",
404 },
405 nextModelSelection: {
406 instanceId: ProviderInstanceId.make("grok"),
407 model: "grok-build",
408 },
409 }),
410 ).toBeNull();
411 });
412​
413 it("blocks started-session model changes for providers that require a new thread", () => {
414 expect(
415 getStartedThreadModelChangeBlockReason({
416 providers,
417 hasStartedSession: true,
418 currentModelSelection: {
419 instanceId: ProviderInstanceId.make("grok"),
420 model: "grok-build",
421 },
422 nextModelSelection: {
423 instanceId: ProviderInstanceId.make("grok"),
424 model: "grok-other",
425 },
426 }),
427 ).toEqual({
428 title: "Start a new chat to change models",
429 description:
430 "This provider does not allow switching models after a conversation has started.",
431 });
432 });
433});
434​
435describe("resolveSendEnvMode", () => {
436 it("keeps worktree mode only for git repositories", () => {
437 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
438 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
439 });
440});
441​
442describe("branchMismatchKey", () => {
443 it("builds a key from thread id and both branches", () => {
444 expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
445 "thread-1:feat/a:feat/b",
446 );
447 });
448​
449 it("returns null without a thread or mismatch", () => {
450 expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
451 expect(branchMismatchKey("thread-1", null)).toBeNull();
452 });
453});
454​
455describe("shouldShowBranchMismatchBanner", () => {
456 const base = {
457 hasMismatch: true,
458 isDismissed: false,
459 composerHasContent: false,
460 wasShownForCurrentMismatch: false,
461 };
462​
463 it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
464 expect(shouldShowBranchMismatchBanner(base)).toBe(false);
465 });
466​
467 it("shows once the composer has draft content", () => {
468 expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
469 });
470​
471 it("stays mounted after the draft clears once shown for the current mismatch", () => {
472 expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
473 true,
474 );
475 });
476​
477 it("never shows when dismissed or without a mismatch", () => {
478 expect(
479 shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
480 ).toBe(false);
481 expect(
482 shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
483 ).toBe(false);
484 });
485});
486​
487describe("shouldShowPlanFollowUpPrompt", () => {
488 const base = {
489 pendingUserInputCount: 0,
490 interactionMode: "plan" as const,
491 latestTurnSettled: true,
492 hasActionableProposedPlan: true,
493 hasComposerAttachments: false,
494 };
495​
496 it("shows plan actions for a settled actionable plan without attachments", () => {
497 expect(shouldShowPlanFollowUpPrompt(base)).toBe(true);
498 });
499​
500 it("hides plan actions while the composer has staged attachments", () => {
501 expect(shouldShowPlanFollowUpPrompt({ ...base, hasComposerAttachments: true })).toBe(false);
502 });
503​
504 it("preserves the existing plan follow-up gates", () => {
505 expect(shouldShowPlanFollowUpPrompt({ ...base, pendingUserInputCount: 1 })).toBe(false);
506 expect(shouldShowPlanFollowUpPrompt({ ...base, interactionMode: "default" })).toBe(false);
507 expect(shouldShowPlanFollowUpPrompt({ ...base, latestTurnSettled: false })).toBe(false);
508 expect(shouldShowPlanFollowUpPrompt({ ...base, hasActionableProposedPlan: false })).toBe(false);
509 });
510});
511​
512describe("session branch mismatch dismissal", () => {
513 it("tracks dismissed keys and treats other keys as active", () => {
514 expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
515 dismissBranchMismatchForSession("t1:a:b");
516 expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
517 expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
518 expect(isBranchMismatchDismissedForSession(null)).toBe(false);
519 });
520});
521​
522describe("reconcileMountedTerminalThreadIds", () => {
523 it("keeps open threads and makes the active thread most recent", () => {
524 expect(
525 reconcileMountedTerminalThreadIds({
526 currentThreadIds: ["thread-a", "thread-b", "thread-c"],
527 openThreadIds: ["thread-a", "thread-b", "thread-c"],
528 activeThreadId: "thread-a",
529 activeThreadTerminalOpen: true,
530 maxHiddenThreadCount: 2,
531 }),
532 ).toEqual(["thread-b", "thread-c", "thread-a"]);
533 });
534​
535 it("drops closed threads and enforces the hidden mounted cap", () => {
536 const ids = Array.from(
537 { length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
538 (_, index) => `thread-${index}`,
539 );
540 expect(
541 reconcileMountedTerminalThreadIds({
542 currentThreadIds: ids,
543 openThreadIds: ids.slice(1),
544 activeThreadId: null,
545 activeThreadTerminalOpen: false,
546 }),
547 ).toEqual(ids.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
548 });
549});
550​
551describe("reconcileRetainedMountedThreadIds", () => {
552 it("retains hidden open threads and adds the active open thread", () => {
553 expect(
554 reconcileRetainedMountedThreadIds({
555 currentThreadIds: [ThreadId.make("thread-hidden")],
556 openThreadIds: [ThreadId.make("thread-hidden")],
557 activeThreadId: ThreadId.make("thread-active"),
558 activeThreadOpen: true,
559 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
560 }),
561 ).toEqual([ThreadId.make("thread-hidden"), ThreadId.make("thread-active")]);
562 });
563​
564 it("can retain the active thread as hidden when it is inactive", () => {
565 expect(
566 reconcileRetainedMountedThreadIds({
567 currentThreadIds: [ThreadId.make("thread-active")],
568 openThreadIds: [ThreadId.make("thread-active")],
569 activeThreadId: ThreadId.make("thread-active"),
570 activeThreadOpen: false,
571 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
572 retainInactiveActiveThread: true,
573 }),
574 ).toEqual([ThreadId.make("thread-active")]);
575 });
576​
577 it("evicts the oldest hidden threads beyond the configured cap", () => {
578 const currentThreadIds = Array.from(
579 { length: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS + 2 },
580 (_, index) => ThreadId.make(`thread-${index + 1}`),
581 );
582​
583 expect(
584 reconcileRetainedMountedThreadIds({
585 currentThreadIds,
586 openThreadIds: currentThreadIds,
587 activeThreadId: null,
588 activeThreadOpen: false,
589 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
590 }),
591 ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_PREVIEW_THREADS));
592 });
593});
594​
595describe("shouldWriteThreadErrorToCurrentServerThread", () => {
596 it("requires the environment, route thread, and target thread to match", () => {
597 const routeThreadRef = { environmentId, threadId };
598​
599 expect(
600 shouldWriteThreadErrorToCurrentServerThread({
601 serverThread: { environmentId, id: threadId },
602 routeThreadRef,
603 targetThreadId: threadId,
604 }),
605 ).toBe(true);
606 expect(
607 shouldWriteThreadErrorToCurrentServerThread({
608 serverThread: null,
609 routeThreadRef,
610 targetThreadId: threadId,
611 }),
612 ).toBe(false);
613 });
614});
615​
616describe("startNewThreadForProject", () => {
617 it("starts a thread through the supplied shared handler for the active project", () => {
618 const calls: Array<{ environmentId: EnvironmentId; projectId: ProjectId }> = [];
619 const projectRef = { environmentId, projectId };
620​
621 expect(
622 startNewThreadForProject(projectRef, (nextProjectRef) => {
623 calls.push(nextProjectRef);
624 return Promise.resolve();
625 }),
626 ).toBe(true);
627 expect(calls).toEqual([projectRef]);
628 });
629​
630 it("does nothing when the active project is unavailable", () => {
631 let called = false;
632​
633 expect(
634 startNewThreadForProject(null, () => {
635 called = true;
636 return Promise.resolve();
637 }),
638 ).toBe(false);
639 expect(called).toBe(false);
640 });
641});
642​
643describe("hasServerAcknowledgedLocalDispatch", () => {
644 it("does not acknowledge unchanged server state", () => {
645 const localDispatch = createLocalDispatchSnapshot(
646 makeThread({ latestRun: completedTurn, runtime: readySession }),
647 );
648​
649 expect(
650 hasServerAcknowledgedLocalDispatch({
651 localDispatch,
652 phase: "ready",
653 latestRun: completedTurn,
654 runtime: readySession,
655 hasPendingApproval: false,
656 hasPendingUserInput: false,
657 threadError: null,
658 }),
659 ).toBe(false);
660 });
661​
662 it("acknowledges a settled newer turn", () => {
663 const localDispatch = createLocalDispatchSnapshot(
664 makeThread({ latestRun: completedTurn, runtime: readySession }),
665 );
666 const newerTurn = {
667 ...completedTurn,
668 runId: RunId.make("turn-2"),
669 requestedAt: "2026-03-29T00:01:00.000Z",
670 startedAt: "2026-03-29T00:01:01.000Z",
671 completedAt: "2026-03-29T00:01:30.000Z",
672 };
673​
674 expect(
675 hasServerAcknowledgedLocalDispatch({
676 localDispatch,
677 phase: "ready",
678 latestRun: newerTurn,
679 runtime: { ...readySession, updatedAt: newerTurn.completedAt },
680 hasPendingApproval: false,
681 hasPendingUserInput: false,
682 threadError: null,
683 }),
684 ).toBe(true);
685 });
686​
687 it("waits for the matching running turn before acknowledging", () => {
688 const localDispatch = createLocalDispatchSnapshot(
689 makeThread({ latestRun: completedTurn, runtime: readySession }),
690 );
691 const runningTurn = {
692 ...completedTurn,
693 runId: RunId.make("turn-2"),
694 status: "running" as const,
695 requestedAt: "2026-03-29T00:01:00.000Z",
696 startedAt: "2026-03-29T00:01:01.000Z",
697 completedAt: null,
698 };
699​
700 expect(
701 hasServerAcknowledgedLocalDispatch({
702 localDispatch,
703 phase: "running",
704 latestRun: runningTurn,
705 runtime: {
706 ...readySession,
707 status: "running",
708 activeRunId: RunId.make("turn-other"),
709 },
710 hasPendingApproval: false,
711 hasPendingUserInput: false,
712 threadError: null,
713 }),
714 ).toBe(false);
715 expect(
716 hasServerAcknowledgedLocalDispatch({
717 localDispatch,
718 phase: "running",
719 latestRun: runningTurn,
720 runtime: {
721 ...readySession,
722 status: "running",
723 activeRunId: runningTurn.runId,
724 },
725 hasPendingApproval: false,
726 hasPendingUserInput: false,
727 threadError: null,
728 }),
729 ).toBe(true);
730 });
731​
732 it("acknowledges a steering message projected onto the current running run", () => {
733 const runningRun = {
734 ...completedTurn,
735 status: "running" as const,
736 completedAt: null,
737 };
738 const runningRuntime = {
739 ...readySession,
740 status: "running" as const,
741 activeRunId: runningRun.runId,
742 };
743 const localDispatch = createLocalDispatchSnapshot(
744 makeThread({ latestRun: runningRun, runtime: runningRuntime }),
745 { latestUserMessageId: MessageId.make("message-before-steer") },
746 );
747​
748 expect(
749 hasServerAcknowledgedLocalDispatch({
750 localDispatch,
751 phase: "running",
752 latestRun: runningRun,
753 latestUserMessageId: MessageId.make("message-steer"),
754 runtime: runningRuntime,
755 hasPendingApproval: false,
756 hasPendingUserInput: false,
757 threadError: null,
758 }),
759 ).toBe(true);
760 });
761​
762 it("acknowledges pending user interaction and errors immediately", () => {
763 const localDispatch = createLocalDispatchSnapshot(makeThread());
764 const common = {
765 localDispatch,
766 phase: "ready" as const,
767 latestRun: null,
768 runtime: null,
769 hasPendingApproval: false,
770 hasPendingUserInput: false,
771 threadError: null,
772 };
773​
774 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingApproval: true })).toBe(true);
775 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingUserInput: true })).toBe(true);
776 expect(hasServerAcknowledgedLocalDispatch({ ...common, threadError: "failed" })).toBe(true);
777 });
778});
779​
780describe("deriveCommittedServerUserMessageIds", () => {
781 it("tracks only committed user turn items, not assistant rows or projection-only messages", () => {
782 const turnStartId = MessageId.make("message-turn-start");
783 const steerId = MessageId.make("message-steer");
784 const assistantId = MessageId.make("message-assistant");
785 const committedAt = DateTime.makeUnsafe("2026-06-26T17:50:15.180Z");
786 const runId = RunId.make("run:thread:thread-1:ordinal:1");
787 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
788 {
789 position: 0,
790 visibility: "local",
791 sourceThreadId: threadId,
792 sourceItemId: TurnItemId.make("turn-item:message-turn-start"),
793 item: {
794 id: TurnItemId.make("turn-item:message-turn-start"),
795 threadId,
796 runId,
797 nodeId: null,
798 providerThreadId: null,
799 providerTurnId: null,
800 nativeItemRef: null,
801 parentItemId: null,
802 ordinal: 1,
803 status: "completed",
804 title: null,
805 startedAt: committedAt,
806 completedAt: committedAt,
807 updatedAt: committedAt,
808 createdBy: "user",
809 creationSource: "web",
810 type: "user_message",
811 messageId: turnStartId,
812 inputIntent: "turn_start",
813 text: "start",
814 attachments: [],
815 },
816 },
817 {
818 position: 1,
819 visibility: "local",
820 sourceThreadId: threadId,
821 sourceItemId: TurnItemId.make("turn-item:message-assistant"),
822 item: {
823 id: TurnItemId.make("turn-item:message-assistant"),
824 threadId,
825 runId,
826 nodeId: null,
827 providerThreadId: null,
828 providerTurnId: null,
829 nativeItemRef: null,
830 parentItemId: null,
831 ordinal: 2,
832 status: "completed",
833 title: null,
834 startedAt: committedAt,
835 completedAt: committedAt,
836 updatedAt: committedAt,
837 type: "assistant_message",
838 messageId: assistantId,
839 text: "working",
840 streaming: false,
841 },
842 },
843 {
844 position: 2,
845 visibility: "local",
846 sourceThreadId: threadId,
847 sourceItemId: TurnItemId.make("turn-item:message-steer"),
848 item: {
849 id: TurnItemId.make("turn-item:message-steer"),
850 threadId,
851 runId,
852 nodeId: null,
853 providerThreadId: null,
854 providerTurnId: null,
855 nativeItemRef: null,
856 parentItemId: null,
857 ordinal: 3,
858 status: "completed",
859 title: null,
860 startedAt: committedAt,
861 completedAt: committedAt,
862 updatedAt: committedAt,
863 createdBy: "user",
864 creationSource: "web",
865 type: "user_message",
866 messageId: steerId,
867 inputIntent: "steer",
868 text: "continue",
869 attachments: [],
870 },
871 },
872 ];
873​
874 expect(deriveCommittedServerUserMessageIds(visibleTurnItems)).toEqual(
875 new Set([turnStartId, steerId]),
876 );
877 });
878});