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

Sidebar.logic.test.ts

928 lines26.7 KB

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 };
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​
314describe("resolveAdjacentThreadId", () => {
315 it("resolves adjacent thread ids in ordered sidebar traversal", () => {
316 const threads = [
317 ThreadId.make("thread-1"),
318 ThreadId.make("thread-2"),
319 ThreadId.make("thread-3"),
320 ];
321​
322 expect(
323 resolveAdjacentThreadId({
324 threadIds: threads,
325 currentThreadId: threads[1] ?? null,
326 direction: "previous",
327 }),
328 ).toBe(threads[0]);
329 expect(
330 resolveAdjacentThreadId({
331 threadIds: threads,
332 currentThreadId: threads[1] ?? null,
333 direction: "next",
334 }),
335 ).toBe(threads[2]);
336 expect(
337 resolveAdjacentThreadId({
338 threadIds: threads,
339 currentThreadId: null,
340 direction: "next",
341 }),
342 ).toBe(threads[0]);
343 expect(
344 resolveAdjacentThreadId({
345 threadIds: threads,
346 currentThreadId: null,
347 direction: "previous",
348 }),
349 ).toBe(threads[2]);
350 expect(
351 resolveAdjacentThreadId({
352 threadIds: threads,
353 currentThreadId: threads[0] ?? null,
354 direction: "previous",
355 }),
356 ).toBeNull();
357 });
358});
359​
360describe("getVisibleSidebarThreadIds", () => {
361 it("returns only the rendered visible thread order across projects", () => {
362 expect(
363 getVisibleSidebarThreadIds([
364 {
365 renderedThreadIds: [
366 ThreadId.make("thread-12"),
367 ThreadId.make("thread-11"),
368 ThreadId.make("thread-10"),
369 ],
370 },
371 {
372 renderedThreadIds: [ThreadId.make("thread-8"), ThreadId.make("thread-6")],
373 },
374 ]),
375 ).toEqual([
376 ThreadId.make("thread-12"),
377 ThreadId.make("thread-11"),
378 ThreadId.make("thread-10"),
379 ThreadId.make("thread-8"),
380 ThreadId.make("thread-6"),
381 ]);
382 });
383​
384 it("skips threads from collapsed projects whose thread panels are not shown", () => {
385 expect(
386 getVisibleSidebarThreadIds([
387 {
388 shouldShowThreadPanel: false,
389 renderedThreadIds: [ThreadId.make("thread-hidden-2"), ThreadId.make("thread-hidden-1")],
390 },
391 {
392 shouldShowThreadPanel: true,
393 renderedThreadIds: [ThreadId.make("thread-12"), ThreadId.make("thread-11")],
394 },
395 ]),
396 ).toEqual([ThreadId.make("thread-12"), ThreadId.make("thread-11")]);
397 });
398});
399​
400describe("isContextMenuPointerDown", () => {
401 it("treats secondary-button presses as context menu gestures on all platforms", () => {
402 expect(
403 isContextMenuPointerDown({
404 button: 2,
405 ctrlKey: false,
406 isMac: false,
407 }),
408 ).toBe(true);
409 });
410​
411 it("treats ctrl+primary-click as a context menu gesture on macOS", () => {
412 expect(
413 isContextMenuPointerDown({
414 button: 0,
415 ctrlKey: true,
416 isMac: true,
417 }),
418 ).toBe(true);
419 });
420​
421 it("does not treat ctrl+primary-click as a context menu gesture off macOS", () => {
422 expect(
423 isContextMenuPointerDown({
424 button: 0,
425 ctrlKey: true,
426 isMac: false,
427 }),
428 ).toBe(false);
429 });
430});
431​
432describe("resolveThreadStatusPill", () => {
433 const baseThread = {
434 hasActionableProposedPlan: false,
435 hasPendingApprovals: false,
436 hasPendingUserInput: false,
437 interactionMode: "plan" as const,
438 latestTurn: null,
439 lastVisitedAt: undefined,
440 session: {
441 provider: "codex" as const,
442 status: "running" as const,
443 createdAt: "2026-03-09T10:00:00.000Z",
444 updatedAt: "2026-03-09T10:00:00.000Z",
445 orchestrationStatus: "running" as const,
446 },
447 };
448​
449 it("shows pending approval before all other statuses", () => {
450 expect(
451 resolveThreadStatusPill({
452 thread: {
453 ...baseThread,
454 hasPendingApprovals: true,
455 hasPendingUserInput: true,
456 },
457 }),
458 ).toMatchObject({ label: "Pending Approval", pulse: false });
459 });
460​
461 it("shows awaiting input when plan mode is blocked on user answers", () => {
462 expect(
463 resolveThreadStatusPill({
464 thread: {
465 ...baseThread,
466 hasPendingUserInput: true,
467 },
468 }),
469 ).toMatchObject({ label: "Awaiting Input", pulse: false });
470 });
471​
472 it("falls back to working when the thread is actively running without blockers", () => {
473 expect(
474 resolveThreadStatusPill({
475 thread: baseThread,
476 }),
477 ).toMatchObject({ label: "Working", pulse: true });
478 });
479​
480 it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
481 expect(
482 resolveThreadStatusPill({
483 thread: {
484 ...baseThread,
485 hasActionableProposedPlan: true,
486 latestTurn: makeLatestTurn(),
487 session: {
488 ...baseThread.session,
489 status: "ready",
490 orchestrationStatus: "ready",
491 },
492 },
493 }),
494 ).toMatchObject({ label: "Plan Ready", pulse: false });
495 });
496​
497 it("does not show plan ready after the proposed plan was implemented elsewhere", () => {
498 expect(
499 resolveThreadStatusPill({
500 thread: {
501 ...baseThread,
502 latestTurn: makeLatestTurn(),
503 session: {
504 ...baseThread.session,
505 status: "ready",
506 orchestrationStatus: "ready",
507 },
508 },
509 }),
510 ).toMatchObject({ label: "Completed", pulse: false });
511 });
512​
513 it("shows completed when there is an unseen completion and no active blocker", () => {
514 expect(
515 resolveThreadStatusPill({
516 thread: {
517 ...baseThread,
518 interactionMode: "default",
519 latestTurn: makeLatestTurn(),
520 lastVisitedAt: "2026-03-09T10:04:00.000Z",
521 session: {
522 ...baseThread.session,
523 status: "ready",
524 orchestrationStatus: "ready",
525 },
526 },
527 }),
528 ).toMatchObject({ label: "Completed", pulse: false });
529 });
530});
531​
532describe("resolveThreadRowClassName", () => {
533 it("uses the darker selected palette when a thread is both selected and active", () => {
534 const className = resolveThreadRowClassName({ isActive: true, isSelected: true });
535 expect(className).toContain("bg-primary/22");
536 expect(className).toContain("hover:bg-primary/26");
537 expect(className).toContain("dark:bg-primary/30");
538 expect(className).not.toContain("bg-accent/85");
539 });
540​
541 it("uses selected hover colors for selected threads", () => {
542 const className = resolveThreadRowClassName({ isActive: false, isSelected: true });
543 expect(className).toContain("bg-primary/15");
544 expect(className).toContain("hover:bg-primary/19");
545 expect(className).toContain("dark:bg-primary/22");
546 expect(className).not.toContain("hover:bg-accent");
547 });
548​
549 it("keeps the accent palette for active-only threads", () => {
550 const className = resolveThreadRowClassName({ isActive: true, isSelected: false });
551 expect(className).toContain("bg-accent/85");
552 expect(className).toContain("hover:bg-accent");
553 });
554});
555​
556describe("resolveProjectStatusIndicator", () => {
557 it("returns null when no threads have a notable status", () => {
558 expect(resolveProjectStatusIndicator([null, null])).toBeNull();
559 });
560​
561 it("surfaces the highest-priority actionable state across project threads", () => {
562 expect(
563 resolveProjectStatusIndicator([
564 {
565 label: "Completed",
566 colorClass: "text-emerald-600",
567 dotClass: "bg-emerald-500",
568 pulse: false,
569 },
570 {
571 label: "Pending Approval",
572 colorClass: "text-amber-600",
573 dotClass: "bg-amber-500",
574 pulse: false,
575 },
576 {
577 label: "Working",
578 colorClass: "text-sky-600",
579 dotClass: "bg-sky-500",
580 pulse: true,
581 },
582 ]),
583 ).toMatchObject({ label: "Pending Approval", dotClass: "bg-amber-500" });
584 });
585​
586 it("prefers plan-ready over completed when no stronger action is needed", () => {
587 expect(
588 resolveProjectStatusIndicator([
589 {
590 label: "Completed",
591 colorClass: "text-emerald-600",
592 dotClass: "bg-emerald-500",
593 pulse: false,
594 },
595 {
596 label: "Plan Ready",
597 colorClass: "text-violet-600",
598 dotClass: "bg-violet-500",
599 pulse: false,
600 },
601 ]),
602 ).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
603 });
604});
605​
606describe("getVisibleThreadsForProject", () => {
607 it("includes the active thread even when it falls below the folded preview", () => {
608 const threads = Array.from({ length: 8 }, (_, index) =>
609 makeThread({
610 id: ThreadId.make(`thread-${index + 1}`),
611 title: `Thread ${index + 1}`,
612 }),
613 );
614​
615 const result = getVisibleThreadsForProject({
616 threads,
617 activeThreadId: ThreadId.make("thread-8"),
618 isThreadListExpanded: false,
619 previewLimit: 6,
620 });
621​
622 expect(result.hasHiddenThreads).toBe(true);
623 expect(result.visibleThreads.map((thread) => thread.id)).toEqual([
624 ThreadId.make("thread-1"),
625 ThreadId.make("thread-2"),
626 ThreadId.make("thread-3"),
627 ThreadId.make("thread-4"),
628 ThreadId.make("thread-5"),
629 ThreadId.make("thread-6"),
630 ThreadId.make("thread-8"),
631 ]);
632 expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ThreadId.make("thread-7")]);
633 });
634​
635 it("returns all threads when the list is expanded", () => {
636 const threads = Array.from({ length: 8 }, (_, index) =>
637 makeThread({
638 id: ThreadId.make(`thread-${index + 1}`),
639 }),
640 );
641​
642 const result = getVisibleThreadsForProject({
643 threads,
644 activeThreadId: ThreadId.make("thread-8"),
645 isThreadListExpanded: true,
646 previewLimit: 6,
647 });
648​
649 expect(result.hasHiddenThreads).toBe(true);
650 expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
651 threads.map((thread) => thread.id),
652 );
653 expect(result.hiddenThreads).toEqual([]);
654 });
655});
656​
657function makeProject(overrides: Partial<Project> = {}): Project {
658 const { defaultModelSelection, ...rest } = overrides;
659 return {
660 id: ProjectId.make("project-1"),
661 environmentId: localEnvironmentId,
662 name: "Project",
663 cwd: "/tmp/project",
664 defaultModelSelection: {
665 provider: "codex",
666 model: "gpt-5.4",
667 ...defaultModelSelection,
668 },
669 createdAt: "2026-03-09T10:00:00.000Z",
670 updatedAt: "2026-03-09T10:00:00.000Z",
671 scripts: [],
672 ...rest,
673 };
675​
676function makeThread(overrides: Partial<Thread> = {}): Thread {
677 return {
678 id: ThreadId.make("thread-1"),
679 environmentId: localEnvironmentId,
680 codexThreadId: null,
681 projectId: ProjectId.make("project-1"),
682 title: "Thread",
683 modelSelection: {
684 provider: "codex",
685 model: "gpt-5.4",
686 ...overrides?.modelSelection,
687 },
688 runtimeMode: DEFAULT_RUNTIME_MODE,
689 interactionMode: DEFAULT_INTERACTION_MODE,
690 session: null,
691 messages: [],
692 proposedPlans: [],
693 error: null,
694 createdAt: "2026-03-09T10:00:00.000Z",
695 archivedAt: null,
696 updatedAt: "2026-03-09T10:00:00.000Z",
697 latestTurn: null,
698 branch: null,
699 worktreePath: null,
700 turnDiffSummaries: [],
701 activities: [],
702 ...overrides,
703 };
705​
706describe("getFallbackThreadIdAfterDelete", () => {
707 it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
708 const fallbackThreadId = getFallbackThreadIdAfterDelete({
709 threads: [
710 makeThread({
711 id: ThreadId.make("thread-oldest"),
712 projectId: ProjectId.make("project-1"),
713 createdAt: "2026-03-09T10:00:00.000Z",
714 messages: [],
715 }),
716 makeThread({
717 id: ThreadId.make("thread-active"),
718 projectId: ProjectId.make("project-1"),
719 createdAt: "2026-03-09T10:05:00.000Z",
720 messages: [],
721 }),
722 makeThread({
723 id: ThreadId.make("thread-newest"),
724 projectId: ProjectId.make("project-1"),
725 createdAt: "2026-03-09T10:10:00.000Z",
726 messages: [],
727 }),
728 makeThread({
729 id: ThreadId.make("thread-other-project"),
730 projectId: ProjectId.make("project-2"),
731 createdAt: "2026-03-09T10:20:00.000Z",
732 messages: [],
733 }),
734 ],
735 deletedThreadId: ThreadId.make("thread-active"),
736 sortOrder: "created_at",
737 });
738​
739 expect(fallbackThreadId).toBe(ThreadId.make("thread-newest"));
740 });
741​
742 it("skips other threads being deleted in the same action", () => {
743 const fallbackThreadId = getFallbackThreadIdAfterDelete({
744 threads: [
745 makeThread({
746 id: ThreadId.make("thread-active"),
747 projectId: ProjectId.make("project-1"),
748 createdAt: "2026-03-09T10:05:00.000Z",
749 messages: [],
750 }),
751 makeThread({
752 id: ThreadId.make("thread-newest"),
753 projectId: ProjectId.make("project-1"),
754 createdAt: "2026-03-09T10:10:00.000Z",
755 messages: [],
756 }),
757 makeThread({
758 id: ThreadId.make("thread-next"),
759 projectId: ProjectId.make("project-1"),
760 createdAt: "2026-03-09T10:07:00.000Z",
761 messages: [],
762 }),
763 ],
764 deletedThreadId: ThreadId.make("thread-active"),
765 deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]),
766 sortOrder: "created_at",
767 });
768​
769 expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
770 });
771});
772describe("sortProjectsForSidebar", () => {
773 it("sorts projects by the most recent user message across their threads", () => {
774 const projects = [
775 makeProject({ id: ProjectId.make("project-1"), name: "Older project" }),
776 makeProject({ id: ProjectId.make("project-2"), name: "Newer project" }),
777 ];
778 const threads = [
779 makeThread({
780 projectId: ProjectId.make("project-1"),
781 updatedAt: "2026-03-09T10:20:00.000Z",
782 messages: [
783 {
784 id: "message-1" as never,
785 role: "user",
786 text: "older project user message",
787 createdAt: "2026-03-09T10:01:00.000Z",
788 streaming: false,
789 completedAt: "2026-03-09T10:01:00.000Z",
790 },
791 ],
792 }),
793 makeThread({
794 id: ThreadId.make("thread-2"),
795 projectId: ProjectId.make("project-2"),
796 updatedAt: "2026-03-09T10:05:00.000Z",
797 messages: [
798 {
799 id: "message-2" as never,
800 role: "user",
801 text: "newer project user message",
802 createdAt: "2026-03-09T10:05:00.000Z",
803 streaming: false,
804 completedAt: "2026-03-09T10:05:00.000Z",
805 },
806 ],
807 }),
808 ];
809​
810 const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
811​
812 expect(sorted.map((project) => project.id)).toEqual([
813 ProjectId.make("project-2"),
814 ProjectId.make("project-1"),
815 ]);
816 });
817​
818 it("falls back to project timestamps when a project has no threads", () => {
819 const sorted = sortProjectsForSidebar(
820 [
821 makeProject({
822 id: ProjectId.make("project-1"),
823 name: "Older project",
824 updatedAt: "2026-03-09T10:01:00.000Z",
825 }),
826 makeProject({
827 id: ProjectId.make("project-2"),
828 name: "Newer project",
829 updatedAt: "2026-03-09T10:05:00.000Z",
830 }),
831 ],
832 [],
833 "updated_at",
834 );
835​
836 expect(sorted.map((project) => project.id)).toEqual([
837 ProjectId.make("project-2"),
838 ProjectId.make("project-1"),
839 ]);
840 });
841​
842 it("falls back to name and id ordering when projects have no sortable timestamps", () => {
843 const sorted = sortProjectsForSidebar(
844 [
845 makeProject({
846 id: ProjectId.make("project-2"),
847 name: "Beta",
848 createdAt: undefined,
849 updatedAt: undefined,
850 }),
851 makeProject({
852 id: ProjectId.make("project-1"),
853 name: "Alpha",
854 createdAt: undefined,
855 updatedAt: undefined,
856 }),
857 ],
858 [],
859 "updated_at",
860 );
861​
862 expect(sorted.map((project) => project.id)).toEqual([
863 ProjectId.make("project-1"),
864 ProjectId.make("project-2"),
865 ]);
866 });
867​
868 it("preserves manual project ordering", () => {
869 const projects = [
870 makeProject({ id: ProjectId.make("project-2"), name: "Second" }),
871 makeProject({ id: ProjectId.make("project-1"), name: "First" }),
872 ];
873​
874 const sorted = sortProjectsForSidebar(projects, [], "manual");
875​
876 expect(sorted.map((project) => project.id)).toEqual([
877 ProjectId.make("project-2"),
878 ProjectId.make("project-1"),
879 ]);
880 });
881​
882 it("ignores archived threads when sorting projects", () => {
883 const sorted = sortProjectsForSidebar(
884 [
885 makeProject({
886 id: ProjectId.make("project-1"),
887 name: "Visible project",
888 updatedAt: "2026-03-09T10:01:00.000Z",
889 }),
890 makeProject({
891 id: ProjectId.make("project-2"),
892 name: "Archived-only project",
893 updatedAt: "2026-03-09T10:00:00.000Z",
894 }),
895 ],
896 [
897 makeThread({
898 id: ThreadId.make("thread-visible"),
899 projectId: ProjectId.make("project-1"),
900 updatedAt: "2026-03-09T10:02:00.000Z",
901 archivedAt: null,
902 }),
903 makeThread({
904 id: ThreadId.make("thread-archived"),
905 projectId: ProjectId.make("project-2"),
906 updatedAt: "2026-03-09T10:10:00.000Z",
907 archivedAt: "2026-03-09T10:11:00.000Z",
908 }),
909 ].filter((thread) => thread.archivedAt === null),
910 "updated_at",
911 );
912​
913 expect(sorted.map((project) => project.id)).toEqual([
914 ProjectId.make("project-1"),
915 ProjectId.make("project-2"),
916 ]);
917 });
918​
919 it("returns the project timestamp when no threads are present", () => {
920 const timestamp = getProjectSortTimestamp(
921 makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
922 [],
923 "updated_at",
924 );
925​
926 expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
927 });
928});