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