Open History to see the last commit
1import { presentThreadShell } from "@t3tools/client-runtime/state/models";
2import * as DateTime from "effect/DateTime";
3import { deriveActiveWorkStartedAt } from "../session-logic.ts";
4import { describe, expect, it, vi } from "vite-plus/test";
5import * as Cause from "effect/Cause";
6import { AsyncResult } from "effect/reactivity";
7import {
8 archiveSelectedThreadEntries,
9 deleteSelectedThreadEntries,
10 getFallbackThreadIdAfterDelete,
11 hasUnseenCompletion,
12 resolveSidebarRowThreadId,
13 isSidebarThreadWorking,
14 orderItemsByPreferredIds,
15 pinOrderKeyBetween,
16 resolveProjectStatusIndicator,
17 resolveSidebarSweepKeys,
18 resolveSidebarThreadStatus,
19 resolveSidebarV2TopStatus,
20 resolveThreadStatusPill,
21 resolveWorkingStartedAt,
22 searchSidebarThreads,
23 shouldRecedeSidebarThread,
24 sortInboxThreadsByReturn,
25 resolveSidebarDropTarget,
26 planSidebarThreadDrop,
27 sortPinnedThreadsForSidebar,
28 sortProjectsForSidebar,
29 sortScopedProjectsForSidebar,
30 sortSidebarV2ProjectGroups,
31 shouldNavigateAfterThreadPark,
32 type SidebarListItem,
33 type SidebarListMarker,
34 type SidebarSection,
35 resolveSidebarDropVerb,
36} from "./Sidebar.logic";
37import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
38import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
39
40import {
41 DEFAULT_INTERACTION_MODE,
42 DEFAULT_RUNTIME_MODE,
43 type Project,
44 type Thread,
45} from "../types";
46import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures";
47import { completeSidebarRouteReveal, pendingSidebarRouteReveal } from "./sidebar/routeReveal";
48
49const localEnvironmentId = EnvironmentId.make("environment-local");
50
51describe("deleteSelectedThreadEntries", () => {
52 const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
53 const success = AsyncResult.success(undefined);
54 const failure = AsyncResult.failure(Cause.fail(new Error("Delete failed")));
55 const interrupted = AsyncResult.failure(Cause.interrupt());
56
57 it("waits for each delete and excludes only earlier successes from worktree checks", async () => {
58 let resolveDelete!: (result: typeof success) => void;
59 const pendingDelete = new Promise<typeof success>((resolve) => {
60 resolveDelete = resolve;
61 });
62 const worktreeChecks: { threadKey: string; deletedThreadKeys: string[] }[] = [];
63 const deletion = deleteSelectedThreadEntries({
64 entries,
65 delete: async ({ threadKey }, deletedThreadKeys) => {
66 worktreeChecks.push({ threadKey, deletedThreadKeys: [...deletedThreadKeys] });
67 return threadKey === "one" ? pendingDelete : success;
68 },
69 });
70
71 expect(worktreeChecks).toEqual([{ threadKey: "one", deletedThreadKeys: [] }]);
72 resolveDelete(success);
73 const outcome = await deletion;
74
75 expect(worktreeChecks).toEqual([
76 { threadKey: "one", deletedThreadKeys: [] },
77 { threadKey: "two", deletedThreadKeys: ["one"] },
78 { threadKey: "three", deletedThreadKeys: ["one", "two"] },
79 ]);
80 expect(outcome).toEqual({
81 deletedThreadKeys: new Set(["one", "two", "three"]),
82 firstFailure: null,
83 });
84 });
85
86 it("continues after ordinary failures and keeps the first failure", async () => {
87 const laterFailure = AsyncResult.failure(Cause.fail(new Error("Later failure")));
88 const deletedKeysAtLastEntry: string[][] = [];
89 const outcome = await deleteSelectedThreadEntries({
90 entries: [...entries, { threadKey: "four" }],
91 delete: async ({ threadKey }, deletedThreadKeys) => {
92 if (threadKey === "one") return failure;
93 if (threadKey === "three") return laterFailure;
94 if (threadKey === "four") deletedKeysAtLastEntry.push([...deletedThreadKeys]);
95 return success;
96 },
97 });
98
99 expect(deletedKeysAtLastEntry).toEqual([["two"]]);
100 expect(outcome).toEqual({
101 deletedThreadKeys: new Set(["two", "four"]),
102 firstFailure: failure,
103 });
104 });
105
106 it.each([
107 { firstResult: success, deletedThreadKeys: new Set(["one"]), firstFailure: null },
108 { firstResult: failure, deletedThreadKeys: new Set<string>(), firstFailure: failure },
109 ])("stops on interruption and preserves earlier results %#", async (testCase) => {
110 const attemptedThreadKeys: string[] = [];
111 const outcome = await deleteSelectedThreadEntries({
112 entries,
113 delete: async ({ threadKey }) => {
114 attemptedThreadKeys.push(threadKey);
115 return threadKey === "one" ? testCase.firstResult : interrupted;
116 },
117 });
118
119 expect(attemptedThreadKeys).toEqual(["one", "two"]);
120 expect(outcome).toEqual({
121 deletedThreadKeys: testCase.deletedThreadKeys,
122 firstFailure: testCase.firstFailure,
123 });
124 });
125});
126
127describe("archiveSelectedThreadEntries", () => {
128 const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
129 const success = { _tag: "Success" } as const;
130 const failure = { _tag: "Failure" } as const;
131
132 it("stops at a mutation failure and retains prior successes", async () => {
133 const archive = vi.fn(async (entry: (typeof entries)[number], onArchived: () => void) => {
134 if (entry.threadKey === "two") return failure;
135 onArchived();
136 return success;
137 });
138 const outcome = await archiveSelectedThreadEntries({ entries, archive });
139
140 expect(archive).toHaveBeenCalledTimes(2);
141 expect(outcome).toEqual({
142 archivedThreadKeys: ["one"],
143 mutationFailure: failure,
144 followupFailures: [],
145 });
146 });
147
148 it("continues after a post-archive failure", async () => {
149 const archive = vi.fn(async (entry: (typeof entries)[number], onArchived: () => void) => {
150 onArchived();
151 return entry.threadKey === "two" ? failure : success;
152 });
153 const outcome = await archiveSelectedThreadEntries({ entries, archive });
154
155 expect(archive).toHaveBeenCalledTimes(3);
156 expect(outcome).toEqual({
157 archivedThreadKeys: ["one", "two", "three"],
158 mutationFailure: null,
159 followupFailures: [failure],
160 });
161 });
162});
163
164describe("sidebar thread lineage helpers", () => {
165 it("maps an open subagent to its nearest visible ancestor's sidebar row", () => {
166 const environmentId = EnvironmentId.make("environment-row");
167 const otherEnvironmentId = EnvironmentId.make("environment-other");
168 const subagentOf = (id: string, parentId: ThreadId, environment = environmentId) =>
169 makeThreadFixture({
170 id: ThreadId.make(id),
171 environmentId: environment,
172 lineage: {
173 rootThreadId: parentId,
174 parentThreadId: parentId,
175 relationshipToParent: "subagent",
176 },
177 });
178 const root = makeThreadFixture({ id: ThreadId.make("thread-root"), environmentId });
179 const fork = makeThreadFixture({
180 id: ThreadId.make("thread-fork"),
181 environmentId,
182 lineage: {
183 rootThreadId: root.id,
184 parentThreadId: root.id,
185 relationshipToParent: "fork",
186 },
187 });
188 const child = subagentOf("thread-child", root.id);
189 const grandchild = subagentOf("thread-grandchild", child.id);
190 const forkChild = subagentOf("thread-fork-child", fork.id);
191 const orphan = subagentOf("thread-orphan", ThreadId.make("thread-missing"));
192 const elsewhere = subagentOf("thread-elsewhere", root.id, otherEnvironmentId);
193 const threads = [root, fork, child, grandchild, forkChild, orphan, elsewhere];
194
195 expect(resolveSidebarRowThreadId(child.id, environmentId, threads)).toBe(root.id);
196 expect(resolveSidebarRowThreadId(grandchild.id, environmentId, threads)).toBe(root.id);
197 expect(resolveSidebarRowThreadId(forkChild.id, environmentId, threads)).toBe(fork.id);
198 expect(resolveSidebarRowThreadId(elsewhere.id, otherEnvironmentId, threads)).toBe(elsewhere.id);
199 expect(resolveSidebarRowThreadId(orphan.id, environmentId, threads)).toBe(orphan.id);
200 const loopA = subagentOf("thread-loop-a", ThreadId.make("thread-loop-b"));
201 const loopB = subagentOf("thread-loop-b", loopA.id);
202 expect(resolveSidebarRowThreadId(loopA.id, environmentId, [loopA, loopB])).toBe(loopA.id);
203 });
204});
205
206function makeLatestRun(overrides?: {
207 completedAt?: string | null;
208 startedAt?: string | null;
209}): NonNullable<Thread["latestRun"]> {
210 return {
211 runId: "turn-1" as never,
212 status: "completed",
213 assistantMessageId: null,
214 requestedAt: "2026-03-09T10:00:00.000Z",
215 startedAt:
216 overrides?.startedAt !== undefined ? overrides.startedAt : "2026-03-09T10:00:00.000Z",
217 completedAt:
218 overrides?.completedAt !== undefined ? overrides.completedAt : "2026-03-09T10:05:00.000Z",
219 };
220}
221
222describe("orderItemsByPreferredIds", () => {
223 it("resolves legacy preference aliases without materializing project state", () => {
224 const ordered = orderItemsByPreferredIds({
225 items: [
226 { id: "physical-a", cwd: "/work/a" },
227 { id: "physical-b", cwd: "/work/b" },
228 { id: "physical-c", cwd: "/work/c" },
229 ],
230 preferredIds: ["legacy:/work/c", "legacy:/work/a"],
231 getId: (project) => project.id,
232 getPreferenceIds: (project) => [project.id, `legacy:${project.cwd}`],
233 });
234
235 expect(ordered.map((project) => project.id)).toEqual([
236 "physical-c",
237 "physical-a",
238 "physical-b",
239 ]);
240 });
241});
242
243describe("resolveSidebarThreadStatus", () => {
244 const runtime = {
245 status: "running" as const,
246 activeRunId: null,
247 providerInstanceId: ProviderInstanceId.make("codex"),
248 providerName: "Codex",
249 lastError: null,
250 updatedAt: "2026-03-09T10:00:00.000Z",
251 };
252
253 const idle = { hasPendingApprovals: false, hasPendingUserInput: false, runtime: null };
254
255 it("prioritizes awaiting input over a running runtime, below approval", () => {
256 expect(
257 resolveSidebarThreadStatus({
258 ...idle,
259 hasPendingUserInput: true,
260 runtime,
261 blockedOnThreadWait: true,
262 }),
263 ).toBe("input");
264 expect(
265 resolveSidebarThreadStatus({
266 ...idle,
267 hasPendingApprovals: true,
268 hasPendingUserInput: true,
269 blockedOnThreadWait: true,
270 runtime,
271 }),
272 ).toBe("approval");
273 });
274
275 it("shows a waiting guest message as a Request, below the agent's own requests", () => {
276 expect(resolveSidebarThreadStatus({ ...idle, pendingGuestMessageCount: 1, runtime })).toBe(
277 "request",
278 );
279 expect(
280 resolveSidebarThreadStatus({
281 ...idle,
282 hasPendingUserInput: true,
283 pendingGuestMessageCount: 1,
284 }),
285 ).toBe("input");
286 });
287
288 it("keeps usage-limit stops Limited and visible until the thread recovers", () => {
289 const limited = {
290 ...runtime,
291 status: "failed" as const,
292 lastError: "Plan limit reached",
293 lastErrorClass: "usage_limit" as const,
294 };
295 expect(resolveSidebarThreadStatus({ ...idle, runtime: limited })).toBe("limited");
296 expect(
297 resolveSidebarThreadStatus({ ...idle, runtime: { ...limited, status: "running" } }),
298 ).toBe("working");
299 expect(
300 resolveSidebarThreadStatus({ ...idle, runtime: { ...limited, status: "completed" } }),
301 ).toBe("ready");
302 expect(resolveSidebarV2TopStatus({ status: "limited", isUnread: false, isWoke: false })).toBe(
303 "limited",
304 );
305 expect(
306 shouldRecedeSidebarThread({
307 status: "limited",
308 isUnread: false,
309 isWoke: false,
310 isActive: false,
311 isSelected: false,
312 }),
313 ).toBe(false);
314 });
315
316 it("reports failed only while the latest run failed", () => {
317 expect(
318 resolveSidebarThreadStatus({
319 ...idle,
320 runtime: { ...runtime, status: "failed" as const, lastError: "boom" },
321 }),
322 ).toBe("failed");
323 expect(
324 resolveSidebarThreadStatus({
325 ...idle,
326 runtime: { ...runtime, status: "completed" as const, lastError: "persisted" },
327 }),
328 ).toBe("ready");
329 expect(
330 resolveSidebarThreadStatus({
331 ...idle,
332 runtime: { ...runtime, status: "idle" as const, lastError: "persisted" },
333 }),
334 ).toBe("waiting");
335 });
336});
337
338describe("searchSidebarThreads", () => {
339 const searchThread = (id: string, title: string, latestUserMessageAt: string) => ({
340 environmentId: localEnvironmentId,
341 id: ThreadId.make(id),
342 title,
343 branch: null,
344 createdAt: "2026-01-01T00:00:00.000Z",
345 updatedAt: latestUserMessageAt,
346 latestUserMessageAt,
347 opens: null,
348 });
349 const threads = [
350 searchThread("thread-1", "Fix workspace search", "2026-10-20T00:00:00.000Z"),
351 searchThread("thread-2", "Review providers", "2026-10-22T00:00:00.000Z"),
352 searchThread("thread-3", "WORKTREE cleanup", "2026-09-01T00:00:00.000Z"),
353 searchThread("thread-4", "Homework notes", "2026-10-22T00:00:00.000Z"),
354 ];
355 const now = Date.parse("2026-10-23T00:00:00.000Z");
356 const contentKeys = (...ids: ReadonlyArray<string>) =>
357 new Set(
358 ids.map((id) =>
359 threadSearchMatchKey({ environmentId: localEnvironmentId, threadId: ThreadId.make(id) }),
360 ),
361 );
362
363 it("ranks word matches by recent use, then lists message matches once", () => {
364 expect(searchSidebarThreads(threads, "work", contentKeys("thread-1", "thread-2"), now)).toEqual(
365 {
366 titleMatches: [threads[0], threads[2], threads[3]],
367 contentMatches: [threads[1]],
368 },
369 );
370 });
371});
372
373describe("resolveWorkingStartedAt", () => {
374 const runtime = {
375 status: "running" as const,
376 providerName: "Codex",
377 providerInstanceId: ProviderInstanceId.make("codex"),
378 activeRunId: RunId.make("turn-1"),
379 lastError: null,
380 updatedAt: "2026-03-09T10:02:00.000Z",
381 };
382
383 it("does not invent a start from activity updates when the newest run completed", () => {
384 expect(
385 resolveWorkingStartedAt({
386 latestRun: makeLatestRun(),
387 runtime,
388 }),
389 ).toBeNull();
390 });
391
392 it.each(["queued", "cancelled"] as const)(
393 "shares the detail timer when a newer run is %s",
394 (status) => {
395 const activityStartedAt = "2026-03-09T10:00:00.000Z";
396 const latestRun = {
397 ...makeLatestRun(),
398 runId: RunId.make("newer-run"),
399 status,
400 startedAt: null,
401 completedAt: status === "queued" ? null : "2026-03-09T10:05:00.000Z",
402 };
403 for (const updatedAt of ["2026-03-09T10:30:00.000Z", "2026-03-09T10:50:00.000Z"]) {
404 const activeRuntime = { ...runtime, updatedAt, activityStartedAt };
405 expect(resolveWorkingStartedAt({ latestRun, runtime: activeRuntime })).toBe(
406 activityStartedAt,
407 );
408 expect(deriveActiveWorkStartedAt(latestRun, activeRuntime, updatedAt)).toBe(
409 activityStartedAt,
410 );
411 }
412 expect(
413 deriveActiveWorkStartedAt(
414 latestRun,
415 { ...runtime, activityStartedAt: null },
416 "2026-03-09T10:50:00.000Z",
417 ),
418 ).toBeNull();
419 },
420 );
421});
422
423describe("resolveThreadStatusPill", () => {
424 const baseThread = {
425 hasActionableProposedPlan: false,
426 hasPendingApprovals: false,
427 hasPendingUserInput: false,
428 interactionMode: "plan" as const,
429 latestRun: null,
430 lastVisitedAt: undefined,
431 runtime: {
432 status: "running" as const,
433 providerName: "Codex",
434 providerInstanceId: ProviderInstanceId.make("codex"),
435 activeRunId: "turn-1" as never,
436 lastError: null,
437 updatedAt: "2026-03-09T10:00:00.000Z",
438 },
439 };
440
441 it("shows an active thread wait without a pulse and resumes Working when it ends", () => {
442 const blocked = { ...baseThread, blockedOnThreadWait: true };
443 expect(resolveSidebarThreadStatus(blocked)).toBe("waiting");
444 expect(resolveThreadStatusPill({ thread: blocked })).toMatchObject({
445 label: "Waiting",
446 pulse: false,
447 });
448
449 const resumed = { ...blocked, blockedOnThreadWait: false };
450 expect(resolveSidebarThreadStatus(resumed)).toBe("working");
451 expect(resolveThreadStatusPill({ thread: resumed })).toMatchObject({
452 label: "Working",
453 pulse: true,
454 });
455 });
456
457 it("shows waiting for an idle thread with pending background tasks", () => {
458 expect(
459 resolveThreadStatusPill({
460 thread: {
461 ...baseThread,
462 pendingBackgroundTasks: [
463 { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
464 ],
465 runtime: {
466 ...baseThread.runtime,
467 status: "idle",
468 activeRunId: null,
469 },
470 },
471 }),
472 ).toMatchObject({
473 label: "Waiting",
474 colorClass: "text-sidebar-muted-foreground",
475 dotClass: "bg-sidebar-muted-foreground",
476 pulse: false,
477 });
478 });
479
480 it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
481 expect(
482 resolveThreadStatusPill({
483 thread: {
484 ...baseThread,
485 hasActionableProposedPlan: true,
486 latestRun: makeLatestRun(),
487 runtime: {
488 ...baseThread.runtime,
489 status: "completed",
490 activeRunId: null,
491 },
492 },
493 }),
494 ).toMatchObject({ label: "Plan Ready", pulse: false });
495 });
496
497 it("does not manufacture completed state without a client visit marker", () => {
498 expect(
499 resolveThreadStatusPill({
500 thread: {
501 ...baseThread,
502 latestRun: makeLatestRun(),
503 runtime: {
504 ...baseThread.runtime,
505 status: "completed",
506 activeRunId: null,
507 },
508 },
509 }),
510 ).toBeNull();
511 });
512
513 it("shows completed when there is an unseen completion and no active blocker", () => {
514 expect(
515 resolveThreadStatusPill({
516 thread: {
517 ...baseThread,
518 interactionMode: "default",
519 latestRun: makeLatestRun(),
520 lastVisitedAt: "2026-03-09T10:04:00.000Z",
521 runtime: {
522 ...baseThread.runtime,
523 status: "completed",
524 activeRunId: null,
525 },
526 },
527 }),
528 ).toMatchObject({ label: "Completed", pulse: false });
529 });
530
531 it("shows failed, not completed, when the unseen run failed", () => {
532 expect(
533 resolveThreadStatusPill({
534 thread: {
535 ...baseThread,
536 interactionMode: "default",
537 latestRun: { ...makeLatestRun(), status: "failed" },
538 lastVisitedAt: "2026-03-09T10:04:00.000Z",
539 runtime: {
540 ...baseThread.runtime,
541 status: "failed",
542 activeRunId: null,
543 lastError: "Provider turn failed.",
544 },
545 },
546 }),
547 ).toMatchObject({ label: "Failed", pulse: false });
548 });
549
550 it("shows failed, not plan ready, when a plan run proposed a plan and then failed", () => {
551 expect(
552 resolveThreadStatusPill({
553 thread: {
554 ...baseThread,
555 hasActionableProposedPlan: true,
556 latestRun: { ...makeLatestRun(), status: "failed" },
557 lastVisitedAt: "2026-03-09T10:04:00.000Z",
558 runtime: { ...baseThread.runtime, status: "failed", activeRunId: null },
559 },
560 }),
561 ).toMatchObject({ label: "Failed" });
562 });
563
564 it("drops the failed pill once the failure has been seen", () => {
565 expect(
566 resolveThreadStatusPill({
567 thread: {
568 ...baseThread,
569 interactionMode: "default",
570 latestRun: { ...makeLatestRun(), status: "failed" },
571 lastVisitedAt: "2026-03-09T10:06:00.000Z",
572 runtime: { ...baseThread.runtime, status: "failed", activeRunId: null },
573 },
574 }),
575 ).toBeNull();
576 });
577});
578
579describe("resolveProjectStatusIndicator", () => {
580 it("ranks waiting below active work and above plan-ready", () => {
581 const waiting = {
582 label: "Waiting" as const,
583 colorClass: "text-sidebar-muted-foreground",
584 dotClass: "bg-sidebar-muted-foreground",
585 pulse: false,
586 };
587
588 expect(
589 resolveProjectStatusIndicator([
590 waiting,
591 {
592 label: "Working",
593 colorClass: "text-sky-600",
594 dotClass: "bg-sky-500",
595 pulse: true,
596 },
597 ]),
598 ).toMatchObject({ label: "Working" });
599 expect(
600 resolveProjectStatusIndicator([
601 {
602 label: "Plan Ready",
603 colorClass: "text-violet-600",
604 dotClass: "bg-violet-500",
605 pulse: false,
606 },
607 waiting,
608 ]),
609 ).toMatchObject({ label: "Waiting" });
610 });
611});
612
613function makeProject(overrides: Partial<Project> = {}): Project {
614 const { defaultModelSelection, ...rest } = overrides;
615 return {
616 id: ProjectId.make("project-1"),
617 environmentId: localEnvironmentId,
618 title: "Project",
619 workspaceRoot: "/tmp/project",
620 repositoryIdentity: null,
621 defaultModelSelection: {
622 instanceId: ProviderInstanceId.make("codex"),
623 model: "gpt-5.4",
624 ...defaultModelSelection,
625 },
626 createdAt: "2026-03-09T10:00:00.000Z",
627 updatedAt: "2026-03-09T10:00:00.000Z",
628 scripts: [],
629 ...rest,
630 };
631}
632
633function makeThread(overrides: ThreadFixtureOverrides = {}): Thread {
634 return makeThreadFixture({
635 id: ThreadId.make("thread-1"),
636 environmentId: localEnvironmentId,
637 projectId: ProjectId.make("project-1"),
638 title: "Thread",
639 modelSelection: {
640 instanceId: ProviderInstanceId.make("codex"),
641 model: "gpt-5.4",
642 ...overrides?.modelSelection,
643 },
644 runtimeMode: DEFAULT_RUNTIME_MODE,
645 interactionMode: DEFAULT_INTERACTION_MODE,
646 runtime: null,
647 messages: [],
648 proposedPlans: [],
649 createdAt: "2026-03-09T10:00:00.000Z",
650 archivedAt: null,
651 settledOverride: null,
652 settledAt: null,
653 deletedAt: null,
654 updatedAt: "2026-03-09T10:00:00.000Z",
655 latestRun: null,
656 branch: null,
657 worktreePath: null,
658 ...overrides,
659 });
660}
661
662describe("getFallbackThreadIdAfterDelete", () => {
663 it("skips other threads being deleted in the same action", () => {
664 const fallbackThreadId = getFallbackThreadIdAfterDelete({
665 threads: [
666 makeThread({
667 id: ThreadId.make("thread-active"),
668 projectId: ProjectId.make("project-1"),
669 createdAt: "2026-03-09T10:05:00.000Z",
670 messages: [],
671 }),
672 makeThread({
673 id: ThreadId.make("thread-newest"),
674 projectId: ProjectId.make("project-1"),
675 createdAt: "2026-03-09T10:10:00.000Z",
676 messages: [],
677 }),
678 makeThread({
679 id: ThreadId.make("thread-next"),
680 projectId: ProjectId.make("project-1"),
681 createdAt: "2026-03-09T10:07:00.000Z",
682 messages: [],
683 }),
684 ],
685 deletedThreadId: ThreadId.make("thread-active"),
686 deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]),
687 sortOrder: "created_at",
688 });
689
690 expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
691 });
692});
693describe("sortProjectsForSidebar", () => {
694 it("sorts projects by the most recent user message across their threads", () => {
695 const projects = [
696 makeProject({ id: ProjectId.make("project-1"), title: "Older project" }),
697 makeProject({ id: ProjectId.make("project-2"), title: "Newer project" }),
698 ];
699 const threads = [
700 makeThread({
701 projectId: ProjectId.make("project-1"),
702 updatedAt: "2026-03-09T10:20:00.000Z",
703 messages: [
704 {
705 id: "message-1" as never,
706 role: "user",
707 text: "older project user message",
708 runId: null,
709 createdAt: "2026-03-09T10:01:00.000Z",
710 updatedAt: "2026-03-09T10:01:00.000Z",
711 streaming: false,
712 },
713 ],
714 }),
715 makeThread({
716 id: ThreadId.make("thread-2"),
717 projectId: ProjectId.make("project-2"),
718 updatedAt: "2026-03-09T10:05:00.000Z",
719 messages: [
720 {
721 id: "message-2" as never,
722 role: "user",
723 text: "newer project user message",
724 runId: null,
725 createdAt: "2026-03-09T10:05:00.000Z",
726 updatedAt: "2026-03-09T10:05:00.000Z",
727 streaming: false,
728 },
729 ],
730 }),
731 ];
732
733 const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
734
735 expect(sorted.map((project) => project.id)).toEqual([
736 ProjectId.make("project-2"),
737 ProjectId.make("project-1"),
738 ]);
739 });
740});
741
742describe("sortScopedProjectsForSidebar", () => {
743 it("keeps identical project ids in different environments separate", () => {
744 const remoteEnvironmentId = EnvironmentId.make("environment-remote");
745 const sharedProjectId = ProjectId.make("shared-project");
746 const projects = [
747 makeProject({
748 environmentId: localEnvironmentId,
749 id: sharedProjectId,
750 title: "Local project",
751 }),
752 makeProject({
753 environmentId: remoteEnvironmentId,
754 id: sharedProjectId,
755 title: "Remote project",
756 }),
757 ];
758 const threads = [
759 makeThread({
760 environmentId: localEnvironmentId,
761 projectId: sharedProjectId,
762 updatedAt: "2026-03-09T10:02:00.000Z",
763 }),
764 makeThread({
765 environmentId: remoteEnvironmentId,
766 projectId: sharedProjectId,
767 updatedAt: "2026-03-09T10:10:00.000Z",
768 }),
769 ];
770
771 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
772
773 expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);
774 });
775
776 it("does not use archived threads as project activity", () => {
777 const projects = [
778 makeProject({
779 id: ProjectId.make("project-visible"),
780 title: "Visible project",
781 updatedAt: "2026-03-09T10:01:00.000Z",
782 }),
783 makeProject({
784 id: ProjectId.make("project-archived"),
785 title: "Archived-only project",
786 updatedAt: "2026-03-09T10:00:00.000Z",
787 }),
788 ];
789 const threads = [
790 makeThread({
791 id: ThreadId.make("thread-visible"),
792 projectId: ProjectId.make("project-visible"),
793 updatedAt: "2026-03-09T10:02:00.000Z",
794 }),
795 makeThread({
796 id: ThreadId.make("thread-archived"),
797 projectId: ProjectId.make("project-archived"),
798 updatedAt: "2026-03-09T10:10:00.000Z",
799 archivedAt: "2026-03-09T10:11:00.000Z",
800 }),
801 ];
802
803 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
804
805 expect(sorted.map((project) => project.title)).toEqual([
806 "Visible project",
807 "Archived-only project",
808 ]);
809 });
810});
811
812describe("sortSidebarV2ProjectGroups", () => {
813 it("does not let a hidden subagent thread reorder projects", () => {
814 const olderProjectId = ProjectId.make("project-older");
815 const newerProjectId = ProjectId.make("project-newer");
816 const olderRootThreadId = ThreadId.make("thread-older-root");
817 const projects = [
818 {
819 ...makeProject({ id: olderProjectId, title: "A older project" }),
820 projectKey: "logical-older",
821 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: olderProjectId }],
822 },
823 {
824 ...makeProject({ id: newerProjectId, title: "Z newer project" }),
825 projectKey: "logical-newer",
826 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: newerProjectId }],
827 },
828 ];
829 const threads = [
830 makeThread({
831 id: olderRootThreadId,
832 projectId: olderProjectId,
833 updatedAt: "2026-03-09T10:01:00.000Z",
834 }),
835 makeThread({
836 id: ThreadId.make("thread-newer-root"),
837 projectId: newerProjectId,
838 updatedAt: "2026-03-09T10:05:00.000Z",
839 }),
840 makeThread({
841 id: ThreadId.make("thread-hidden-subagent"),
842 projectId: olderProjectId,
843 updatedAt: "2026-03-09T10:10:00.000Z",
844 lineage: {
845 rootThreadId: olderRootThreadId,
846 parentThreadId: olderRootThreadId,
847 relationshipToParent: "subagent",
848 },
849 }),
850 ];
851
852 expect(
853 sortSidebarV2ProjectGroups(projects, threads, "updated_at").map(
854 (project) => project.projectKey,
855 ),
856 ).toEqual(["logical-newer", "logical-older"]);
857 });
858});
859
860describe("pinOrderKeyBetween", () => {
861 it("stays strictly ordered under repeated top insertion", () => {
862 let head: string | null = null;
863 const keys: string[] = [];
864 for (let i = 0; i < 100; i += 1) {
865 const key: string = pinOrderKeyBetween(null, head)!;
866 expect(key).not.toBeNull();
867 if (head !== null) expect(key < head).toBe(true);
868 keys.push(key);
869 head = key;
870 }
871 expect(new Set(keys).size).toBe(100);
872 });
873
874 it("stays strictly ordered under repeated middle insertion", () => {
875 let low = pinOrderKeyBetween(null, null)!;
876 let high = pinOrderKeyBetween(low, null)!;
877 for (let i = 0; i < 100; i += 1) {
878 const key: string = pinOrderKeyBetween(low, high)!;
879 expect(low < key && key < high).toBe(true);
880 if (i % 2 === 0) low = key;
881 else high = key;
882 }
883 });
884
885 it("returns null for corrupt or out-of-order bounds instead of throwing", () => {
886 expect(pinOrderKeyBetween("z", "a")).toBeNull();
887 expect(pinOrderKeyBetween("A!", null)).toBeNull();
888 expect(pinOrderKeyBetween(null, "ma")).toBeNull();
889 expect(pinOrderKeyBetween("m", "m")).toBeNull();
890 });
891});
892
893describe("sortPinnedThreadsForSidebar", () => {
894 const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({
895 id: input.id,
896 createdAt: input.createdAt,
897 pinOrderKey: input.pinOrderKey ?? null,
898 });
899
900 it("sorts keyed threads by key ahead of keyless threads in creation order", () => {
901 const sorted = sortPinnedThreadsForSidebar([
902 pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }),
903 pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }),
904 pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }),
905 pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }),
906 ]);
907
908 expect(sorted.map((thread) => thread.id)).toEqual([
909 "first",
910 "second",
911 "keyless-new",
912 "keyless-old",
913 ]);
914 });
915
916 it("breaks equal keys by id so raced writes render identically everywhere", () => {
917 const sorted = sortPinnedThreadsForSidebar([
918 pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }),
919 pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }),
920 ]);
921
922 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
923 });
924});
925
926describe("resolveSidebarSweepKeys", () => {
927 const ordered = ["a", "b", "c", "d", "blocked"];
928 const canSettle = (key: string) => key !== "blocked";
929
930 it("leaves out rows that cannot settle and rows that left the list", () => {
931 expect(resolveSidebarSweepKeys(ordered, "c", "blocked", canSettle)).toEqual(["c", "d"]);
932 expect(resolveSidebarSweepKeys(ordered, "gone", "a", canSettle)).toEqual([]);
933 });
934});
935
936describe("navigation after parking a thread", () => {
937 it.each([
938 ["settle", "settled", null, "thread", true],
939 ["settle", "active", null, "thread", false],
940 ["settle", "settled", null, "other-thread", false],
941 ["snooze", null, "2099-01-01T00:00:00.000Z", "thread", true],
942 ["snooze", null, null, "thread", false],
943 ["snooze", null, "2026-09-12T09:00:00.000Z", "thread", false],
944 ["snooze", null, "2099-01-01T00:00:00.000Z", "thread", false, true],
945 ["snooze", null, "2099-01-01T00:00:00.000Z", "other-thread", false],
946 ] as const)(
947 "%s with state %s / %s on %s navigates: %s",
948 (
949 action,
950 settledOverride,
951 snoozedUntil,
952 currentThreadKey,
953 expected,
954 hasPendingApprovals: boolean = false,
955 ) => {
956 expect(
957 shouldNavigateAfterThreadPark({
958 threadKey: "thread",
959 currentThreadKey,
960 action,
961 now: "2026-09-12T10:00:00.000Z",
962 thread: {
963 settledOverride,
964 snoozedUntil,
965 snoozedAt: null,
966 session: null,
967 latestTurn: null,
968 hasPendingApprovals,
969 hasPendingUserInput: false,
970 },
971 }),
972 ).toBe(expected);
973 },
974 );
975});
976
977describe("unseen completion with background work", () => {
978 it.each([
979 {
980 roster: "dev server",
981 task: { kind: "command" },
982 status: "ready",
983 topStatus: "done",
984 receded: false,
985 pill: "Completed",
986 },
987 {
988 roster: "dev server watchdog",
989 task: { kind: "monitor" },
990 status: "ready",
991 topStatus: "done",
992 receded: false,
993 pill: "Completed",
994 },
995 {
996 roster: "awaited command",
997 task: { kind: "command", awaited: true },
998 status: "waiting",
999 topStatus: "waiting",
1000 receded: true,
1001 pill: "Waiting",
1002 },
1003 ] as const)("presents a completed thread with a $roster roster", (expected) => {
1004 const thread = presentThreadShell(localEnvironmentId, {
1005 ...makeThreadFixture().source,
1006 latestRunId: RunId.make("run-background-completion"),
1007 status: "completed",
1008 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
1009 lastVisitedAt: DateTime.makeUnsafe("2026-06-20T00:59:00.000Z"),
1010 pendingBackgroundTasks: [{ taskId: "background-work", ...expected.task }],
1011 });
1012 const status = resolveSidebarThreadStatus(thread);
1013 const isUnread = hasUnseenCompletion(thread);
1014
1015 expect(isUnread).toBe(true);
1016 expect(status).toBe(expected.status);
1017 expect(resolveSidebarV2TopStatus({ status, isUnread, isWoke: false })).toBe(expected.topStatus);
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});