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