Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime";
2import { EnvironmentId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
3import { afterEach, describe, expect, it, vi } from "vitest";
4import { type EnvironmentState, useStore } from "../store";
5import { type Thread } from "../types";
6
7import {
8 MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
9 buildExpiredTerminalContextToastCopy,
10 createLocalDispatchSnapshot,
11 deriveComposerSendState,
12 hasServerAcknowledgedLocalDispatch,
13 reconcileMountedTerminalThreadIds,
14 shouldWriteThreadErrorToCurrentServerThread,
15 waitForStartedServerThread,
16} from "./ChatView.logic";
17
18const localEnvironmentId = EnvironmentId.make("environment-local");
19
20describe("deriveComposerSendState", () => {
21 it("treats expired terminal pills as non-sendable content", () => {
22 const state = deriveComposerSendState({
23 prompt: "\uFFFC",
24 imageCount: 0,
25 terminalContexts: [
26 {
27 id: "ctx-expired",
28 threadId: ThreadId.make("thread-1"),
29 terminalId: "default",
30 terminalLabel: "Terminal 1",
31 lineStart: 4,
32 lineEnd: 4,
33 text: "",
34 createdAt: "2026-03-17T12:52:29.000Z",
35 },
36 ],
37 });
38
39 expect(state.trimmedPrompt).toBe("");
40 expect(state.sendableTerminalContexts).toEqual([]);
41 expect(state.expiredTerminalContextCount).toBe(1);
42 expect(state.hasSendableContent).toBe(false);
43 });
44
45 it("keeps text sendable while excluding expired terminal pills", () => {
46 const state = deriveComposerSendState({
47 prompt: `yoo \uFFFC waddup`,
48 imageCount: 0,
49 terminalContexts: [
50 {
51 id: "ctx-expired",
52 threadId: ThreadId.make("thread-1"),
53 terminalId: "default",
54 terminalLabel: "Terminal 1",
55 lineStart: 4,
56 lineEnd: 4,
57 text: "",
58 createdAt: "2026-03-17T12:52:29.000Z",
59 },
60 ],
61 });
62
63 expect(state.trimmedPrompt).toBe("yoo waddup");
64 expect(state.expiredTerminalContextCount).toBe(1);
65 expect(state.hasSendableContent).toBe(true);
66 });
67});
68
69describe("buildExpiredTerminalContextToastCopy", () => {
70 it("formats clear empty-state guidance", () => {
71 expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
72 title: "Expired terminal context won't be sent",
73 description: "Remove it or re-add it to include terminal output.",
74 });
75 });
76
77 it("formats omission guidance for sent messages", () => {
78 expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
79 title: "Expired terminal contexts omitted from message",
80 description: "Re-add it if you want that terminal output included.",
81 });
82 });
83});
84
85describe("reconcileMountedTerminalThreadIds", () => {
86 it("keeps previously mounted open threads and adds the active open thread", () => {
87 expect(
88 reconcileMountedTerminalThreadIds({
89 currentThreadIds: [ThreadId.make("thread-hidden"), ThreadId.make("thread-stale")],
90 openThreadIds: [ThreadId.make("thread-hidden"), ThreadId.make("thread-active")],
91 activeThreadId: ThreadId.make("thread-active"),
92 activeThreadTerminalOpen: true,
93 }),
94 ).toEqual([ThreadId.make("thread-hidden"), ThreadId.make("thread-active")]);
95 });
96
97 it("drops mounted threads once their terminal drawer is no longer open", () => {
98 expect(
99 reconcileMountedTerminalThreadIds({
100 currentThreadIds: [ThreadId.make("thread-closed")],
101 openThreadIds: [],
102 activeThreadId: ThreadId.make("thread-closed"),
103 activeThreadTerminalOpen: false,
104 }),
105 ).toEqual([]);
106 });
107
108 it("keeps only the most recently active hidden terminal threads", () => {
109 expect(
110 reconcileMountedTerminalThreadIds({
111 currentThreadIds: [
112 ThreadId.make("thread-1"),
113 ThreadId.make("thread-2"),
114 ThreadId.make("thread-3"),
115 ],
116 openThreadIds: [
117 ThreadId.make("thread-1"),
118 ThreadId.make("thread-2"),
119 ThreadId.make("thread-3"),
120 ThreadId.make("thread-4"),
121 ],
122 activeThreadId: ThreadId.make("thread-4"),
123 activeThreadTerminalOpen: true,
124 maxHiddenThreadCount: 2,
125 }),
126 ).toEqual([ThreadId.make("thread-2"), ThreadId.make("thread-3"), ThreadId.make("thread-4")]);
127 });
128
129 it("moves the active thread to the end so it is treated as most recently used", () => {
130 expect(
131 reconcileMountedTerminalThreadIds({
132 currentThreadIds: [
133 ThreadId.make("thread-a"),
134 ThreadId.make("thread-b"),
135 ThreadId.make("thread-c"),
136 ],
137 openThreadIds: [
138 ThreadId.make("thread-a"),
139 ThreadId.make("thread-b"),
140 ThreadId.make("thread-c"),
141 ],
142 activeThreadId: ThreadId.make("thread-a"),
143 activeThreadTerminalOpen: true,
144 maxHiddenThreadCount: 2,
145 }),
146 ).toEqual([ThreadId.make("thread-b"), ThreadId.make("thread-c"), ThreadId.make("thread-a")]);
147 });
148
149 it("defaults to the hidden mounted terminal cap", () => {
150 const currentThreadIds = Array.from(
151 { length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
152 (_, index) => ThreadId.make(`thread-${index + 1}`),
153 );
154
155 expect(
156 reconcileMountedTerminalThreadIds({
157 currentThreadIds,
158 openThreadIds: currentThreadIds,
159 activeThreadId: null,
160 activeThreadTerminalOpen: false,
161 }),
162 ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
163 });
164});
165
166describe("shouldWriteThreadErrorToCurrentServerThread", () => {
167 it("routes errors to the active server thread when route and target match", () => {
168 const threadId = ThreadId.make("thread-1");
169 const routeThreadRef = scopeThreadRef(localEnvironmentId, threadId);
170
171 expect(
172 shouldWriteThreadErrorToCurrentServerThread({
173 serverThread: {
174 environmentId: localEnvironmentId,
175 id: threadId,
176 },
177 routeThreadRef,
178 targetThreadId: threadId,
179 }),
180 ).toBe(true);
181 });
182
183 it("does not route draft-thread errors into server-backed state", () => {
184 const threadId = ThreadId.make("thread-1");
185
186 expect(
187 shouldWriteThreadErrorToCurrentServerThread({
188 serverThread: undefined,
189 routeThreadRef: scopeThreadRef(localEnvironmentId, threadId),
190 targetThreadId: threadId,
191 }),
192 ).toBe(false);
193 });
194});
195
196const makeThread = (input?: {
197 id?: ThreadId;
198 latestTurn?: {
199 turnId: TurnId;
200 state: "running" | "completed";
201 requestedAt: string;
202 startedAt: string | null;
203 completedAt: string | null;
204 } | null;
205}): Thread => ({
206 id: input?.id ?? ThreadId.make("thread-1"),
207 environmentId: localEnvironmentId,
208 codexThreadId: null,
209 projectId: ProjectId.make("project-1"),
210 title: "Thread",
211 modelSelection: { provider: "codex" as const, model: "gpt-5.4" },
212 runtimeMode: "full-access" as const,
213 interactionMode: "default" as const,
214 session: null,
215 messages: [],
216 proposedPlans: [],
217 error: null,
218 createdAt: "2026-03-29T00:00:00.000Z",
219 archivedAt: null,
220 updatedAt: "2026-03-29T00:00:00.000Z",
221 latestTurn: input?.latestTurn
222 ? {
223 ...input.latestTurn,
224 assistantMessageId: null,
225 }
226 : null,
227 branch: null,
228 worktreePath: null,
229 turnDiffSummaries: [],
230 activities: [],
231});
232
233function setStoreThreads(threads: ReadonlyArray<ReturnType<typeof makeThread>>) {
234 const projectId = ProjectId.make("project-1");
235 const environmentState: EnvironmentState = {
236 projectIds: [projectId],
237 projectById: {
238 [projectId]: {
239 id: projectId,
240 environmentId: localEnvironmentId,
241 name: "Project",
242 cwd: "/tmp/project",
243 defaultModelSelection: {
244 provider: "codex",
245 model: "gpt-5.4",
246 },
247 createdAt: "2026-03-29T00:00:00.000Z",
248 updatedAt: "2026-03-29T00:00:00.000Z",
249 scripts: [],
250 },
251 },
252 threadIds: threads.map((thread) => thread.id),
253 threadIdsByProjectId: {
254 [projectId]: threads.map((thread) => thread.id),
255 },
256 threadShellById: Object.fromEntries(
257 threads.map((thread) => [
258 thread.id,
259 {
260 id: thread.id,
261 environmentId: thread.environmentId,
262 codexThreadId: thread.codexThreadId,
263 projectId: thread.projectId,
264 title: thread.title,
265 modelSelection: thread.modelSelection,
266 runtimeMode: thread.runtimeMode,
267 interactionMode: thread.interactionMode,
268 error: thread.error,
269 createdAt: thread.createdAt,
270 archivedAt: thread.archivedAt,
271 updatedAt: thread.updatedAt,
272 branch: thread.branch,
273 worktreePath: thread.worktreePath,
274 },
275 ]),
276 ),
277 threadSessionById: Object.fromEntries(threads.map((thread) => [thread.id, thread.session])),
278 threadTurnStateById: Object.fromEntries(
279 threads.map((thread) => [
280 thread.id,
281 {
282 latestTurn: thread.latestTurn,
283 ...(thread.pendingSourceProposedPlan
284 ? { pendingSourceProposedPlan: thread.pendingSourceProposedPlan }
285 : {}),
286 },
287 ]),
288 ),
289 messageIdsByThreadId: Object.fromEntries(
290 threads.map((thread) => [thread.id, thread.messages.map((message) => message.id)]),
291 ),
292 messageByThreadId: Object.fromEntries(
293 threads.map((thread) => [
294 thread.id,
295 Object.fromEntries(thread.messages.map((message) => [message.id, message])),
296 ]),
297 ),
298 activityIdsByThreadId: Object.fromEntries(
299 threads.map((thread) => [thread.id, thread.activities.map((activity) => activity.id)]),
300 ),
301 activityByThreadId: Object.fromEntries(
302 threads.map((thread) => [
303 thread.id,
304 Object.fromEntries(thread.activities.map((activity) => [activity.id, activity])),
305 ]),
306 ),
307 proposedPlanIdsByThreadId: Object.fromEntries(
308 threads.map((thread) => [thread.id, thread.proposedPlans.map((plan) => plan.id)]),
309 ),
310 proposedPlanByThreadId: Object.fromEntries(
311 threads.map((thread) => [
312 thread.id,
313 Object.fromEntries(thread.proposedPlans.map((plan) => [plan.id, plan])),
314 ]),
315 ),
316 turnDiffIdsByThreadId: Object.fromEntries(
317 threads.map((thread) => [
318 thread.id,
319 thread.turnDiffSummaries.map((summary) => summary.turnId),
320 ]),
321 ),
322 turnDiffSummaryByThreadId: Object.fromEntries(
323 threads.map((thread) => [
324 thread.id,
325 Object.fromEntries(thread.turnDiffSummaries.map((summary) => [summary.turnId, summary])),
326 ]),
327 ),
328 sidebarThreadSummaryById: {},
329 bootstrapComplete: true,
330 };
331 useStore.setState({
332 activeEnvironmentId: localEnvironmentId,
333 environmentStateById: {
334 [localEnvironmentId]: environmentState,
335 },
336 });
337}
338
339afterEach(() => {
340 vi.useRealTimers();
341 vi.restoreAllMocks();
342 setStoreThreads([]);
343});
344
345describe("waitForStartedServerThread", () => {
346 it("resolves immediately when the thread is already started", async () => {
347 const threadId = ThreadId.make("thread-started");
348 setStoreThreads([
349 makeThread({
350 id: threadId,
351 latestTurn: {
352 turnId: TurnId.make("turn-started"),
353 state: "running",
354 requestedAt: "2026-03-29T00:00:01.000Z",
355 startedAt: "2026-03-29T00:00:01.000Z",
356 completedAt: null,
357 },
358 }),
359 ]);
360
361 await expect(
362 waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId)),
363 ).resolves.toBe(true);
364 });
365
366 it("waits for the thread to start via subscription updates", async () => {
367 const threadId = ThreadId.make("thread-wait");
368 setStoreThreads([makeThread({ id: threadId })]);
369
370 const promise = waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId), 500);
371
372 setStoreThreads([
373 makeThread({
374 id: threadId,
375 latestTurn: {
376 turnId: TurnId.make("turn-started"),
377 state: "running",
378 requestedAt: "2026-03-29T00:00:01.000Z",
379 startedAt: "2026-03-29T00:00:01.000Z",
380 completedAt: null,
381 },
382 }),
383 ]);
384
385 await expect(promise).resolves.toBe(true);
386 });
387
388 it("handles the thread starting between the initial read and subscription setup", async () => {
389 const threadId = ThreadId.make("thread-race");
390 setStoreThreads([makeThread({ id: threadId })]);
391
392 const originalSubscribe = useStore.subscribe.bind(useStore);
393 let raced = false;
394 vi.spyOn(useStore, "subscribe").mockImplementation((listener) => {
395 if (!raced) {
396 raced = true;
397 setStoreThreads([
398 makeThread({
399 id: threadId,
400 latestTurn: {
401 turnId: TurnId.make("turn-race"),
402 state: "running",
403 requestedAt: "2026-03-29T00:00:01.000Z",
404 startedAt: "2026-03-29T00:00:01.000Z",
405 completedAt: null,
406 },
407 }),
408 ]);
409 }
410 return originalSubscribe(listener);
411 });
412
413 await expect(
414 waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId), 500),
415 ).resolves.toBe(true);
416 });
417
418 it("returns false after the timeout when the thread never starts", async () => {
419 vi.useFakeTimers();
420
421 const threadId = ThreadId.make("thread-timeout");
422 setStoreThreads([makeThread({ id: threadId })]);
423 const promise = waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId), 500);
424
425 await vi.advanceTimersByTimeAsync(500);
426
427 await expect(promise).resolves.toBe(false);
428 });
429});
430
431describe("hasServerAcknowledgedLocalDispatch", () => {
432 const projectId = ProjectId.make("project-1");
433 const previousLatestTurn = {
434 turnId: TurnId.make("turn-1"),
435 state: "completed" as const,
436 requestedAt: "2026-03-29T00:00:00.000Z",
437 startedAt: "2026-03-29T00:00:01.000Z",
438 completedAt: "2026-03-29T00:00:10.000Z",
439 assistantMessageId: null,
440 };
441
442 const previousSession = {
443 provider: "codex" as const,
444 status: "ready" as const,
445 createdAt: "2026-03-29T00:00:00.000Z",
446 updatedAt: "2026-03-29T00:00:10.000Z",
447 orchestrationStatus: "idle" as const,
448 };
449
450 it("does not clear local dispatch before server state changes", () => {
451 const localDispatch = createLocalDispatchSnapshot({
452 id: ThreadId.make("thread-1"),
453 environmentId: localEnvironmentId,
454 codexThreadId: null,
455 projectId,
456 title: "Thread",
457 modelSelection: { provider: "codex", model: "gpt-5.4" },
458 runtimeMode: "full-access",
459 interactionMode: "default",
460 session: previousSession,
461 messages: [],
462 proposedPlans: [],
463 error: null,
464 createdAt: "2026-03-29T00:00:00.000Z",
465 archivedAt: null,
466 updatedAt: "2026-03-29T00:00:10.000Z",
467 latestTurn: previousLatestTurn,
468 branch: null,
469 worktreePath: null,
470 turnDiffSummaries: [],
471 activities: [],
472 });
473
474 expect(
475 hasServerAcknowledgedLocalDispatch({
476 localDispatch,
477 phase: "ready",
478 latestTurn: previousLatestTurn,
479 session: previousSession,
480 hasPendingApproval: false,
481 hasPendingUserInput: false,
482 threadError: null,
483 }),
484 ).toBe(false);
485 });
486
487 it("clears local dispatch when a new turn is already settled", () => {
488 const localDispatch = createLocalDispatchSnapshot({
489 id: ThreadId.make("thread-1"),
490 environmentId: localEnvironmentId,
491 codexThreadId: null,
492 projectId,
493 title: "Thread",
494 modelSelection: { provider: "codex", model: "gpt-5.4" },
495 runtimeMode: "full-access",
496 interactionMode: "default",
497 session: previousSession,
498 messages: [],
499 proposedPlans: [],
500 error: null,
501 createdAt: "2026-03-29T00:00:00.000Z",
502 archivedAt: null,
503 updatedAt: "2026-03-29T00:00:10.000Z",
504 latestTurn: previousLatestTurn,
505 branch: null,
506 worktreePath: null,
507 turnDiffSummaries: [],
508 activities: [],
509 });
510
511 expect(
512 hasServerAcknowledgedLocalDispatch({
513 localDispatch,
514 phase: "ready",
515 latestTurn: {
516 ...previousLatestTurn,
517 turnId: TurnId.make("turn-2"),
518 requestedAt: "2026-03-29T00:01:00.000Z",
519 startedAt: "2026-03-29T00:01:01.000Z",
520 completedAt: "2026-03-29T00:01:30.000Z",
521 },
522 session: {
523 ...previousSession,
524 updatedAt: "2026-03-29T00:01:30.000Z",
525 },
526 hasPendingApproval: false,
527 hasPendingUserInput: false,
528 threadError: null,
529 }),
530 ).toBe(true);
531 });
532
533 it("clears local dispatch when the session changes without an observed running phase", () => {
534 const localDispatch = createLocalDispatchSnapshot({
535 id: ThreadId.make("thread-1"),
536 environmentId: localEnvironmentId,
537 codexThreadId: null,
538 projectId,
539 title: "Thread",
540 modelSelection: { provider: "codex", model: "gpt-5.4" },
541 runtimeMode: "full-access",
542 interactionMode: "default",
543 session: previousSession,
544 messages: [],
545 proposedPlans: [],
546 error: null,
547 createdAt: "2026-03-29T00:00:00.000Z",
548 archivedAt: null,
549 updatedAt: "2026-03-29T00:00:10.000Z",
550 latestTurn: previousLatestTurn,
551 branch: null,
552 worktreePath: null,
553 turnDiffSummaries: [],
554 activities: [],
555 });
556
557 expect(
558 hasServerAcknowledgedLocalDispatch({
559 localDispatch,
560 phase: "ready",
561 latestTurn: previousLatestTurn,
562 session: {
563 ...previousSession,
564 updatedAt: "2026-03-29T00:00:11.000Z",
565 },
566 hasPendingApproval: false,
567 hasPendingUserInput: false,
568 threadError: null,
569 }),
570 ).toBe(true);
571 });
572});