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

Sidebar.logic.test.ts

971 lines28.1 KB

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