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

Sidebar.logic.test.ts

989 lines28.9 KB

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