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