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