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

Sidebar.logic.test.ts

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