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