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