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