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