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

Sidebar.logic.test.ts

1,101 lines32.3 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 createThreadJumpHintVisibilityController,
4 getSidebarThreadIdsToPrewarm,
5 getVisibleSidebarThreadIds,
6 resolveAdjacentThreadId,
7 getFallbackThreadIdAfterDelete,
8 getVisibleThreadsForProject,
9 getProjectSortTimestamp,
10 getSidebarForkParentThreadId,
11 hasUnseenCompletion,
12 isContextMenuPointerDown,
13 isSidebarSubagentThread,
14 isTrailingDoubleClick,
15 orderItemsByPreferredIds,
16 resolveProjectStatusIndicator,
17 resolveSidebarNewThreadSeedContext,
18 resolveSidebarNewThreadEnvMode,
19 resolveSidebarStageBadgeLabel,
20 resolveThreadRowClassName,
21 resolveThreadStatusPill,
22 shouldClearThreadSelectionOnMouseDown,
23 sortProjectsForSidebar,
24 THREAD_JUMP_HINT_SHOW_DELAY_MS,
25} from "./Sidebar.logic";
26import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
27import {
28 DEFAULT_INTERACTION_MODE,
29 DEFAULT_RUNTIME_MODE,
30 type Project,
31 type Thread,
32} from "../types";
33import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures";
34​
35const localEnvironmentId = EnvironmentId.make("environment-local");
36​
37describe("resolveSidebarStageBadgeLabel", () => {
38 it("returns Nightly for nightly primary server versions", () => {
39 expect(
40 resolveSidebarStageBadgeLabel({
41 primaryServerVersion: "0.0.28-nightly.20260616.12",
42 fallbackStageLabel: "Alpha",
43 }),
44 ).toBe("Nightly");
45 });
46​
47 it("returns the fallback label for stable primary server versions", () => {
48 expect(
49 resolveSidebarStageBadgeLabel({
50 primaryServerVersion: "0.0.27",
51 fallbackStageLabel: "Alpha",
52 }),
53 ).toBe("Alpha");
54 });
55​
56 it("returns the fallback label when the primary server version is missing", () => {
57 expect(
58 resolveSidebarStageBadgeLabel({
59 primaryServerVersion: null,
60 fallbackStageLabel: "Dev",
61 }),
62 ).toBe("Dev");
63 });
64​
65 it("returns the fallback label for malformed nightly prerelease versions", () => {
66 expect(
67 resolveSidebarStageBadgeLabel({
68 primaryServerVersion: "0.0.28-nightly.20260616",
69 fallbackStageLabel: "Alpha",
70 }),
71 ).toBe("Alpha");
72 });
73});
74​
75describe("sidebar thread lineage helpers", () => {
76 it("identifies subagent threads so the sidebar can hide them", () => {
77 const parentId = ThreadId.make("thread-parent");
78 const subagent = makeThreadFixture({
79 lineage: {
80 rootThreadId: parentId,
81 parentThreadId: parentId,
82 relationshipToParent: "subagent",
83 },
84 });
85​
86 expect(isSidebarSubagentThread(subagent)).toBe(true);
87 expect(isSidebarSubagentThread(makeThreadFixture())).toBe(false);
88 });
89​
90 it("resolves the parent thread for fork sidebar affordances", () => {
91 const parentId = ThreadId.make("thread-parent");
92 const fallbackParentId = ThreadId.make("thread-fallback-parent");
93 const runFork = makeThreadFixture({
94 forkedFrom: { type: "run", threadId: parentId, runId: "run-1" as never },
95 lineage: {
96 rootThreadId: parentId,
97 parentThreadId: fallbackParentId,
98 relationshipToParent: "fork",
99 },
100 });
101 const lineageFork = makeThreadFixture({
102 lineage: {
103 rootThreadId: parentId,
104 parentThreadId: fallbackParentId,
105 relationshipToParent: "fork",
106 },
107 });
108​
109 expect(getSidebarForkParentThreadId(runFork)).toBe(parentId);
110 expect(getSidebarForkParentThreadId(lineageFork)).toBe(fallbackParentId);
111 expect(getSidebarForkParentThreadId(makeThreadFixture())).toBeNull();
112 });
113});
114​
115function makeLatestRun(overrides?: {
116 completedAt?: string | null;
117 startedAt?: string | null;
118}): NonNullable<Thread["latestRun"]> {
119 return {
120 runId: "turn-1" as never,
121 status: "completed",
122 assistantMessageId: null,
123 requestedAt: "2026-03-09T10:00:00.000Z",
124 startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
125 completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
126 };
128​
129describe("hasUnseenCompletion", () => {
130 it("returns true when a thread completed after its last visit", () => {
131 expect(
132 hasUnseenCompletion({
133 hasActionableProposedPlan: false,
134 hasPendingApprovals: false,
135 hasPendingUserInput: false,
136 interactionMode: "default",
137 latestRun: makeLatestRun(),
138 lastVisitedAt: "2026-03-09T10:04:00.000Z",
139 runtime: null,
140 }),
141 ).toBe(true);
142 });
143​
144 it("treats a missing client visit marker as read", () => {
145 expect(
146 hasUnseenCompletion({
147 hasActionableProposedPlan: false,
148 hasPendingApprovals: false,
149 hasPendingUserInput: false,
150 interactionMode: "default",
151 latestRun: makeLatestRun(),
152 lastVisitedAt: undefined,
153 runtime: null,
154 }),
155 ).toBe(false);
156 });
157});
158​
159describe("createThreadJumpHintVisibilityController", () => {
160 beforeEach(() => {
161 vi.useFakeTimers();
162 });
163​
164 afterEach(() => {
165 vi.useRealTimers();
166 });
167​
168 it("delays showing jump hints until the configured delay elapses", () => {
169 const visibilityChanges: boolean[] = [];
170 const controller = createThreadJumpHintVisibilityController({
171 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
172 onVisibilityChange: (visible) => {
173 visibilityChanges.push(visible);
174 },
175 });
176​
177 controller.sync(true);
178 vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1);
179​
180 expect(visibilityChanges).toEqual([]);
181​
182 vi.advanceTimersByTime(1);
183​
184 expect(visibilityChanges).toEqual([true]);
185 });
186​
187 it("hides immediately when the modifiers are released", () => {
188 const visibilityChanges: boolean[] = [];
189 const controller = createThreadJumpHintVisibilityController({
190 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
191 onVisibilityChange: (visible) => {
192 visibilityChanges.push(visible);
193 },
194 });
195​
196 controller.sync(true);
197 vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
198 controller.sync(false);
199​
200 expect(visibilityChanges).toEqual([true, false]);
201 });
202​
203 it("cancels a pending reveal when the modifier is released early", () => {
204 const visibilityChanges: boolean[] = [];
205 const controller = createThreadJumpHintVisibilityController({
206 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
207 onVisibilityChange: (visible) => {
208 visibilityChanges.push(visible);
209 },
210 });
211​
212 controller.sync(true);
213 vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2));
214 controller.sync(false);
215 vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
216​
217 expect(visibilityChanges).toEqual([]);
218 });
219});
220​
221describe("getSidebarThreadIdsToPrewarm", () => {
222 it("returns only the first visible thread ids up to the prewarm limit", () => {
223 expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
224 });
225​
226 it("returns all visible thread ids when they fit within the limit", () => {
227 expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
228 });
229​
230 it("returns no thread ids when the limit is zero", () => {
231 expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
232 });
233});
234​
235describe("shouldClearThreadSelectionOnMouseDown", () => {
236 it("preserves selection for thread items", () => {
237 const child = {
238 closest: (selector: string) =>
239 selector.includes("[data-thread-item]") ? ({} as Element) : null,
240 } as unknown as HTMLElement;
241​
242 expect(shouldClearThreadSelectionOnMouseDown(child)).toBe(false);
243 });
244​
245 it("preserves selection for thread list toggle controls", () => {
246 const selectionSafe = {
247 closest: (selector: string) =>
248 selector.includes("[data-thread-selection-safe]") ? ({} as Element) : null,
249 } as unknown as HTMLElement;
250​
251 expect(shouldClearThreadSelectionOnMouseDown(selectionSafe)).toBe(false);
252 });
253​
254 it("clears selection for unrelated sidebar clicks", () => {
255 const unrelated = {
256 closest: () => null,
257 } as unknown as HTMLElement;
258​
259 expect(shouldClearThreadSelectionOnMouseDown(unrelated)).toBe(true);
260 });
261});
262​
263describe("isTrailingDoubleClick", () => {
264 it("treats a single click as a normal activation", () => {
265 expect(isTrailingDoubleClick(1)).toBe(false);
266 });
267​
268 it("treats synthetic/keyboard activations (detail 0) as a normal activation", () => {
269 expect(isTrailingDoubleClick(0)).toBe(false);
270 });
271​
272 it("ignores the second click of a double-click so it does not navigate", () => {
273 expect(isTrailingDoubleClick(2)).toBe(true);
274 });
275​
276 it("ignores further clicks of a triple-click", () => {
277 expect(isTrailingDoubleClick(3)).toBe(true);
278 });
279});
280​
281describe("resolveSidebarNewThreadEnvMode", () => {
282 it("uses the app default when the caller does not request a specific mode", () => {
283 expect(
284 resolveSidebarNewThreadEnvMode({
285 defaultEnvMode: "worktree",
286 }),
287 ).toBe("worktree");
288 });
289​
290 it("preserves an explicit requested mode over the app default", () => {
291 expect(
292 resolveSidebarNewThreadEnvMode({
293 requestedEnvMode: "local",
294 defaultEnvMode: "worktree",
295 }),
296 ).toBe("local");
297 });
298});
299​
300describe("resolveSidebarNewThreadSeedContext", () => {
301 it("prefers the default worktree mode over active thread context", () => {
302 expect(
303 resolveSidebarNewThreadSeedContext({
304 projectId: "project-1",
305 defaultEnvMode: "worktree",
306 activeThread: {
307 projectId: "project-1",
308 branch: "feature/existing",
309 worktreePath: "/repo/.t3/worktrees/existing",
310 },
311 activeDraftThread: {
312 projectId: "project-1",
313 branch: "feature/draft",
314 worktreePath: "/repo/.t3/worktrees/draft",
315 envMode: "worktree",
316 startFromOrigin: true,
317 },
318 }),
319 ).toEqual({
320 envMode: "worktree",
321 });
322 });
323​
324 it("inherits the active server thread context when creating a new thread in the same project", () => {
325 expect(
326 resolveSidebarNewThreadSeedContext({
327 projectId: "project-1",
328 defaultEnvMode: "local",
329 activeThread: {
330 projectId: "project-1",
331 branch: "effect-atom",
332 worktreePath: null,
333 },
334 activeDraftThread: null,
335 }),
336 ).toEqual({
337 branch: "effect-atom",
338 worktreePath: null,
339 envMode: "local",
340 });
341 });
342​
343 it("prefers the active draft thread context when it matches the target project", () => {
344 expect(
345 resolveSidebarNewThreadSeedContext({
346 projectId: "project-1",
347 defaultEnvMode: "local",
348 activeThread: {
349 projectId: "project-1",
350 branch: "effect-atom",
351 worktreePath: null,
352 },
353 activeDraftThread: {
354 projectId: "project-1",
355 branch: "feature/new-draft",
356 worktreePath: "/repo/worktree",
357 envMode: "worktree",
358 startFromOrigin: true,
359 },
360 }),
361 ).toEqual({
362 branch: "feature/new-draft",
363 worktreePath: "/repo/worktree",
364 envMode: "worktree",
365 startFromOrigin: true,
366 });
367 });
368​
369 it("falls back to the default env mode when there is no matching active thread context", () => {
370 expect(
371 resolveSidebarNewThreadSeedContext({
372 projectId: "project-2",
373 defaultEnvMode: "worktree",
374 activeThread: {
375 projectId: "project-1",
376 branch: "effect-atom",
377 worktreePath: null,
378 },
379 activeDraftThread: null,
380 }),
381 ).toEqual({
382 envMode: "worktree",
383 });
384 });
385});
386​
387describe("orderItemsByPreferredIds", () => {
388 it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
389 const ordered = orderItemsByPreferredIds({
390 items: [
391 { id: ProjectId.make("project-1"), name: "One" },
392 { id: ProjectId.make("project-2"), name: "Two" },
393 { id: ProjectId.make("project-3"), name: "Three" },
394 ],
395 preferredIds: [
396 ProjectId.make("project-3"),
397 ProjectId.make("project-missing"),
398 ProjectId.make("project-1"),
399 ],
400 getId: (project) => project.id,
401 });
402​
403 expect(ordered.map((project) => project.id)).toEqual([
404 ProjectId.make("project-3"),
405 ProjectId.make("project-1"),
406 ProjectId.make("project-2"),
407 ]);
408 });
409​
410 it("does not duplicate items when preferred ids repeat", () => {
411 const ordered = orderItemsByPreferredIds({
412 items: [
413 { id: ProjectId.make("project-1"), name: "One" },
414 { id: ProjectId.make("project-2"), name: "Two" },
415 ],
416 preferredIds: [
417 ProjectId.make("project-2"),
418 ProjectId.make("project-1"),
419 ProjectId.make("project-2"),
420 ],
421 getId: (project) => project.id,
422 });
423​
424 expect(ordered.map((project) => project.id)).toEqual([
425 ProjectId.make("project-2"),
426 ProjectId.make("project-1"),
427 ]);
428 });
429​
430 it("honors projectOrder physical keys via getProjectOrderKey", async () => {
431 // Regression guard for #1904 / the regression introduced by #2055:
432 // `projectOrder` is populated with physical keys (envId + cwd-derived)
433 // by the store and by drag-end handlers. Readers must identify projects
434 // with the same key format, or manual sort silently snaps back.
435 const { getProjectOrderKey } = await import("../logicalProject");
436 const projects = [
437 {
438 environmentId: EnvironmentId.make("environment-local"),
439 id: ProjectId.make("id-alpha"),
440 workspaceRoot: "/work/alpha",
441 },
442 {
443 environmentId: EnvironmentId.make("environment-local"),
444 id: ProjectId.make("id-beta"),
445 workspaceRoot: "/work/beta",
446 },
447 {
448 environmentId: EnvironmentId.make("environment-local"),
449 id: ProjectId.make("id-gamma"),
450 workspaceRoot: "/work/gamma",
451 },
452 ];
453 const ordered = orderItemsByPreferredIds({
454 items: projects,
455 preferredIds: [getProjectOrderKey(projects[2]!), getProjectOrderKey(projects[0]!)],
456 getId: getProjectOrderKey,
457 });
458​
459 expect(ordered.map((project) => project.workspaceRoot)).toEqual([
460 "/work/gamma",
461 "/work/alpha",
462 "/work/beta",
463 ]);
464 });
465​
466 it("resolves legacy preference aliases without materializing project state", () => {
467 const ordered = orderItemsByPreferredIds({
468 items: [
469 { id: "physical-a", cwd: "/work/a" },
470 { id: "physical-b", cwd: "/work/b" },
471 { id: "physical-c", cwd: "/work/c" },
472 ],
473 preferredIds: ["legacy:/work/c", "legacy:/work/a"],
474 getId: (project) => project.id,
475 getPreferenceIds: (project) => [project.id, `legacy:${project.cwd}`],
476 });
477​
478 expect(ordered.map((project) => project.id)).toEqual([
479 "physical-c",
480 "physical-a",
481 "physical-b",
482 ]);
483 });
484});
485​
486describe("resolveAdjacentThreadId", () => {
487 it("resolves adjacent thread ids in ordered sidebar traversal", () => {
488 const threads = [
489 ThreadId.make("thread-1"),
490 ThreadId.make("thread-2"),
491 ThreadId.make("thread-3"),
492 ];
493​
494 expect(
495 resolveAdjacentThreadId({
496 threadIds: threads,
497 currentThreadId: threads[1] ?? null,
498 direction: "previous",
499 }),
500 ).toBe(threads[0]);
501 expect(
502 resolveAdjacentThreadId({
503 threadIds: threads,
504 currentThreadId: threads[1] ?? null,
505 direction: "next",
506 }),
507 ).toBe(threads[2]);
508 expect(
509 resolveAdjacentThreadId({
510 threadIds: threads,
511 currentThreadId: null,
512 direction: "next",
513 }),
514 ).toBe(threads[0]);
515 expect(
516 resolveAdjacentThreadId({
517 threadIds: threads,
518 currentThreadId: null,
519 direction: "previous",
520 }),
521 ).toBe(threads[2]);
522 expect(
523 resolveAdjacentThreadId({
524 threadIds: threads,
525 currentThreadId: threads[0] ?? null,
526 direction: "previous",
527 }),
528 ).toBeNull();
529 });
530});
531​
532describe("getVisibleSidebarThreadIds", () => {
533 it("returns only the rendered visible thread order across projects", () => {
534 expect(
535 getVisibleSidebarThreadIds([
536 {
537 renderedThreadIds: [
538 ThreadId.make("thread-12"),
539 ThreadId.make("thread-11"),
540 ThreadId.make("thread-10"),
541 ],
542 },
543 {
544 renderedThreadIds: [ThreadId.make("thread-8"), ThreadId.make("thread-6")],
545 },
546 ]),
547 ).toEqual([
548 ThreadId.make("thread-12"),
549 ThreadId.make("thread-11"),
550 ThreadId.make("thread-10"),
551 ThreadId.make("thread-8"),
552 ThreadId.make("thread-6"),
553 ]);
554 });
555​
556 it("skips threads from collapsed projects whose thread panels are not shown", () => {
557 expect(
558 getVisibleSidebarThreadIds([
559 {
560 shouldShowThreadPanel: false,
561 renderedThreadIds: [ThreadId.make("thread-hidden-2"), ThreadId.make("thread-hidden-1")],
562 },
563 {
564 shouldShowThreadPanel: true,
565 renderedThreadIds: [ThreadId.make("thread-12"), ThreadId.make("thread-11")],
566 },
567 ]),
568 ).toEqual([ThreadId.make("thread-12"), ThreadId.make("thread-11")]);
569 });
570});
571​
572describe("isContextMenuPointerDown", () => {
573 it("treats secondary-button presses as context menu gestures on all platforms", () => {
574 expect(
575 isContextMenuPointerDown({
576 button: 2,
577 ctrlKey: false,
578 isMac: false,
579 }),
580 ).toBe(true);
581 });
582​
583 it("treats ctrl+primary-click as a context menu gesture on macOS", () => {
584 expect(
585 isContextMenuPointerDown({
586 button: 0,
587 ctrlKey: true,
588 isMac: true,
589 }),
590 ).toBe(true);
591 });
592​
593 it("does not treat ctrl+primary-click as a context menu gesture off macOS", () => {
594 expect(
595 isContextMenuPointerDown({
596 button: 0,
597 ctrlKey: true,
598 isMac: false,
599 }),
600 ).toBe(false);
601 });
602});
603​
604describe("resolveThreadStatusPill", () => {
605 const baseThread = {
606 hasActionableProposedPlan: false,
607 hasPendingApprovals: false,
608 hasPendingUserInput: false,
609 interactionMode: "plan" as const,
610 latestRun: null,
611 lastVisitedAt: undefined,
612 runtime: {
613 status: "running" as const,
614 providerName: "Codex",
615 providerInstanceId: ProviderInstanceId.make("codex"),
616 activeRunId: "turn-1" as never,
617 lastError: null,
618 updatedAt: "2026-03-09T10:00:00.000Z",
619 },
620 };
621​
622 it("shows pending approval before all other statuses", () => {
623 expect(
624 resolveThreadStatusPill({
625 thread: {
626 ...baseThread,
627 hasPendingApprovals: true,
628 hasPendingUserInput: true,
629 },
630 }),
631 ).toMatchObject({ label: "Pending Approval", pulse: false });
632 });
633​
634 it("shows awaiting input when plan mode is blocked on user answers", () => {
635 expect(
636 resolveThreadStatusPill({
637 thread: {
638 ...baseThread,
639 hasPendingUserInput: true,
640 },
641 }),
642 ).toMatchObject({ label: "Awaiting Input", pulse: false });
643 });
644​
645 it("falls back to working when the thread is actively running without blockers", () => {
646 expect(
647 resolveThreadStatusPill({
648 thread: baseThread,
649 }),
650 ).toMatchObject({ label: "Working", pulse: true });
651 });
652​
653 it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
654 expect(
655 resolveThreadStatusPill({
656 thread: {
657 ...baseThread,
658 hasActionableProposedPlan: true,
659 latestRun: makeLatestRun(),
660 runtime: {
661 ...baseThread.runtime,
662 status: "completed",
663 activeRunId: null,
664 },
665 },
666 }),
667 ).toMatchObject({ label: "Plan Ready", pulse: false });
668 });
669​
670 it("does not manufacture completed state without a client visit marker", () => {
671 expect(
672 resolveThreadStatusPill({
673 thread: {
674 ...baseThread,
675 latestRun: makeLatestRun(),
676 runtime: {
677 ...baseThread.runtime,
678 status: "completed",
679 activeRunId: null,
680 },
681 },
682 }),
683 ).toBeNull();
684 });
685​
686 it("shows completed when there is an unseen completion and no active blocker", () => {
687 expect(
688 resolveThreadStatusPill({
689 thread: {
690 ...baseThread,
691 interactionMode: "default",
692 latestRun: makeLatestRun(),
693 lastVisitedAt: "2026-03-09T10:04:00.000Z",
694 runtime: {
695 ...baseThread.runtime,
696 status: "completed",
697 activeRunId: null,
698 },
699 },
700 }),
701 ).toMatchObject({ label: "Completed", pulse: false });
702 });
703});
704​
705describe("resolveThreadRowClassName", () => {
706 it("uses the darker selected palette when a thread is both selected and active", () => {
707 const className = resolveThreadRowClassName({ isActive: true, isSelected: true });
708 expect(className).toContain("bg-primary/22");
709 expect(className).toContain("hover:bg-primary/26");
710 expect(className).toContain("dark:bg-primary/30");
711 expect(className).not.toContain("bg-accent/85");
712 });
713​
714 it("uses selected hover colors for selected threads", () => {
715 const className = resolveThreadRowClassName({ isActive: false, isSelected: true });
716 expect(className).toContain("bg-primary/15");
717 expect(className).toContain("hover:bg-primary/19");
718 expect(className).toContain("dark:bg-primary/22");
719 expect(className).not.toContain("hover:bg-accent");
720 });
721​
722 it("keeps the accent palette for active-only threads", () => {
723 const className = resolveThreadRowClassName({ isActive: true, isSelected: false });
724 expect(className).toContain("bg-accent/85");
725 expect(className).toContain("hover:bg-accent");
726 });
727});
728​
729describe("resolveProjectStatusIndicator", () => {
730 it("returns null when no threads have a notable status", () => {
731 expect(resolveProjectStatusIndicator([null, null])).toBeNull();
732 });
733​
734 it("surfaces the highest-priority actionable state across project threads", () => {
735 expect(
736 resolveProjectStatusIndicator([
737 {
738 label: "Completed",
739 colorClass: "text-emerald-600",
740 dotClass: "bg-emerald-500",
741 pulse: false,
742 },
743 {
744 label: "Pending Approval",
745 colorClass: "text-amber-600",
746 dotClass: "bg-amber-500",
747 pulse: false,
748 },
749 {
750 label: "Working",
751 colorClass: "text-sky-600",
752 dotClass: "bg-sky-500",
753 pulse: true,
754 },
755 ]),
756 ).toMatchObject({ label: "Pending Approval", dotClass: "bg-amber-500" });
757 });
758​
759 it("prefers plan-ready over completed when no stronger action is needed", () => {
760 expect(
761 resolveProjectStatusIndicator([
762 {
763 label: "Completed",
764 colorClass: "text-emerald-600",
765 dotClass: "bg-emerald-500",
766 pulse: false,
767 },
768 {
769 label: "Plan Ready",
770 colorClass: "text-violet-600",
771 dotClass: "bg-violet-500",
772 pulse: false,
773 },
774 ]),
775 ).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
776 });
777});
778​
779describe("getVisibleThreadsForProject", () => {
780 it("includes the active thread even when it falls below the folded preview", () => {
781 const threads = Array.from({ length: 8 }, (_, index) =>
782 makeThread({
783 id: ThreadId.make(`thread-${index + 1}`),
784 title: `Thread ${index + 1}`,
785 }),
786 );
787​
788 const result = getVisibleThreadsForProject({
789 threads,
790 activeThreadId: ThreadId.make("thread-8"),
791 isThreadListExpanded: false,
792 previewLimit: 6,
793 });
794​
795 expect(result.hasHiddenThreads).toBe(true);
796 expect(result.visibleThreads.map((thread) => thread.id)).toEqual([
797 ThreadId.make("thread-1"),
798 ThreadId.make("thread-2"),
799 ThreadId.make("thread-3"),
800 ThreadId.make("thread-4"),
801 ThreadId.make("thread-5"),
802 ThreadId.make("thread-6"),
803 ThreadId.make("thread-8"),
804 ]);
805 expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ThreadId.make("thread-7")]);
806 });
807​
808 it("returns all threads when the list is expanded", () => {
809 const threads = Array.from({ length: 8 }, (_, index) =>
810 makeThread({
811 id: ThreadId.make(`thread-${index + 1}`),
812 }),
813 );
814​
815 const result = getVisibleThreadsForProject({
816 threads,
817 activeThreadId: ThreadId.make("thread-8"),
818 isThreadListExpanded: true,
819 previewLimit: 6,
820 });
821​
822 expect(result.hasHiddenThreads).toBe(true);
823 expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
824 threads.map((thread) => thread.id),
825 );
826 expect(result.hiddenThreads).toEqual([]);
827 });
828});
829​
830function makeProject(overrides: Partial<Project> = {}): Project {
831 const { defaultModelSelection, ...rest } = overrides;
832 return {
833 id: ProjectId.make("project-1"),
834 environmentId: localEnvironmentId,
835 title: "Project",
836 workspaceRoot: "/tmp/project",
837 repositoryIdentity: null,
838 defaultModelSelection: {
839 instanceId: ProviderInstanceId.make("codex"),
840 model: "gpt-5.4",
841 ...defaultModelSelection,
842 },
843 createdAt: "2026-03-09T10:00:00.000Z",
844 updatedAt: "2026-03-09T10:00:00.000Z",
845 scripts: [],
846 ...rest,
847 };
849​
850function makeThread(overrides: ThreadFixtureOverrides = {}): Thread {
851 return makeThreadFixture({
852 id: ThreadId.make("thread-1"),
853 environmentId: localEnvironmentId,
854 projectId: ProjectId.make("project-1"),
855 title: "Thread",
856 modelSelection: {
857 instanceId: ProviderInstanceId.make("codex"),
858 model: "gpt-5.4",
859 ...overrides?.modelSelection,
860 },
861 runtimeMode: DEFAULT_RUNTIME_MODE,
862 interactionMode: DEFAULT_INTERACTION_MODE,
863 runtime: null,
864 messages: [],
865 proposedPlans: [],
866 createdAt: "2026-03-09T10:00:00.000Z",
867 archivedAt: null,
868 deletedAt: null,
869 updatedAt: "2026-03-09T10:00:00.000Z",
870 latestRun: null,
871 branch: null,
872 worktreePath: null,
873 ...overrides,
874 });
876​
877describe("getFallbackThreadIdAfterDelete", () => {
878 it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
879 const fallbackThreadId = getFallbackThreadIdAfterDelete({
880 threads: [
881 makeThread({
882 id: ThreadId.make("thread-oldest"),
883 projectId: ProjectId.make("project-1"),
884 createdAt: "2026-03-09T10:00:00.000Z",
885 messages: [],
886 }),
887 makeThread({
888 id: ThreadId.make("thread-active"),
889 projectId: ProjectId.make("project-1"),
890 createdAt: "2026-03-09T10:05:00.000Z",
891 messages: [],
892 }),
893 makeThread({
894 id: ThreadId.make("thread-newest"),
895 projectId: ProjectId.make("project-1"),
896 createdAt: "2026-03-09T10:10:00.000Z",
897 messages: [],
898 }),
899 makeThread({
900 id: ThreadId.make("thread-other-project"),
901 projectId: ProjectId.make("project-2"),
902 createdAt: "2026-03-09T10:20:00.000Z",
903 messages: [],
904 }),
905 ],
906 deletedThreadId: ThreadId.make("thread-active"),
907 sortOrder: "created_at",
908 });
909​
910 expect(fallbackThreadId).toBe(ThreadId.make("thread-newest"));
911 });
912​
913 it("skips other threads being deleted in the same action", () => {
914 const fallbackThreadId = getFallbackThreadIdAfterDelete({
915 threads: [
916 makeThread({
917 id: ThreadId.make("thread-active"),
918 projectId: ProjectId.make("project-1"),
919 createdAt: "2026-03-09T10:05:00.000Z",
920 messages: [],
921 }),
922 makeThread({
923 id: ThreadId.make("thread-newest"),
924 projectId: ProjectId.make("project-1"),
925 createdAt: "2026-03-09T10:10:00.000Z",
926 messages: [],
927 }),
928 makeThread({
929 id: ThreadId.make("thread-next"),
930 projectId: ProjectId.make("project-1"),
931 createdAt: "2026-03-09T10:07:00.000Z",
932 messages: [],
933 }),
934 ],
935 deletedThreadId: ThreadId.make("thread-active"),
936 deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]),
937 sortOrder: "created_at",
938 });
939​
940 expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
941 });
942});
943describe("sortProjectsForSidebar", () => {
944 it("sorts projects by the most recent user message across their threads", () => {
945 const projects = [
946 makeProject({ id: ProjectId.make("project-1"), title: "Older project" }),
947 makeProject({ id: ProjectId.make("project-2"), title: "Newer project" }),
948 ];
949 const threads = [
950 makeThread({
951 projectId: ProjectId.make("project-1"),
952 updatedAt: "2026-03-09T10:20:00.000Z",
953 messages: [
954 {
955 id: "message-1" as never,
956 role: "user",
957 text: "older project user message",
958 runId: null,
959 createdAt: "2026-03-09T10:01:00.000Z",
960 updatedAt: "2026-03-09T10:01:00.000Z",
961 streaming: false,
962 },
963 ],
964 }),
965 makeThread({
966 id: ThreadId.make("thread-2"),
967 projectId: ProjectId.make("project-2"),
968 updatedAt: "2026-03-09T10:05:00.000Z",
969 messages: [
970 {
971 id: "message-2" as never,
972 role: "user",
973 text: "newer project user message",
974 runId: null,
975 createdAt: "2026-03-09T10:05:00.000Z",
976 updatedAt: "2026-03-09T10:05:00.000Z",
977 streaming: false,
978 },
979 ],
980 }),
981 ];
982​
983 const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
984​
985 expect(sorted.map((project) => project.id)).toEqual([
986 ProjectId.make("project-2"),
987 ProjectId.make("project-1"),
988 ]);
989 });
990​
991 it("falls back to project timestamps when a project has no threads", () => {
992 const sorted = sortProjectsForSidebar(
993 [
994 makeProject({
995 id: ProjectId.make("project-1"),
996 title: "Older project",
997 updatedAt: "2026-03-09T10:01:00.000Z",
998 }),
999 makeProject({
1000 id: ProjectId.make("project-2"),
1001 title: "Newer project",
1002 updatedAt: "2026-03-09T10:05:00.000Z",
1003 }),
1004 ],
1005 [],
1006 "updated_at",
1007 );
1008​
1009 expect(sorted.map((project) => project.id)).toEqual([
1010 ProjectId.make("project-2"),
1011 ProjectId.make("project-1"),
1012 ]);
1013 });
1014​
1015 it("falls back to name and id ordering when projects have no sortable timestamps", () => {
1016 const sorted = sortProjectsForSidebar(
1018 makeProject({
1019 id: ProjectId.make("project-2"),
1020 title: "Beta",
1021 createdAt: "invalid-created-at" as never,
1022 updatedAt: "invalid-updated-at" as never,
1023 }),
1024 makeProject({
1025 id: ProjectId.make("project-1"),
1026 title: "Alpha",
1027 createdAt: "invalid-created-at" as never,
1028 updatedAt: "invalid-updated-at" as never,
1029 }),
1030 ],
1031 [],
1032 "updated_at",
1033 );
1034​
1035 expect(sorted.map((project) => project.id)).toEqual([
1036 ProjectId.make("project-1"),
1037 ProjectId.make("project-2"),
1038 ]);
1039 });
1040​
1041 it("preserves manual project ordering", () => {
1042 const projects = [
1043 makeProject({ id: ProjectId.make("project-2"), title: "Second" }),
1044 makeProject({ id: ProjectId.make("project-1"), title: "First" }),
1045 ];
1046​
1047 const sorted = sortProjectsForSidebar(projects, [], "manual");
1048​
1049 expect(sorted.map((project) => project.id)).toEqual([
1050 ProjectId.make("project-2"),
1051 ProjectId.make("project-1"),
1052 ]);
1053 });
1054​
1055 it("ignores archived threads when sorting projects", () => {
1056 const sorted = sortProjectsForSidebar(
1058 makeProject({
1059 id: ProjectId.make("project-1"),
1060 title: "Visible project",
1061 updatedAt: "2026-03-09T10:01:00.000Z",
1062 }),
1063 makeProject({
1064 id: ProjectId.make("project-2"),
1065 title: "Archived-only project",
1066 updatedAt: "2026-03-09T10:00:00.000Z",
1067 }),
1068 ],
1070 makeThread({
1071 id: ThreadId.make("thread-visible"),
1072 projectId: ProjectId.make("project-1"),
1073 updatedAt: "2026-03-09T10:02:00.000Z",
1074 archivedAt: null,
1075 }),
1076 makeThread({
1077 id: ThreadId.make("thread-archived"),
1078 projectId: ProjectId.make("project-2"),
1079 updatedAt: "2026-03-09T10:10:00.000Z",
1080 archivedAt: "2026-03-09T10:11:00.000Z",
1081 }),
1082 ].filter((thread) => thread.archivedAt === null),
1083 "updated_at",
1084 );
1085​
1086 expect(sorted.map((project) => project.id)).toEqual([
1087 ProjectId.make("project-1"),
1088 ProjectId.make("project-2"),
1089 ]);
1090 });
1091​
1092 it("returns the project timestamp when no threads are present", () => {
1093 const timestamp = getProjectSortTimestamp(
1094 makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
1095 [],
1096 "updated_at",
1097 );
1098​
1099 expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
1100 });
1101});