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