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