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