Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 archiveSelectedThreadEntries,
4 buildBulkTitleRegenerationContextMenuItem,
5 buildMultiSelectThreadContextMenuItems,
6 createThreadJumpHintVisibilityController,
7 getSidebarThreadIdsToPrewarm,
8 getVisibleSidebarThreadIds,
9 resolveAdjacentThreadId,
10 getFallbackThreadIdAfterDelete,
11 getVisibleThreadsForProject,
12 getProjectSortTimestamp,
13 hasUnseenCompletion,
14 isContextMenuPointerDown,
15 isTrailingDoubleClick,
16 orderItemsByPreferredIds,
17 resolveProjectStatusIndicator,
18 resolveSidebarStageBadgeLabel,
19 resolveThreadRowClassName,
20 resolveSidebarV2Status,
21 resolveThreadStatusPill,
22 resolveWorkingStartedAt,
23 searchSidebarThreadsByTitle,
24 formatWorkingDurationLabel,
25 shouldNavigateAfterProjectRemoval,
26 shouldClearThreadSelectionOnMouseDown,
27 sortLogicalProjectsForSidebar,
28 sortSettledThreadsForSidebarV2,
29 sortThreadsForSidebarV2,
30 sortProjectsForSidebar,
31 sortScopedProjectsForSidebar,
32 THREAD_JUMP_HINT_SHOW_DELAY_MS,
33} from "./Sidebar.logic";
34import {
35 EnvironmentId,
36 OrchestrationLatestTurn,
37 ProjectId,
38 ProviderInstanceId,
39 ThreadId,
40} from "@t3tools/contracts";
41
42import {
43 DEFAULT_INTERACTION_MODE,
44 DEFAULT_RUNTIME_MODE,
45 type Project,
46 type Thread,
47} from "../types";
48
49const localEnvironmentId = EnvironmentId.make("environment-local");
50
51describe("shouldNavigateAfterProjectRemoval", () => {
52 const projectThreads = [{ environmentId: "environment-local", id: "thread-1" }];
53
54 it("navigates away from a draft route owned by the removed project", () => {
55 expect(
56 shouldNavigateAfterProjectRemoval({
57 routeTarget: { kind: "draft", draftId: "draft-1" as never },
58 projectThreads,
59 projectDraftId: "draft-1",
60 }),
61 ).toBe(true);
62 });
63
64 it("does not navigate away from a different draft route", () => {
65 expect(
66 shouldNavigateAfterProjectRemoval({
67 routeTarget: { kind: "draft", draftId: "draft-2" as never },
68 projectThreads,
69 projectDraftId: "draft-1",
70 }),
71 ).toBe(false);
72 });
73
74 it("navigates away from a server thread owned by the removed project", () => {
75 expect(
76 shouldNavigateAfterProjectRemoval({
77 routeTarget: {
78 kind: "server",
79 threadRef: {
80 environmentId: EnvironmentId.make("environment-local"),
81 threadId: ThreadId.make("thread-1"),
82 },
83 },
84 projectThreads,
85 projectDraftId: null,
86 }),
87 ).toBe(true);
88 });
89
90 it("does not navigate from an unrelated route", () => {
91 expect(
92 shouldNavigateAfterProjectRemoval({
93 routeTarget: null,
94 projectThreads,
95 projectDraftId: null,
96 }),
97 ).toBe(false);
98 });
99});
100
101describe("archiveSelectedThreadEntries", () => {
102 const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
103 const success = { _tag: "Success" } as const;
104 const failure = { _tag: "Failure" } as const;
105
106 it("records every entry after full success", async () => {
107 const outcome = await archiveSelectedThreadEntries({
108 entries,
109 archive: async (_entry, onArchived) => {
110 onArchived();
111 return success;
112 },
113 });
114
115 expect(outcome).toEqual({
116 archivedThreadKeys: ["one", "two", "three"],
117 mutationFailure: null,
118 followupFailures: [],
119 });
120 });
121
122 it("stops at a mutation failure and retains prior successes", async () => {
123 const archive = vi.fn(async (entry: (typeof entries)[number], onArchived: () => void) => {
124 if (entry.threadKey === "two") return failure;
125 onArchived();
126 return success;
127 });
128 const outcome = await archiveSelectedThreadEntries({ entries, archive });
129
130 expect(archive).toHaveBeenCalledTimes(2);
131 expect(outcome).toEqual({
132 archivedThreadKeys: ["one"],
133 mutationFailure: failure,
134 followupFailures: [],
135 });
136 });
137
138 it("continues after a post-archive failure", async () => {
139 const archive = vi.fn(async (entry: (typeof entries)[number], onArchived: () => void) => {
140 onArchived();
141 return entry.threadKey === "two" ? failure : success;
142 });
143 const outcome = await archiveSelectedThreadEntries({ entries, archive });
144
145 expect(archive).toHaveBeenCalledTimes(3);
146 expect(outcome).toEqual({
147 archivedThreadKeys: ["one", "two", "three"],
148 mutationFailure: null,
149 followupFailures: [failure],
150 });
151 });
152});
153
154describe("buildBulkTitleRegenerationContextMenuItem", () => {
155 it("counts only threads that can start a new regeneration", () => {
156 expect(
157 buildBulkTitleRegenerationContextMenuItem({
158 supportedCount: 4,
159 actionableCount: 3,
160 }),
161 ).toEqual({
162 id: "regenerate-title",
163 label: "Regenerate titles (3)",
164 });
165 });
166
167 it("shows a disabled progress item when every supported thread is pending", () => {
168 expect(
169 buildBulkTitleRegenerationContextMenuItem({
170 supportedCount: 2,
171 actionableCount: 0,
172 }),
173 ).toEqual({
174 id: "regenerate-title",
175 label: "Regenerating… (2)",
176 disabled: true,
177 });
178 });
179
180 it("omits the action when no selected environment supports it", () => {
181 expect(
182 buildBulkTitleRegenerationContextMenuItem({
183 supportedCount: 0,
184 actionableCount: 0,
185 }),
186 ).toBeNull();
187 });
188});
189
190describe("buildMultiSelectThreadContextMenuItems", () => {
191 it("offers bulk archive with the selected count", () => {
192 expect(
193 buildMultiSelectThreadContextMenuItems({ count: 3, hasRunningThread: false }),
194 ).toContainEqual({ id: "archive", label: "Archive (3)", disabled: false });
195 });
196
197 it("disables bulk archive when a selected thread is running", () => {
198 expect(
199 buildMultiSelectThreadContextMenuItems({ count: 2, hasRunningThread: true }),
200 ).toContainEqual({ id: "archive", label: "Archive (2)", disabled: true });
201 });
202});
203
204describe("resolveSidebarStageBadgeLabel", () => {
205 it("returns Nightly for nightly primary server versions", () => {
206 expect(
207 resolveSidebarStageBadgeLabel({
208 primaryServerVersion: "0.0.28-nightly.20260616.12",
209 fallbackStageLabel: "Alpha",
210 }),
211 ).toBe("Nightly");
212 });
213
214 it("returns the fallback label for stable primary server versions", () => {
215 expect(
216 resolveSidebarStageBadgeLabel({
217 primaryServerVersion: "0.0.27",
218 fallbackStageLabel: "Alpha",
219 }),
220 ).toBe("Alpha");
221 });
222
223 it("returns the fallback label when the primary server version is missing", () => {
224 expect(
225 resolveSidebarStageBadgeLabel({
226 primaryServerVersion: null,
227 fallbackStageLabel: "Dev",
228 }),
229 ).toBe("Dev");
230 });
231
232 it("returns the fallback label for malformed nightly prerelease versions", () => {
233 expect(
234 resolveSidebarStageBadgeLabel({
235 primaryServerVersion: "0.0.28-nightly.20260616",
236 fallbackStageLabel: "Alpha",
237 }),
238 ).toBe("Alpha");
239 });
240});
241
242function makeLatestTurn(overrides?: {
243 completedAt?: string | null;
244 startedAt?: string | null;
245}): OrchestrationLatestTurn {
246 return {
247 turnId: "turn-1" as never,
248 state: "completed",
249 assistantMessageId: null,
250 requestedAt: "2026-03-09T10:00:00.000Z",
251 startedAt:
252 overrides?.startedAt !== undefined ? overrides.startedAt : "2026-03-09T10:00:00.000Z",
253 completedAt:
254 overrides?.completedAt !== undefined ? overrides.completedAt : "2026-03-09T10:05:00.000Z",
255 };
256}
257
258describe("hasUnseenCompletion", () => {
259 it("returns true when a thread completed after its last visit", () => {
260 expect(
261 hasUnseenCompletion({
262 hasActionableProposedPlan: false,
263 hasPendingApprovals: false,
264 hasPendingUserInput: false,
265 interactionMode: "default",
266 latestTurn: makeLatestTurn(),
267 lastVisitedAt: "2026-03-09T10:04:00.000Z",
268 session: null,
269 }),
270 ).toBe(true);
271 });
272
273 it("treats a missing client visit marker as read", () => {
274 expect(
275 hasUnseenCompletion({
276 hasActionableProposedPlan: false,
277 hasPendingApprovals: false,
278 hasPendingUserInput: false,
279 interactionMode: "default",
280 latestTurn: makeLatestTurn(),
281 lastVisitedAt: undefined,
282 session: null,
283 }),
284 ).toBe(false);
285 });
286});
287
288describe("createThreadJumpHintVisibilityController", () => {
289 beforeEach(() => {
290 vi.useFakeTimers();
291 });
292
293 afterEach(() => {
294 vi.useRealTimers();
295 });
296
297 it("delays showing jump hints until the configured delay elapses", () => {
298 const visibilityChanges: boolean[] = [];
299 const controller = createThreadJumpHintVisibilityController({
300 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
301 onVisibilityChange: (visible) => {
302 visibilityChanges.push(visible);
303 },
304 });
305
306 controller.sync(true);
307 vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1);
308
309 expect(visibilityChanges).toEqual([]);
310
311 vi.advanceTimersByTime(1);
312
313 expect(visibilityChanges).toEqual([true]);
314 });
315
316 it("hides immediately when the modifiers are released", () => {
317 const visibilityChanges: boolean[] = [];
318 const controller = createThreadJumpHintVisibilityController({
319 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
320 onVisibilityChange: (visible) => {
321 visibilityChanges.push(visible);
322 },
323 });
324
325 controller.sync(true);
326 vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
327 controller.sync(false);
328
329 expect(visibilityChanges).toEqual([true, false]);
330 });
331
332 it("cancels a pending reveal when the modifier is released early", () => {
333 const visibilityChanges: boolean[] = [];
334 const controller = createThreadJumpHintVisibilityController({
335 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
336 onVisibilityChange: (visible) => {
337 visibilityChanges.push(visible);
338 },
339 });
340
341 controller.sync(true);
342 vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2));
343 controller.sync(false);
344 vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
345
346 expect(visibilityChanges).toEqual([]);
347 });
348});
349
350describe("getSidebarThreadIdsToPrewarm", () => {
351 it("returns only the first visible thread ids up to the prewarm limit", () => {
352 expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
353 });
354
355 it("returns all visible thread ids when they fit within the limit", () => {
356 expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
357 });
358
359 it("returns no thread ids when the limit is zero", () => {
360 expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
361 });
362});
363
364describe("shouldClearThreadSelectionOnMouseDown", () => {
365 it("preserves selection for thread items", () => {
366 const child = {
367 closest: (selector: string) =>
368 selector.includes("[data-thread-item]") ? ({} as Element) : null,
369 } as unknown as HTMLElement;
370
371 expect(shouldClearThreadSelectionOnMouseDown(child)).toBe(false);
372 });
373
374 it("preserves selection for thread list toggle controls", () => {
375 const selectionSafe = {
376 closest: (selector: string) =>
377 selector.includes("[data-thread-selection-safe]") ? ({} as Element) : null,
378 } as unknown as HTMLElement;
379
380 expect(shouldClearThreadSelectionOnMouseDown(selectionSafe)).toBe(false);
381 });
382
383 it("clears selection for unrelated sidebar clicks", () => {
384 const unrelated = {
385 closest: () => null,
386 } as unknown as HTMLElement;
387
388 expect(shouldClearThreadSelectionOnMouseDown(unrelated)).toBe(true);
389 });
390});
391
392describe("isTrailingDoubleClick", () => {
393 it("treats a single click as a normal activation", () => {
394 expect(isTrailingDoubleClick(1)).toBe(false);
395 });
396
397 it("treats synthetic/keyboard activations (detail 0) as a normal activation", () => {
398 expect(isTrailingDoubleClick(0)).toBe(false);
399 });
400
401 it("ignores the second click of a double-click so it does not navigate", () => {
402 expect(isTrailingDoubleClick(2)).toBe(true);
403 });
404
405 it("ignores further clicks of a triple-click", () => {
406 expect(isTrailingDoubleClick(3)).toBe(true);
407 });
408});
409
410describe("orderItemsByPreferredIds", () => {
411 it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
412 const ordered = orderItemsByPreferredIds({
413 items: [
414 { id: ProjectId.make("project-1"), name: "One" },
415 { id: ProjectId.make("project-2"), name: "Two" },
416 { id: ProjectId.make("project-3"), name: "Three" },
417 ],
418 preferredIds: [
419 ProjectId.make("project-3"),
420 ProjectId.make("project-missing"),
421 ProjectId.make("project-1"),
422 ],
423 getId: (project) => project.id,
424 });
425
426 expect(ordered.map((project) => project.id)).toEqual([
427 ProjectId.make("project-3"),
428 ProjectId.make("project-1"),
429 ProjectId.make("project-2"),
430 ]);
431 });
432
433 it("does not duplicate items when preferred ids repeat", () => {
434 const ordered = orderItemsByPreferredIds({
435 items: [
436 { id: ProjectId.make("project-1"), name: "One" },
437 { id: ProjectId.make("project-2"), name: "Two" },
438 ],
439 preferredIds: [
440 ProjectId.make("project-2"),
441 ProjectId.make("project-1"),
442 ProjectId.make("project-2"),
443 ],
444 getId: (project) => project.id,
445 });
446
447 expect(ordered.map((project) => project.id)).toEqual([
448 ProjectId.make("project-2"),
449 ProjectId.make("project-1"),
450 ]);
451 });
452
453 it("honors projectOrder physical keys via getProjectOrderKey", async () => {
454 // Regression guard for #1904 / the regression introduced by #2055:
455 // `projectOrder` is populated with physical keys (envId + cwd-derived)
456 // by the store and by drag-end handlers. Readers must identify projects
457 // with the same key format, or manual sort silently snaps back.
458 const { getProjectOrderKey } = await import("../logicalProject");
459 const projects = [
460 {
461 environmentId: EnvironmentId.make("environment-local"),
462 id: ProjectId.make("id-alpha"),
463 workspaceRoot: "/work/alpha",
464 },
465 {
466 environmentId: EnvironmentId.make("environment-local"),
467 id: ProjectId.make("id-beta"),
468 workspaceRoot: "/work/beta",
469 },
470 {
471 environmentId: EnvironmentId.make("environment-local"),
472 id: ProjectId.make("id-gamma"),
473 workspaceRoot: "/work/gamma",
474 },
475 ];
476 const ordered = orderItemsByPreferredIds({
477 items: projects,
478 preferredIds: [getProjectOrderKey(projects[2]!), getProjectOrderKey(projects[0]!)],
479 getId: getProjectOrderKey,
480 });
481
482 expect(ordered.map((project) => project.workspaceRoot)).toEqual([
483 "/work/gamma",
484 "/work/alpha",
485 "/work/beta",
486 ]);
487 });
488
489 it("resolves legacy preference aliases without materializing project state", () => {
490 const ordered = orderItemsByPreferredIds({
491 items: [
492 { id: "physical-a", cwd: "/work/a" },
493 { id: "physical-b", cwd: "/work/b" },
494 { id: "physical-c", cwd: "/work/c" },
495 ],
496 preferredIds: ["legacy:/work/c", "legacy:/work/a"],
497 getId: (project) => project.id,
498 getPreferenceIds: (project) => [project.id, `legacy:${project.cwd}`],
499 });
500
501 expect(ordered.map((project) => project.id)).toEqual([
502 "physical-c",
503 "physical-a",
504 "physical-b",
505 ]);
506 });
507});
508
509describe("resolveAdjacentThreadId", () => {
510 it("resolves adjacent thread ids in ordered sidebar traversal", () => {
511 const threads = [
512 ThreadId.make("thread-1"),
513 ThreadId.make("thread-2"),
514 ThreadId.make("thread-3"),
515 ];
516
517 expect(
518 resolveAdjacentThreadId({
519 threadIds: threads,
520 currentThreadId: threads[1] ?? null,
521 direction: "previous",
522 }),
523 ).toBe(threads[0]);
524 expect(
525 resolveAdjacentThreadId({
526 threadIds: threads,
527 currentThreadId: threads[1] ?? null,
528 direction: "next",
529 }),
530 ).toBe(threads[2]);
531 expect(
532 resolveAdjacentThreadId({
533 threadIds: threads,
534 currentThreadId: null,
535 direction: "next",
536 }),
537 ).toBe(threads[0]);
538 expect(
539 resolveAdjacentThreadId({
540 threadIds: threads,
541 currentThreadId: null,
542 direction: "previous",
543 }),
544 ).toBe(threads[2]);
545 expect(
546 resolveAdjacentThreadId({
547 threadIds: threads,
548 currentThreadId: threads[0] ?? null,
549 direction: "previous",
550 }),
551 ).toBeNull();
552 });
553});
554
555describe("getVisibleSidebarThreadIds", () => {
556 it("returns only the rendered visible thread order across projects", () => {
557 expect(
558 getVisibleSidebarThreadIds([
559 {
560 renderedThreadIds: [
561 ThreadId.make("thread-12"),
562 ThreadId.make("thread-11"),
563 ThreadId.make("thread-10"),
564 ],
565 },
566 {
567 renderedThreadIds: [ThreadId.make("thread-8"), ThreadId.make("thread-6")],
568 },
569 ]),
570 ).toEqual([
571 ThreadId.make("thread-12"),
572 ThreadId.make("thread-11"),
573 ThreadId.make("thread-10"),
574 ThreadId.make("thread-8"),
575 ThreadId.make("thread-6"),
576 ]);
577 });
578
579 it("skips threads from collapsed projects whose thread panels are not shown", () => {
580 expect(
581 getVisibleSidebarThreadIds([
582 {
583 shouldShowThreadPanel: false,
584 renderedThreadIds: [ThreadId.make("thread-hidden-2"), ThreadId.make("thread-hidden-1")],
585 },
586 {
587 shouldShowThreadPanel: true,
588 renderedThreadIds: [ThreadId.make("thread-12"), ThreadId.make("thread-11")],
589 },
590 ]),
591 ).toEqual([ThreadId.make("thread-12"), ThreadId.make("thread-11")]);
592 });
593});
594
595describe("isContextMenuPointerDown", () => {
596 it("treats secondary-button presses as context menu gestures on all platforms", () => {
597 expect(
598 isContextMenuPointerDown({
599 button: 2,
600 ctrlKey: false,
601 isMac: false,
602 }),
603 ).toBe(true);
604 });
605
606 it("treats ctrl+primary-click as a context menu gesture on macOS", () => {
607 expect(
608 isContextMenuPointerDown({
609 button: 0,
610 ctrlKey: true,
611 isMac: true,
612 }),
613 ).toBe(true);
614 });
615
616 it("does not treat ctrl+primary-click as a context menu gesture off macOS", () => {
617 expect(
618 isContextMenuPointerDown({
619 button: 0,
620 ctrlKey: true,
621 isMac: false,
622 }),
623 ).toBe(false);
624 });
625});
626
627describe("resolveSidebarV2Status", () => {
628 const session = {
629 threadId: ThreadId.make("thread-1"),
630 status: "running" as const,
631 providerName: "Codex",
632 providerInstanceId: ProviderInstanceId.make("codex"),
633 runtimeMode: DEFAULT_RUNTIME_MODE,
634 activeTurnId: "turn-1" as never,
635 lastError: null,
636 updatedAt: "2026-03-09T10:00:00.000Z",
637 };
638
639 const idle = { hasPendingApprovals: false, hasPendingUserInput: false };
640
641 it("prioritizes approval over a running session", () => {
642 expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe(
643 "approval",
644 );
645 });
646
647 it("prioritizes awaiting input over a running session, below approval", () => {
648 expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, session })).toBe("input");
649 expect(
650 resolveSidebarV2Status({
651 ...idle,
652 hasPendingApprovals: true,
653 hasPendingUserInput: true,
654 session,
655 }),
656 ).toBe("approval");
657 });
658
659 it("reports working for running and starting sessions", () => {
660 expect(resolveSidebarV2Status({ ...idle, session })).toBe("working");
661 expect(
662 resolveSidebarV2Status({
663 ...idle,
664 session: { ...session, status: "starting" as const },
665 }),
666 ).toBe("working");
667 });
668
669 it("reports failed only while the session status is error", () => {
670 expect(
671 resolveSidebarV2Status({
672 ...idle,
673 session: { ...session, status: "error" as const, lastError: "boom" },
674 }),
675 ).toBe("failed");
676 expect(
677 resolveSidebarV2Status({
678 ...idle,
679 session: { ...session, status: "stopped" as const, lastError: "persisted" },
680 }),
681 ).toBe("ready");
682 expect(
683 resolveSidebarV2Status({
684 ...idle,
685 session: { ...session, status: "ready" as const, lastError: "persisted" },
686 }),
687 ).toBe("ready");
688 });
689
690 it("defaults to ready with no session", () => {
691 expect(resolveSidebarV2Status({ ...idle, session: null })).toBe("ready");
692 });
693});
694
695describe("searchSidebarThreadsByTitle", () => {
696 const threads = [
697 { id: "thread-1", title: "Fix workspace search", project: "Alpha" },
698 { id: "thread-2", title: "Review providers", project: "Workspace" },
699 { id: "thread-3", title: "WORKTREE cleanup", project: "Beta" },
700 ];
701
702 it("matches thread titles case-insensitively and preserves their order", () => {
703 expect(searchSidebarThreadsByTitle(threads, "work")).toEqual([threads[0], threads[2]]);
704 });
705
706 it("does not match project metadata", () => {
707 expect(searchSidebarThreadsByTitle(threads, "workspace")).toEqual([threads[0]]);
708 });
709
710 it("returns no results for an empty query", () => {
711 expect(searchSidebarThreadsByTitle(threads, " ")).toEqual([]);
712 });
713});
714
715describe("sortThreadsForSidebarV2", () => {
716 const sortable = (input: { id: string; createdAt: string }) => ({
717 id: input.id,
718 createdAt: input.createdAt,
719 });
720
721 it("orders by creation time, newest first, ignoring activity", () => {
722 const sorted = sortThreadsForSidebarV2([
723 sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }),
724 sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }),
725 sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }),
726 ]);
727
728 expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
729 });
730
731 it("breaks creation-time ties by id so the order is stable", () => {
732 const sorted = sortThreadsForSidebarV2([
733 sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }),
734 sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }),
735 ]);
736
737 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
738 });
739});
740
741describe("sortSettledThreadsForSidebarV2", () => {
742 const settled = (input: {
743 id: string;
744 settledAt?: string | null;
745 latestUserMessageAt?: string | null;
746 latestTurn?: OrchestrationLatestTurn | null;
747 updatedAt?: string;
748 }) => ({
749 id: input.id,
750 settledAt: input.settledAt ?? null,
751 latestUserMessageAt: input.latestUserMessageAt ?? null,
752 latestTurn: input.latestTurn ?? null,
753 updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z",
754 });
755
756 it("orders by settle time, most recently settled first", () => {
757 const sorted = sortSettledThreadsForSidebarV2([
758 settled({
759 id: "settled-first",
760 settledAt: "2026-03-09T10:00:00.000Z",
761 // Created/active later than the other thread: settle time must win.
762 latestUserMessageAt: "2026-03-09T09:59:00.000Z",
763 }),
764 settled({
765 id: "settled-last",
766 settledAt: "2026-03-09T12:00:00.000Z",
767 latestUserMessageAt: "2026-03-09T08:00:00.000Z",
768 }),
769 ]);
770
771 expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]);
772 });
773
774 it("falls back to last activity for auto-settled threads without a settledAt stamp", () => {
775 const sorted = sortSettledThreadsForSidebarV2([
776 settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }),
777 settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
778 settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }),
779 ]);
780
781 expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]);
782 });
783
784 it("counts a turn completion as activity for auto-settled threads", () => {
785 // The message came in before the other thread's, but its turn finished
786 // after: completion time is the real "work ended" moment.
787 const sorted = sortSettledThreadsForSidebarV2([
788 settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
789 settled({
790 id: "completed-later",
791 latestUserMessageAt: "2026-03-09T10:00:00.000Z",
792 latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }),
793 }),
794 ]);
795
796 expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
797 });
798
799 it("breaks timestamp ties by id so the order is stable", () => {
800 const sorted = sortSettledThreadsForSidebarV2([
801 settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
802 settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
803 ]);
804
805 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
806 });
807});
808
809describe("resolveWorkingStartedAt", () => {
810 const session = {
811 threadId: ThreadId.make("thread-1"),
812 status: "running" as const,
813 providerName: "Codex",
814 providerInstanceId: ProviderInstanceId.make("codex"),
815 runtimeMode: DEFAULT_RUNTIME_MODE,
816 activeTurnId: "turn-1" as never,
817 lastError: null,
818 updatedAt: "2026-03-09T10:02:00.000Z",
819 };
820
821 it("uses the running turn's start time", () => {
822 expect(
823 resolveWorkingStartedAt({
824 latestTurn: makeLatestTurn({ completedAt: null }),
825 session,
826 }),
827 ).toBe("2026-03-09T10:00:00.000Z");
828 });
829
830 it("uses the request time while a turn awaits adoption", () => {
831 expect(
832 resolveWorkingStartedAt({
833 latestTurn: makeLatestTurn({ startedAt: null, completedAt: null }),
834 session,
835 }),
836 ).toBe("2026-03-09T10:00:00.000Z");
837 });
838
839 it("falls back to the session transition when the latest turn already completed", () => {
840 expect(
841 resolveWorkingStartedAt({
842 latestTurn: makeLatestTurn(),
843 session,
844 }),
845 ).toBe("2026-03-09T10:02:00.000Z");
846 });
847
848 it("skips a malformed startedAt instead of returning it", () => {
849 expect(
850 resolveWorkingStartedAt({
851 latestTurn: makeLatestTurn({ startedAt: "not-a-date", completedAt: null }),
852 session,
853 }),
854 ).toBe("2026-03-09T10:00:00.000Z");
855 });
856
857 it("returns null with neither a running turn nor a session", () => {
858 expect(resolveWorkingStartedAt({ latestTurn: null, session: null })).toBeNull();
859 });
860});
861
862describe("formatWorkingDurationLabel", () => {
863 it("formats seconds, minutes, and hours", () => {
864 expect(formatWorkingDurationLabel(0)).toBe("0s");
865 expect(formatWorkingDurationLabel(42_000)).toBe("42s");
866 expect(formatWorkingDurationLabel(5 * 60_000)).toBe("5m");
867 expect(formatWorkingDurationLabel(90 * 60_000)).toBe("1h 30m");
868 });
869
870 it("clamps negative and non-finite elapsed values to zero", () => {
871 expect(formatWorkingDurationLabel(-5_000)).toBe("0s");
872 expect(formatWorkingDurationLabel(Number.NaN)).toBe("0s");
873 });
874});
875
876describe("resolveThreadStatusPill", () => {
877 const baseThread = {
878 hasActionableProposedPlan: false,
879 hasPendingApprovals: false,
880 hasPendingUserInput: false,
881 interactionMode: "plan" as const,
882 latestTurn: null,
883 lastVisitedAt: undefined,
884 session: {
885 threadId: ThreadId.make("thread-1"),
886 status: "running" as const,
887 providerName: "Codex",
888 providerInstanceId: ProviderInstanceId.make("codex"),
889 runtimeMode: DEFAULT_RUNTIME_MODE,
890 activeTurnId: "turn-1" as never,
891 lastError: null,
892 updatedAt: "2026-03-09T10:00:00.000Z",
893 },
894 };
895
896 it("shows pending approval before all other statuses", () => {
897 expect(
898 resolveThreadStatusPill({
899 thread: {
900 ...baseThread,
901 hasPendingApprovals: true,
902 hasPendingUserInput: true,
903 },
904 }),
905 ).toMatchObject({ label: "Pending Approval", pulse: false });
906 });
907
908 it("shows awaiting input when plan mode is blocked on user answers", () => {
909 expect(
910 resolveThreadStatusPill({
911 thread: {
912 ...baseThread,
913 hasPendingUserInput: true,
914 },
915 }),
916 ).toMatchObject({ label: "Awaiting Input", pulse: false });
917 });
918
919 it("falls back to working when the thread is actively running without blockers", () => {
920 expect(
921 resolveThreadStatusPill({
922 thread: baseThread,
923 }),
924 ).toMatchObject({ label: "Working", pulse: true });
925 });
926
927 it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
928 expect(
929 resolveThreadStatusPill({
930 thread: {
931 ...baseThread,
932 hasActionableProposedPlan: true,
933 latestTurn: makeLatestTurn(),
934 session: {
935 ...baseThread.session,
936 status: "ready",
937 activeTurnId: null,
938 },
939 },
940 }),
941 ).toMatchObject({ label: "Plan Ready", pulse: false });
942 });
943
944 it("does not manufacture completed state without a client visit marker", () => {
945 expect(
946 resolveThreadStatusPill({
947 thread: {
948 ...baseThread,
949 latestTurn: makeLatestTurn(),
950 session: {
951 ...baseThread.session,
952 status: "ready",
953 activeTurnId: null,
954 },
955 },
956 }),
957 ).toBeNull();
958 });
959
960 it("shows completed when there is an unseen completion and no active blocker", () => {
961 expect(
962 resolveThreadStatusPill({
963 thread: {
964 ...baseThread,
965 interactionMode: "default",
966 latestTurn: makeLatestTurn(),
967 lastVisitedAt: "2026-03-09T10:04:00.000Z",
968 session: {
969 ...baseThread.session,
970 status: "ready",
971 activeTurnId: null,
972 },
973 },
974 }),
975 ).toMatchObject({ label: "Completed", pulse: false });
976 });
977});
978
979describe("resolveThreadRowClassName", () => {
980 it("uses the active sidebar surface when a thread is both selected and active", () => {
981 const className = resolveThreadRowClassName({ isActive: true, isSelected: true });
982 expect(className).toContain("bg-sidebar-row-active");
983 expect(className).toContain("text-sidebar-foreground");
984 expect(className).not.toContain("bg-primary");
985 });
986
987 it("uses selected hover colors for selected threads", () => {
988 const className = resolveThreadRowClassName({ isActive: false, isSelected: true });
989 expect(className).toContain("bg-sidebar-row-selected");
990 expect(className).toContain("hover:bg-sidebar-row-active");
991 expect(className).not.toContain("bg-primary");
992 });
993
994 it("uses the active sidebar surface for active-only threads", () => {
995 const className = resolveThreadRowClassName({ isActive: true, isSelected: false });
996 expect(className).toContain("bg-sidebar-row-active");
997 expect(className).toContain("hover:bg-sidebar-row-active");
998 });
999});
1000
1001describe("resolveProjectStatusIndicator", () => {
1002 it("returns null when no threads have a notable status", () => {
1003 expect(resolveProjectStatusIndicator([null, null])).toBeNull();
1004 });
1005
1006 it("surfaces the highest-priority actionable state across project threads", () => {
1007 expect(
1008 resolveProjectStatusIndicator([
1009 {
1010 label: "Completed",
1011 colorClass: "text-emerald-600",
1012 dotClass: "bg-emerald-500",
1013 pulse: false,
1014 },
1015 {
1016 label: "Pending Approval",
1017 colorClass: "text-amber-600",
1018 dotClass: "bg-amber-500",
1019 pulse: false,
1020 },
1021 {
1022 label: "Working",
1023 colorClass: "text-sky-600",
1024 dotClass: "bg-sky-500",
1025 pulse: true,
1026 },
1027 ]),
1028 ).toMatchObject({ label: "Pending Approval", dotClass: "bg-amber-500" });
1029 });
1030
1031 it("prefers plan-ready over completed when no stronger action is needed", () => {
1032 expect(
1033 resolveProjectStatusIndicator([
1034 {
1035 label: "Completed",
1036 colorClass: "text-emerald-600",
1037 dotClass: "bg-emerald-500",
1038 pulse: false,
1039 },
1040 {
1041 label: "Plan Ready",
1042 colorClass: "text-violet-600",
1043 dotClass: "bg-violet-500",
1044 pulse: false,
1045 },
1046 ]),
1047 ).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
1048 });
1049});
1050
1051describe("getVisibleThreadsForProject", () => {
1052 it("includes the active thread even when it falls below the folded preview", () => {
1053 const threads = Array.from({ length: 8 }, (_, index) =>
1054 makeThread({
1055 id: ThreadId.make(`thread-${index + 1}`),
1056 title: `Thread ${index + 1}`,
1057 }),
1058 );
1059
1060 const result = getVisibleThreadsForProject({
1061 threads,
1062 activeThreadId: ThreadId.make("thread-8"),
1063 isThreadListExpanded: false,
1064 previewLimit: 6,
1065 });
1066
1067 expect(result.hasHiddenThreads).toBe(true);
1068 expect(result.visibleThreads.map((thread) => thread.id)).toEqual([
1069 ThreadId.make("thread-1"),
1070 ThreadId.make("thread-2"),
1071 ThreadId.make("thread-3"),
1072 ThreadId.make("thread-4"),
1073 ThreadId.make("thread-5"),
1074 ThreadId.make("thread-6"),
1075 ThreadId.make("thread-8"),
1076 ]);
1077 expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ThreadId.make("thread-7")]);
1078 });
1079
1080 it("returns all threads when the list is expanded", () => {
1081 const threads = Array.from({ length: 8 }, (_, index) =>
1082 makeThread({
1083 id: ThreadId.make(`thread-${index + 1}`),
1084 }),
1085 );
1086
1087 const result = getVisibleThreadsForProject({
1088 threads,
1089 activeThreadId: ThreadId.make("thread-8"),
1090 isThreadListExpanded: true,
1091 previewLimit: 6,
1092 });
1093
1094 expect(result.hasHiddenThreads).toBe(true);
1095 expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
1096 threads.map((thread) => thread.id),
1097 );
1098 expect(result.hiddenThreads).toEqual([]);
1099 });
1100});
1101
1102function makeProject(overrides: Partial<Project> = {}): Project {
1103 const { defaultModelSelection, ...rest } = overrides;
1104 return {
1105 id: ProjectId.make("project-1"),
1106 environmentId: localEnvironmentId,
1107 title: "Project",
1108 workspaceRoot: "/tmp/project",
1109 repositoryIdentity: null,
1110 defaultModelSelection: {
1111 instanceId: ProviderInstanceId.make("codex"),
1112 model: "gpt-5.4",
1113 ...defaultModelSelection,
1114 },
1115 createdAt: "2026-03-09T10:00:00.000Z",
1116 updatedAt: "2026-03-09T10:00:00.000Z",
1117 scripts: [],
1118 ...rest,
1119 };
1120}
1121
1122function makeThread(overrides: Partial<Thread> = {}): Thread {
1123 return {
1124 id: ThreadId.make("thread-1"),
1125 environmentId: localEnvironmentId,
1126 projectId: ProjectId.make("project-1"),
1127 title: "Thread",
1128 modelSelection: {
1129 instanceId: ProviderInstanceId.make("codex"),
1130 model: "gpt-5.4",
1131 ...overrides?.modelSelection,
1132 },
1133 runtimeMode: DEFAULT_RUNTIME_MODE,
1134 interactionMode: DEFAULT_INTERACTION_MODE,
1135 session: null,
1136 messages: [],
1137 proposedPlans: [],
1138 createdAt: "2026-03-09T10:00:00.000Z",
1139 archivedAt: null,
1140 settledOverride: null,
1141 settledAt: null,
1142 deletedAt: null,
1143 updatedAt: "2026-03-09T10:00:00.000Z",
1144 latestTurn: null,
1145 branch: null,
1146 worktreePath: null,
1147 checkpoints: [],
1148 activities: [],
1149 ...overrides,
1150 };
1151}
1152
1153describe("getFallbackThreadIdAfterDelete", () => {
1154 it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
1155 const fallbackThreadId = getFallbackThreadIdAfterDelete({
1156 threads: [
1157 makeThread({
1158 id: ThreadId.make("thread-oldest"),
1159 projectId: ProjectId.make("project-1"),
1160 createdAt: "2026-03-09T10:00:00.000Z",
1161 messages: [],
1162 }),
1163 makeThread({
1164 id: ThreadId.make("thread-active"),
1165 projectId: ProjectId.make("project-1"),
1166 createdAt: "2026-03-09T10:05:00.000Z",
1167 messages: [],
1168 }),
1169 makeThread({
1170 id: ThreadId.make("thread-newest"),
1171 projectId: ProjectId.make("project-1"),
1172 createdAt: "2026-03-09T10:10:00.000Z",
1173 messages: [],
1174 }),
1175 makeThread({
1176 id: ThreadId.make("thread-other-project"),
1177 projectId: ProjectId.make("project-2"),
1178 createdAt: "2026-03-09T10:20:00.000Z",
1179 messages: [],
1180 }),
1181 ],
1182 deletedThreadId: ThreadId.make("thread-active"),
1183 sortOrder: "created_at",
1184 });
1185
1186 expect(fallbackThreadId).toBe(ThreadId.make("thread-newest"));
1187 });
1188
1189 it("skips other threads being deleted in the same action", () => {
1190 const fallbackThreadId = getFallbackThreadIdAfterDelete({
1191 threads: [
1192 makeThread({
1193 id: ThreadId.make("thread-active"),
1194 projectId: ProjectId.make("project-1"),
1195 createdAt: "2026-03-09T10:05:00.000Z",
1196 messages: [],
1197 }),
1198 makeThread({
1199 id: ThreadId.make("thread-newest"),
1200 projectId: ProjectId.make("project-1"),
1201 createdAt: "2026-03-09T10:10:00.000Z",
1202 messages: [],
1203 }),
1204 makeThread({
1205 id: ThreadId.make("thread-next"),
1206 projectId: ProjectId.make("project-1"),
1207 createdAt: "2026-03-09T10:07:00.000Z",
1208 messages: [],
1209 }),
1210 ],
1211 deletedThreadId: ThreadId.make("thread-active"),
1212 deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]),
1213 sortOrder: "created_at",
1214 });
1215
1216 expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
1217 });
1218});
1219describe("sortProjectsForSidebar", () => {
1220 it("sorts projects by the most recent user message across their threads", () => {
1221 const projects = [
1222 makeProject({ id: ProjectId.make("project-1"), title: "Older project" }),
1223 makeProject({ id: ProjectId.make("project-2"), title: "Newer project" }),
1224 ];
1225 const threads = [
1226 makeThread({
1227 projectId: ProjectId.make("project-1"),
1228 updatedAt: "2026-03-09T10:20:00.000Z",
1229 messages: [
1230 {
1231 id: "message-1" as never,
1232 role: "user",
1233 text: "older project user message",
1234 turnId: null,
1235 createdAt: "2026-03-09T10:01:00.000Z",
1236 updatedAt: "2026-03-09T10:01:00.000Z",
1237 streaming: false,
1238 },
1239 ],
1240 }),
1241 makeThread({
1242 id: ThreadId.make("thread-2"),
1243 projectId: ProjectId.make("project-2"),
1244 updatedAt: "2026-03-09T10:05:00.000Z",
1245 messages: [
1246 {
1247 id: "message-2" as never,
1248 role: "user",
1249 text: "newer project user message",
1250 turnId: null,
1251 createdAt: "2026-03-09T10:05:00.000Z",
1252 updatedAt: "2026-03-09T10:05:00.000Z",
1253 streaming: false,
1254 },
1255 ],
1256 }),
1257 ];
1258
1259 const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
1260
1261 expect(sorted.map((project) => project.id)).toEqual([
1262 ProjectId.make("project-2"),
1263 ProjectId.make("project-1"),
1264 ]);
1265 });
1266
1267 it("falls back to project timestamps when a project has no threads", () => {
1268 const sorted = sortProjectsForSidebar(
1269 [
1270 makeProject({
1271 id: ProjectId.make("project-1"),
1272 title: "Older project",
1273 updatedAt: "2026-03-09T10:01:00.000Z",
1274 }),
1275 makeProject({
1276 id: ProjectId.make("project-2"),
1277 title: "Newer project",
1278 updatedAt: "2026-03-09T10:05:00.000Z",
1279 }),
1280 ],
1281 [],
1282 "updated_at",
1283 );
1284
1285 expect(sorted.map((project) => project.id)).toEqual([
1286 ProjectId.make("project-2"),
1287 ProjectId.make("project-1"),
1288 ]);
1289 });
1290
1291 it("falls back to name and id ordering when projects have no sortable timestamps", () => {
1292 const sorted = sortProjectsForSidebar(
1293 [
1294 makeProject({
1295 id: ProjectId.make("project-2"),
1296 title: "Beta",
1297 createdAt: "invalid-created-at" as never,
1298 updatedAt: "invalid-updated-at" as never,
1299 }),
1300 makeProject({
1301 id: ProjectId.make("project-1"),
1302 title: "Alpha",
1303 createdAt: "invalid-created-at" as never,
1304 updatedAt: "invalid-updated-at" as never,
1305 }),
1306 ],
1307 [],
1308 "updated_at",
1309 );
1310
1311 expect(sorted.map((project) => project.id)).toEqual([
1312 ProjectId.make("project-1"),
1313 ProjectId.make("project-2"),
1314 ]);
1315 });
1316
1317 it("preserves manual project ordering", () => {
1318 const projects = [
1319 makeProject({ id: ProjectId.make("project-2"), title: "Second" }),
1320 makeProject({ id: ProjectId.make("project-1"), title: "First" }),
1321 ];
1322
1323 const sorted = sortProjectsForSidebar(projects, [], "manual");
1324
1325 expect(sorted.map((project) => project.id)).toEqual([
1326 ProjectId.make("project-2"),
1327 ProjectId.make("project-1"),
1328 ]);
1329 });
1330
1331 it("ignores archived threads when sorting projects", () => {
1332 const sorted = sortProjectsForSidebar(
1333 [
1334 makeProject({
1335 id: ProjectId.make("project-1"),
1336 title: "Visible project",
1337 updatedAt: "2026-03-09T10:01:00.000Z",
1338 }),
1339 makeProject({
1340 id: ProjectId.make("project-2"),
1341 title: "Archived-only project",
1342 updatedAt: "2026-03-09T10:00:00.000Z",
1343 }),
1344 ],
1345 [
1346 makeThread({
1347 id: ThreadId.make("thread-visible"),
1348 projectId: ProjectId.make("project-1"),
1349 updatedAt: "2026-03-09T10:02:00.000Z",
1350 archivedAt: null,
1351 }),
1352 makeThread({
1353 id: ThreadId.make("thread-archived"),
1354 projectId: ProjectId.make("project-2"),
1355 updatedAt: "2026-03-09T10:10:00.000Z",
1356 archivedAt: "2026-03-09T10:11:00.000Z",
1357 }),
1358 ].filter((thread) => thread.archivedAt === null),
1359 "updated_at",
1360 );
1361
1362 expect(sorted.map((project) => project.id)).toEqual([
1363 ProjectId.make("project-1"),
1364 ProjectId.make("project-2"),
1365 ]);
1366 });
1367
1368 it("returns the project timestamp when no threads are present", () => {
1369 const timestamp = getProjectSortTimestamp(
1370 makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
1371 [],
1372 "updated_at",
1373 );
1374
1375 expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
1376 });
1377});
1378
1379describe("sortScopedProjectsForSidebar", () => {
1380 it("keeps identical project ids in different environments separate", () => {
1381 const remoteEnvironmentId = EnvironmentId.make("environment-remote");
1382 const sharedProjectId = ProjectId.make("shared-project");
1383 const projects = [
1384 makeProject({
1385 environmentId: localEnvironmentId,
1386 id: sharedProjectId,
1387 title: "Local project",
1388 }),
1389 makeProject({
1390 environmentId: remoteEnvironmentId,
1391 id: sharedProjectId,
1392 title: "Remote project",
1393 }),
1394 ];
1395 const threads = [
1396 makeThread({
1397 environmentId: localEnvironmentId,
1398 projectId: sharedProjectId,
1399 updatedAt: "2026-03-09T10:02:00.000Z",
1400 }),
1401 makeThread({
1402 environmentId: remoteEnvironmentId,
1403 projectId: sharedProjectId,
1404 updatedAt: "2026-03-09T10:10:00.000Z",
1405 }),
1406 ];
1407
1408 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
1409
1410 expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);
1411 });
1412
1413 it("does not use archived threads as project activity", () => {
1414 const projects = [
1415 makeProject({
1416 id: ProjectId.make("project-visible"),
1417 title: "Visible project",
1418 updatedAt: "2026-03-09T10:01:00.000Z",
1419 }),
1420 makeProject({
1421 id: ProjectId.make("project-archived"),
1422 title: "Archived-only project",
1423 updatedAt: "2026-03-09T10:00:00.000Z",
1424 }),
1425 ];
1426 const threads = [
1427 makeThread({
1428 id: ThreadId.make("thread-visible"),
1429 projectId: ProjectId.make("project-visible"),
1430 updatedAt: "2026-03-09T10:02:00.000Z",
1431 }),
1432 makeThread({
1433 id: ThreadId.make("thread-archived"),
1434 projectId: ProjectId.make("project-archived"),
1435 updatedAt: "2026-03-09T10:10:00.000Z",
1436 archivedAt: "2026-03-09T10:11:00.000Z",
1437 }),
1438 ];
1439
1440 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
1441
1442 expect(sorted.map((project) => project.title)).toEqual([
1443 "Visible project",
1444 "Archived-only project",
1445 ]);
1446 });
1447});
1448
1449describe("sortLogicalProjectsForSidebar", () => {
1450 it("uses saved order only in manual mode and activity order otherwise", () => {
1451 const olderProjectId = ProjectId.make("project-older");
1452 const newerProjectId = ProjectId.make("project-newer");
1453 const projects = [
1454 {
1455 ...makeProject({ id: olderProjectId, title: "Older project" }),
1456 projectKey: "logical-older",
1457 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: olderProjectId }],
1458 },
1459 {
1460 ...makeProject({ id: newerProjectId, title: "Newer project" }),
1461 projectKey: "logical-newer",
1462 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: newerProjectId }],
1463 },
1464 ];
1465 const threads = [
1466 makeThread({
1467 projectId: olderProjectId,
1468 updatedAt: "2026-03-09T10:01:00.000Z",
1469 }),
1470 makeThread({
1471 id: ThreadId.make("thread-newer"),
1472 projectId: newerProjectId,
1473 updatedAt: "2026-03-09T10:05:00.000Z",
1474 }),
1475 ];
1476
1477 expect(sortLogicalProjectsForSidebar(projects, threads, "manual")).toEqual(projects);
1478 expect(
1479 sortLogicalProjectsForSidebar(projects, threads, "updated_at").map(
1480 (project) => project.projectKey,
1481 ),
1482 ).toEqual(["logical-newer", "logical-older"]);
1483 });
1484});