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