Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agentic-ide): reorder threads by drag and archive them per project

rubenluetke10-beep26395fdd0045
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx
index 9a64617062..aacfc9932b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import { Check, Folder, FolderOpen, Loader2, Mic, MoreHorizontal, Pencil, Plus, SquarePlus, Trash2, X } from "lucide-react";
+import { Archive, ArchiveRestore, Check, ChevronDown, ChevronRight, Folder, FolderOpen, Loader2, Mic, MoreHorizontal, Pencil, Plus, SquarePlus, Trash2, X } from "lucide-react";
import { AgentMark } from "@/components/agentic/AgentMark";
import { patchAgentChatSession, type AgentChatSession } from "@/lib/agentChatApi";
import type { IdeProject } from "@/lib/agenticIdeApi";
@@ -8,13 +8,15 @@ import { useEventStore } from "@/store/events";
import { useIdeProjectsStore } from "@/store/ideProjects";
import { useIdeThreadsStore } from "@/store/ideThreads";
import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "./ThreadPopover";
-import { shortAge, threadStatus, threadTitle, threadsByProject, useThreadChatStore, type ThreadStatus } from "./threadModel";
+import { arrangeThreads, moveThreadId, shortAge, threadStatus, threadTitle, threadsByProject, useThreadChatStore, type ThreadStatus } from "./threadModel";
const EXPANSION_KEY = "jarvis.ide.threadExpansion.v1";
/** Threads a project shows before "Show more". */
const FOLDED_COUNT = 6;
/** How often the list asks for fresh session rows while it is on screen. */
const POLL_MS = 4000;
+/** What a dragged thread row carries, so only a thread row is a valid drop. */
+const THREAD_DRAG_MIME = "application/x-jarvis-thread";
function readExpansion(): Record<string, boolean> {
try {
@@ -48,7 +50,9 @@ function StatusMark({ status }: { status: ThreadStatus }) {
* The sidebar while the IDE shows threads: every project with its threads,
* each named by the title its coding CLI gave the conversation and marked
* with that CLI's logo. A project row opens and folds; its "+" starts a new
- * thread in it.
+ * thread in it. Threads are dragged (or moved with Alt+arrow keys) into the
+ * person's own order, and archived from the row menu into a folded
+ * "Archived" list under their project, from where they come back.
*/
export function ThreadTree() {
const projects = useIdeProjectsStore((state) => state.projects);
@@ -64,10 +68,18 @@ export function ThreadTree() {
const openThread = useIdeThreadsStore((state) => state.openThread);
const newThread = useIdeThreadsStore((state) => state.newThread);
const forgetThread = useIdeThreadsStore((state) => state.forgetThread);
+ const archived = useIdeThreadsStore((state) => state.archived);
+ const order = useIdeThreadsStore((state) => state.order);
+ const archiveThread = useIdeThreadsStore((state) => state.archiveThread);
+ const restoreThread = useIdeThreadsStore((state) => state.restoreThread);
+ const setThreadOrder = useIdeThreadsStore((state) => state.setThreadOrder);
const [expansion, setExpansion] = useState(readExpansion);
const [showAll, setShowAll] = useState<Record<string, boolean>>({});
const [renaming, setRenaming] = useState<{ sessionId: string; title: string } | null>(null);
const [menu, setMenu] = useState<{ sessionId: string; projectId: string } | null>(null);
+ const [archiveOpen, setArchiveOpen] = useState<Record<string, boolean>>({});
+ const [dragged, setDragged] = useState<{ sessionId: string; projectId: string } | null>(null);
+ const [dropTarget, setDropTarget] = useState<{ sessionId: string; before: boolean } | null>(null);
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const menuAnchor = useRef<HTMLElement | null>(null);
@@ -112,6 +124,13 @@ export function ThreadTree() {
}
};
+ const move = (projectId: string, ids: readonly string[], sourceId: string, targetId: string, before: boolean) => {
+ const next = moveThreadId(ids, sourceId, targetId, before);
+ if (next.some((id, index) => id !== ids[index])) setThreadOrder(projectId, next);
+ };
+
+ const clearDrag = () => { setDragged(null); setDropTarget(null); };
+
const remove = async (sessionId: string) => {
setConfirmDelete(null);
setBusy(sessionId);
@@ -124,7 +143,12 @@ export function ThreadTree() {
};
const projectRow = (project: IdeProject) => {
- const threads = grouped.get(project.id) ?? [];
+ const all = grouped.get(project.id) ?? [];
+ const threads = arrangeThreads(all.filter((thread) => !(thread.session_id in archived)), order[project.id]);
+ const stored = all.filter((thread) => thread.session_id in archived)
+ .sort((a, b) => (archived[b.session_id] ?? 0) - (archived[a.session_id] ?? 0));
+ const ids = threads.map((thread) => thread.session_id);
+ const archiveShown = archiveOpen[project.id] ?? false;
const draftHere = selection.sessionId === null && selection.projectId === project.id;
const open = expansion[project.id] ?? (threads.length > 0 || draftHere);
const shown = showAll[project.id] ? threads : threads.slice(0, FOLDED_COUNT);
@@ -170,8 +194,46 @@ export function ThreadTree() {
className="rounded p-1 text-muted-foreground hover:text-foreground"><X className="h-4 w-4" /></button>
</form>;
}
+ const dropHere = dropTarget?.sessionId === session.session_id ? dropTarget : null;
return <div key={session.session_id} data-testid={`thread-row-${session.session_id}`}
- className={cn("group/thread relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted", (selected || menuOpen) && "bg-muted")}
+ draggable
+ onDragStart={(event) => {
+ event.dataTransfer.setData(THREAD_DRAG_MIME, session.session_id);
+ event.dataTransfer.effectAllowed = "move";
+ setDragged({ sessionId: session.session_id, projectId: project.id });
+ }}
+ onDragEnd={clearDrag}
+ onDragOver={(event) => {
+ // A thread moves within its own project; a drop elsewhere is no drop.
+ if (!dragged || dragged.projectId !== project.id || dragged.sessionId === session.session_id) return;
+ if (!event.dataTransfer.types.includes(THREAD_DRAG_MIME)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ const rect = event.currentTarget.getBoundingClientRect();
+ const before = event.clientY - rect.top < rect.height / 2;
+ setDropTarget((current) => current?.sessionId === session.session_id && current.before === before ? current : { sessionId: session.session_id, before });
+ }}
+ onDragLeave={(event) => {
+ const next = event.relatedTarget as Node | null;
+ if (next && event.currentTarget.contains(next)) return;
+ setDropTarget((current) => current?.sessionId === session.session_id ? null : current);
+ }}
+ onDrop={(event) => {
+ if (!dragged || dragged.projectId !== project.id) return;
+ event.preventDefault();
+ const rect = event.currentTarget.getBoundingClientRect();
+ const before = event.clientY - rect.top < rect.height / 2;
+ const sourceId = dragged.sessionId;
+ clearDrag();
+ move(project.id, ids, sourceId, session.session_id, before);
+ }}
+ className={cn(
+ "group/thread relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted",
+ (selected || menuOpen) && "bg-muted",
+ dragged?.sessionId === session.session_id && "opacity-40",
+ dropHere?.before && "before:absolute before:-top-0.5 before:left-2 before:right-2 before:h-0.5 before:rounded-full before:bg-primary",
+ dropHere && !dropHere.before && "after:absolute after:-bottom-0.5 after:left-2 after:right-2 after:h-0.5 after:rounded-full after:bg-primary",
+ )}
onContextMenu={(event) => {
event.preventDefault();
// Keep the app-wide edit menu (EditContextMenu) from opening on top.
@@ -182,7 +244,14 @@ export function ThreadTree() {
<button type="button" aria-current={selected ? "page" : undefined}
onClick={() => openThread(session.session_id, project.id)}
onDoubleClick={() => setRenaming({ sessionId: session.session_id, title: threadTitle(session) })}
- title={threadTitle(session)}
+ onKeyDown={(event) => {
+ if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return;
+ event.preventDefault();
+ const index = ids.indexOf(session.session_id);
+ const neighbour = ids[event.key === "ArrowUp" ? index - 1 : index + 1];
+ if (neighbour) move(project.id, ids, session.session_id, neighbour, event.key === "ArrowUp");
+ }}
+ title={`${threadTitle(session)} — drag to reorder, or press Alt plus arrow keys to move`}
className={cn(
"flex min-h-8 min-w-0 flex-1 items-center gap-2 rounded-md py-1 pl-8 pr-2 text-left text-[15px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
selected ? "text-foreground-strong" : "text-foreground",
@@ -222,11 +291,52 @@ export function ThreadTree() {
className="flex min-h-7 items-center gap-2 rounded-md pl-8 text-left text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Plus aria-hidden className="h-3.5 w-3.5" />Start a thread
</button>}
+ {stored.length > 0 && <button type="button" aria-expanded={archiveShown}
+ data-testid={`thread-archived-${project.id}`}
+ onClick={() => setArchiveOpen((current) => ({ ...current, [project.id]: !archiveShown }))}
+ className="flex min-h-7 items-center gap-1 rounded-md pl-8 text-left text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {archiveShown ? <ChevronDown aria-hidden className="h-3.5 w-3.5" /> : <ChevronRight aria-hidden className="h-3.5 w-3.5" />}
+ Archived ({stored.length})
+ </button>}
+ {archiveShown && stored.map((session) => {
+ const selected = session.session_id === openSessionId && selection.sessionId !== null;
+ const menuOpen = menu?.sessionId === session.session_id;
+ return <div key={session.session_id} data-testid={`thread-archived-row-${session.session_id}`}
+ className={cn("group/thread relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted", (selected || menuOpen) && "bg-muted")}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ menuAnchor.current = event.currentTarget;
+ setMenu({ sessionId: session.session_id, projectId: project.id });
+ }}>
+ <button type="button" aria-current={selected ? "page" : undefined}
+ onClick={() => openThread(session.session_id, project.id)} title={threadTitle(session)}
+ className="flex min-h-8 min-w-0 flex-1 items-center gap-2 rounded-md py-1 pl-8 pr-2 text-left text-[15px] text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <span className="min-w-0 flex-1 truncate">{threadTitle(session)}</span>
+ {busy === session.session_id
+ ? <Loader2 aria-hidden className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />
+ : <span className="shrink-0 text-xs tabular-nums transition-opacity group-hover/thread:opacity-0 [@media(hover:none)]:opacity-0">{shortAge(session.updated_ms)}</span>}
+ </button>
+ <div className={cn(
+ "absolute inset-y-0 right-0 flex items-center rounded-r-md bg-gradient-to-l from-muted from-60% to-transparent pl-5 pr-1 transition-opacity",
+ menuOpen ? "opacity-100" : "pointer-events-none opacity-0 group-hover/thread:pointer-events-auto group-hover/thread:opacity-100 group-focus-within/thread:pointer-events-auto group-focus-within/thread:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",
+ )}>
+ <button type="button" aria-label={`Restore ${threadTitle(session)}`} title="Restore"
+ onClick={() => restoreThread(session.session_id)}
+ className="rounded p-1 text-muted-foreground hover:bg-background/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <ArchiveRestore className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ </div>;
+ })}
</div>}
</div>;
};
const menuSession = menu ? sessions.find((session) => session.session_id === menu.sessionId) ?? null : null;
+ const menuArchived = menuSession !== null && menuSession.session_id in archived;
+ // A thread that is working or waiting for an answer stays in view: archived, nobody would see it ask.
+ const menuBusy = Boolean(menuSession?.running) || Boolean(menuSession?.pending_approvals?.length);
return <div data-testid="ide-thread-tree" className="flex-1 px-2 pb-3 pt-2">
<div className="flex h-8 items-center justify-between gap-2 pl-2 pr-1 text-[15px] font-semibold text-foreground">
@@ -263,6 +373,11 @@ export function ThreadTree() {
onSelect={() => { setRenaming({ sessionId: menuSession.session_id, title: threadTitle(menuSession) }); setMenu(null); }} />
<ThreadMenuItem icon={<SquarePlus className="h-3.5 w-3.5" />} label="New thread in this project"
onSelect={() => { newThread(menu.projectId); setMenu(null); }} />
+ {menuArchived
+ ? <ThreadMenuItem icon={<ArchiveRestore className="h-3.5 w-3.5" />} label="Restore"
+ onSelect={() => { restoreThread(menuSession.session_id); setMenu(null); }} />
+ : <ThreadMenuItem icon={<Archive className="h-3.5 w-3.5" />} label="Archive" disabled={menuBusy}
+ onSelect={() => { archiveThread(menuSession.session_id); setMenu(null); }} />}
<ThreadMenuSeparator />
<ThreadMenuItem icon={<Trash2 className="h-3.5 w-3.5" />} label="Delete" danger disabled={Boolean(menuSession.running)}
onSelect={() => setConfirmDelete(menu.sessionId)} />
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx
index 41fd9b9630..24a965cde0 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx
@@ -72,7 +72,7 @@ beforeEach(() => {
api.sendAgentChatMessage.mockReset().mockResolvedValue({ turn_id: "t1" });
api.patchAgentChatSession.mockReset().mockResolvedValue(sessionRow());
useIdeProjectsStore.setState({ projects: [project], activeWorkspaceId: null });
- useIdeThreadsStore.setState({ layout: "threads", selection: { projectId: "p1", sessionId: null }, projectOf: {}, seen: {}, focusNonce: 0 });
+ useIdeThreadsStore.setState({ layout: "threads", selection: { projectId: "p1", sessionId: null }, projectOf: {}, seen: {}, archived: {}, order: {}, focusNonce: 0 });
useThreadChatStore.getState().newChat();
});
@@ -165,4 +165,35 @@ describe("ThreadTree", () => {
fireEvent.click(screen.getByTestId("thread-new-p1"));
expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null });
});
+
+ it("archives a thread from its menu and brings it back from the project's archive", async () => {
+ api.fetchAgentChatSessions.mockResolvedValue([sessionRow({ cli_title: "Fix login test" })]);
+ useIdeThreadsStore.setState({ selection: { projectId: "p1", sessionId: "s1" } });
+ render(<ThreadTree />);
+ await waitFor(() => expect(screen.getByText("Fix login test")).toBeTruthy());
+ fireEvent.contextMenu(screen.getByTestId("thread-row-s1"));
+ fireEvent.click(screen.getByRole("menuitem", { name: /Archive/ }));
+ expect(screen.queryByTestId("thread-row-s1")).toBeNull();
+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null });
+ expect(JSON.parse(localStorage.getItem("jarvis.agenticIde.threadArchived.v1") ?? "{}")).toHaveProperty("s1");
+
+ fireEvent.click(screen.getByTestId("thread-archived-p1"));
+ fireEvent.click(screen.getByRole("button", { name: "Restore Fix login test" }));
+ expect(screen.getByTestId("thread-row-s1")).toBeTruthy();
+ expect(screen.queryByTestId("thread-archived-p1")).toBeNull();
+ });
+
+ it("moves a thread with Alt and the arrow keys and keeps that order", async () => {
+ api.fetchAgentChatSessions.mockResolvedValue([
+ sessionRow({ session_id: "s1", cli_title: "Older", updated_ms: 1 }),
+ sessionRow({ session_id: "s2", cli_title: "Newer", updated_ms: 5 }),
+ ]);
+ render(<ThreadTree />);
+ await waitFor(() => expect(screen.getByText("Older")).toBeTruthy());
+ const titles = () => screen.getAllByTestId(/^thread-row-/).map((row) => row.textContent);
+ expect(titles()[0]).toContain("Newer");
+ fireEvent.keyDown(screen.getByText("Older"), { key: "ArrowUp", altKey: true });
+ expect(titles()[0]).toContain("Older");
+ expect(useIdeThreadsStore.getState().order).toEqual({ p1: ["s1", "s2"] });
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.ts
index c111b44e45..bb691f7938 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { AgentChatSession } from "@/lib/agentChatApi";
import type { IdeProject } from "@/lib/agenticIdeApi";
-import { comparablePath, isInside, projectIdFor, shortAge, threadStatus, threadTitle, threadsByProject } from "./threadModel";
+import { arrangeThreads, comparablePath, isInside, moveThreadId, projectIdFor, shortAge, threadStatus, threadTitle, threadsByProject } from "./threadModel";
function project(id: string, path: string): IdeProject {
return {
@@ -87,3 +87,33 @@ describe("shortAge", () => {
expect(shortAge(now - 15 * 86_400_000, now)).toBe("2w");
});
});
+
+describe("arrangeThreads", () => {
+ const rows = [
+ { session_id: "a", updated_ms: 30 },
+ { session_id: "b", updated_ms: 20 },
+ { session_id: "c", updated_ms: 10 },
+ { session_id: "d", updated_ms: 40 },
+ ];
+
+ it("keeps the given order when nothing was placed", () => {
+ expect(arrangeThreads(rows, undefined).map((row) => row.session_id)).toEqual(["a", "b", "c", "d"]);
+ });
+
+ it("puts unplaced threads first, newest first, then the placed ones in their order", () => {
+ expect(arrangeThreads(rows, ["c", "a", "gone"]).map((row) => row.session_id)).toEqual(["d", "b", "c", "a"]);
+ });
+});
+
+describe("moveThreadId", () => {
+ it("moves a thread before or after another", () => {
+ expect(moveThreadId(["a", "b", "c"], "c", "a", true)).toEqual(["c", "a", "b"]);
+ expect(moveThreadId(["a", "b", "c"], "a", "c", false)).toEqual(["b", "c", "a"]);
+ expect(moveThreadId(["a", "b", "c"], "a", "b", false)).toEqual(["b", "a", "c"]);
+ });
+
+ it("leaves the order alone for an unknown or identical id", () => {
+ expect(moveThreadId(["a", "b"], "x", "a", true)).toEqual(["a", "b"]);
+ expect(moveThreadId(["a", "b"], "a", "a", true)).toEqual(["a", "b"]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.ts
index 693e7c6e59..4ffa273697 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.ts
@@ -75,6 +75,31 @@ export function threadsByProject(
return out;
}
+/**
+ * A project's threads in the person's own order. Threads they never placed
+ * (new ones, restored ones) lead, newest first; the dragged ones follow in
+ * the order they were left in, whatever their activity since.
+ */
+export function arrangeThreads<T extends Pick<AgentChatSession, "session_id" | "updated_ms">>(
+ threads: readonly T[],
+ order: readonly string[] | undefined,
+): T[] {
+ if (!order || order.length === 0) return [...threads];
+ const place = new Map(order.map((id, index) => [id, index]));
+ const loose = threads.filter((thread) => !place.has(thread.session_id)).sort((a, b) => b.updated_ms - a.updated_ms);
+ const placed = threads.filter((thread) => place.has(thread.session_id))
+ .sort((a, b) => (place.get(a.session_id) ?? 0) - (place.get(b.session_id) ?? 0));
+ return [...loose, ...placed];
+}
+
+/** `ids` with `sourceId` moved just before or after `targetId`; unchanged when either is missing. */
+export function moveThreadId(ids: readonly string[], sourceId: string, targetId: string, before: boolean): string[] {
+ if (sourceId === targetId || !ids.includes(sourceId) || !ids.includes(targetId)) return [...ids];
+ const rest = ids.filter((id) => id !== sourceId);
+ const at = rest.indexOf(targetId) + (before ? 0 : 1);
+ return [...rest.slice(0, at), sourceId, ...rest.slice(at)];
+}
+
/** The row's state: a waiting approval first, then work, then news since the last look. */
export function threadStatus(
session: Pick<AgentChatSession, "session_id" | "running" | "pending_approvals" | "updated_ms">,
diff --git a/jarvis/ui/web/frontend/src/store/ideThreads.ts b/jarvis/ui/web/frontend/src/store/ideThreads.ts
index 6ac794ce81..074bef6c46 100644
--- a/jarvis/ui/web/frontend/src/store/ideThreads.ts
+++ b/jarvis/ui/web/frontend/src/store/ideThreads.ts
@@ -11,7 +11,9 @@ import { create } from "zustand";
* The open thread is either an existing chat session (`sessionId`) or a draft
* in one project (`sessionId: null`) whose first message creates the session.
* Both survive a reload through localStorage, which may be blocked — every
- * read and write degrades to the defaults instead of throwing.
+ * read and write degrades to the defaults instead of throwing. So does the
+ * person's own arrangement of the list: the order they dragged a project's
+ * threads into and the threads they archived out of it.
*/
export type IdeLayout = "grid" | "threads";
@@ -29,8 +31,15 @@ const LAYOUT_KEY = "jarvis.agenticIde.layout.v1";
const SELECTION_KEY = "jarvis.agenticIde.threadSelection.v1";
const PROJECT_OF_KEY = "jarvis.agenticIde.threadProjects.v1";
const SEEN_KEY = "jarvis.agenticIde.threadSeen.v1";
+const ARCHIVED_KEY = "jarvis.agenticIde.threadArchived.v1";
+const ORDER_KEY = "jarvis.agenticIde.threadOrder.v1";
/** Bounds on the two maps kept in storage — oldest entries go first. */
const MAX_REMEMBERED = 400;
+/**
+ * The archive's bound. Dropping an entry brings an old thread back into the
+ * list, so this one is far roomier than the maps above.
+ */
+const MAX_ARCHIVED = 4000;
function read<T>(key: string, parse: (raw: unknown) => T | null, fallback: T): T {
try {
@@ -71,11 +80,26 @@ const parseNumberMap = (raw: unknown): Record<string, number> | null => {
return Object.fromEntries(Object.entries(raw).filter(([, value]) => typeof value === "number")) as Record<string, number>;
};
-/** Drop the oldest keys once a map outgrows `MAX_REMEMBERED` (insertion order). */
-function bounded<T>(map: Record<string, T>): Record<string, T> {
+const parseOrder = (raw: unknown): Record<string, string[]> | null => {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const out: Record<string, string[]> = {};
+ for (const [projectId, ids] of Object.entries(raw)) {
+ if (Array.isArray(ids)) out[projectId] = ids.filter((id): id is string => typeof id === "string");
+ }
+ return out;
+};
+
+/** Drop the oldest keys once a map outgrows `limit` (insertion order). */
+function bounded<T>(map: Record<string, T>, limit = MAX_REMEMBERED): Record<string, T> {
const keys = Object.keys(map);
- if (keys.length <= MAX_REMEMBERED) return map;
- return Object.fromEntries(keys.slice(keys.length - MAX_REMEMBERED).map((key) => [key, map[key]]));
+ if (keys.length <= limit) return map;
+ return Object.fromEntries(keys.slice(keys.length - limit).map((key) => [key, map[key]]));
+}
+
+/** Every project's order without `sessionId`; the same object when it was in none. */
+function withoutInOrder(order: Record<string, string[]>, sessionId: string): Record<string, string[]> {
+ if (!Object.values(order).some((ids) => ids.includes(sessionId))) return order;
+ return Object.fromEntries(Object.entries(order).map(([projectId, ids]) => [projectId, ids.filter((id) => id !== sessionId)]));
}
interface IdeThreadsState {
@@ -88,6 +112,10 @@ interface IdeThreadsState {
projectOf: Record<string, string>;
/** When each thread was last looked at (its `updated_ms` then) — drives the "new" dot. */
seen: Record<string, number>;
+ /** Threads moved out of the list, with when; each project shows them under "Archived". */
+ archived: Record<string, number>;
+ /** Each project's threads in the order the person dragged them into. */
+ order: Record<string, string[]>;
/** Bumped to ask the thread view to focus its composer. */
focusNonce: number;
@@ -103,6 +131,12 @@ interface IdeThreadsState {
markSeen: (sessionId: string, updatedMs: number) => void;
/** A thread was deleted: forget everything kept about it. */
forgetThread: (sessionId: string) => void;
+ /** Move a thread out of the list; an open one gives way to its project's draft. */
+ archiveThread: (sessionId: string) => void;
+ /** Bring an archived thread back; it returns at the top of its project. */
+ restoreThread: (sessionId: string) => void;
+ /** Keep a project's threads in this order. */
+ setThreadOrder: (projectId: string, sessionIds: readonly string[]) => void;
}
export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({
@@ -110,6 +144,8 @@ export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({
selection: read(SELECTION_KEY, parseSelection, { projectId: "", sessionId: null }),
projectOf: read(PROJECT_OF_KEY, parseStringMap, {}),
seen: read(SEEN_KEY, parseNumberMap, {}),
+ archived: read(ARCHIVED_KEY, parseNumberMap, {}),
+ order: read(ORDER_KEY, parseOrder, {}),
focusNonce: 0,
setLayout: (layout) => {
@@ -149,12 +185,40 @@ export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({
forgetThread: (sessionId) => {
const { [sessionId]: _project, ...projectOf } = get().projectOf;
const { [sessionId]: _seen, ...seen } = get().seen;
+ const { [sessionId]: _archived, ...archived } = get().archived;
+ const order = withoutInOrder(get().order, sessionId);
write(PROJECT_OF_KEY, projectOf);
write(SEEN_KEY, seen);
+ write(ARCHIVED_KEY, archived);
+ write(ORDER_KEY, order);
const selection = get().selection.sessionId === sessionId
? { projectId: get().selection.projectId, sessionId: null }
: get().selection;
write(SELECTION_KEY, selection);
- set({ projectOf, seen, selection });
+ set({ projectOf, seen, archived, order, selection });
+ },
+ archiveThread: (sessionId) => {
+ const { [sessionId]: _previous, ...rest } = get().archived;
+ const archived = bounded({ ...rest, [sessionId]: Date.now() }, MAX_ARCHIVED);
+ // Out of the dragged order too, so a restored thread comes back on top.
+ const order = withoutInOrder(get().order, sessionId);
+ write(ARCHIVED_KEY, archived);
+ write(ORDER_KEY, order);
+ const selection = get().selection.sessionId === sessionId
+ ? { projectId: get().selection.projectId, sessionId: null }
+ : get().selection;
+ write(SELECTION_KEY, selection);
+ set({ archived, order, selection });
+ },
+ restoreThread: (sessionId) => {
+ if (!(sessionId in get().archived)) return;
+ const { [sessionId]: _archived, ...archived } = get().archived;
+ write(ARCHIVED_KEY, archived);
+ set({ archived });
+ },
+ setThreadOrder: (projectId, sessionIds) => {
+ const order = { ...get().order, [projectId]: [...sessionIds] };
+ write(ORDER_KEY, order);
+ set({ order });
},
}));