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

Sidebar.logic.test.ts

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