Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.logic.test.ts

1,240 lines40.5 KB

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 };
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("keeps usage-limit stops Limited and visible until the thread recovers", () => {
276 const limited = {
277 ...runtime,
278 status: "failed" as const,
279 lastError: "Plan limit reached",
280 lastErrorClass: "usage_limit" as const,
281 };
282 expect(resolveSidebarThreadStatus({ ...idle, runtime: limited })).toBe("limited");
283 expect(
284 resolveSidebarThreadStatus({ ...idle, runtime: { ...limited, status: "running" } }),
285 ).toBe("working");
286 expect(
287 resolveSidebarThreadStatus({ ...idle, runtime: { ...limited, status: "completed" } }),
288 ).toBe("ready");
289 expect(resolveSidebarV2TopStatus({ status: "limited", isUnread: false, isWoke: false })).toBe(
290 "limited",
291 );
292 expect(
293 shouldRecedeSidebarThread({
294 status: "limited",
295 isUnread: false,
296 isWoke: false,
297 isActive: false,
298 isSelected: false,
299 }),
300 ).toBe(false);
301 });
302​
303 it("reports failed only while the latest run failed", () => {
304 expect(
305 resolveSidebarThreadStatus({
306 ...idle,
307 runtime: { ...runtime, status: "failed" as const, lastError: "boom" },
308 }),
309 ).toBe("failed");
310 expect(
311 resolveSidebarThreadStatus({
312 ...idle,
313 runtime: { ...runtime, status: "completed" as const, lastError: "persisted" },
314 }),
315 ).toBe("ready");
316 expect(
317 resolveSidebarThreadStatus({
318 ...idle,
319 runtime: { ...runtime, status: "idle" as const, lastError: "persisted" },
320 }),
321 ).toBe("waiting");
322 });
323});
324​
325describe("searchSidebarThreads", () => {
326 const searchThread = (id: string, title: string, project: string) => ({
327 environmentId: localEnvironmentId,
328 id: ThreadId.make(id),
329 title,
330 project,
331 });
332 const threads = [
333 searchThread("thread-1", "Fix workspace search", "Alpha"),
334 searchThread("thread-2", "Review providers", "Workspace"),
335 searchThread("thread-3", "WORKTREE cleanup", "Beta"),
336 ];
337 const contentKeys = (...ids: ReadonlyArray<string>) =>
338 new Set(
339 ids.map((id) =>
340 threadSearchMatchKey({ environmentId: localEnvironmentId, threadId: ThreadId.make(id) }),
341 ),
342 );
343​
344 it("lists a thread matching both title and content once", () => {
345 expect(searchSidebarThreads(threads, "work", contentKeys("thread-1"))).toEqual([
346 threads[0],
347 threads[2],
348 ]);
349 });
350});
351​
352describe("resolveWorkingStartedAt", () => {
353 const runtime = {
354 status: "running" as const,
355 providerName: "Codex",
356 providerInstanceId: ProviderInstanceId.make("codex"),
357 activeRunId: RunId.make("turn-1"),
358 lastError: null,
359 updatedAt: "2026-03-09T10:02:00.000Z",
360 };
361​
362 it("does not invent a start from activity updates when the newest run completed", () => {
363 expect(
364 resolveWorkingStartedAt({
365 latestRun: makeLatestRun(),
366 runtime,
367 }),
368 ).toBeNull();
369 });
370​
371 it.each(["queued", "cancelled"] as const)(
372 "shares the detail timer when a newer run is %s",
373 (status) => {
374 const activityStartedAt = "2026-03-09T10:00:00.000Z";
375 const latestRun = {
376 ...makeLatestRun(),
377 runId: RunId.make("newer-run"),
378 status,
379 startedAt: null,
380 completedAt: status === "queued" ? null : "2026-03-09T10:05:00.000Z",
381 };
382 for (const updatedAt of ["2026-03-09T10:30:00.000Z", "2026-03-09T10:50:00.000Z"]) {
383 const activeRuntime = { ...runtime, updatedAt, activityStartedAt };
384 expect(resolveWorkingStartedAt({ latestRun, runtime: activeRuntime })).toBe(
385 activityStartedAt,
386 );
387 expect(deriveActiveWorkStartedAt(latestRun, activeRuntime, updatedAt)).toBe(
388 activityStartedAt,
389 );
390 }
391 expect(
392 deriveActiveWorkStartedAt(
393 latestRun,
394 { ...runtime, activityStartedAt: null },
395 "2026-03-09T10:50:00.000Z",
396 ),
397 ).toBeNull();
398 },
399 );
400});
401​
402describe("resolveThreadStatusPill", () => {
403 const baseThread = {
404 hasActionableProposedPlan: false,
405 hasPendingApprovals: false,
406 hasPendingUserInput: false,
407 interactionMode: "plan" as const,
408 latestRun: null,
409 lastVisitedAt: undefined,
410 runtime: {
411 status: "running" as const,
412 providerName: "Codex",
413 providerInstanceId: ProviderInstanceId.make("codex"),
414 activeRunId: "turn-1" as never,
415 lastError: null,
416 updatedAt: "2026-03-09T10:00:00.000Z",
417 },
418 };
419​
420 it("shows an active thread wait without a pulse and resumes Working when it ends", () => {
421 const blocked = { ...baseThread, blockedOnThreadWait: true };
422 expect(resolveSidebarThreadStatus(blocked)).toBe("waiting");
423 expect(resolveThreadStatusPill({ thread: blocked })).toMatchObject({
424 label: "Waiting",
425 pulse: false,
426 });
427​
428 const resumed = { ...blocked, blockedOnThreadWait: false };
429 expect(resolveSidebarThreadStatus(resumed)).toBe("working");
430 expect(resolveThreadStatusPill({ thread: resumed })).toMatchObject({
431 label: "Working",
432 pulse: true,
433 });
434 });
435​
436 it("shows waiting for an idle thread with pending background tasks", () => {
437 expect(
438 resolveThreadStatusPill({
439 thread: {
440 ...baseThread,
441 pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],
442 runtime: {
443 ...baseThread.runtime,
444 status: "idle",
445 activeRunId: null,
446 },
447 },
448 }),
449 ).toMatchObject({
450 label: "Waiting",
451 colorClass: "text-sidebar-muted-foreground",
452 dotClass: "bg-sidebar-muted-foreground",
453 pulse: false,
454 });
455 });
456​
457 it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
458 expect(
459 resolveThreadStatusPill({
460 thread: {
461 ...baseThread,
462 hasActionableProposedPlan: true,
463 latestRun: makeLatestRun(),
464 runtime: {
465 ...baseThread.runtime,
466 status: "completed",
467 activeRunId: null,
468 },
469 },
470 }),
471 ).toMatchObject({ label: "Plan Ready", pulse: false });
472 });
473​
474 it("does not manufacture completed state without a client visit marker", () => {
475 expect(
476 resolveThreadStatusPill({
477 thread: {
478 ...baseThread,
479 latestRun: makeLatestRun(),
480 runtime: {
481 ...baseThread.runtime,
482 status: "completed",
483 activeRunId: null,
484 },
485 },
486 }),
487 ).toBeNull();
488 });
489​
490 it("shows completed when there is an unseen completion and no active blocker", () => {
491 expect(
492 resolveThreadStatusPill({
493 thread: {
494 ...baseThread,
495 interactionMode: "default",
496 latestRun: makeLatestRun(),
497 lastVisitedAt: "2026-03-09T10:04:00.000Z",
498 runtime: {
499 ...baseThread.runtime,
500 status: "completed",
501 activeRunId: null,
502 },
503 },
504 }),
505 ).toMatchObject({ label: "Completed", pulse: false });
506 });
507​
508 it("shows failed, not completed, when the unseen run failed", () => {
509 expect(
510 resolveThreadStatusPill({
511 thread: {
512 ...baseThread,
513 interactionMode: "default",
514 latestRun: { ...makeLatestRun(), status: "failed" },
515 lastVisitedAt: "2026-03-09T10:04:00.000Z",
516 runtime: {
517 ...baseThread.runtime,
518 status: "failed",
519 activeRunId: null,
520 lastError: "Provider turn failed.",
521 },
522 },
523 }),
524 ).toMatchObject({ label: "Failed", pulse: false });
525 });
526​
527 it("shows failed, not plan ready, when a plan run proposed a plan and then failed", () => {
528 expect(
529 resolveThreadStatusPill({
530 thread: {
531 ...baseThread,
532 hasActionableProposedPlan: true,
533 latestRun: { ...makeLatestRun(), status: "failed" },
534 lastVisitedAt: "2026-03-09T10:04:00.000Z",
535 runtime: { ...baseThread.runtime, status: "failed", activeRunId: null },
536 },
537 }),
538 ).toMatchObject({ label: "Failed" });
539 });
540​
541 it("drops the failed pill once the failure has been seen", () => {
542 expect(
543 resolveThreadStatusPill({
544 thread: {
545 ...baseThread,
546 interactionMode: "default",
547 latestRun: { ...makeLatestRun(), status: "failed" },
548 lastVisitedAt: "2026-03-09T10:06:00.000Z",
549 runtime: { ...baseThread.runtime, status: "failed", activeRunId: null },
550 },
551 }),
552 ).toBeNull();
553 });
554});
555​
556describe("resolveProjectStatusIndicator", () => {
557 it("ranks waiting below active work and above plan-ready", () => {
558 const waiting = {
559 label: "Waiting" as const,
560 colorClass: "text-sidebar-muted-foreground",
561 dotClass: "bg-sidebar-muted-foreground",
562 pulse: false,
563 };
564​
565 expect(
566 resolveProjectStatusIndicator([
567 waiting,
568 {
569 label: "Working",
570 colorClass: "text-sky-600",
571 dotClass: "bg-sky-500",
572 pulse: true,
573 },
574 ]),
575 ).toMatchObject({ label: "Working" });
576 expect(
577 resolveProjectStatusIndicator([
578 {
579 label: "Plan Ready",
580 colorClass: "text-violet-600",
581 dotClass: "bg-violet-500",
582 pulse: false,
583 },
584 waiting,
585 ]),
586 ).toMatchObject({ label: "Waiting" });
587 });
588});
589​
590function makeProject(overrides: Partial<Project> = {}): Project {
591 const { defaultModelSelection, ...rest } = overrides;
592 return {
593 id: ProjectId.make("project-1"),
594 environmentId: localEnvironmentId,
595 title: "Project",
596 workspaceRoot: "/tmp/project",
597 repositoryIdentity: null,
598 defaultModelSelection: {
599 instanceId: ProviderInstanceId.make("codex"),
600 model: "gpt-5.4",
601 ...defaultModelSelection,
602 },
603 createdAt: "2026-03-09T10:00:00.000Z",
604 updatedAt: "2026-03-09T10:00:00.000Z",
605 scripts: [],
606 ...rest,
607 };
609​
610function makeThread(overrides: ThreadFixtureOverrides = {}): Thread {
611 return makeThreadFixture({
612 id: ThreadId.make("thread-1"),
613 environmentId: localEnvironmentId,
614 projectId: ProjectId.make("project-1"),
615 title: "Thread",
616 modelSelection: {
617 instanceId: ProviderInstanceId.make("codex"),
618 model: "gpt-5.4",
619 ...overrides?.modelSelection,
620 },
621 runtimeMode: DEFAULT_RUNTIME_MODE,
622 interactionMode: DEFAULT_INTERACTION_MODE,
623 runtime: null,
624 messages: [],
625 proposedPlans: [],
626 createdAt: "2026-03-09T10:00:00.000Z",
627 archivedAt: null,
628 settledOverride: null,
629 settledAt: null,
630 deletedAt: null,
631 updatedAt: "2026-03-09T10:00:00.000Z",
632 latestRun: null,
633 branch: null,
634 worktreePath: null,
635 ...overrides,
636 });
638​
639describe("getFallbackThreadIdAfterDelete", () => {
640 it("skips other threads being deleted in the same action", () => {
641 const fallbackThreadId = getFallbackThreadIdAfterDelete({
642 threads: [
643 makeThread({
644 id: ThreadId.make("thread-active"),
645 projectId: ProjectId.make("project-1"),
646 createdAt: "2026-03-09T10:05:00.000Z",
647 messages: [],
648 }),
649 makeThread({
650 id: ThreadId.make("thread-newest"),
651 projectId: ProjectId.make("project-1"),
652 createdAt: "2026-03-09T10:10:00.000Z",
653 messages: [],
654 }),
655 makeThread({
656 id: ThreadId.make("thread-next"),
657 projectId: ProjectId.make("project-1"),
658 createdAt: "2026-03-09T10:07:00.000Z",
659 messages: [],
660 }),
661 ],
662 deletedThreadId: ThreadId.make("thread-active"),
663 deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]),
664 sortOrder: "created_at",
665 });
666​
667 expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
668 });
669});
670describe("sortProjectsForSidebar", () => {
671 it("sorts projects by the most recent user message across their threads", () => {
672 const projects = [
673 makeProject({ id: ProjectId.make("project-1"), title: "Older project" }),
674 makeProject({ id: ProjectId.make("project-2"), title: "Newer project" }),
675 ];
676 const threads = [
677 makeThread({
678 projectId: ProjectId.make("project-1"),
679 updatedAt: "2026-03-09T10:20:00.000Z",
680 messages: [
681 {
682 id: "message-1" as never,
683 role: "user",
684 text: "older project user message",
685 runId: null,
686 createdAt: "2026-03-09T10:01:00.000Z",
687 updatedAt: "2026-03-09T10:01:00.000Z",
688 streaming: false,
689 },
690 ],
691 }),
692 makeThread({
693 id: ThreadId.make("thread-2"),
694 projectId: ProjectId.make("project-2"),
695 updatedAt: "2026-03-09T10:05:00.000Z",
696 messages: [
697 {
698 id: "message-2" as never,
699 role: "user",
700 text: "newer project user message",
701 runId: null,
702 createdAt: "2026-03-09T10:05:00.000Z",
703 updatedAt: "2026-03-09T10:05:00.000Z",
704 streaming: false,
705 },
706 ],
707 }),
708 ];
709​
710 const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
711​
712 expect(sorted.map((project) => project.id)).toEqual([
713 ProjectId.make("project-2"),
714 ProjectId.make("project-1"),
715 ]);
716 });
717});
718​
719describe("sortScopedProjectsForSidebar", () => {
720 it("keeps identical project ids in different environments separate", () => {
721 const remoteEnvironmentId = EnvironmentId.make("environment-remote");
722 const sharedProjectId = ProjectId.make("shared-project");
723 const projects = [
724 makeProject({
725 environmentId: localEnvironmentId,
726 id: sharedProjectId,
727 title: "Local project",
728 }),
729 makeProject({
730 environmentId: remoteEnvironmentId,
731 id: sharedProjectId,
732 title: "Remote project",
733 }),
734 ];
735 const threads = [
736 makeThread({
737 environmentId: localEnvironmentId,
738 projectId: sharedProjectId,
739 updatedAt: "2026-03-09T10:02:00.000Z",
740 }),
741 makeThread({
742 environmentId: remoteEnvironmentId,
743 projectId: sharedProjectId,
744 updatedAt: "2026-03-09T10:10:00.000Z",
745 }),
746 ];
747​
748 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
749​
750 expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);
751 });
752​
753 it("does not use archived threads as project activity", () => {
754 const projects = [
755 makeProject({
756 id: ProjectId.make("project-visible"),
757 title: "Visible project",
758 updatedAt: "2026-03-09T10:01:00.000Z",
759 }),
760 makeProject({
761 id: ProjectId.make("project-archived"),
762 title: "Archived-only project",
763 updatedAt: "2026-03-09T10:00:00.000Z",
764 }),
765 ];
766 const threads = [
767 makeThread({
768 id: ThreadId.make("thread-visible"),
769 projectId: ProjectId.make("project-visible"),
770 updatedAt: "2026-03-09T10:02:00.000Z",
771 }),
772 makeThread({
773 id: ThreadId.make("thread-archived"),
774 projectId: ProjectId.make("project-archived"),
775 updatedAt: "2026-03-09T10:10:00.000Z",
776 archivedAt: "2026-03-09T10:11:00.000Z",
777 }),
778 ];
779​
780 const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
781​
782 expect(sorted.map((project) => project.title)).toEqual([
783 "Visible project",
784 "Archived-only project",
785 ]);
786 });
787});
788​
789describe("sortSidebarV2ProjectGroups", () => {
790 it("does not let a hidden subagent thread reorder projects", () => {
791 const olderProjectId = ProjectId.make("project-older");
792 const newerProjectId = ProjectId.make("project-newer");
793 const olderRootThreadId = ThreadId.make("thread-older-root");
794 const projects = [
795 {
796 ...makeProject({ id: olderProjectId, title: "A older project" }),
797 projectKey: "logical-older",
798 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: olderProjectId }],
799 },
800 {
801 ...makeProject({ id: newerProjectId, title: "Z newer project" }),
802 projectKey: "logical-newer",
803 memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: newerProjectId }],
804 },
805 ];
806 const threads = [
807 makeThread({
808 id: olderRootThreadId,
809 projectId: olderProjectId,
810 updatedAt: "2026-03-09T10:01:00.000Z",
811 }),
812 makeThread({
813 id: ThreadId.make("thread-newer-root"),
814 projectId: newerProjectId,
815 updatedAt: "2026-03-09T10:05:00.000Z",
816 }),
817 makeThread({
818 id: ThreadId.make("thread-hidden-subagent"),
819 projectId: olderProjectId,
820 updatedAt: "2026-03-09T10:10:00.000Z",
821 lineage: {
822 rootThreadId: olderRootThreadId,
823 parentThreadId: olderRootThreadId,
824 relationshipToParent: "subagent",
825 },
826 }),
827 ];
828​
829 expect(
830 sortSidebarV2ProjectGroups(projects, threads, "updated_at").map(
831 (project) => project.projectKey,
832 ),
833 ).toEqual(["logical-newer", "logical-older"]);
834 });
835});
836​
837describe("pinOrderKeyBetween", () => {
838 it("stays strictly ordered under repeated top insertion", () => {
839 let head: string | null = null;
840 const keys: string[] = [];
841 for (let i = 0; i < 100; i += 1) {
842 const key: string = pinOrderKeyBetween(null, head)!;
843 expect(key).not.toBeNull();
844 if (head !== null) expect(key < head).toBe(true);
845 keys.push(key);
846 head = key;
847 }
848 expect(new Set(keys).size).toBe(100);
849 });
850​
851 it("stays strictly ordered under repeated middle insertion", () => {
852 let low = pinOrderKeyBetween(null, null)!;
853 let high = pinOrderKeyBetween(low, null)!;
854 for (let i = 0; i < 100; i += 1) {
855 const key: string = pinOrderKeyBetween(low, high)!;
856 expect(low < key && key < high).toBe(true);
857 if (i % 2 === 0) low = key;
858 else high = key;
859 }
860 });
861​
862 it("returns null for corrupt or out-of-order bounds instead of throwing", () => {
863 expect(pinOrderKeyBetween("z", "a")).toBeNull();
864 expect(pinOrderKeyBetween("A!", null)).toBeNull();
865 expect(pinOrderKeyBetween(null, "ma")).toBeNull();
866 expect(pinOrderKeyBetween("m", "m")).toBeNull();
867 });
868});
869​
870describe("sortPinnedThreadsForSidebar", () => {
871 const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({
872 id: input.id,
873 createdAt: input.createdAt,
874 pinOrderKey: input.pinOrderKey ?? null,
875 });
876​
877 it("sorts keyed threads by key ahead of keyless threads in creation order", () => {
878 const sorted = sortPinnedThreadsForSidebar([
879 pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }),
880 pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }),
881 pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }),
882 pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }),
883 ]);
884​
885 expect(sorted.map((thread) => thread.id)).toEqual([
886 "first",
887 "second",
888 "keyless-new",
889 "keyless-old",
890 ]);
891 });
892​
893 it("breaks equal keys by id so raced writes render identically everywhere", () => {
894 const sorted = sortPinnedThreadsForSidebar([
895 pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }),
896 pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }),
897 ]);
898​
899 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
900 });
901});
902​
903describe("resolveSidebarSweepKeys", () => {
904 const ordered = ["a", "b", "c", "d", "blocked"];
905 const canSettle = (key: string) => key !== "blocked";
906​
907 it("leaves out rows that cannot settle and rows that left the list", () => {
908 expect(resolveSidebarSweepKeys(ordered, "c", "blocked", canSettle)).toEqual(["c", "d"]);
909 expect(resolveSidebarSweepKeys(ordered, "gone", "a", canSettle)).toEqual([]);
910 });
911});
912​
913describe("navigation after parking a thread", () => {
914 it.each([
915 ["settle", "settled", null, "thread", true],
916 ["settle", "active", null, "thread", false],
917 ["settle", "settled", null, "other-thread", false],
918 ["snooze", null, "2099-01-01T00:00:00.000Z", "thread", true],
919 ["snooze", null, null, "thread", false],
920 ["snooze", null, "2026-09-12T09:00:00.000Z", "thread", false],
921 ["snooze", null, "2099-01-01T00:00:00.000Z", "thread", false, true],
922 ["snooze", null, "2099-01-01T00:00:00.000Z", "other-thread", false],
923 ] as const)(
924 "%s with state %s / %s on %s navigates: %s",
925 (
926 action,
927 settledOverride,
928 snoozedUntil,
929 currentThreadKey,
930 expected,
931 hasPendingApprovals: boolean = false,
932 ) => {
933 expect(
934 shouldNavigateAfterThreadPark({
935 threadKey: "thread",
936 currentThreadKey,
937 action,
938 now: "2026-09-12T10:00:00.000Z",
939 thread: {
940 settledOverride,
941 snoozedUntil,
942 snoozedAt: null,
943 session: null,
944 latestTurn: null,
945 hasPendingApprovals,
946 hasPendingUserInput: false,
947 },
948 }),
949 ).toBe(expected);
950 },
951 );
952});
953​
954describe("unseen completion with background work", () => {
955 it.each([
956 { kind: "command", status: "ready", topStatus: "done", receded: false, pill: "Completed" },
957 { kind: "monitor", status: "waiting", topStatus: "waiting", receded: true, pill: "Waiting" },
958 ] as const)("presents a completed thread with a $kind roster", (expected) => {
959 const thread = presentThreadShell(localEnvironmentId, {
960 ...makeThreadFixture().source,
961 latestRunId: RunId.make("run-background-completion"),
962 status: "completed",
963 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
964 lastVisitedAt: DateTime.makeUnsafe("2026-06-20T00:59:00.000Z"),
965 pendingBackgroundTasks: [{ taskId: "background-work", kind: expected.kind }],
966 });
967 const status = resolveSidebarThreadStatus(thread);
968 const isUnread = hasUnseenCompletion(thread);
969​
970 expect(isUnread).toBe(true);
971 expect(status).toBe(expected.status);
972 expect(resolveSidebarV2TopStatus({ status, isUnread, isWoke: false })).toBe(expected.topStatus);
973 expect(
974 shouldRecedeSidebarThread({
975 status,
976 isUnread,
977 isWoke: false,
978 isActive: false,
979 isSelected: false,
980 }),
981 ).toBe(expected.receded);
982 expect(isSidebarThreadWorking(thread)).toBe(expected.receded);
983 expect(resolveThreadStatusPill({ thread })).toMatchObject({ label: expected.pill });
984 });
985});
986​
987describe("Working shelf (beta)", () => {
988 const runtime = {
989 status: "running" as const,
990 activeRunId: null,
991 providerInstanceId: ProviderInstanceId.make("codex"),
992 providerName: "Codex",
993 lastError: null,
994 updatedAt: "2026-03-09T10:00:00.000Z",
995 };
996 const backgroundTask = { taskId: "bg-1", description: "Watch build", kind: "monitor" as const };
997 const idle = {
998 hasActionableProposedPlan: false,
999 hasPendingApprovals: false,
1000 hasPendingUserInput: false,
1001 interactionMode: "default" as const,
1002 latestRun: makeLatestRun(),
1003 runtime: null,
1004 };
1005 const waiting = {
1006 ...idle,
1007 runtime: { ...runtime, status: "idle" as const },
1008 pendingBackgroundTasks: [backgroundTask],
1009 };
1010​
1011 it("folds away running threads and threads waiting on background work only", () => {
1012 expect(isSidebarThreadWorking({ ...idle, runtime })).toBe(true);
1013 expect(isSidebarThreadWorking(waiting)).toBe(true);
1014 expect(isSidebarThreadWorking(idle)).toBe(false);
1015 expect(isSidebarThreadWorking({ ...idle, runtime, hasPendingApprovals: true })).toBe(false);
1016 expect(isSidebarThreadWorking({ ...idle, runtime, hasPendingUserInput: true })).toBe(false);
1017 expect(
1018 isSidebarThreadWorking({
1019 ...waiting,
1020 runtime: { ...runtime, status: "failed" as const, lastError: "boom" },
1021 }),
1022 ).toBe(false);
1023 });
1024​
1025 it("keeps a ready plan in the inbox while background work runs", () => {
1026 expect(
1027 isSidebarThreadWorking({
1028 ...waiting,
1029 interactionMode: "plan",
1030 hasActionableProposedPlan: true,
1031 }),
1032 ).toBe(false);
1033 });
1034​
1035 describe("sortInboxThreadsByReturn", () => {
1036 const thread = (
1037 id: string,
1038 input: { createdAt: string; completedAt?: string | null; unsettledAt?: string },
1039 ) => ({
1040 id: ThreadId.make(id),
1041 environmentId: localEnvironmentId,
1042 createdAt: input.createdAt,
1043 unsettledAt: input.unsettledAt ?? null,
1044 latestRun:
1045 input.completedAt === undefined
1046 ? null
1047 : { ...makeLatestRun({ completedAt: input.completedAt }), requestedAt: input.createdAt },
1048 });
1049​
1050 it("puts the thread that finished last on top, whatever its age", () => {
1051 const sorted = sortInboxThreadsByReturn([
1052 thread("new", { createdAt: "2026-03-09T11:00:00.000Z" }),
1053 thread("old-finished-now", {
1054 createdAt: "2026-03-01T09:00:00.000Z",
1055 completedAt: "2026-03-09T12:00:00.000Z",
1056 }),
1057 thread("reopened", {
1058 createdAt: "2026-03-02T09:00:00.000Z",
1059 unsettledAt: "2026-03-09T11:30:00.000Z",
1060 }),
1061 ]);
1062 expect(sorted.map((entry) => entry.id)).toEqual(["old-finished-now", "reopened", "new"]);
1063 });
1064​
1065 it("counts a return the server does not stamp, like an approval request", () => {
1066 const waiting = thread("asks-approval", {
1067 createdAt: "2026-03-09T09:00:00.000Z",
1068 completedAt: null,
1069 });
1070 const finished = thread("finished", {
1071 createdAt: "2026-03-09T09:30:00.000Z",
1072 completedAt: "2026-03-09T11:00:00.000Z",
1073 });
1074 expect(sortInboxThreadsByReturn([finished, waiting]).map((entry) => entry.id)).toEqual([
1075 "finished",
1076 "asks-approval",
1077 ]);
1078 expect(
1079 sortInboxThreadsByReturn([finished, waiting], (entry) =>
1080 entry === waiting ? Date.parse("2026-03-09T11:05:00.000Z") : undefined,
1081 ).map((entry) => entry.id),
1082 ).toEqual(["asks-approval", "finished"]);
1083 });
1084 });
1085​
1086 describe("dragging", () => {
1087 const marker = (name: SidebarListMarker): SidebarListItem => ({ kind: "marker", marker: name });
1088 const row = (key: string, section: SidebarSection): SidebarListItem => ({
1089 kind: "thread",
1090 key,
1091 section,
1092 });
1093 const items: readonly SidebarListItem[] = [
1094 marker("pinned-header"),
1095 row("p1", "pinned"),
1096 marker("pinned-divider"),
1097 row("a1", "active"),
1098 row("a2", "active"),
1099 marker("working-header"),
1100 row("w1", "working"),
1101 marker("settled-header"),
1102 row("s1", "settled"),
1103 ];
1104​
1105 it("never drops into the Working shelf, and keeps it out of the inbox order", () => {
1106 expect(resolveSidebarDropTarget(items, "a1", "w1")).toBeNull();
1107 expect(resolveSidebarDropTarget(items, "p1", "a2")).toEqual({
1108 section: "active",
1109 pinnedOrder: [],
1110 activeOrder: ["a1", "a2", "p1"],
1111 });
1112 expect(resolveSidebarDropVerb("active", "working")).toBeNull();
1113 });
1114​
1115 it.each([
1116 ["pinned", "p1"],
1117 ["active", "a2"],
1118 ["settled", "s1"],
1119 ] as const)(
1120 "does not move a Working thread into %s when its reference drag ends in the sidebar",
1121 (section, overKey) => {
1122 const target = resolveSidebarDropTarget(items, "w1", overKey);
1123 expect(target?.section).toBe(section);
1124 expect(
1125 planSidebarThreadDrop({
1126 activeKey: "w1",
1127 activeSection: "working",
1128 target: target!,
1129 pinnedOrder: ["p1"],
1130 pinnedKeysById: new Map([["p1", "m"]]),
1131 activeOrder: ["a1", "a2"],
1132 activeKeysById: new Map([
1133 ["a1", "f"],
1134 ["a2", "t"],
1135 ]),
1136 activeTimeOrdered: true,
1137 }),
1138 ).toEqual({ kind: "none" });
1139 },
1140 );
1141​
1142 it("arranges the rows it can write when another row's server cannot store an order", () => {
1143 const plan = planSidebarThreadDrop({
1144 activeKey: "a2",
1145 activeSection: "active",
1146 target: {
1147 section: "active",
1148 pinnedOrder: [],
1149 activeOrder: ["offline", "a2", "a1"],
1150 },
1151 pinnedOrder: [],
1152 pinnedKeysById: new Map(),
1153 activeOrder: ["offline", "a1", "a2"],
1154 activeKeysById: new Map([
1155 ["offline", null],
1156 ["a1", null],
1157 ["a2", null],
1158 ]),
1159 activeReorderableKeys: new Set(["a1", "a2"]),
1160 });
1161 expect(plan.kind).toBe("move-active");
1162 if (plan.kind !== "move-active") return;
1163 expect(plan.assignments.map(({ id }) => id)).toEqual(["a2", "a1"]);
1164 const [a2, a1] = plan.assignments.map(({ orderKey }) => orderKey);
1165 expect(a2! < a1!).toBe(true);
1166​
1167 const above = planSidebarThreadDrop({
1168 activeKey: "a2",
1169 activeSection: "active",
1170 target: { section: "active", pinnedOrder: [], activeOrder: ["a2", "offline"] },
1171 pinnedOrder: [],
1172 pinnedKeysById: new Map(),
1173 activeOrder: ["offline", "a2"],
1174 activeKeysById: new Map([
1175 ["offline", "m"],
1176 ["a2", "t"],
1177 ]),
1178 activeReorderableKeys: new Set(["a2"]),
1179 });
1180 expect(above.kind === "move-active" && above.assignments[0]!.orderKey < "m").toBe(true);
1181 });
1182​
1183 it("only changes lifecycle when the inbox is time-ordered", () => {
1184 const base = {
1185 pinnedOrder: ["p1"],
1186 pinnedKeysById: new Map([["p1", "m"]]),
1187 activeOrder: ["a1", "a2"],
1188 activeKeysById: new Map([
1189 ["a1", "f"],
1190 ["a2", "t"],
1191 ]),
1192 activeTimeOrdered: true,
1193 };
1194 expect(
1195 planSidebarThreadDrop({
1196 ...base,
1197 activeKey: "a1",
1198 activeSection: "active",
1199 target: { section: "active", pinnedOrder: ["p1"], activeOrder: ["a2", "a1"] },
1200 }),
1201 ).toEqual({ kind: "none" });
1202 expect(
1203 planSidebarThreadDrop({
1204 ...base,
1205 activeKey: "p1",
1206 activeSection: "pinned",
1207 target: { section: "active", pinnedOrder: [], activeOrder: ["a1", "p1", "a2"] },
1208 }),
1209 ).toEqual({
1210 kind: "move-active",
1211 order: null,
1212 assignments: [],
1213 unpin: true,
1214 unsettle: false,
1215 unsnooze: false,
1216 });
1217 });
1218 });
1219});
1220​
1221describe("pendingSidebarRouteReveal", () => {
1222 it("keeps a revealed thread settled across a mount that reads no route params", () => {
1223 const reveal = { observedKey: null, pendingKey: null };
1224 expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBe("env:a1");
1225 completeSidebarRouteReveal(reveal);
1226​
1227 // Back from Settings: location commits before the thread match does.
1228 expect(pendingSidebarRouteReveal(reveal, null)).toBeNull();
1229 expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBeNull();
1230​
1231 expect(pendingSidebarRouteReveal(reveal, "env:b1")).toBe("env:b1");
1232 });
1233​
1234 it("keeps a pending reveal through a render without route params", () => {
1235 const reveal = { observedKey: null, pendingKey: null };
1236 pendingSidebarRouteReveal(reveal, "env:a1");
1237 expect(pendingSidebarRouteReveal(reveal, null)).toBeNull();
1238 expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBe("env:a1");
1239 });
1240});