Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatView.logic.test.ts

520 lines15.2 KB

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