Open History to see the last commit
1import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3
4import type { Thread } from "../types";
5import {
6 MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
7 MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
8 buildExpiredTerminalContextToastCopy,
9 createLocalDispatchSnapshot,
10 deriveComposerSendState,
11 getStartedThreadModelChangeBlockReason,
12 hasServerAcknowledgedLocalDispatch,
13 reconcileMountedTerminalThreadIds,
14 reconcileRetainedMountedThreadIds,
15 resolveSendEnvMode,
16 shouldWriteThreadErrorToCurrentServerThread,
17} from "./ChatView.logic";
18
19const environmentId = EnvironmentId.make("environment-local");
20const projectId = ProjectId.make("project-1");
21const threadId = ThreadId.make("thread-1");
22const now = "2026-03-29T00:00:00.000Z";
23
24function makeThread(overrides: Partial<Thread> = {}): Thread {
25 return {
26 id: threadId,
27 environmentId,
28 projectId,
29 title: "Thread",
30 modelSelection: {
31 instanceId: ProviderInstanceId.make("codex"),
32 model: "gpt-5.4",
33 },
34 runtimeMode: "full-access",
35 interactionMode: "default",
36 session: null,
37 messages: [],
38 proposedPlans: [],
39 activities: [],
40 checkpoints: [],
41 createdAt: now,
42 updatedAt: now,
43 archivedAt: null,
44 deletedAt: null,
45 latestTurn: null,
46 branch: null,
47 worktreePath: null,
48 ...overrides,
49 };
50}
51
52const completedTurn = {
53 turnId: TurnId.make("turn-1"),
54 state: "completed" as const,
55 requestedAt: now,
56 startedAt: "2026-03-29T00:00:01.000Z",
57 completedAt: "2026-03-29T00:00:10.000Z",
58 assistantMessageId: null,
59};
60
61const readySession = {
62 threadId,
63 status: "ready" as const,
64 providerName: "codex",
65 providerInstanceId: ProviderInstanceId.make("codex"),
66 runtimeMode: "full-access" as const,
67 activeTurnId: null,
68 lastError: null,
69 updatedAt: "2026-03-29T00:00:10.000Z",
70};
71
72describe("deriveComposerSendState", () => {
73 it("treats expired terminal pills as non-sendable content", () => {
74 const state = deriveComposerSendState({
75 prompt: "\uFFFC",
76 imageCount: 0,
77 terminalContexts: [
78 {
79 id: "ctx-expired",
80 threadId,
81 terminalId: "default",
82 terminalLabel: "Terminal 1",
83 lineStart: 4,
84 lineEnd: 4,
85 text: "",
86 createdAt: now,
87 },
88 ],
89 });
90
91 expect(state.trimmedPrompt).toBe("");
92 expect(state.sendableTerminalContexts).toEqual([]);
93 expect(state.expiredTerminalContextCount).toBe(1);
94 expect(state.hasSendableContent).toBe(false);
95 });
96
97 it("keeps text sendable while excluding expired terminal pills", () => {
98 const state = deriveComposerSendState({
99 prompt: `yoo \uFFFC waddup`,
100 imageCount: 0,
101 terminalContexts: [
102 {
103 id: "ctx-expired",
104 threadId,
105 terminalId: "default",
106 terminalLabel: "Terminal 1",
107 lineStart: 4,
108 lineEnd: 4,
109 text: "",
110 createdAt: now,
111 },
112 ],
113 });
114
115 expect(state.trimmedPrompt).toBe("yoo waddup");
116 expect(state.expiredTerminalContextCount).toBe(1);
117 expect(state.hasSendableContent).toBe(true);
118 });
119
120 it("treats element contexts as sendable content (no text, no images, no terminals)", () => {
121 const state = deriveComposerSendState({
122 prompt: "",
123 imageCount: 0,
124 terminalContexts: [],
125 elementContextCount: 1,
126 });
127
128 expect(state.trimmedPrompt).toBe("");
129 expect(state.expiredTerminalContextCount).toBe(0);
130 expect(state.hasSendableContent).toBe(true);
131 });
132
133 it("does NOT treat zero element contexts as sendable", () => {
134 expect(
135 deriveComposerSendState({
136 prompt: "",
137 imageCount: 0,
138 terminalContexts: [],
139 elementContextCount: 0,
140 }).hasSendableContent,
141 ).toBe(false);
142 });
143});
144
145describe("buildExpiredTerminalContextToastCopy", () => {
146 it("formats empty and omission guidance", () => {
147 expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
148 title: "Expired terminal context won't be sent",
149 description: "Remove it or re-add it to include terminal output.",
150 });
151 expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
152 title: "Expired terminal contexts omitted from message",
153 description: "Re-add it if you want that terminal output included.",
154 });
155 });
156});
157
158describe("getStartedThreadModelChangeBlockReason", () => {
159 const providers = [
160 {
161 instanceId: ProviderInstanceId.make("codex"),
162 },
163 {
164 instanceId: ProviderInstanceId.make("grok"),
165 requiresNewThreadForModelChange: true,
166 },
167 ];
168
169 it("allows model changes before a provider session has started", () => {
170 expect(
171 getStartedThreadModelChangeBlockReason({
172 providers,
173 hasStartedSession: false,
174 currentModelSelection: {
175 instanceId: ProviderInstanceId.make("grok"),
176 model: "grok-build",
177 },
178 nextModelSelection: {
179 instanceId: ProviderInstanceId.make("grok"),
180 model: "grok-other",
181 },
182 }),
183 ).toBeNull();
184 });
185
186 it("allows unchanged model selections for restricted providers", () => {
187 expect(
188 getStartedThreadModelChangeBlockReason({
189 providers,
190 hasStartedSession: true,
191 currentModelSelection: {
192 instanceId: ProviderInstanceId.make("grok"),
193 model: "grok-build",
194 },
195 nextModelSelection: {
196 instanceId: ProviderInstanceId.make("grok"),
197 model: "grok-build",
198 },
199 }),
200 ).toBeNull();
201 });
202
203 it("blocks started-session model changes when either provider requires a new thread", () => {
204 expect(
205 getStartedThreadModelChangeBlockReason({
206 providers,
207 hasStartedSession: true,
208 currentModelSelection: {
209 instanceId: ProviderInstanceId.make("codex"),
210 model: "gpt-5.4",
211 },
212 nextModelSelection: {
213 instanceId: ProviderInstanceId.make("grok"),
214 model: "grok-build",
215 },
216 }),
217 ).toEqual({
218 title: "Start a new chat to change models",
219 description:
220 "This provider does not allow switching models after a conversation has started.",
221 });
222 });
223});
224
225describe("resolveSendEnvMode", () => {
226 it("keeps worktree mode only for git repositories", () => {
227 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
228 expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
229 });
230});
231
232describe("reconcileMountedTerminalThreadIds", () => {
233 it("keeps open threads and makes the active thread most recent", () => {
234 expect(
235 reconcileMountedTerminalThreadIds({
236 currentThreadIds: ["thread-a", "thread-b", "thread-c"],
237 openThreadIds: ["thread-a", "thread-b", "thread-c"],
238 activeThreadId: "thread-a",
239 activeThreadTerminalOpen: true,
240 maxHiddenThreadCount: 2,
241 }),
242 ).toEqual(["thread-b", "thread-c", "thread-a"]);
243 });
244
245 it("drops closed threads and enforces the hidden mounted cap", () => {
246 const ids = Array.from(
247 { length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
248 (_, index) => `thread-${index}`,
249 );
250 expect(
251 reconcileMountedTerminalThreadIds({
252 currentThreadIds: ids,
253 openThreadIds: ids.slice(1),
254 activeThreadId: null,
255 activeThreadTerminalOpen: false,
256 }),
257 ).toEqual(ids.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
258 });
259});
260
261describe("reconcileRetainedMountedThreadIds", () => {
262 it("retains hidden open threads and adds the active open thread", () => {
263 expect(
264 reconcileRetainedMountedThreadIds({
265 currentThreadIds: [ThreadId.make("thread-hidden")],
266 openThreadIds: [ThreadId.make("thread-hidden")],
267 activeThreadId: ThreadId.make("thread-active"),
268 activeThreadOpen: true,
269 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
270 }),
271 ).toEqual([ThreadId.make("thread-hidden"), ThreadId.make("thread-active")]);
272 });
273
274 it("can retain the active thread as hidden when it is inactive", () => {
275 expect(
276 reconcileRetainedMountedThreadIds({
277 currentThreadIds: [ThreadId.make("thread-active")],
278 openThreadIds: [ThreadId.make("thread-active")],
279 activeThreadId: ThreadId.make("thread-active"),
280 activeThreadOpen: false,
281 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
282 retainInactiveActiveThread: true,
283 }),
284 ).toEqual([ThreadId.make("thread-active")]);
285 });
286
287 it("evicts the oldest hidden threads beyond the configured cap", () => {
288 const currentThreadIds = Array.from(
289 { length: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS + 2 },
290 (_, index) => ThreadId.make(`thread-${index + 1}`),
291 );
292
293 expect(
294 reconcileRetainedMountedThreadIds({
295 currentThreadIds,
296 openThreadIds: currentThreadIds,
297 activeThreadId: null,
298 activeThreadOpen: false,
299 maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
300 }),
301 ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_PREVIEW_THREADS));
302 });
303});
304
305describe("shouldWriteThreadErrorToCurrentServerThread", () => {
306 it("requires the environment, route thread, and target thread to match", () => {
307 const routeThreadRef = { environmentId, threadId };
308
309 expect(
310 shouldWriteThreadErrorToCurrentServerThread({
311 serverThread: { environmentId, id: threadId },
312 routeThreadRef,
313 targetThreadId: threadId,
314 }),
315 ).toBe(true);
316 expect(
317 shouldWriteThreadErrorToCurrentServerThread({
318 serverThread: null,
319 routeThreadRef,
320 targetThreadId: threadId,
321 }),
322 ).toBe(false);
323 });
324});
325
326describe("hasServerAcknowledgedLocalDispatch", () => {
327 it("does not acknowledge unchanged server state", () => {
328 const localDispatch = createLocalDispatchSnapshot(
329 makeThread({ latestTurn: completedTurn, session: readySession }),
330 );
331
332 expect(
333 hasServerAcknowledgedLocalDispatch({
334 localDispatch,
335 phase: "ready",
336 latestTurn: completedTurn,
337 session: readySession,
338 hasPendingApproval: false,
339 hasPendingUserInput: false,
340 threadError: null,
341 }),
342 ).toBe(false);
343 });
344
345 it("acknowledges a settled newer turn", () => {
346 const localDispatch = createLocalDispatchSnapshot(
347 makeThread({ latestTurn: completedTurn, session: readySession }),
348 );
349 const newerTurn = {
350 ...completedTurn,
351 turnId: TurnId.make("turn-2"),
352 requestedAt: "2026-03-29T00:01:00.000Z",
353 startedAt: "2026-03-29T00:01:01.000Z",
354 completedAt: "2026-03-29T00:01:30.000Z",
355 };
356
357 expect(
358 hasServerAcknowledgedLocalDispatch({
359 localDispatch,
360 phase: "ready",
361 latestTurn: newerTurn,
362 session: { ...readySession, updatedAt: newerTurn.completedAt },
363 hasPendingApproval: false,
364 hasPendingUserInput: false,
365 threadError: null,
366 }),
367 ).toBe(true);
368 });
369
370 it("waits for the matching running turn before acknowledging", () => {
371 const localDispatch = createLocalDispatchSnapshot(
372 makeThread({ latestTurn: completedTurn, session: readySession }),
373 );
374 const runningTurn = {
375 ...completedTurn,
376 turnId: TurnId.make("turn-2"),
377 state: "running" as const,
378 requestedAt: "2026-03-29T00:01:00.000Z",
379 startedAt: "2026-03-29T00:01:01.000Z",
380 completedAt: null,
381 };
382
383 expect(
384 hasServerAcknowledgedLocalDispatch({
385 localDispatch,
386 phase: "running",
387 latestTurn: runningTurn,
388 session: {
389 ...readySession,
390 status: "running",
391 activeTurnId: TurnId.make("turn-other"),
392 },
393 hasPendingApproval: false,
394 hasPendingUserInput: false,
395 threadError: null,
396 }),
397 ).toBe(false);
398 expect(
399 hasServerAcknowledgedLocalDispatch({
400 localDispatch,
401 phase: "running",
402 latestTurn: runningTurn,
403 session: {
404 ...readySession,
405 status: "running",
406 activeTurnId: runningTurn.turnId,
407 },
408 hasPendingApproval: false,
409 hasPendingUserInput: false,
410 threadError: null,
411 }),
412 ).toBe(true);
413 });
414
415 it("acknowledges pending user interaction and errors immediately", () => {
416 const localDispatch = createLocalDispatchSnapshot(makeThread());
417 const common = {
418 localDispatch,
419 phase: "ready" as const,
420 latestTurn: null,
421 session: null,
422 hasPendingApproval: false,
423 hasPendingUserInput: false,
424 threadError: null,
425 };
426
427 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingApproval: true })).toBe(true);
428 expect(hasServerAcknowledgedLocalDispatch({ ...common, hasPendingUserInput: true })).toBe(true);
429 expect(hasServerAcknowledgedLocalDispatch({ ...common, threadError: "failed" })).toBe(true);
430 });
431});