Open History to see the last commit
1import { presentThreadShell } from "@t3tools/client-runtime/state/models";
2import { isThreadWorking as isSidebarThreadWorking } from "@t3tools/client-runtime/state/thread-inbox";
3import * as DateTime from "effect/DateTime";
4import { deriveActiveWorkStartedAt } from "../session-logic.ts";
5import { describe, expect, it, vi } from "vite-plus/test";
6import * as Cause from "effect/Cause";
7import { AsyncResult } from "effect/reactivity";
8import {
9 archiveSelectedThreadEntries,
10 deleteSelectedThreadEntries,
11 getFallbackThreadIdAfterDelete,
12 hasUnseenCompletion,
13 resolveSidebarRowThreadId,
14 orderItemsByPreferredIds,
15 pinOrderKeyBetween,
16 resolveProjectStatusIndicator,
17 resolveSidebarSweepKeys,
18 resolveSidebarThreadStatus,
19 resolveThreadStatusPill,
20 resolveWorkingStartedAt,
21 searchSidebarThreads,
22 shouldRecedeSidebarThread,
23 sortInboxThreadsByReturn,
24 resolveSidebarDropTarget,
25 planSidebarThreadDrop,
26 sortPinnedThreadsForSidebar,
27 sortProjectsForSidebar,
28 sortScopedProjectsForSidebar,
29 sortSidebarV2ProjectGroups,
30 shouldNavigateAfterThreadPark,
31 type SidebarListItem,
32 type SidebarListMarker,
33 type SidebarSection,
34 resolveSidebarDropVerb,
35 groupSidebarThreadsByProject,
36 resolveSidebarFolderDot,
37 sidebarFolderExpansionKeys,
38} from "./Sidebar.logic";
39import { resolveProjectExpanded } from "../uiStateStore";
40import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
41import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
42
43import {
44 DEFAULT_INTERACTION_MODE,
45 DEFAULT_RUNTIME_MODE,
46 type Project,
47 type Thread,
48} from "../types";
49import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures";
50import {
51 completeSidebarRouteReveal,
52 pendingSidebarRouteReveal,
53 resolveSidebarRouteReveal,
54} from "./sidebar/routeReveal";
55
56const localEnvironmentId = EnvironmentId.make("environment-local");
57
58describe("deleteSelectedThreadEntries", () => {
59 const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
60 const success = AsyncResult.success(undefined);
61 const failure = AsyncResult.failure(Cause.fail(new Error("Delete failed")));
62 const interrupted = AsyncResult.failure(Cause.interrupt());
63
64 it("waits for each delete and excludes only earlier successes from worktree checks", async () => {
65 let resolveDelete!: (result: typeof success) => void;
66 const pendingDelete = new Promise<typeof success>((resolve) => {
67 resolveDelete = resolve;
68 });
69 const worktreeChecks: { threadKey: string; deletedThreadKeys: string[] }[] = [];
70 const deletion = deleteSelectedThreadEntries({
71 entries,
72 delete: async ({ threadKey }, deletedThreadKeys) => {
73 worktreeChecks.push({ threadKey, deletedThreadKeys: [...deletedThreadKeys] });
74 return threadKey === "one" ? pendingDelete : success;
75 },
76 });
77
78 expect(worktreeChecks).toEqual([{ threadKey: "one", deletedThreadKeys: [] }]);
79 resolveDelete(success);
80 const outcome = await deletion;
81
82 expect(worktreeChecks).toEqual([
83 { threadKey: "one", deletedThreadKeys: [] },
84 { threadKey: "two", deletedThreadKeys: ["one"] },
85 { threadKey: "three", deletedThreadKeys: ["one", "two"] },
86 ]);
87 expect(outcome).toEqual({
88 deletedThreadKeys: new Set(["one", "two", "three"]),
89 firstFailure: null,
90 });
91 });
92
93 it("continues after ordinary failures and keeps the first failure", async () => {
94 const laterFailure = AsyncResult.failure(Cause.fail(new Error("Later failure")));
95 const deletedKeysAtLastEntry: string[][] = [];
96 const outcome = await deleteSelectedThreadEntries({
97 entries: [...entries, { threadKey: "four" }],
98 delete: async ({ threadKey }, deletedThreadKeys) => {
99 if (threadKey === "one") return failure;
100 if (threadKey === "three") return laterFailure;
101 if (threadKey === "four") deletedKeysAtLastEntry.push([...deletedThreadKeys]);
102 return success;
103 },
104 });
105
106 expect(deletedKeysAtLastEntry).toEqual([["two"]]);
107 expect(outcome).toEqual({
108 deletedThreadKeys: new Set(["two", "four"]),
109 firstFailure: failure,
110 });
111 });
112
113 it.each([
114 { firstResult: success, deletedThreadKeys: new Set(["one"]), firstFailure: null },
115 { firstResult: failure, deletedThreadKeys: new Set<string>(), firstFailure: failure },
116 ])("stops on interruption and preserves earlier results %#", async (testCase) => {
117 const attemptedThreadKeys: string[] = [];
118 const outcome = await deleteSelectedThreadEntries({
119 entries,
120 delete: async ({ threadKey }) => {
121 attemptedThreadKeys.push(threadKey);
122 return threadKey === "one" ? testCase.firstResult : interrupted;
123 },
124 });
125
126 expect(attemptedThreadKeys).toEqual(["one", "two"]);
127 expect(outcome).toEqual({
128 deletedThreadKeys: testCase.deletedThreadKeys,
129 firstFailure: testCase.firstFailure,
130 });
131 });
132});
133
134describe("archiveSelectedThreadEntries", () => {
135 const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
136 const success = { _tag: "Success" } as const;
137 const failure = { _tag: "Failure" } as const;
138
139 it("stops at a mutation failure and retains prior successes", async () => {
140 const archive = vi.fn(async (entry: (typeof entries)[number], onArchived: () => void) => {
141 if (entry.threadKey === "two") return failure;
142 onArchived();
143 return success;
144 });
145 const outcome = await archiveSelectedThreadEntries({ entries, archive });
146
147 expect(archive).toHaveBeenCalledTimes(2);
148 expect(outcome).toEqual({
149 archivedThreadKeys: ["one"],
150 mutationFailure: failure,
151 followupFailures: [],
152 });
153 });
154
155 it("continues after a post-archive failure", async () => {
156 const archive = vi.fn(async (entry: (typeof entries)[number], onArchived: () => void) => {
157 onArchived();
158 return entry.threadKey === "two" ? failure : success;
159 });
160 const outcome = await archiveSelectedThreadEntries({ entries, archive });
161
162 expect(archive).toHaveBeenCalledTimes(3);
163 expect(outcome).toEqual({
164 archivedThreadKeys: ["one", "two", "three"],
165 mutationFailure: null,
166 followupFailures: [failure],
167 });
168 });
169});
170
171describe("sidebar thread lineage helpers", () => {
172 it("maps an open subagent to its nearest visible ancestor's sidebar row", () => {
173 const environmentId = EnvironmentId.make("environment-row");
174 const otherEnvironmentId = EnvironmentId.make("environment-other");
175 const subagentOf = (id: string, parentId: ThreadId, environment = environmentId) =>
176 makeThreadFixture({
177 id: ThreadId.make(id),
178 environmentId: environment,
179 lineage: {
180 rootThreadId: parentId,
181 parentThreadId: parentId,
182 relationshipToParent: "subagent",
183 },
184 });
185 const root = makeThreadFixture({ id: ThreadId.make("thread-root"), environmentId });
186 const fork = makeThreadFixture({
187 id: ThreadId.make("thread-fork"),
188 environmentId,
189 lineage: {
190 rootThreadId: root.id,
191 parentThreadId: root.id,
192 relationshipToParent: "fork",
193 },
194 });
195 const child = subagentOf("thread-child", root.id);
196 const grandchild = subagentOf("thread-grandchild", child.id);
197 const forkChild = subagentOf("thread-fork-child", fork.id);
198 const orphan = subagentOf("thread-orphan", ThreadId.make("thread-missing"));
199 const elsewhere = subagentOf("thread-elsewhere", root.id, otherEnvironmentId);
200 const threads = [root, fork, child, grandchild, forkChild, orphan, elsewhere];
201
202 expect(resolveSidebarRowThreadId(child.id, environmentId, threads)).toBe(root.id);
203 expect(resolveSidebarRowThreadId(grandchild.id, environmentId, threads)).toBe(root.id);
204 expect(resolveSidebarRowThreadId(forkChild.id, environmentId, threads)).toBe(fork.id);
205 expect(resolveSidebarRowThreadId(elsewhere.id, otherEnvironmentId, threads)).toBe(elsewhere.id);
206 expect(resolveSidebarRowThreadId(orphan.id, environmentId, threads)).toBe(orphan.id);
207 const loopA = subagentOf("thread-loop-a", ThreadId.make("thread-loop-b"));
208 const loopB = subagentOf("thread-loop-b", loopA.id);
209 expect(resolveSidebarRowThreadId(loopA.id, environmentId, [loopA, loopB])).toBe(loopA.id);
210 });
211});
212
213function makeLatestRun(overrides?: {
214 completedAt?: string | null;
215 startedAt?: string | null;
216}): NonNullable<Thread["latestRun"]> {
217 return {
218 runId: "turn-1" as never,
219 status: "completed",
220 assistantMessageId: null,
221 requestedAt: "2026-03-09T10:00:00.000Z",
222 startedAt:
223 overrides?.startedAt !== undefined ? overrides.startedAt : "2026-03-09T10:00:00.000Z",
224 completedAt:
225 overrides?.completedAt !== undefined ? overrides.completedAt : "2026-03-09T10:05:00.000Z",
226 };
227}
228
229describe("orderItemsByPreferredIds", () => {
230 it("resolves legacy preference aliases without materializing project state", () => {
231 const ordered = orderItemsByPreferredIds({
232 items: [
233 { id: "physical-a", cwd: "/work/a" },
234 { id: "physical-b", cwd: "/work/b" },
235 { id: "physical-c", cwd: "/work/c" },
236 ],
237 preferredIds: ["legacy:/work/c", "legacy:/work/a"],
238 getId: (project) => project.id,
239 getPreferenceIds: (project) => [project.id, `legacy:${project.cwd}`],
240 });
241
242 expect(ordered.map((project) => project.id)).toEqual([
243 "physical-c",
244 "physical-a",
245 "physical-b",
246 ]);
247 });
248});
249
250describe("resolveSidebarThreadStatus", () => {
251 const runtime = {
252 status: "running" as const,
253 activeRunId: null,
254 providerInstanceId: ProviderInstanceId.make("codex"),
255 providerName: "Codex",
256 lastError: null,
257 updatedAt: "2026-03-09T10:00:00.000Z",
258 };
259
260 const idle = { hasPendingApprovals: false, hasPendingUserInput: false, runtime: null };
261
262 it("prioritizes awaiting input over a running runtime, below approval", () => {
263 expect(
264 resolveSidebarThreadStatus({
265 ...idle,
266 hasPendingUserInput: true,
267 runtime,
268 blockedOnThreadWait: true,
269 }),
270 ).toBe("input");
271 expect(
272 resolveSidebarThreadStatus({
273 ...idle,
274 hasPendingApprovals: true,
275 hasPendingUserInput: true,
276 blockedOnThreadWait: true,
277 runtime,
278 }),
279 ).toBe("approval");
280 });
281
282 it("shows a waiting guest message as a Request, below the agent's own requests", () => {
283 expect(resolveSidebarThreadStatus({ ...idle, pendingGuestMessageCount: 1, runtime })).toBe(
284 "request",
285 );
286 expect(
287 resolveSidebarThreadStatus({
288 ...idle,
289 hasPendingUserInput: true,
290 pendingGuestMessageCount: 1,
291 }),
292 ).toBe("input");
293 });
294
295 it("keeps usage-limit stops Limited and visible until the thread recovers", () => {
296 const limited = {
297 ...runtime,
298 status: "failed" as const,
299 lastError: "Plan limit reached",
300 lastErrorClass: "usage_limit" as const,
301 };
302 expect(resolveSidebarThreadStatus({ ...idle, runtime: limited })).toBe("limited");
303 expect(
304 resolveSidebarThreadStatus({ ...idle, runtime: { ...limited, status: "running" } }),
305 ).toBe("working");
306 expect(
307 resolveSidebarThreadStatus({ ...idle, runtime: { ...limited, status: "completed" } }),
308 ).toBe("ready");
309 expect(
310 shouldRecedeSidebarThread({
311 status: "limited",
312 isUnread: false,
313 isWoke: false,
314 isActive: false,
315 isSelected: false,
316 }),
317 ).toBe(false);
318 });
319
320 it("reports failed only while the latest run failed", () => {
321 expect(
322 resolveSidebarThreadStatus({
323 ...idle,
324 runtime: { ...runtime, status: "failed" as const, lastError: "boom" },
325 }),
326 ).toBe("failed");
327 expect(
328 resolveSidebarThreadStatus({
329 ...idle,
330 runtime: { ...runtime, status: "completed" as const, lastError: "persisted" },
331 }),
332 ).toBe("ready");
333 expect(
334 resolveSidebarThreadStatus({
335 ...idle,
336 runtime: { ...runtime, status: "idle" as const, lastError: "persisted" },
337 }),
338 ).toBe("waiting");
339 });
340});
341
342describe("searchSidebarThreads", () => {
343 const searchThread = (id: string, title: string, latestUserMessageAt: string) => ({
344 environmentId: localEnvironmentId,
345 id: ThreadId.make(id),
346 title,
347 branch: null,
348 createdAt: "2026-01-01T00:00:00.000Z",
349 updatedAt: latestUserMessageAt,
350 latestUserMessageAt,
351 opens: null,
352 });
353 const threads = [
354 searchThread("thread-1", "Fix workspace search", "2026-10-20T00:00:00.000Z"),
355 searchThread("thread-2", "Review providers", "2026-10-22T00:00:00.000Z"),
356 searchThread("thread-3", "WORKTREE cleanup", "2026-09-01T00:00:00.000Z"),
357 searchThread("thread-4", "Homework notes", "2026-10-22T00:00:00.000Z"),
358 ];
359 const now = Date.parse("2026-10-23T00:00:00.000Z");
360 const contentKeys = (...ids: ReadonlyArray<string>) =>
361 new Set(
362 ids.map((id) =>
363 threadSearchMatchKey({ environmentId: localEnvironmentId, threadId: ThreadId.make(id) }),
364 ),
365 );
366
367 it("ranks word matches by recent use, then lists message matches once", () => {
368 expect(searchSidebarThreads(threads, "work", contentKeys("thread-1", "thread-2"), now)).toEqual(
369 {
370 titleMatches: [threads[0], threads[2], threads[3]],
371 contentMatches: [threads[1]],
372 },
373 );
374 });
375});
376
377describe("resolveWorkingStartedAt", () => {
378 const runtime = {
379 status: "running" as const,
380 providerName: "Codex",
381 providerInstanceId: ProviderInstanceId.make("codex"),
382 activeRunId: RunId.make("turn-1"),
383 lastError: null,
384 updatedAt: "2026-03-09T10:02:00.000Z",
385 };
386
387 it("does not invent a start from activity updates when the newest run completed", () => {
388 expect(
389 resolveWorkingStartedAt({
390 latestRun: makeLatestRun(),
391 runtime,
392 }),
393 ).toBeNull();
394 });
395
396 it.each(["queued", "cancelled"] as const)(
397 "shares the detail timer when a newer run is %s",
398 (status) => {
399 const activityStartedAt = "2026-03-09T10:00:00.000Z";
400 const latestRun = {
401 ...makeLatestRun(),
402 runId: RunId.make("newer-run"),
403 status,
404 startedAt: null,
405 completedAt: status === "queued" ? null : "2026-03-09T10:05:00.000Z",
406 };
407 for (const updatedAt of ["2026-03-09T10:30:00.000Z", "2026-03-09T10:50:00.000Z"]) {
408 const activeRuntime = { ...runtime, updatedAt, activityStartedAt };
409 expect(resolveWorkingStartedAt({ latestRun, runtime: activeRuntime })).toBe(
410 activityStartedAt,
411 );
412 expect(deriveActiveWorkStartedAt(latestRun, activeRuntime, updatedAt)).toBe(
413 activityStartedAt,
414 );
415 }
416 expect(
417 deriveActiveWorkStartedAt(
418 latestRun,
419 { ...runtime, activityStartedAt: null },
420 "2026-03-09T10:50:00.000Z",
421 ),
422 ).toBeNull();
423 },
424 );
425});
426
427describe("resolveThreadStatusPill", () => {
428 const baseThread = {
429 hasActionableProposedPlan: false,
430 hasPendingApprovals: false,
431 hasPendingUserInput: false,
432 interactionMode: "plan" as const,
433 latestRun: null,
434 lastVisitedAt: undefined,
435 runtime: {
436 status: "running" as const,
437 providerName: "Codex",
438 providerInstanceId: ProviderInstanceId.make("codex"),
439 activeRunId: "turn-1" as never,
440 lastError: null,
441 updatedAt: "2026-03-09T10:00:00.000Z",
442 },
443 };
444
445 it("shows an active thread wait without a pulse and resumes Working when it ends", () => {
446 const blocked = { ...baseThread, blockedOnThreadWait: true };
447 expect(resolveSidebarThreadStatus(blocked)).toBe("waiting");
448 expect(resolveThreadStatusPill({ thread: blocked })).toMatchObject({
449 label: "Waiting",
450 pulse: false,
451 });
452
453 const resumed = { ...blocked, blockedOnThreadWait: false };
454 expect(resolveSidebarThreadStatus(resumed)).toBe("working");
455 expect(resolveThreadStatusPill({ thread: resumed })).toMatchObject({
456 label: "Working",
457 pulse: true,
458 });
459 });
460
461 it("shows waiting for an idle thread with pending background tasks", () => {
462 expect(
463 resolveThreadStatusPill({
464 thread: {
465 ...baseThread,
466 pendingBackgroundTasks: [
467 { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
468 ],
469 runtime: {
470 ...baseThread.runtime,
471 status: "idle",
472 activeRunId: null,
473 },
474 },
475 }),
476 ).toMatchObject({
477 label: "Waiting",
478 colorClass: "text-sidebar-muted-foreground",
479 dotClass: "bg-sidebar-muted-foreground",
480 pulse: false,
481 });
482 });
483
484 it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
485 expect(
486 resolveThreadStatusPill({
487 thread: {
488 ...baseThread,
489 hasActionableProposedPlan: true,
490 latestRun: makeLatestRun(),
491 runtime: {
492 ...baseThread.runtime,
493 status: "completed",
494 activeRunId: null,
495 },
496 },
497 }),
498 ).toMatchObject({ label: "Plan Ready", pulse: false });
499 });
500
501 it("does not manufacture completed state without a client visit marker", () => {
502 expect(
503 resolveThreadStatusPill({
504 thread: {
505 ...baseThread,
506 latestRun: makeLatestRun(),
507 runtime: {
508 ...baseThread.runtime,
509 status: "completed",
510 activeRunId: null,
511 },
512 },
513 }),
514 ).toBeNull();
515 });
516
517 it("shows completed when there is an unseen completion and no active blocker", () => {
518 expect(
519 resolveThreadStatusPill({
520 thread: {
521 ...baseThread,
522 interactionMode: "default",
523 latestRun: makeLatestRun(),
524 lastVisitedAt: "2026-03-09T10:04:00.000Z",
525 runtime: {
526 ...baseThread.runtime,
527 status: "completed",
528 activeRunId: null,
529 },
530 },
531 }),
532 ).toMatchObject({ label: "Completed", pulse: false });
533 });
534
535 it("shows failed, not completed, when the unseen run failed", () => {
536 expect(
537 resolveThreadStatusPill({
538 thread: {
539 ...baseThread,
540 interactionMode: "default",
541 latestRun: { ...makeLatestRun(), status: "failed" },
542 lastVisitedAt: "2026-03-09T10:04:00.000Z",
543 runtime: {
544 ...baseThread.runtime,
545 status: "failed",
546 activeRunId: null,
547 lastError: "Provider turn failed.",
548 },
549 },
550 }),
551 ).toMatchObject({ label: "Failed", pulse: false });
552 });
553
554 it("shows failed, not plan ready, when a plan run proposed a plan and then failed", () => {
555 expect(
556 resolveThreadStatusPill({
557 thread: {
558 ...baseThread,
559 hasActionableProposedPlan: true,
560 latestRun: { ...makeLatestRun(), status: "failed" },
561 lastVisitedAt: "2026-03-09T10:04:00.000Z",
562 runtime: { ...baseThread.runtime, status: "failed", activeRunId: null },
563 },
564 }),
565 ).toMatchObject({ label: "Failed" });
566 });
567
568 it("drops the failed pill once the failure has been seen", () => {
569 expect(
570 resolveThreadStatusPill({
571 thread: {
572 ...baseThread,
573 interactionMode: "default",
574 latestRun: { ...makeLatestRun(), status: "failed" },
575 lastVisitedAt: "2026-03-09T10:06:00.000Z",
576 runtime: { ...baseThread.runtime, status: "failed", activeRunId: null },
577 },
578 }),
579 ).toBeNull();
580 });
581});
582
583describe("resolveProjectStatusIndicator", () => {
584 it("ranks waiting below active work and above plan-ready", () => {
585 const waiting = {
586 label: "Waiting" as const,
587 colorClass: "text-sidebar-muted-foreground",
588 dotClass: "bg-sidebar-muted-foreground",
589 pulse: false,
590 };
591
592 expect(
593 resolveProjectStatusIndicator([
594 waiting,
595 {
596 label: "Working",
597 colorClass: "text-sky-600",
598 dotClass: "bg-sky-500",
599 pulse: true,
600 },
601 ]),
602 ).toMatchObject({ label: "Working" });
603 expect(
604 resolveProjectStatusIndicator([
605 {
606 label: "Plan Ready",
607 colorClass: "text-violet-600",
608 dotClass: "bg-violet-500",
609 pulse: false,
610 },
611 waiting,
612 ]),
613 ).toMatchObject({ label: "Waiting" });
614 });
615});
616
617function makeProject(overrides: Partial<Project> = {}): Project {
618 const { defaultModelSelection, ...rest } = overrides;
619 return {
620 id: ProjectId.make("project-1"),
621 environmentId: localEnvironmentId,
622 title: "Project",
623 workspaceRoot: "/tmp/project",
624 repositoryIdentity: null,
625 defaultModelSelection: {
626 instanceId: ProviderInstanceId.make("codex"),
627 model: "gpt-5.4",
628 ...defaultModelSelection,
629 },
630 createdAt: "2026-03-09T10:00:00.000Z",
631 updatedAt: "2026-03-09T10:00:00.000Z",
632 scripts: [],
633 ...rest,
634 };
635}
636
637function makeThread(overrides: ThreadFixtureOverrides = {}): Thread {
638 return makeThreadFixture({
639 id: ThreadId.make("thread-1"),
640 environmentId: localEnvironmentId,
641 projectId: ProjectId.make("project-1"),
642 title: "Thread",
643 modelSelection: {
644 instanceId: ProviderInstanceId.make("codex"),
645 model: "gpt-5.4",
646 ...overrides?.modelSelection,
647 },
648 runtimeMode: DEFAULT_RUNTIME_MODE,
649 interactionMode: DEFAULT_INTERACTION_MODE,
650 runtime: null,
651 messages: [],
652 proposedPlans: [],
653 createdAt: "2026-03-09T10:00:00.000Z",
654 archivedAt: null,
655 settledOverride: null,
656 settledAt: null,
657 deletedAt: null,
658 updatedAt: "2026-03-09T10:00:00.000Z",
659 latestRun: null,
660 branch: null,
661 worktreePath: null,
662 ...overrides,
663 });
664}
665
666describe("getFallbackThreadIdAfterDelete", () => {
667 it("skips other threads being deleted in the same action", () => {
668 const fallbackThreadId = getFallbackThreadIdAfterDelete({
669 threads: [
670 makeThread({
671 id: ThreadId.make("thread-active"),
672 projectId: ProjectId.make("project-1"),
673 createdAt: "2026-03-09T10:05:00.000Z",
674 messages: [],
675 }),
676 makeThread({
677 id: ThreadId.make("thread-newest"),
678 projectId: ProjectId.make("project-1"),
679 createdAt: "2026-03-09T10:10:00.000Z",
680 messages: [],
681 }),
682 makeThread({
683 id: ThreadId.make("thread-next"),
684 projectId: ProjectId.make("project-1"),
685 createdAt: "2026-03-09T10:07:00.000Z",
686 messages: [],
687 }),
688 ],
689 deletedThreadId: ThreadId.make("thread-active"),
690 deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]),
691 sortOrder: "created_at",
692 });
693
694 expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
695 });
696});
697describe("sortProjectsForSidebar", () => {
698 it("sorts projects by the most recent user message across their threads", () => {
699 const projects = [
700 makeProject({ id: ProjectId.make("project-1"), title: "Older project" }),
701 makeProject({ id: ProjectId.make("project-2"), title: "Newer project" }),
702 ];
703 const threads = [
704 makeThread({
705 projectId: ProjectId.make("project-1"),
706 updatedAt: "2026-03-09T10:20:00.000Z",
707 messages: [
708 {
709 id: "message-1" as never,
710 role: "user",
711 text: "older project user message",
712 runId: null,
713 createdAt: "2026-03-09T10:01:00.000Z",
714 updatedAt: "2026-03-09T10:01:00.000Z",
715 streaming: false,
716 },
717 ],
718 }),
719 makeThread({
720 id: ThreadId.make("thread-2"),
721 projectId: ProjectId.make("project-2"),
722 updatedAt: "2026-03-09T10:05:00.000Z",
723 messages: [
724 {
725 id: "message-2" as never,
726 role: "user",
727 text: "newer project user message",
728 runId: null,
729 createdAt: "2026-03-09T10:05:00.000Z",
730 updatedAt: "2026-03-09T10:05:00.000Z",
731 streaming: false,
732 },
733 ],
734 }),
735 ];
736
737 const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
738
739 expect(sorted.map((project) => project.id)).toEqual([
740 ProjectId.make("project-2"),
741 ProjectId.make("project-1"),
742 ]);
743 });
744});
745
746describe("sortScopedProjectsForSidebar", () => {
747 it("keeps identical project ids in different environments separate", () => {
748 const remoteEnvironmentId = EnvironmentId.make("environment-remote");
749 const sharedProjectId = ProjectId.make("shared-project");
750 const projects = [
751 makeProject({
752 environmentId: localEnvironmentId,
753 id: sharedProjectId,
754 title: "Local project",
755 }),
756 makeProject({
757 environmentId: remoteEnvironmentId,
758 id: sharedProjectId,
759 title: "Remote project",
760 }),
761 ];
762 const threads = [
763 makeThread({
764 environmentId: localEnvironmentId,
765 projectId: sharedProjectId,
766 updatedAt: "2026-03-09T10:02:00.000Z",
767 }),
768 makeThread({
769 environmentId: remoteEnvironmentId,
770 projectId: sharedProjectId,
771 updatedAt: "2026-03-09T10:10:00.000Z",
772 }),
773 ];
774
775 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
776
777 expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);
778 });
779
780 it("does not use archived threads as project activity", () => {
781 const projects = [
782 makeProject({
783 id: ProjectId.make("project-visible"),
784 title: "Visible project",
785 updatedAt: "2026-03-09T10:01:00.000Z",
786 }),
787 makeProject({
788 id: ProjectId.make("project-archived"),
789 title: "Archived-only project",
790 updatedAt: "2026-03-09T10:00:00.000Z",
791 }),
792 ];
793 const threads = [
794 makeThread({
795 id: ThreadId.make("thread-visible"),
796 projectId: ProjectId.make("project-visible"),
797 updatedAt: "2026-03-09T10:02:00.000Z",
798 }),
799 makeThread({
800 id: ThreadId.make("thread-archived"),
801 projectId: ProjectId.make("project-archived"),
802 updatedAt: "2026-03-09T10:10:00.000Z",
803 archivedAt: "2026-03-09T10:11:00.000Z",
804 }),
805 ];
806
807 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
808
809 expect(sorted.map((project) => project.title)).toEqual([
810 "Visible project",
811 "Archived-only project",
812 ]);
813 });
814});
815
816describe("sortSidebarV2ProjectGroups", () => {
817 it("does not let a hidden subagent thread reorder projects", () => {
818 const olderProjectId = ProjectId.make("project-older");
819 const newerProjectId = ProjectId.make("project-newer");
820 const olderRootThreadId = ThreadId.make("thread-older-root");
821 const projects = [
822 {
823 ...makeProject({ id: olderProjectId, title: "A older project" }),
824 projectKey: "logical-older",
825 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: olderProjectId }],
826 },
827 {
828 ...makeProject({ id: newerProjectId, title: "Z newer project" }),
829 projectKey: "logical-newer",
830 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: newerProjectId }],
831 },
832 ];
833 const threads = [
834 makeThread({
835 id: olderRootThreadId,
836 projectId: olderProjectId,
837 updatedAt: "2026-03-09T10:01:00.000Z",
838 }),
839 makeThread({
840 id: ThreadId.make("thread-newer-root"),
841 projectId: newerProjectId,
842 updatedAt: "2026-03-09T10:05:00.000Z",
843 }),
844 makeThread({
845 id: ThreadId.make("thread-hidden-subagent"),
846 projectId: olderProjectId,
847 updatedAt: "2026-03-09T10:10:00.000Z",
848 lineage: {
849 rootThreadId: olderRootThreadId,
850 parentThreadId: olderRootThreadId,
851 relationshipToParent: "subagent",
852 },
853 }),
854 ];
855
856 expect(
857 sortSidebarV2ProjectGroups(projects, threads, "updated_at", new Set()).map(
858 (project) => project.projectKey,
859 ),
860 ).toEqual(["logical-newer", "logical-older"]);
861 });
862});
863
864describe("pinOrderKeyBetween", () => {
865 it("stays strictly ordered under repeated top insertion", () => {
866 let head: string | null = null;
867 const keys: string[] = [];
868 for (let i = 0; i < 100; i += 1) {
869 const key: string = pinOrderKeyBetween(null, head)!;
870 expect(key).not.toBeNull();
871 if (head !== null) expect(key < head).toBe(true);
872 keys.push(key);
873 head = key;
874 }
875 expect(new Set(keys).size).toBe(100);
876 });
877
878 it("stays strictly ordered under repeated middle insertion", () => {
879 let low = pinOrderKeyBetween(null, null)!;
880 let high = pinOrderKeyBetween(low, null)!;
881 for (let i = 0; i < 100; i += 1) {
882 const key: string = pinOrderKeyBetween(low, high)!;
883 expect(low < key && key < high).toBe(true);
884 if (i % 2 === 0) low = key;
885 else high = key;
886 }
887 });
888
889 it("returns null for corrupt or out-of-order bounds instead of throwing", () => {
890 expect(pinOrderKeyBetween("z", "a")).toBeNull();
891 expect(pinOrderKeyBetween("A!", null)).toBeNull();
892 expect(pinOrderKeyBetween(null, "ma")).toBeNull();
893 expect(pinOrderKeyBetween("m", "m")).toBeNull();
894 });
895});
896
897describe("sortPinnedThreadsForSidebar", () => {
898 const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({
899 id: input.id,
900 createdAt: input.createdAt,
901 pinOrderKey: input.pinOrderKey ?? null,
902 });
903
904 it("sorts keyed threads by key ahead of keyless threads in creation order", () => {
905 const sorted = sortPinnedThreadsForSidebar([
906 pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }),
907 pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }),
908 pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }),
909 pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }),
910 ]);
911
912 expect(sorted.map((thread) => thread.id)).toEqual([
913 "first",
914 "second",
915 "keyless-new",
916 "keyless-old",
917 ]);
918 });
919
920 it("breaks equal keys by id so raced writes render identically everywhere", () => {
921 const sorted = sortPinnedThreadsForSidebar([
922 pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }),
923 pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }),
924 ]);
925
926 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
927 });
928});
929
930describe("resolveSidebarSweepKeys", () => {
931 const ordered = ["a", "b", "c", "d", "blocked"];
932 const canSettle = (key: string) => key !== "blocked";
933
934 it("leaves out rows that cannot settle and rows that left the list", () => {
935 expect(resolveSidebarSweepKeys(ordered, "c", "blocked", canSettle)).toEqual(["c", "d"]);
936 expect(resolveSidebarSweepKeys(ordered, "gone", "a", canSettle)).toEqual([]);
937 });
938});
939
940describe("navigation after parking a thread", () => {
941 it.each([
942 ["settle", "settled", null, "thread", true],
943 ["settle", "active", null, "thread", false],
944 ["settle", "settled", null, "other-thread", false],
945 ["snooze", null, "2099-01-01T00:00:00.000Z", "thread", true],
946 ["snooze", null, null, "thread", false],
947 ["snooze", null, "2026-09-12T09:00:00.000Z", "thread", false],
948 ["snooze", null, "2099-01-01T00:00:00.000Z", "thread", false, true],
949 ["snooze", null, "2099-01-01T00:00:00.000Z", "other-thread", false],
950 ] as const)(
951 "%s with state %s / %s on %s navigates: %s",
952 (
953 action,
954 settledOverride,
955 snoozedUntil,
956 currentThreadKey,
957 expected,
958 hasPendingApprovals: boolean = false,
959 ) => {
960 expect(
961 shouldNavigateAfterThreadPark({
962 threadKey: "thread",
963 currentThreadKey,
964 action,
965 now: "2026-09-12T10:00:00.000Z",
966 thread: {
967 settledOverride,
968 snoozedUntil,
969 snoozedAt: null,
970 session: null,
971 latestTurn: null,
972 hasPendingApprovals,
973 hasPendingUserInput: false,
974 },
975 }),
976 ).toBe(expected);
977 },
978 );
979});
980
981describe("unseen completion with background work", () => {
982 it.each([
983 {
984 roster: "dev server",
985 task: { kind: "command" },
986 status: "ready",
987 receded: false,
988 pill: "Completed",
989 },
990 {
991 roster: "dev server watchdog",
992 task: { kind: "monitor" },
993 status: "ready",
994 receded: false,
995 pill: "Completed",
996 },
997 {
998 roster: "awaited command",
999 task: { kind: "command", awaited: true },
1000 status: "waiting",
1001 receded: true,
1002 pill: "Waiting",
1003 },
1004 ] as const)("presents a completed thread with a $roster roster", (expected) => {
1005 const thread = presentThreadShell(localEnvironmentId, {
1006 ...makeThreadFixture().source,
1007 latestRunId: RunId.make("run-background-completion"),
1008 status: "completed",
1009 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
1010 lastVisitedAt: DateTime.makeUnsafe("2026-06-20T00:59:00.000Z"),
1011 pendingBackgroundTasks: [{ taskId: "background-work", ...expected.task }],
1012 });
1013 const status = resolveSidebarThreadStatus(thread);
1014 const isUnread = hasUnseenCompletion(thread);
1015
1016 expect(isUnread).toBe(true);
1017 expect(status).toBe(expected.status);
1018 expect(
1019 shouldRecedeSidebarThread({
1020 status,
1021 isUnread,
1022 isWoke: false,
1023 isActive: false,
1024 isSelected: false,
1025 }),
1026 ).toBe(expected.receded);
1027 expect(isSidebarThreadWorking(thread)).toBe(expected.receded);
1028 expect(resolveThreadStatusPill({ thread })).toMatchObject({ label: expected.pill });
1029 });
1030});
1031
1032describe("Working shelf (beta)", () => {
1033 const runtime = {
1034 status: "running" as const,
1035 activeRunId: null,
1036 providerInstanceId: ProviderInstanceId.make("codex"),
1037 providerName: "Codex",
1038 lastError: null,
1039 updatedAt: "2026-03-09T10:00:00.000Z",
1040 };
1041 const backgroundTask = {
1042 taskId: "bg-1",
1043 description: "Watch build",
1044 kind: "monitor" as const,
1045 awaited: true as const,
1046 };
1047 const idle = {
1048 hasActionableProposedPlan: false,
1049 hasPendingApprovals: false,
1050 hasPendingUserInput: false,
1051 interactionMode: "default" as const,
1052 latestRun: makeLatestRun(),
1053 runtime: null,
1054 };
1055 const waiting = {
1056 ...idle,
1057 runtime: { ...runtime, status: "idle" as const },
1058 pendingBackgroundTasks: [backgroundTask],
1059 };
1060
1061 it("folds away running threads and threads waiting on background work only", () => {
1062 expect(isSidebarThreadWorking({ ...idle, runtime })).toBe(true);
1063 expect(isSidebarThreadWorking(waiting)).toBe(true);
1064 expect(isSidebarThreadWorking(idle)).toBe(false);
1065 expect(isSidebarThreadWorking({ ...idle, runtime, hasPendingApprovals: true })).toBe(false);
1066 expect(isSidebarThreadWorking({ ...idle, runtime, hasPendingUserInput: true })).toBe(false);
1067 expect(
1068 isSidebarThreadWorking({
1069 ...waiting,
1070 runtime: { ...runtime, status: "failed" as const, lastError: "boom" },
1071 }),
1072 ).toBe(false);
1073 });
1074
1075 it("keeps a ready plan in the inbox while background work runs", () => {
1076 expect(
1077 isSidebarThreadWorking({
1078 ...waiting,
1079 interactionMode: "plan",
1080 hasActionableProposedPlan: true,
1081 }),
1082 ).toBe(false);
1083 });
1084
1085 describe("sortInboxThreadsByReturn", () => {
1086 const thread = (
1087 id: string,
1088 input: { createdAt: string; completedAt?: string | null; unsettledAt?: string },
1089 ) => ({
1090 id: ThreadId.make(id),
1091 environmentId: localEnvironmentId,
1092 createdAt: input.createdAt,
1093 unsettledAt: input.unsettledAt ?? null,
1094 latestRun:
1095 input.completedAt === undefined
1096 ? null
1097 : { ...makeLatestRun({ completedAt: input.completedAt }), requestedAt: input.createdAt },
1098 });
1099
1100 it("puts the thread that finished last on top, whatever its age", () => {
1101 const sorted = sortInboxThreadsByReturn([
1102 thread("new", { createdAt: "2026-03-09T11:00:00.000Z" }),
1103 thread("old-finished-now", {
1104 createdAt: "2026-03-01T09:00:00.000Z",
1105 completedAt: "2026-03-09T12:00:00.000Z",
1106 }),
1107 thread("reopened", {
1108 createdAt: "2026-03-02T09:00:00.000Z",
1109 unsettledAt: "2026-03-09T11:30:00.000Z",
1110 }),
1111 ]);
1112 expect(sorted.map((entry) => entry.id)).toEqual(["old-finished-now", "reopened", "new"]);
1113 });
1114
1115 it("counts a return the server does not stamp, like an approval request", () => {
1116 const waiting = thread("asks-approval", {
1117 createdAt: "2026-03-09T09:00:00.000Z",
1118 completedAt: null,
1119 });
1120 const finished = thread("finished", {
1121 createdAt: "2026-03-09T09:30:00.000Z",
1122 completedAt: "2026-03-09T11:00:00.000Z",
1123 });
1124 expect(sortInboxThreadsByReturn([finished, waiting]).map((entry) => entry.id)).toEqual([
1125 "finished",
1126 "asks-approval",
1127 ]);
1128 expect(
1129 sortInboxThreadsByReturn([finished, waiting], (entry) =>
1130 entry === waiting ? Date.parse("2026-03-09T11:05:00.000Z") : undefined,
1131 ).map((entry) => entry.id),
1132 ).toEqual(["asks-approval", "finished"]);
1133 });
1134 });
1135
1136 describe("dragging", () => {
1137 const marker = (name: SidebarListMarker): SidebarListItem => ({ kind: "marker", marker: name });
1138 const row = (key: string, section: SidebarSection): SidebarListItem => ({
1139 kind: "thread",
1140 key,
1141 section,
1142 });
1143 const items: readonly SidebarListItem[] = [
1144 marker("pinned-header"),
1145 row("p1", "pinned"),
1146 marker("pinned-divider"),
1147 row("a1", "active"),
1148 row("a2", "active"),
1149 marker("working-header"),
1150 row("w1", "working"),
1151 marker("settled-header"),
1152 row("s1", "settled"),
1153 ];
1154
1155 it("never drops into the Working shelf, and keeps it out of the inbox order", () => {
1156 expect(resolveSidebarDropTarget(items, "a1", "w1")).toBeNull();
1157 expect(resolveSidebarDropTarget(items, "p1", "a2")).toEqual({
1158 section: "active",
1159 pinnedOrder: [],
1160 activeOrder: ["a1", "a2", "p1"],
1161 });
1162 expect(resolveSidebarDropVerb("active", "working")).toBeNull();
1163 });
1164
1165 it.each([
1166 ["pinned", "p1"],
1167 ["active", "a2"],
1168 ["settled", "s1"],
1169 ] as const)(
1170 "does not move a Working thread into %s when its reference drag ends in the sidebar",
1171 (section, overKey) => {
1172 const target = resolveSidebarDropTarget(items, "w1", overKey);
1173 expect(target?.section).toBe(section);
1174 expect(
1175 planSidebarThreadDrop({
1176 activeKey: "w1",
1177 activeSection: "working",
1178 target: target!,
1179 pinnedOrder: ["p1"],
1180 pinnedKeysById: new Map([["p1", "m"]]),
1181 activeOrder: ["a1", "a2"],
1182 activeKeysById: new Map([
1183 ["a1", "f"],
1184 ["a2", "t"],
1185 ]),
1186 activeTimeOrdered: true,
1187 }),
1188 ).toEqual({ kind: "none" });
1189 },
1190 );
1191
1192 it("arranges the rows it can write when another row's server cannot store an order", () => {
1193 const plan = planSidebarThreadDrop({
1194 activeKey: "a2",
1195 activeSection: "active",
1196 target: {
1197 section: "active",
1198 pinnedOrder: [],
1199 activeOrder: ["offline", "a2", "a1"],
1200 },
1201 pinnedOrder: [],
1202 pinnedKeysById: new Map(),
1203 activeOrder: ["offline", "a1", "a2"],
1204 activeKeysById: new Map([
1205 ["offline", null],
1206 ["a1", null],
1207 ["a2", null],
1208 ]),
1209 activeReorderableKeys: new Set(["a1", "a2"]),
1210 });
1211 expect(plan.kind).toBe("move-active");
1212 if (plan.kind !== "move-active") return;
1213 expect(plan.assignments.map(({ id }) => id)).toEqual(["a2", "a1"]);
1214 const [a2, a1] = plan.assignments.map(({ orderKey }) => orderKey);
1215 expect(a2! < a1!).toBe(true);
1216
1217 const above = planSidebarThreadDrop({
1218 activeKey: "a2",
1219 activeSection: "active",
1220 target: { section: "active", pinnedOrder: [], activeOrder: ["a2", "offline"] },
1221 pinnedOrder: [],
1222 pinnedKeysById: new Map(),
1223 activeOrder: ["offline", "a2"],
1224 activeKeysById: new Map([
1225 ["offline", "m"],
1226 ["a2", "t"],
1227 ]),
1228 activeReorderableKeys: new Set(["a2"]),
1229 });
1230 expect(above.kind === "move-active" && above.assignments[0]!.orderKey < "m").toBe(true);
1231 });
1232
1233 it("only changes lifecycle when the inbox is time-ordered", () => {
1234 const base = {
1235 pinnedOrder: ["p1"],
1236 pinnedKeysById: new Map([["p1", "m"]]),
1237 activeOrder: ["a1", "a2"],
1238 activeKeysById: new Map([
1239 ["a1", "f"],
1240 ["a2", "t"],
1241 ]),
1242 activeTimeOrdered: true,
1243 };
1244 expect(
1245 planSidebarThreadDrop({
1246 ...base,
1247 activeKey: "a1",
1248 activeSection: "active",
1249 target: { section: "active", pinnedOrder: ["p1"], activeOrder: ["a2", "a1"] },
1250 }),
1251 ).toEqual({ kind: "none" });
1252 expect(
1253 planSidebarThreadDrop({
1254 ...base,
1255 activeKey: "p1",
1256 activeSection: "pinned",
1257 target: { section: "active", pinnedOrder: [], activeOrder: ["a1", "p1", "a2"] },
1258 }),
1259 ).toEqual({
1260 kind: "move-active",
1261 order: null,
1262 assignments: [],
1263 unpin: true,
1264 unsettle: false,
1265 unsnooze: false,
1266 });
1267 });
1268 });
1269});
1270
1271describe("pendingSidebarRouteReveal", () => {
1272 it("keeps a revealed thread settled across a mount that reads no route params", () => {
1273 const reveal = { observedKey: null, pendingKey: null };
1274 expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBe("env:a1");
1275 completeSidebarRouteReveal(reveal);
1276
1277 // Back from Settings: location commits before the thread match does.
1278 expect(pendingSidebarRouteReveal(reveal, null)).toBeNull();
1279 expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBeNull();
1280
1281 expect(pendingSidebarRouteReveal(reveal, "env:b1")).toBe("env:b1");
1282 });
1283
1284 it("keeps a pending reveal through a render without route params", () => {
1285 const reveal = { observedKey: null, pendingKey: null };
1286 pendingSidebarRouteReveal(reveal, "env:a1");
1287 expect(pendingSidebarRouteReveal(reveal, null)).toBeNull();
1288 expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBe("env:a1");
1289 });
1290});
1291
1292describe("resolveSidebarRouteReveal", () => {
1293 const scopedProjectKeys = new Set(["environment-test:project-scoped"]);
1294 const hidden = makeThreadFixture({ projectId: ProjectId.make("project-other") });
1295 const hiddenKey = "environment-test:thread-test";
1296 const findThread = (key: string) => (key === hiddenKey ? hidden : undefined);
1297
1298 it("widens the scope for a newly opened thread the scope hides", () => {
1299 expect(
1300 resolveSidebarRouteReveal({
1301 reveal: { observedKey: "environment-test:other", pendingKey: null },
1302 routeKey: hiddenKey,
1303 isSearching: false,
1304 scopedProjectKeys,
1305 delegatedUnderParent: new Set(),
1306 findThread,
1307 }),
1308 ).toEqual({ pendingKey: hiddenKey, widensScope: true });
1309 });
1310
1311 it("never widens for a thread whose reveal already completed", () => {
1312 // A remount's once-per-mount scroll must keep the scope the user chose.
1313 expect(
1314 resolveSidebarRouteReveal({
1315 reveal: { observedKey: hiddenKey, pendingKey: null },
1316 routeKey: hiddenKey,
1317 isSearching: false,
1318 scopedProjectKeys,
1319 delegatedUnderParent: new Set(),
1320 findThread,
1321 }),
1322 ).toEqual({ pendingKey: null, widensScope: false });
1323 });
1324
1325 it("widens again for a thread reopened before the thread between them listed its row", () => {
1326 // The user scoped away from the open thread, then went to a thread whose row
1327 // never mounted, then came back.
1328 const reveal = { observedKey: hiddenKey, pendingKey: null };
1329 const resolve = (routeKey: string) =>
1330 resolveSidebarRouteReveal({
1331 reveal,
1332 routeKey,
1333 isSearching: false,
1334 scopedProjectKeys,
1335 delegatedUnderParent: new Set(),
1336 findThread,
1337 });
1338 resolve("environment-test:unlisted");
1339 expect(resolve(hiddenKey)).toEqual({ pendingKey: hiddenKey, widensScope: true });
1340 });
1341
1342 it("holds a pending reveal without widening while searching", () => {
1343 expect(
1344 resolveSidebarRouteReveal({
1345 reveal: { observedKey: hiddenKey, pendingKey: hiddenKey },
1346 routeKey: hiddenKey,
1347 isSearching: true,
1348 scopedProjectKeys,
1349 delegatedUnderParent: new Set(),
1350 findThread,
1351 }),
1352 ).toEqual({ pendingKey: hiddenKey, widensScope: false });
1353 });
1354});
1355
1356describe("sidebarFolderExpansionKeys", () => {
1357 it("honors a collapse the legacy sidebar saved under a member's cwd", () => {
1358 const keys = sidebarFolderExpansionKeys({
1359 projectKey: "github.com/pingdotgg/t3code",
1360 memberProjects: [{ physicalProjectKey: "local:/code/t3code", workspaceRoot: "/code/t3code" }],
1361 });
1362 const cwdKey = keys.at(-1)!;
1363
1364 expect(resolveProjectExpanded({}, keys)).toBe(true);
1365 expect(resolveProjectExpanded({ [cwdKey]: false }, keys)).toBe(false);
1366 expect(resolveProjectExpanded({ [keys[0]!]: true, [cwdKey]: false }, keys)).toBe(true);
1367 });
1368});
1369
1370describe("groupSidebarThreadsByProject", () => {
1371 it("puts each thread in its project's folder and drops empty projects unless kept", () => {
1372 const remoteEnvironmentId = EnvironmentId.make("environment-remote");
1373 const t3code = ProjectId.make("t3code");
1374 const t3codeRemote = ProjectId.make("t3code-remote");
1375 const fleet = ProjectId.make("fleet");
1376 const thread = (id: string, environmentId: EnvironmentId, projectId: ProjectId) => ({
1377 id,
1378 environmentId,
1379 projectId,
1380 });
1381 const groups = [
1382 {
1383 projectKey: "t3code",
1384 memberProjectRefs: [
1385 { environmentId: localEnvironmentId, projectId: t3code },
1386 { environmentId: remoteEnvironmentId, projectId: t3codeRemote },
1387 ],
1388 },
1389 {
1390 projectKey: "fleet",
1391 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: fleet }],
1392 },
1393 ];
1394
1395 const threads = [
1396 thread("a", localEnvironmentId, t3code),
1397 thread("orphan", localEnvironmentId, ProjectId.make("deleted")),
1398 thread("b", remoteEnvironmentId, t3codeRemote),
1399 ];
1400 const summarize = (keepEmpty: boolean) =>
1401 groupSidebarThreadsByProject(groups, threads, keepEmpty).map((folder) => ({
1402 projectKey: folder.group.projectKey,
1403 threads: folder.threads.map((entry) => entry.id),
1404 }));
1405
1406 expect(summarize(true)).toEqual([
1407 { projectKey: "t3code", threads: ["a", "b"] },
1408 { projectKey: "fleet", threads: [] },
1409 ]);
1410 expect(summarize(false)).toEqual([{ projectKey: "t3code", threads: ["a", "b"] }]);
1411 });
1412});
1413
1414describe("resolveSidebarFolderDot", () => {
1415 it("flags the most urgent hidden thread and stays quiet otherwise", () => {
1416 const idle = {
1417 hasActionableProposedPlan: false,
1418 hasPendingApprovals: false,
1419 hasPendingUserInput: false,
1420 interactionMode: "default" as const,
1421 latestRun: makeLatestRun(),
1422 lastVisitedAt: "2026-03-09T10:06:00.000Z",
1423 runtime: null,
1424 };
1425 const runtime = {
1426 status: "running" as const,
1427 activeRunId: null,
1428 providerInstanceId: ProviderInstanceId.make("codex"),
1429 providerName: "Codex",
1430 lastError: null,
1431 updatedAt: "2026-03-09T10:00:00.000Z",
1432 };
1433 const working = { ...idle, runtime };
1434 const unread = { ...idle, lastVisitedAt: "2026-03-09T10:04:00.000Z" };
1435 const limited = {
1436 ...idle,
1437 runtime: { ...runtime, status: "failed" as const, lastErrorClass: "usage_limit" as const },
1438 };
1439
1440 expect(resolveSidebarFolderDot([idle])).toBeNull();
1441 // A waiting thread stays quiet even with an unread completion, like its row.
1442 expect(
1443 resolveSidebarFolderDot([{ ...unread, runtime: { ...runtime, status: "idle" as const } }]),
1444 ).toBeNull();
1445 expect(resolveSidebarFolderDot([idle, working])).toBe("working");
1446 expect(resolveSidebarFolderDot([working, unread])).toBe("unread");
1447 expect(resolveSidebarFolderDot([unread, limited])).toBe("attention");
1448 });
1449});