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

Sidebar.logic.test.ts

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