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

ChatView.logic.test.ts

720 lines21.9 KB

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