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