Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

merge: paginated conversation library (PR #723)

justrachf96556db6d2b
diff --cc apps/native/README.md
index ec660dd8,07b6de50..63037212
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@@ -67,15 -67,16 +67,18 @@@ and re-reads `current` after every resp
graff's fuzzy `--model` resolution actually chose.
History is graff's own: every tab's agent autosaves to
- `.graff/sessions/<name>.session.json` in the workspace (`--resume <name>`),
- and the sidebar lists that directory — grouped by day, searchable — via
- `/api/sessions`, which peeks each file's header rather than parsing it.
- Opening a past session renders its saved transcript at once and spawns the
- tab's agent with `--resume`, so a follow-up continues the conversation with
- the model's memory intact.
+ `.graff/sessions/<name>.session.json` (`--resume <name>`). `/api/sessions`
+ peeks each file's header (not the messages array), lists the current
+ workspace then `~/.graff/sessions` (ADR 0059), and pages 24 at a time
+ (`?limit=&cursor=&q=&scope=`). The sidebar shows a dated preview; Conversations
+ is the full library — grouped by day, searchable, infinite-scroll. Opening
+ a past session renders its transcript at once and spawns the tab's agent
+ with `--resume`, so a follow-up continues with the model's memory intact.
++`?root=` scopes any of it to one workspace, and `DELETE` archives a chat
++(the file moves into an `archived/` directory beside it) or removes it.
The workspace itself is walkable: `/api/fs` (list/read, plus macOS
-`open`/`open -R` passthroughs) is sandboxed to the agent's cwd and backs
+`open`/`open -R` passthroughs) is sandboxed to the tab's cwd and backs
a files pane — the folder chip in the tab bar or the sidebar's
Workspace item opens it. Tool-row chips and path-looking inline code in
answers (`src/acp.zig`) jump straight to that file; markdown files
diff --cc apps/native/app/api/sessions/route.ts
index 1245a7bc,f656a485..4580b657
--- a/apps/native/app/api/sessions/route.ts
+++ b/apps/native/app/api/sessions/route.ts
@@@ -1,34 -1,29 +1,30 @@@
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, statSync, unlinkSync } from "node:fs";
-import { existsSync, readFileSync, statSync } from "node:fs";
++import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
import path from "node:path";
import { NextRequest } from "next/server";
+import { resolveRoot } from "@/lib/server-root";
+ import {
+ MAX_FULL_BYTES,
+ NAME_RE,
++ SESSION_EXT,
+ clampLimit,
+ findSessionFile,
+ homeDir,
+ listSessionRows,
+ pageSessions,
+ peekHeader,
+ type ListScope,
+ } from "@/lib/session-store";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-/** Same resolution as /api/acp: the workspace the agent itself runs in. */
-function workspaceRoot(): string {
- if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;
- if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;
- const fromApp = path.resolve(process.cwd(), "../..");
- if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;
- return process.cwd();
-}
+// graff autosaves every conversation to `<cwd>/.graff/sessions/<name>.session.json`
- // (src/session_index.zig owns the layout). The header — provider, model, title,
- // updated_ms — is written before the (possibly multi-MB) messages array, so the
- // list peeks the prefix instead of parsing whole files.
- const SESSIONS_DIR = ".graff/sessions";
- // Archived chats leave the list but stay on disk, next to graff's own
- // sessions, so a chat can be put away without losing the conversation.
- const ARCHIVE_DIR = ".graff/sessions/archived";
- const EXT = ".session.json";
- const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
- const PEEK_BYTES = 64 * 1024;
- const MAX_FULL_BYTES = 16 * 1024 * 1024;
-
- type Header = { title?: unknown; updated_ms?: unknown; model?: unknown; provider?: unknown };
-
- export type StoredSessionRow = {
- name: string;
- title: string | null;
- updatedMs: number;
- model: string | null;
- provider: string | null;
- size: number;
- };
++// (src/session_index.zig owns the layout). Reading, paging and searching that
++// index lives in lib/session-store.ts; this route is the HTTP shape over it.
++//
++// Archived chats leave the list but stay on disk, in an `archived/` directory
++// beside graff's own sessions, so a chat can be put away without losing it.
++const ARCHIVE_SUBDIR = "archived";
function str(v: unknown): string | null {
return typeof v === "string" && v.length > 0 ? v : null;
@@@ -82,12 -35,8 +36,12 @@@ function parseScope(raw: string | null)
}
export async function GET(req: NextRequest) {
- // `?root=` is the workspace whose sessions are wanted (each workspace
- // keeps its own .graff/sessions); absent, the agent's default workspace.
- const root = workspaceRoot();
++ // `?root=` is the workspace whose sessions are wanted (each workspace keeps
++ // its own .graff/sessions); absent, the agent's default workspace.
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const root = resolved.root;
- const dir = path.join(root, SESSIONS_DIR);
+ const home = homeDir();
const name = req.nextUrl.searchParams.get("name");
if (name !== null) {
if (!NAME_RE.test(name)) return Response.json({ error: "bad session name" }, { status: 400 });
@@@ -110,42 -69,11 +74,40 @@@
return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });
}
}
- if (!existsSync(dir)) return Response.json({ cwd: root, sessions: [] });
- const rows: StoredSessionRow[] = [];
- for (const entry of readdirSync(dir)) {
- if (!entry.endsWith(EXT)) continue;
- const row = rowFor(dir, entry);
- if (row) rows.push(row);
- }
- rows.sort((a, b) => b.updatedMs - a.updatedMs);
- return Response.json({ cwd: root, sessions: rows });
+ const page = pageSessions(listSessionRows(root, home), {
+ limit: clampLimit(req.nextUrl.searchParams.get("limit")),
+ cursor: req.nextUrl.searchParams.get("cursor"),
+ q: req.nextUrl.searchParams.get("q"),
+ scope: parseScope(req.nextUrl.searchParams.get("scope")),
+ });
+ return Response.json({ cwd: root, ...page });
}
+
- /** Put a chat away (`?archive=1`, the default: the file moves under
- * `.graff/sessions/archived/`) or remove it for good. Either way it leaves
- * the sidebar; only delete loses the conversation. */
++/** Put a chat away (`?archive=1`, the default: the file moves into an
++ * `archived/` directory beside it) or remove it for good. Either way it
++ * leaves the list; only delete loses the conversation. A session saved in
++ * the home tree rather than this workspace is archived where it lives. */
+export async function DELETE(req: NextRequest) {
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const name = req.nextUrl.searchParams.get("name");
+ if (name === null || !NAME_RE.test(name)) return Response.json({ error: "bad session name" }, { status: 400 });
- const dir = path.join(resolved.root, SESSIONS_DIR);
- const file = path.join(dir, `${name}${EXT}`);
- if (!existsSync(file)) return Response.json({ error: "no such session" }, { status: 404 });
++ const found = findSessionFile(resolved.root, name, homeDir());
++ if (!found) return Response.json({ error: "no such session" }, { status: 404 });
+ const archive = req.nextUrl.searchParams.get("archive") !== "0";
+ try {
+ if (!archive) {
- unlinkSync(file);
++ unlinkSync(found.file);
+ return Response.json({ ok: true, name, archived: false });
+ }
- const target = path.join(resolved.root, ARCHIVE_DIR);
++ const target = path.join(path.dirname(found.file), ARCHIVE_SUBDIR);
+ mkdirSync(target, { recursive: true });
- let dest = path.join(target, `${name}${EXT}`);
++ let dest = path.join(target, `${name}${SESSION_EXT}`);
+ // Never overwrite an earlier archive of the same name.
- if (existsSync(dest)) dest = path.join(target, `${name}.${Date.now()}${EXT}`);
- renameSync(file, dest);
++ if (existsSync(dest)) dest = path.join(target, `${name}.${Date.now()}${SESSION_EXT}`);
++ renameSync(found.file, dest);
+ return Response.json({ ok: true, name, archived: true });
+ } catch (err) {
+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });
+ }
+}
diff --cc apps/native/components/primitives/SidebarNav.tsx
index 7be6fbb2,8ed1e634..6d69f373
--- a/apps/native/components/primitives/SidebarNav.tsx
+++ b/apps/native/components/primitives/SidebarNav.tsx
@@@ -8,9 -9,9 +8,10 @@@ import
IconCrossSmall,
IconEditBig,
IconFolder,
+ IconGlobe,
IconHome,
IconMagnifyingGlass,
+ IconChat,
IconPlusMedium,
IconPopsicle2,
IconSettingsGear1,
@@@ -31,8 -31,8 +32,9 @@@ const WORKSPACE = { key: "graff", name
const NAV_ITEMS: { key: string; label: string; icon: ReactNode; count?: string }[] = [
{ key: "home", label: "Home", icon: <IconHome size={18} /> },
+ { key: "conversations", label: "Conversations", icon: <IconChat size={18} /> },
{ key: "workspace", label: "Workspace", icon: <IconFolder size={18} /> },
+ { key: "browser", label: "Browser", icon: <IconGlobe size={18} /> },
];
export type SidebarRecent = {
@@@ -67,26 -67,15 +69,29 @@@ type SidebarNavProps =
footerLabel?: string;
footerIcon?: ReactNode;
onFooterClick?: () => void;
+ /** Tooltip on the footer control. */
+ footerTitle?: string;
recents?: SidebarRecent[];
+ /** How many saved sessions exist (sidebar only shows a preview). */
+ recentsTotal?: number;
+ onSeeAll?: () => void;
variant?: string;
+ /** The active workspace (the folder graff runs in); the demo shows a placeholder. */
+ workspace?: SidebarWorkspace;
+ /** Every workspace the switcher offers, the active one included. */
+ workspaces?: SidebarWorkspace[];
+ onSwitchWorkspace?: (path: string) => void;
+ onNewWorkspace?: () => void;
+ /** Put a saved chat away, or (deleting) remove it for good. */
+ onArchiveRecent?: (id: string) => void;
+ onDeleteRecent?: (id: string) => void;
+ onWorkspaceSettings?: () => void;
};
+export type SidebarWorkspace = { path: string; name: string };
+
const SIDEBAR_MOTION = {
- expandedWidth: 224,
+ expandedWidth: 248,
collapsedWidth: 52,
duration: 280,
copyDuration: 180,
@@@ -249,15 -221,9 +254,17 @@@ export default function SidebarNav(
footerLabel = "Upgrade",
footerIcon,
onFooterClick,
+ footerTitle,
recents = DEFAULT_RECENTS,
+ workspace,
+ workspaces = [],
+ onSwitchWorkspace,
+ onNewWorkspace,
+ onWorkspaceSettings,
+ onArchiveRecent,
+ onDeleteRecent,
+ recentsTotal,
+ onSeeAll,
}: SidebarNavProps) {
const [collapsed, setCollapsed] = useState(false);
const [internalNav, setInternalNav] = useState("chats");
@@@ -499,61 -440,38 +506,79 @@@
active ? "bg-hover-2 group-hover/glide:bg-transparent" : ""
}`}
>
- <span className={`sidebar-copy min-w-0 flex-1 truncate text-[14px] font-medium ${active ? "text-ink" : "text-ink-2"}`}>
- {item.label}
+ <span className="sidebar-copy flex min-w-0 flex-1 flex-col">
+ <span className={`truncate text-[13.5px] font-medium ${active ? "text-ink" : "text-ink-2"}`}>
+ {item.label}
+ </span>
+ {item.hint && (
+ <span className="truncate text-[11px] text-ink-3">{item.hint}</span>
+ )}
</span>
</button>
+ {(onArchiveRecent || onDeleteRecent) && (
+ <span className="sidebar-copy absolute inset-y-0 right-3 z-20 flex items-center gap-0.5 opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100">
+ {onArchiveRecent && (
+ <button
+ type="button"
+ aria-label={`Archive ${item.label}`}
+ title="Archive this chat — it leaves the list but stays on disk"
+ onClick={(event) => {
+ event.stopPropagation();
+ onArchiveRecent(item.id);
+ }}
+ className="flex size-6 items-center justify-center rounded-[6px] text-ink-3 transition-colors hover:bg-hover-2 hover:text-ink"
+ >
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <rect x="3" y="4" width="18" height="4" rx="1" />
+ <path d="M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" />
+ </svg>
+ </button>
+ )}
+ {onDeleteRecent && (
+ <button
+ type="button"
+ aria-label={`Delete ${item.label}`}
+ title="Delete this chat for good"
+ onClick={(event) => {
+ event.stopPropagation();
+ onDeleteRecent(item.id);
+ }}
+ className="flex size-6 items-center justify-center rounded-[6px] text-ink-3 transition-colors hover:bg-hover-2 hover:text-red"
+ >
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3" />
+ </svg>
+ </button>
+ )}
+ </span>
+ )}
+ </div>
</Fragment>
);
})}
- {query && visibleRecents.length === 0 && (
- <div className="sidebar-copy mx-2 px-2 py-2 text-[12.5px] text-ink-3">No chats found</div>
+ {visibleRecents.length === 0 && (
+ <div className="sidebar-copy mx-2 px-2 py-2 text-[12.5px] text-ink-3">
+ {query ? "No chats found" : "No chats yet — start one and it appears here."}
+ </div>
)}
+ {!query && onSeeAll && (recentsTotal ?? recents.length) > recents.length && (
+ <button
+ data-row
+ type="button"
+ onClick={() => {
+ selectNav("conversations");
+ onSeeAll();
+ }}
+ className="sidebar-row relative z-10 mx-2 flex h-8 items-center rounded-[8px] px-2 text-left text-[12.5px] font-medium text-ink-3 transition-[background-color,color,transform] duration-150 hover:text-ink active:scale-[0.98]"
+ >
+ See all {recentsTotal?.toLocaleString()} conversations
+ </button>
+ )}
</GlideGroup>
+ </div>
</div>
- <div className="sidebar-copy mx-2 mt-3 w-[208px] border-t border-line pt-3">
+ <div className="sidebar-copy mx-2 mt-3 w-[232px] border-t border-line pt-3">
<button
type="button"
onClick={onFooterClick ?? onNewChat}
diff --cc apps/native/components/site/ChatEmpty.tsx
index bd340334,a8f80440..81726437
--- a/apps/native/components/site/ChatEmpty.tsx
+++ b/apps/native/components/site/ChatEmpty.tsx
@@@ -46,15 -42,10 +44,15 @@@ export default function EmptyState(
models: PromptModel[];
modelKey?: string;
onModelChange: (key: string) => void;
+ /** Earlier prompts for ArrowUp recall in the composer. */
+ history?: readonly string[];
+ /** This tab's workspace; absent, the server's default from `health`. */
+ cwd?: string;
}) {
+ const where = cwd ?? health?.cwd;
+ const [offset, setOffset] = useState(0);
const shown = [0, 1, 2].map((i) => STARTER_PROMPTS[(offset + i) % STARTER_PROMPTS.length]);
+ const shuffle = () => setOffset((current) => (current + 3) % STARTER_PROMPTS.length);
const [stage, setStage] = useState(0);
useEffect(() => {
const timers = [
diff --cc apps/native/components/site/ConversationsPane.tsx
index 00000000,d966ca5b..d56a84b8
mode 000000,100644..100644
--- a/apps/native/components/site/ConversationsPane.tsx
+++ b/apps/native/components/site/ConversationsPane.tsx
@@@ -1,0 -1,219 +1,222 @@@
+ "use client";
+
+ import { useEffect, useRef, useState } from "react";
+ import { IconEditBig, IconMagnifyingGlass } from "@/lib/icons";
+ import {
+ groupSessions,
+ listSessionsPage,
+ relativeTime,
+ type SessionScope,
+ type StoredSession,
+ } from "@/lib/sessions";
+
+ const PAGE = 24;
+ const SCOPES: { key: SessionScope; label: string }[] = [
+ { key: "all", label: "All" },
+ { key: "local", label: "This workspace" },
+ { key: "elsewhere", label: "Saved elsewhere" },
+ ];
+
+ function useDebounced(value: string, ms = 180): string {
+ const [out, setOut] = useState(value);
+ useEffect(() => {
+ const t = setTimeout(() => setOut(value), ms);
+ return () => clearTimeout(t);
+ }, [value, ms]);
+ return out;
+ }
+
+ export default function ConversationsPane({
+ activeId,
+ onPick,
+ onNewChat,
++ root,
+ }: {
+ activeId?: string | null;
+ onPick: (name: string) => void;
+ onNewChat?: () => void;
++ /** The workspace whose sessions to list; absent, the server's default. */
++ root?: string;
+ }) {
+ const [query, setQuery] = useState("");
+ const [scope, setScope] = useState<SessionScope>("all");
+ const [rows, setRows] = useState<StoredSession[]>([]);
+ const [cursor, setCursor] = useState<string | null>(null);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(true);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const sentinelRef = useRef<HTMLDivElement>(null);
+ const q = useDebounced(query);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
- void listSessionsPage({ limit: PAGE, q, scope })
++ void listSessionsPage({ limit: PAGE, q, scope, root })
+ .then((page) => {
+ if (cancelled) return;
+ setRows(page.sessions);
+ setCursor(page.nextCursor);
+ setTotal(page.total);
+ })
+ .catch((err: unknown) => {
+ if (!cancelled) setError(err instanceof Error ? err.message : String(err));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
- }, [q, scope]);
++ }, [q, scope, root]);
+
+ useEffect(() => {
+ const el = sentinelRef.current;
+ if (!el || !cursor) return;
+ const io = new IntersectionObserver(
+ (entries) => {
+ if (!entries.some((e) => e.isIntersecting)) return;
+ if (loadingMore || loading) return;
+ const next = cursor;
+ if (!next) return;
+ setLoadingMore(true);
- void listSessionsPage({ limit: PAGE, cursor: next, q, scope })
++ void listSessionsPage({ limit: PAGE, cursor: next, q, scope, root })
+ .then((page) => {
+ setRows((current) => {
+ const seen = new Set(current.map((r) => r.name));
+ return [...current, ...page.sessions.filter((r) => !seen.has(r.name))];
+ });
+ setCursor(page.nextCursor);
+ setTotal(page.total);
+ })
+ .catch(() => undefined)
+ .finally(() => setLoadingMore(false));
+ },
+ { rootMargin: "160px" },
+ );
+ io.observe(el);
+ return () => io.disconnect();
+ }, [cursor, loading, loadingMore, q, scope]);
+
+ const groups = groupSessions(rows);
+ const empty = !loading && rows.length === 0;
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <header className="shrink-0 border-b border-line px-5 pt-5 pb-4 sm:px-8">
+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-4">
+ <div className="flex items-end justify-between gap-4">
+ <div>
+ <h1 className="text-[22px] font-medium tracking-[-0.02em] text-ink">Conversations</h1>
+ <p className="mt-0.5 text-[12.5px] text-ink-3">
+ {loading && rows.length === 0
+ ? "Reading saved sessions…"
+ : total === 1
+ ? "1 saved session"
+ : `${total.toLocaleString()} saved sessions`}
+ {scope === "elsewhere" ? " from other workspaces" : scope === "local" ? " in this workspace" : " · this workspace and home"}
+ </p>
+ </div>
+ {onNewChat && (
+ <button
+ type="button"
+ onClick={onNewChat}
+ className="flex h-8 items-center gap-1.5 rounded-control bg-hover-2 px-2.5 text-[12.5px] font-medium text-ink transition-[background-color,transform] duration-150 hover:bg-line-strong active:scale-[0.98]"
+ >
+ <IconEditBig size={14} />
+ New chat
+ </button>
+ )}
+ </div>
+
+ <div className="flex h-9 items-center gap-2 rounded-[10px] bg-field px-2.5 text-ink-3 shadow-hairline focus-within:text-ink-2">
+ <IconMagnifyingGlass size={15} />
+ <input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search title, model, or workspace"
+ aria-label="Search conversations"
+ className="min-w-0 flex-1 bg-transparent text-[13.5px] font-medium text-ink outline-none placeholder:text-ink-3"
+ />
+ </div>
+
+ <div className="flex flex-wrap gap-1.5">
+ {SCOPES.map((item) => (
+ <button
+ key={item.key}
+ type="button"
+ aria-pressed={scope === item.key}
+ onClick={() => setScope(item.key)}
+ className={`h-7 rounded-full px-2.5 text-[12px] font-medium transition-colors duration-100 ${
+ scope === item.key ? "bg-hover-2 text-ink" : "text-ink-3 hover:bg-hover hover:text-ink"
+ }`}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </header>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-6 px-5 py-5 sm:px-8">
+ {error && <p className="text-[13px] text-orange">{error}</p>}
+ {empty && (
+ <div className="flex flex-col items-center justify-center gap-1 rounded-[14px] bg-inset px-6 py-16 text-center">
+ <span className="text-[14px] font-medium text-ink">
+ {query.trim() || scope !== "all" ? "No conversations match" : "No saved conversations yet"}
+ </span>
+ <span className="text-[12.5px] text-ink-3">
+ {query.trim() || scope !== "all"
+ ? "Try another search or show all sessions."
+ : "A turn autosaves here. New chat starts a fresh one."}
+ </span>
+ </div>
+ )}
+ {groups.map((section) => (
+ <section key={section.group}>
+ <h2 className="mb-2 px-1 text-[11.5px] font-medium tracking-wide text-ink-3">{section.group}</h2>
+ <ul className="flex flex-col gap-1">
+ {section.items.map((row) => {
+ const active = row.name === activeId;
+ return (
+ <li key={row.name}>
+ <button
+ type="button"
+ onClick={() => onPick(row.name)}
+ className={`flex w-full items-start gap-3 rounded-[12px] px-3 py-2.5 text-left transition-[background-color,transform] duration-150 active:scale-[0.995] ${
+ active ? "bg-hover-2" : "hover:bg-hover"
+ }`}
+ >
+ <span className="mt-1.5 size-1.5 shrink-0 rounded-full" style={{ background: active ? "var(--accent)" : "var(--ink-3)" }} />
+ <span className="min-w-0 flex-1">
+ <span className={`block truncate text-[14.5px] font-medium ${active ? "text-ink" : "text-ink"}`}>
+ {row.title ?? row.name}
+ </span>
+ <span className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[12px] text-ink-3">
+ {row.model && <span className="font-mono text-[11.5px]">{row.model}</span>}
+ {row.local === false && <span>{row.origin ?? "another workspace"}</span>}
+ {row.local !== false && <span>This workspace</span>}
+ </span>
+ </span>
+ <span className="shrink-0 pt-0.5 text-[12px] tabular-nums text-ink-3">{relativeTime(row.updatedMs)}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ ))}
+ <div ref={sentinelRef} className="h-4" />
+ {loadingMore && <p className="pb-4 text-center text-[12.5px] text-ink-3">Loading more…</p>}
+ {!loading && !cursor && rows.length > 0 && (
+ <p className="pb-6 text-center text-[12px] text-ink-3">
+ {rows.length === total ? "That's all of them." : `Showing ${rows.length} of ${total.toLocaleString()}`}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
diff --cc apps/native/components/site/GraffHarness.tsx
index 88dbc5e9,105045fe..fb7474e1
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@@ -1,20 -1,19 +1,20 @@@
"use client";
-import { useEffect, useRef, useState, type RefObject } from "react";
-import Markdown from "@/components/primitives/Markdown";
+import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";
import SidebarNav from "@/components/primitives/SidebarNav";
+ import ConversationsPane from "@/components/site/ConversationsPane";
-import EmptyState from "@/components/site/EmptyState";
import FilesPane from "@/components/site/FilesPane";
-import { IconChat, IconFolder } from "@/lib/icons";
+import BrowserPane from "@/components/site/BrowserPane";
- import { IconFolder, IconGlobe } from "@/lib/icons";
++import { IconChat, IconFolder, IconGlobe } from "@/lib/icons";
+import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";
+import { browserClose, browserHandle, browserNav } from "@/lib/browser-client";
import TaskRows from "@/components/primitives/TaskRows";
-import ThinkingState from "@/components/primitives/ThinkingState";
-import ToolChips from "@/components/primitives/ToolChips";
import { ThemeToggle } from "@/components/site/ThemeToggle";
+import { AssistantBody, UserBubble } from "@/components/site/ChatBubbles";
+import EmptyState from "@/components/site/ChatEmpty";
import {
MODELS,
- STARTER_PROMPTS,
cancel,
chatHandle,
checkHealth,
@@@ -25,31 -24,228 +25,34 @@@
prompt,
type Health,
} from "@/lib/acp-client";
-import { applyAcpUpdate, emptyTurn, finishAcpTurn, turnBlocks, type AssistantTurn } from "@/lib/acp";
-import { listSessionsPage, loadSession, toSidebarRecent, type StoredSession } from "@/lib/sessions";
-
-/** Typewriter reveal over the ACP text, the way every AI app streams: a
- * readable base rate with gentle backlog catch-up (capped so a one-shot
- * final answer still visibly types out), and the drain keeps playing after
- * the turn's result lands — done-state chrome waits for the last word.
- * Mounted mid-history it starts caught-up, so old messages never replay.
- * Catch-up lands on whitespace so markdown chips/lists don't reflow every
- * mid-token character — that wrap-jitter stacked with scrollIntoView. */
-function useSmoothStream(target: string): string {
- const [shown, setShown] = useState(target);
- const shownRef = useRef(target);
- useEffect(() => {
- if (!target.startsWith(shownRef.current)) {
- shownRef.current = target;
- setShown(target);
- return;
- }
- if (target === shownRef.current) return;
- let raf = 0;
- let last = performance.now();
- const tick = (now: number) => {
- const dt = Math.min(now - last, 80);
- last = now;
- const have = shownRef.current.length;
- const behind = target.length - have;
- if (behind <= 0) return;
- const rate = Math.min(180 + behind * 1.4, 2800);
- let next = have + Math.max(1, Math.round((rate * dt) / 1000));
- if (next < target.length) {
- const rest = target.slice(next, next + 24);
- const cut = rest.search(/[\s\n]/);
- if (cut > 0) next += cut + 1;
- } else {
- next = target.length;
- }
- shownRef.current = target.slice(0, next);
- setShown(shownRef.current);
- if (shownRef.current.length < target.length) raf = requestAnimationFrame(tick);
- };
- raf = requestAnimationFrame(tick);
- return () => cancelAnimationFrame(raf);
- }, [target]);
- return shown;
-}
+import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
+import { isFollowingTail, pinScrollerTail } from "@/lib/follow-scroll";
+import { dropQueuedPrompt, enqueuePrompt, shiftQueuedPrompt, type QueuedPrompt } from "@/lib/prompt-queue";
- import { dateGroup, listSessions, loadSession, relativeTime, removeSession, type StoredSession } from "@/lib/sessions";
++import { dateGroup, listSessionsPage, loadSession, relativeTime, removeSession, toSidebarRecent, type StoredSession } from "@/lib/sessions";
+import { loadHistory, mergeHistory, pushHistory, saveHistory } from "@/lib/prompt-history";
+import WorkspaceDialog from "@/components/site/WorkspaceDialog";
+import {
+ basename,
+ findWorkspace,
+ loadActiveWorkspace,
+ loadWorkspaces,
+ removeWorkspace,
+ saveActiveWorkspace,
+ saveWorkspaces,
+ shellQuote,
+ upsertWorkspace,
+ type Workspace,
+} from "@/lib/workspaces";
-/** Pin the thread scroller to its tail without scrollIntoView. WKWebView
- * treats block:end on a tall article as a viewport realignment every frame
- * — the whole reply judders while the typewriter runs. */
-function pinScrollerTail(el: HTMLElement | null): void {
- if (!el) return;
- const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
- if (fromBottom < 240) el.scrollTop = el.scrollHeight;
-}
+/** Whether the sidecar browser pane was open, restored after a reload. */
+const BROWSER_OPEN_KEY = "graff.native.browser.open";
-function UserBubble({ text }: { text: string }) {
- return (
- <div className="flex justify-end pl-10 sm:pl-24" style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}>
- <div
- className="rounded-xl px-3.5 py-2 text-[13px] leading-relaxed text-ink shadow-hairline"
- style={{ background: "color-mix(in oklab, var(--accent) 12%, var(--surface))" }}
- >
- {text}
- </div>
- </div>
- );
-}
+/** Columns the split view will show at once, the active chat included. */
+const MAX_COLUMNS = 4;
-function AssistantBody({
- turn,
- onOpenPath,
- onReview,
- scroller,
-}: {
- turn: AssistantTurn;
- onOpenPath?: (path: string) => void;
- /** Open the workspace changes review (the Codex "Changed N files" bar). */
- onReview?: () => void;
- scroller?: RefObject<HTMLDivElement | null>;
-}) {
- const thinking = turn.status === "thinking";
- const blocks = turnBlocks(turn.text, turn.tools);
- const lastText = [...blocks].reverse().find((b) => b.kind === "text");
- const lastTextBody = lastText?.kind === "text" ? lastText.text : "";
- const smoothText = useSmoothStream(lastTextBody);
- const draining = smoothText.length < lastTextBody.length;
- // Follow the typewriter tail — the parent's pin tracks the wire text,
- // which goes quiet while the reveal is still playing out. Pin the
- // overflow scroller directly; do not scrollIntoView (WKWebView jitter).
- useEffect(() => {
- if (draining) pinScrollerTail(scroller?.current ?? null);
- }, [smoothText, draining, scroller]);
- // "Thought for Ns": the harness stamps `thoughtMs` on the turn as it streams
- // (ACP updates carry no timestamps); a live turn without one yet is timed here.
- const startRef = useRef(Date.now());
- const [thoughtSecs, setThoughtSecs] = useState<number | null>(
- turn.thoughtMs !== undefined ? Math.max(1, Math.round(turn.thoughtMs / 1000)) : null,
- );
- useEffect(() => {
- if (thinking) return;
- setThoughtSecs((current) => {
- if (current !== null) return current;
- const ms = turn.thoughtMs ?? Date.now() - startRef.current;
- return Math.max(1, Math.round(ms / 1000));
- });
- }, [thinking, turn.thoughtMs]);
- const reasoningRows = turn.reasoning
- ? turn.reasoning
- .split(/\n+/)
- .map((line) => line.trim())
- .filter(Boolean)
- .map((primary) => ({ primary }))
- : [];
- const toChipRows = (tools: typeof turn.tools) =>
- tools.map((tool) => ({
- id: tool.id,
- icon: tool.icon,
- label: tool.name,
- chip: tool.chip,
- mono: tool.icon === "run" || tool.icon === "write" || tool.icon === "read",
- detailMono: tool.icon === "run" || tool.icon === "write",
- detail: tool.detail,
- path: tool.path,
- status: tool.status,
- startedAt: tool.startedAt,
- elapsedMs: tool.elapsedMs,
- }));
-
- const lastTextIndex = blocks.reduce((acc, b, i) => (b.kind === "text" ? i : acc), -1);
- const lastBlock = blocks[blocks.length - 1];
- const waitingOnTools =
- turn.status === "streaming" &&
- !lastTextBody &&
- (lastBlock?.kind === "tools" || blocks.length === 0);
-
- return (
- <article className="min-w-0" style={{ overflowAnchor: "none", animation: "fade-in 280ms ease both" }}>
- {/* Keep the header once the model has actually thought (streamed
- * reasoning, or a think long enough to notice): unmounting it when the
- * think ends made the answer jump up into the space it left. */}
- {(thinking || reasoningRows.length > 0 || (turn.thoughtMs ?? 0) >= 1500) && (
- <ThinkingState
- variant="Reasoning"
- rows={reasoningRows.length ? reasoningRows : [{ primary: "Waiting on the model…", shimmer: true }]}
- activeLabel={turn.model ? `Thinking · ${turn.model}` : "Thinking"}
- doneLabel={thoughtSecs ? `Thought for ${thoughtSecs}s` : "Thought"}
- working={thinking}
- />
- )}
- {blocks.map((block, i) =>
- block.kind === "tools" ? (
- <div key={`tools-${block.tools[0]?.id ?? i}`} className="mt-3">
- <ToolChips
- rows={toChipRows(block.tools)}
- diffs={i === blocks.length - 1 || (i === blocks.length - 2 && lastBlock?.kind === "text") ? turn.diffs : []}
- onOpenPath={onOpenPath}
- />
- </div>
- ) : (
- <div key={`text-${i}`} className="mt-3 max-w-[630px]">
- <Markdown
- text={i === lastTextIndex ? smoothText : block.text}
- streaming={i === lastTextIndex && (draining || turn.status === "streaming" || turn.status === "thinking")}
- onOpenPath={onOpenPath}
- />
- </div>
- ),
- )}
- {waitingOnTools && (
- <div className="mt-4">
- <span
- className="bg-clip-text text-[13px] font-medium whitespace-nowrap text-transparent"
- style={{
- backgroundImage: "linear-gradient(90deg, var(--ink-3) 35%, var(--ink) 50%, var(--ink-3) 65%)",
- backgroundSize: "200% 100%",
- animation: "shimmer-text 1.4s linear infinite",
- }}
- >
- {turn.tools.some((tool) => tool.status === "running") ? "Running tools…" : "Writing…"}
- </span>
- </div>
- )}
- {turn.error && (
- <p className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>
- )}
- {turn.recap && turn.status === "done" && !draining && (
- <p className="mt-3 text-[12px] text-ink-3">{turn.recap}</p>
- )}
- {turn.costUsd !== undefined && turn.status === "done" && !draining && (
- <p className="mt-1 font-mono text-[11px] text-ink-3">${turn.costUsd.toFixed(4)}</p>
- )}
- {turn.status === "done" && !draining && turn.diffs.length > 0 && onReview && (
- <button
- type="button"
- onClick={onReview}
- className="mt-4 flex h-9 w-full max-w-[630px] items-center gap-2 rounded-[10px] bg-surface px-3 text-left shadow-btn transition-colors duration-100 hover:bg-hover"
- style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}
- >
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="shrink-0 text-ink-3" aria-hidden>
- <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
- <path d="M14 2v6h6" />
- </svg>
- <span className="text-[12.5px] font-medium text-ink">
- Changed {turn.diffs.length} file{turn.diffs.length === 1 ? "" : "s"}
- </span>
- <span className="font-mono text-[11.5px] tabular-nums">
- <span className="text-green">+{turn.diffs.reduce((n, d) => n + d.add, 0)}</span>{" "}
- <span className="text-red">−{turn.diffs.reduce((n, d) => n + d.del, 0)}</span>
- </span>
- <span className="ml-auto flex items-center gap-0.5 text-[12.5px] font-medium text-ink-2">
- Review
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
- <path d="M9 18l6-6-6-6" />
- </svg>
- </span>
- </button>
- )}
- </article>
- );
-}
++/** Rows the sidebar previews; the library pages the rest. */
++const SIDEBAR_PAGE = 12;
+
type Msg =
| { id: number; role: "user"; text: string }
| { id: number; role: "assistant"; turn: AssistantTurn };
@@@ -91,45 -283,10 +94,53 @@@ export default function GraffHarness()
// resolution decides, and `current` from that call re-points the picker.
const [models, setModels] = useState<PromptModel[]>(MODELS);
const [model, setModelKey] = useState<string | null>(process.env.NEXT_PUBLIC_GRAFF_MODEL || null);
- const [pane, setPane] = useState<"chat" | "workspace" | "conversations">("chat");
- const filesOpen = pane === "workspace";
+ const [filesOpen, setFilesOpen] = useState(false);
const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);
const fileReqRef = useRef(0);
+ // Shell-style prompt recall (ArrowUp in the composer), kept per browser so
+ // a new tab or a reload still has the last prompts under the cursor.
+ const [history, setHistory] = useState<string[]>([]);
+ useEffect(() => {
+ setHistory(loadHistory(window.localStorage));
+ }, []);
+ // Workspaces are the folders graff runs in. The list and the active pick
+ // live in this browser; the server only validates a root it is handed.
+ // Refs mirror the state for the async paths (spawn, session list) that
+ // must not read a stale closure.
+ const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
+ const [activePath, setActivePath] = useState<string | null>(null);
+ const workspacesRef = useRef<Workspace[]>([]);
+ const activePathRef = useRef<string | null>(null);
+ const [dialog, setDialog] = useState<null | { mode: "new" } | { mode: "settings" }>(null);
+ const [copiedResume, setCopiedResume] = useState(false);
+ // The sidecar browser: one Chrome tab per chat, and the pins the user
+ // drops on it, which ride ahead of the chat's next prompt.
+ const [browserOpen, setBrowserOpen] = useState(false);
++ // The conversation library: every saved chat, paged and searchable. It takes
++ // the whole chat area, so opening it leaves the other side panes.
++ const [conversationsOpen, setConversationsOpen] = useState(false);
+ // The pane comes back after a reload (with its last page: the pane
+ // remembers that itself). Read after mount so the server render matches.
+ const browserOpenRestored = useRef(false);
+ useEffect(() => {
+ try {
+ if (!browserOpenRestored.current) {
+ browserOpenRestored.current = true;
+ if (window.localStorage.getItem(BROWSER_OPEN_KEY) === "1") setBrowserOpen(true);
+ return;
+ }
+ window.localStorage.setItem(BROWSER_OPEN_KEY, browserOpen ? "1" : "0");
+ } catch {
+ // no storage
+ }
+ }, [browserOpen]);
++ const openConversations = () => {
++ setFilesOpen(false);
++ setBrowserOpen(false);
++ setConversationsOpen(true);
++ };
+ const [pinsByChat, setPinsByChat] = useState<Record<number, BrowserPin[]>>({});
+ const pinsRef = useRef<Record<number, BrowserPin[]>>({});
const chatIdRef = useRef(1);
const msgIdRef = useRef(0);
const scrollRef = useRef<HTMLDivElement>(null);
@@@ -299,16 -370,15 +310,17 @@@
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- /** Re-read graff's session directory; tabs adopt the titles graff saved. */
+ /** Re-read the active workspace's session directory; tabs adopt the
+ * titles graff saved. */
const refreshStored = async () => {
try {
- const list = await listSessions(activePathRef.current ?? undefined);
- setStored(list);
- const page = await listSessionsPage({ limit: 12 });
++ const page = await listSessionsPage({ root: activePathRef.current ?? undefined, limit: SIDEBAR_PAGE });
+ setStored(page.sessions);
+ setStoredTotal(page.total);
setChats((current) =>
current.map((c) => {
+ if (c.titledByModel) return c;
- const saved = c.session ? list.find((s) => s.name === c.session) : undefined;
+ const saved = c.session ? page.sessions.find((s) => s.name === c.session) : undefined;
return saved?.title && saved.title !== c.title ? { ...c, title: saved.title } : c;
}),
);
@@@ -317,20 -387,20 +329,22 @@@
}
};
- const openPath = (path: string) => {
- setPane("workspace");
+ const openPath = useCallback((path: string) => {
++ setConversationsOpen(false);
+ setFilesOpen(true);
setFileRequest({ path, n: (fileReqRef.current += 1) });
- };
+ }, []);
- const openChanges = () => {
- setPane("workspace");
+ const openChanges = useCallback(() => {
++ setConversationsOpen(false);
+ setFilesOpen(true);
setFileRequest({ path: "", n: (fileReqRef.current += 1), changes: true });
- };
+ }, []);
- const changeModel = (key: string) => {
- // New tabs inherit the pick; the active tab respawns its agent with it
+ const changeModel = (key: string, forChat?: number) => {
+ // New tabs inherit the pick; the tab respawns its agent with it
// (a fresh context — the agent cannot swap models mid-session).
- const chatId = chatThread.id;
+ const chatId = forChat ?? chatThread.id;
setModelKey(key);
setChatModel(chatId, key);
void requireSession(chatId, true, key)
@@@ -464,27 -470,20 +478,29 @@@
const openChat = (id: number) => {
const session = newSessionName();
sessionNamesRef.current.set(id, session);
- setChats((current) => [...current, { id, title: null, messages: [], model: model ?? undefined, session }]);
+ const cwd = activePathRef.current ?? undefined;
+ const ws = findWorkspace(workspacesRef.current, cwd);
+ setChats((current) => [...current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd }]);
setActiveId(id);
- setPane("chat");
+ setFilesOpen(false);
++ setConversationsOpen(false);
+ setFollowing(true);
// Spawn eagerly so the first send is not stuck behind agent + MCP boot.
void requireSession(id).catch(() => undefined);
};
/** Open a saved graff session: its transcript renders from the file at once,
* and the tab's agent starts with `--resume` so a follow-up remembers it. */
- const openStored = async (name: string) => {
- const existing = chats.find((c) => c.session === name);
+ const openStored = async (name: string, atCwd?: string) => {
+ // The sidebar lists the active workspace, so the session lives there;
+ // the same name in another workspace is a different conversation. A
+ // reopened tab names its own workspace instead.
+ const cwd = atCwd ?? activePathRef.current ?? undefined;
+ const existing = chats.find((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));
if (existing) {
setActiveId(existing.id);
- setPane("chat");
+ setFilesOpen(false);
++ setConversationsOpen(false);
return;
}
let loaded: Awaited<ReturnType<typeof loadSession>>;
@@@ -499,11 -498,10 +515,12 @@@
sessionNamesRef.current.set(id, name);
setChats((current) => [
...current,
- { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name },
+ { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name, cwd },
]);
setActiveId(id);
- setPane("chat");
+ setFilesOpen(false);
++ setConversationsOpen(false);
+ setFollowing(true);
void requireSession(id, false, loaded.meta.model ?? undefined).catch(() => undefined);
};
@@@ -598,290 -534,25 +615,287 @@@
void openStored(id);
};
- // A new message glides the thread to the bottom; streaming growth (reasoning,
- // text, tool rows) follows instantly and only while the reader is already at
- // the tail. Re-issuing a *smooth* scroll on every chunk restarted the scroll
- // animation each token — the whole thread juddered while the model thought.
- const messageCount = chatThread.messages.length;
+ /** Put a saved chat away, or remove it for good. Its tab closes with it,
+ * and the row goes at once rather than after the next poll. */
+ const dropStored = (name: string, archive: boolean) => {
+ const cwd = activePathRef.current ?? undefined;
+ const open = chatsRef.current.find((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));
+ if (open) closeChat(open.id);
+ setStored((current) => current.filter((s) => s.name !== name));
+ void removeSession(name, { root: cwd, archive })
+ .catch(() => undefined)
+ .then(() => refreshStored());
+ };
+
+ /* ── workspaces ── */
+
+ const persistWorkspaces = (list: Workspace[]) => {
+ workspacesRef.current = list;
+ setWorkspaces(list);
+ saveWorkspaces(window.localStorage, list);
+ };
+
+ const activate = (path: string | null) => {
+ activePathRef.current = path;
+ setActivePath(path);
+ saveActiveWorkspace(window.localStorage, path);
+ void refreshStored();
+ };
+
+ /** Move a tab to another folder. Only sound for a tab with no messages:
+ * an agent is bound to its folder at spawn, so this starts a fresh one
+ * there, and a conversation would lose the ground it was standing on. */
+ const moveChatTo = (chatId: number, path: string) => {
+ const ws = findWorkspace(workspacesRef.current, path);
+ const next = chatsRef.current.map((c) => (c.id === chatId ? { ...c, cwd: path, model: c.model ?? ws?.model } : c));
+ // requireSession reads the chat from this ref in the same tick, before
+ // React has re-rendered with the new cwd.
+ chatsRef.current = next;
+ setChats(next);
+ setPanes((current) => current.filter((pane) => pane !== chatId));
+ setActiveId(chatId);
+ void requireSession(chatId, true)
+ .then(() => adoptCatalog(chatId))
+ .catch(() => undefined);
+ };
+
+ /** Switch the sidebar to a workspace and land on a tab that runs there.
+ * The tab in front follows the switch when nothing has been asked in it
+ * yet — picking a folder should change the folder you are looking at.
+ * A tab with a conversation keeps its own folder, and says which. */
+ const switchWorkspace = (path: string) => {
+ if (path === activePathRef.current) return;
+ activate(path);
+ setFilesOpen(false);
+ const here = chatsRef.current.find((c) => c.id === activeId);
+ if (here && here.messages.length === 0) {
+ moveChatTo(here.id, path);
+ return;
+ }
+ const empty = chatsRef.current.find((c) => c.cwd === path && c.messages.length === 0);
+ if (empty) {
+ setActiveId(empty.id);
+ return;
+ }
+ openChat((chatIdRef.current += 1));
+ };
+
+ const addWorkspace = (path: string) => {
+ const list = upsertWorkspace(workspacesRef.current, { path, name: basename(path) });
+ persistWorkspaces(list);
+ setDialog(null);
+ const added = findWorkspace(list, path);
+ if (added) switchWorkspace(added.path);
+ };
+
+ const saveWorkspace = (ws: Workspace) => {
+ persistWorkspaces(upsertWorkspace(workspacesRef.current, ws));
+ setDialog(null);
+ };
+
+ /** Drop a workspace from the switcher (nothing on disk changes). If it
+ * was active, the next row — or the server default — takes over. */
+ const forgetWorkspace = (path: string) => {
+ const list = removeWorkspace(workspacesRef.current, path);
+ persistWorkspaces(list);
+ setDialog(null);
+ if (activePathRef.current === path) {
+ const next = list[0]?.path ?? health?.cwd ?? null;
+ if (next) switchWorkspace(next);
+ else activate(null);
+ }
+ };
+
+ /** The footer names the tab's own graff session; clicking it copies the
+ * command that continues the same conversation in a terminal. */
+ const copyResume = () => {
+ const name = chatThread.session;
+ if (!name || typeof navigator === "undefined" || !navigator.clipboard) return;
+ const cmd = chatThread.cwd ? `cd ${shellQuote(chatThread.cwd)} && graff --resume ${name}` : `graff --resume ${name}`;
+ void navigator.clipboard
+ .writeText(cmd)
+ .then(() => {
+ setCopiedResume(true);
+ window.setTimeout(() => setCopiedResume(false), 1400);
+ })
+ .catch(() => undefined);
+ };
+
+ // Every visible column follows its own tail: jump to the bottom when it
+ // appears, and stop following as soon as the reader scrolls up in it.
useEffect(() => {
- if (!active) return;
- const el = scrollRef.current;
- if (el) el.scrollTop = el.scrollHeight;
- }, [messageCount, activeId, active]);
+ const off: (() => void)[] = [];
+ for (const id of columnKey.split(",").filter(Boolean).map(Number)) {
+ const el = scrollEls.current.get(id);
+ if (!el) continue;
+ el.scrollTop = el.scrollHeight;
+ setTailing((current) => (current[id] === true ? current : { ...current, [id]: true }));
+ const onScroll = () => {
+ const next = isFollowingTail(el);
+ setTailing((current) => (current[id] === next ? current : { ...current, [id]: next }));
+ };
+ el.addEventListener("scroll", onScroll, { passive: true });
+ off.push(() => el.removeEventListener("scroll", onScroll));
+ }
+ return () => off.forEach((stop) => stop());
+ }, [columnKey]);
+
useEffect(() => {
- if (!active) return;
- pinScrollerTail(scrollRef.current);
- }, [active, lastAssistant?.turn.text, lastAssistant?.turn.reasoning, lastAssistant?.turn.tools.length]);
+ for (const id of columnKey.split(",").filter(Boolean).map(Number)) {
+ pinScrollerTail(scrollEls.current.get(id) ?? null, tailing[id] ?? true);
+ }
+ }, [chats, tailing, columnKey]);
- // The sidebar is graff's session directory, newest first, bucketed by day.
- // Sidebar preview: first page of the session index, newest first.
- const recents = stored.map((s) => toSidebarRecent(s));
++ // Sidebar preview: the first page of the session index, newest first. A
++ // session open in a tab shows the tab's name (the model wrote it from the
++ // first prompt); one only on disk shows whatever graff saved.
+ const now = Date.now();
- // A session open in a tab shows the tab's name (the model wrote it from
- // the first prompt); one only on disk shows whatever graff saved.
- const recents = stored.map((s) => ({
- id: s.name,
- label: chats.find((c) => c.session === s.name)?.title ?? s.title ?? s.name,
- group: dateGroup(s.updatedMs, now),
- hint: [s.model, relativeTime(s.updatedMs, now)].filter(Boolean).join(" · "),
- }));
++ const recents = stored.map((s) => {
++ const row = toSidebarRecent(s, now);
++ const live = chats.find((c) => c.session === s.name)?.title;
++ return live ? { ...row, label: live } : row;
++ });
- const workspaceName = health?.cwd ? (health.cwd.split("/").pop() || health.cwd) : "workspace";
+ // The tab bar's folder chip is the *tab's* workspace; the sidebar's
+ // switcher is the *active* one (where new tabs open). They differ only
+ // after a switch, and each says so on hover.
+ const cwdOf = (thread: Chat) => thread.cwd ?? activePath ?? health?.cwd;
+ const workspaceNameOf = (thread: Chat) => {
+ const dir = cwdOf(thread);
+ return findWorkspace(workspaces, dir)?.name ?? (dir ? basename(dir) : "workspace");
+ };
+ const chatCwd = cwdOf(chatThread);
+ const chatWorkspace = findWorkspace(workspaces, chatCwd);
+ const workspaceName = chatWorkspace?.name ?? (chatCwd ? basename(chatCwd) : "workspace");
+ const pinCount = (pinsByChat[chatThread.id] ?? []).length;
+ const activeWorkspace = findWorkspace(workspaces, activePath);
+ const sidebarWorkspace = activeWorkspace ?? (activePath ? { path: activePath, name: basename(activePath) } : undefined);
+ const footerTitle = chatThread.session
+ ? `graff session ${chatThread.session}${sessionId ? ` · ACP ${sessionId}` : ""}${chatCwd ? ` · ${chatCwd}` : ""}\nClick to copy the command that resumes it in a terminal.`
+ : undefined;
+
+ /** One chat column: its transcript (or the empty state) and its composer.
+ * A plain function, not a component, so the split view can render two of
+ * them without React remounting either on every parent render. */
+ const columnBody = (thread: Chat) => {
+ const isFollowing = tailing[thread.id] ?? true;
+ const hasMessages = thread.messages.length > 0;
+ const threadBusy = busyIds.has(thread.id);
+ const threadModel = thread.model ?? model ?? undefined;
+ const threadQueued = queues[thread.id] ?? [];
+ const threadPins = (pinsByChat[thread.id] ?? []).length;
+ const threadHistory = mergeHistory(history, thread.messages.flatMap((m) => (m.role === "user" ? [m.text] : [])));
+ return (
+ <>
+
+ {hasMessages ? (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div ref={paneRef(thread.id)} className="min-h-0 flex-1 overflow-y-auto overscroll-contain" style={{ overflowAnchor: "none" }}>
+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">
+ {thread.messages.map((message, index) =>
+ message.role === "user" ? (
+ <UserBubble key={message.id} text={message.text} />
+ ) : (
+ <AssistantBody
+ key={message.id}
+ turn={message.turn}
+ onOpenPath={openPath}
+ onReview={openChanges}
+ scroller={scrollRef}
+ following={isFollowing && index === thread.messages.length - 1}
+ />
+ ),
+ )}
+ </div>
+ </div>
+ <div className="shrink-0 bg-page px-4 pt-3 pb-6 sm:px-8">
+ <div className="mx-auto max-w-[720px]">
+ {threadPins > 0 && (
+ <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">
+ <span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span>
+ <span className="min-w-0 flex-1 truncate text-ink">
+ {threadPins} element{threadPins === 1 ? "" : "s"} in the browser go with your next message
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ setActiveId(thread.id);
+ setFilesOpen(false);
+ setBrowserOpen(true);
+ }}
+ className="shrink-0 rounded px-1.5 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink"
+ >
+ Show
+ </button>
+ <button
+ type="button"
+ aria-label="Clear pins"
+ onClick={() => setPins(thread.id, [])}
+ className="flex size-5 shrink-0 items-center justify-center rounded-[5px] text-ink-3 hover:bg-hover hover:text-ink"
+ >
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>
+ <path d="M18 6L6 18M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ )}
+ {threadQueued.length > 0 && (
+ <ul className="mb-2 flex flex-col gap-1">
+ {threadQueued.map((item) => (
+ <li
+ key={item.id}
+ className="flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline"
+ >
+ <span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Queued</span>
+ <span className="min-w-0 flex-1 truncate text-ink">{item.text}</span>
+ <button
+ type="button"
+ aria-label="Remove from queue"
+ onClick={() => setQueue(thread.id, dropQueuedPrompt(queuesRef.current[thread.id] ?? [], item.id))}
+ className="flex size-5 shrink-0 items-center justify-center rounded-[5px] text-ink-3 hover:bg-hover hover:text-ink"
+ >
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>
+ <path d="M18 6L6 18M6 6l12 12" />
+ </svg>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ <PromptBar
+ demo={false}
+ tall
+ placeholder={threadBusy ? "Queue a follow-up…" : "Follow up"}
+ models={models}
+ modelKey={threadModel}
+ onModelChange={(key: string) => changeModel(key, thread.id)}
+ onSend={(text: string) => void send(text, thread.id)}
+ history={threadHistory}
+ busy={threadBusy}
+ onStop={() => {
+ const live = sessionsRef.current.get(thread.id);
+ if (live) void cancel(handleOf(thread.id), live);
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <EmptyState
+ onSend={(text: string) => void send(text, thread.id)}
+ health={health}
+ history={threadHistory}
+ cwd={cwdOf(thread)}
- offset={offset}
- shuffle={() => setOffset((current) => (current + 3) % STARTER_PROMPTS.length)}
+ models={models}
+ modelKey={threadModel}
+ onModelChange={(key: string) => changeModel(key, thread.id)}
+ />
+ </div>
+ )}
+ </>
+ );
+ };
const tabBar = (
<div className="flex h-11 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
@@@ -899,13 -570,7 +913,16 @@@
aria-label="Working"
/>
)}
- <button type="button" aria-pressed={c.id === activeId} onClick={() => { setActiveId(c.id); setPane("chat"); }} title={c.title ?? "New chat"} className="min-w-0 flex-1 text-left">
+ <button
+ type="button"
+ aria-pressed={c.id === activeId}
- onClick={() => focusChat(c.id)}
++ onClick={() => {
++ focusChat(c.id);
++ setConversationsOpen(false);
++ }}
+ title={c.title ?? "New chat"}
+ className="min-w-0 flex-1 text-left"
+ >
<span className="block truncate">{c.title ?? "New chat"}</span>
</button>
<button
@@@ -933,29 -596,24 +950,42 @@@
</svg>
</button>
<div className="ml-auto flex items-center gap-2 pr-1">
+ <button
+ type="button"
- aria-pressed={pane === "conversations"}
- onClick={() => setPane((current) => (current === "conversations" ? "chat" : "conversations"))}
++ aria-pressed={conversationsOpen}
++ onClick={openConversations}
+ title="All conversations"
+ className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${
- pane === "conversations" ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"
++ conversationsOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"
+ }`}
+ >
+ <IconChat size={14} />
+ <span className="hidden sm:inline">Chats</span>
+ </button>
+ <button
+ type="button"
+ aria-pressed={panes.length > 0}
+ onClick={toggleSplit}
+ title={panes.length > 0 ? "Close the splits (⌘\\)" : "Split the view: another chat beside this one (⌘D adds one)"}
+ className={`flex size-7 items-center justify-center rounded-[7px] transition-colors duration-100 ${
+ panes.length > 0 ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"
+ }`}
+ >
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <rect x="3" y="4" width="18" height="16" rx="2" />
+ <path d="M12 4v16" />
+ </svg>
+ </button>
<button
type="button"
aria-pressed={filesOpen}
- onClick={() => setPane((current) => (current === "workspace" ? "chat" : "workspace"))}
- title={health?.cwd ?? "Workspace files"}
- className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${
+ onClick={() => {
+ setBrowserOpen(false);
++ setConversationsOpen(false);
+ setFilesOpen((open) => !open);
+ }}
+ title={`${chatCwd ?? "Workspace"}\nShow this chat's files`}
+ className={`flex h-7 items-center gap-1.5 rounded-l-[7px] pl-2 pr-1.5 text-[12px] font-medium transition-colors duration-100 ${
filesOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"
}`}
>
@@@ -1063,85 -638,76 +1094,108 @@@
activeId={chatThread.session ?? null}
onPick={pickRecent}
onNewChat={newChat}
- activeNav={filesOpen ? "workspace" : browserOpen ? "browser" : "chats"}
- onSeeAll={() => setPane("conversations")}
- activeNav={pane === "workspace" ? "workspace" : pane === "conversations" ? "conversations" : "home"}
++ onSeeAll={openConversations}
++ activeNav={filesOpen ? "workspace" : browserOpen ? "browser" : conversationsOpen ? "conversations" : "home"}
onNavigate={(key) => {
- if (key === "workspace") setPane("workspace");
- else if (key === "conversations") setPane("conversations");
- else setPane("chat");
+ setFilesOpen(key === "workspace");
+ setBrowserOpen(key === "browser");
++ setConversationsOpen(key === "conversations");
}}
- footerLabel={sessionId ? `Session ${sessionId.slice(0, 8)}` : "Connecting…"}
- onFooterClick={() => undefined}
+ workspace={sidebarWorkspace}
+ workspaces={workspaces.map((w) => ({ path: w.path, name: w.name }))}
+ onSwitchWorkspace={switchWorkspace}
+ onArchiveRecent={(id) => dropStored(id, true)}
+ onDeleteRecent={(id) => dropStored(id, false)}
+ onNewWorkspace={() => setDialog({ mode: "new" })}
+ onWorkspaceSettings={() => setDialog(sidebarWorkspace ? { mode: "settings" } : { mode: "new" })}
+ footerLabel={copiedResume ? "Copied resume command" : (chatThread.session ?? "Connecting…")}
+ footerTitle={footerTitle}
+ onFooterClick={copyResume}
/>
<div className="flex min-w-0 flex-1 flex-col gap-2.5">
<div className="flex min-h-0 flex-1 gap-2.5">
- {columns.map((thread, slot) => (
- <section
- key={thread.id}
- data-chat={thread.id}
- className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page"
- >
- {slot === 0 ? (
- tabBar
- ) : (
- <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-3">
- {busyIds.has(thread.id) && (
- <span className="size-1.5 shrink-0 animate-pulse rounded-full" style={{ background: "var(--accent)" }} aria-label="Working" />
- )}
- <button
- type="button"
- onClick={() => focusChat(thread.id)}
- title="Make this the main chat"
- className="min-w-0 flex-1 truncate text-left text-[12.5px] font-medium text-ink"
- >
- {thread.title ?? "New chat"}
- </button>
- <span
- title={cwdOf(thread) ?? "workspace"}
- className="flex h-7 shrink-0 items-center gap-1.5 rounded-[7px] px-1.5 text-[12px] font-medium text-ink-2"
- >
- <IconFolder size={14} />
- <span className="max-w-32 truncate font-mono text-[11.5px]">{workspaceNameOf(thread)}</span>
- </span>
- <button
- type="button"
- aria-label="Close this split"
- title="Close this split"
- onClick={() => closePane(thread.id)}
- className="flex size-7 shrink-0 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
- >
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>
- <path d="M18 6L6 18M6 6l12 12" />
- </svg>
- </button>
- </div>
- )}
- {columnBody(thread)}
- <section className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">
- {tabBar}
- {pane === "conversations" ? (
++ {conversationsOpen ? (
++ <section className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">
++ {tabBar}
+ <ConversationsPane
++ root={chatCwd}
+ activeId={chatThread.session ?? null}
- onPick={pickRecent}
- onNewChat={newChat}
++ onPick={(name) => {
++ setConversationsOpen(false);
++ pickRecent(name);
++ }}
++ onNewChat={() => {
++ setConversationsOpen(false);
++ newChat();
++ }}
+ />
- ) : active ? (
- <div className="flex min-h-0 flex-1 flex-col">
- <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
- <div className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">
- {chatThread.messages.map((message) =>
- message.role === "user" ? (
- <UserBubble key={message.id} text={message.text} />
- ) : (
- <AssistantBody key={message.id} turn={message.turn} onOpenPath={openPath} onReview={openChanges} scroller={scrollRef} />
- ),
+ </section>
- ))}
++ ) : (
++ <>
++ {columns.map((thread, slot) => (
++ <section
++ key={thread.id}
++ data-chat={thread.id}
++ className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page"
++ >
++ {slot === 0 ? (
++ tabBar
++ ) : (
++ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-3">
++ {busyIds.has(thread.id) && (
++ <span className="size-1.5 shrink-0 animate-pulse rounded-full" style={{ background: "var(--accent)" }} aria-label="Working" />
+ )}
++ <button
++ type="button"
++ onClick={() => focusChat(thread.id)}
++ title="Make this the main chat"
++ className="min-w-0 flex-1 truncate text-left text-[12.5px] font-medium text-ink"
++ >
++ {thread.title ?? "New chat"}
++ </button>
++ <span
++ title={cwdOf(thread) ?? "workspace"}
++ className="flex h-7 shrink-0 items-center gap-1.5 rounded-[7px] px-1.5 text-[12px] font-medium text-ink-2"
++ >
++ <IconFolder size={14} />
++ <span className="max-w-32 truncate font-mono text-[11.5px]">{workspaceNameOf(thread)}</span>
++ </span>
++ <button
++ type="button"
++ aria-label="Close this split"
++ title="Close this split"
++ onClick={() => closePane(thread.id)}
++ className="flex size-7 shrink-0 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
++ >
++ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>
++ <path d="M18 6L6 18M6 6l12 12" />
++ </svg>
++ </button>
+ </div>
- </div>
- <div className="shrink-0 bg-page px-4 pt-3 pb-6 sm:px-8">
- <div className="mx-auto max-w-[720px]">
- <PromptBar
- demo={false}
- tall
- placeholder={busy ? "Agent is working…" : "Follow up"}
- models={models}
- modelKey={chatModel}
- onModelChange={changeModel}
- onSend={send}
- disabled={busy}
- busy={busy}
- onStop={() => {
- const live = sessionsRef.current.get(chatThread.id);
- if (live) void cancel(handleOf(chatThread.id), live);
- }}
- />
- </div>
- </div>
- </div>
- ) : (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <EmptyState
- onSend={send}
- health={health}
- models={models}
- modelKey={chatModel}
- onModelChange={changeModel}
- />
- </div>
- )}
- </section>
++ )}
++ {columnBody(thread)}
++ </section>
++ ))}
++
++ </>
++ )}
+
- {filesOpen && <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />}
++ {filesOpen && !conversationsOpen && <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />}
- {browserOpen && (
- {filesOpen && <FilesPane requested={fileRequest} onClose={() => setPane("chat")} />}
++ {browserOpen && !conversationsOpen && (
+ <BrowserPane
+ key={chatThread.id}
+ chat={handleOf(chatThread.id)}
+ memoryKey={chatCwd}
+ pins={pinsByChat[chatThread.id] ?? []}
+ onPinsChange={(next) => setPins(chatThread.id, next)}
+ onAsk={() => void send("Make the changes I pinned in the browser.")}
+ onClose={() => setBrowserOpen(false)}
+ />
+ )}
- {!filesOpen && !browserOpen && active && paneTodos.length > 0 && (
- {pane === "chat" && active && paneTodos.length > 0 && (
++ {!filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (
<aside
className="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"
style={{ animation: "fade-in 300ms ease both" }}
diff --cc apps/native/lib/sessions.ts
index 06e0f0e3,bb5d908d..645533e5
--- a/apps/native/lib/sessions.ts
+++ b/apps/native/lib/sessions.ts
@@@ -25,33 -38,36 +38,61 @@@ export type TranscriptMsg
const BASE = "/api/sessions";
+function withRoot(params: Record<string, string | undefined>): string {
+ const q = new URLSearchParams();
+ for (const [k, v] of Object.entries(params)) if (v !== undefined) q.set(k, v);
+ const s = q.toString();
+ return s ? `?${s}` : "";
+}
+
- /** Sessions saved under `<root>/.graff/sessions`; absent root = the default workspace. */
+/** Put a saved chat away (the file moves under `.graff/sessions/archived/`)
+ * or, with `archive: false`, remove it for good. */
+export async function removeSession(name: string, opts: { root?: string; archive?: boolean } = {}): Promise<void> {
+ const params = new URLSearchParams({ name });
+ if (opts.root) params.set("root", opts.root);
+ if (opts.archive === false) params.set("archive", "0");
+ const res = await fetch(`${BASE}?${params.toString()}`, { method: "DELETE", cache: "no-store" });
+ if (!res.ok) throw new Error(`sessions → ${res.status}`);
+}
+
- export async function listSessions(root?: string): Promise<StoredSession[]> {
- const res = await fetch(`${BASE}${withRoot({ root })}`, { cache: "no-store" });
++/** One page of the session index. `root` scopes it to a workspace, absent =
++ * the server's default; the rest is the cursor, the query and the scope. */
+ export async function listSessionsPage(opts: {
+ limit?: number;
+ cursor?: string | null;
+ q?: string;
+ scope?: SessionScope;
++ root?: string;
+ } = {}): Promise<SessionPage> {
- const params = new URLSearchParams();
- if (opts.limit) params.set("limit", String(opts.limit));
- if (opts.cursor) params.set("cursor", opts.cursor);
- if (opts.q?.trim()) params.set("q", opts.q.trim());
- if (opts.scope && opts.scope !== "all") params.set("scope", opts.scope);
- const qs = params.toString();
- const res = await fetch(qs ? `${BASE}?${qs}` : BASE, { cache: "no-store" });
++ const res = await fetch(
++ `${BASE}${withRoot({
++ root: opts.root,
++ limit: opts.limit ? String(opts.limit) : undefined,
++ cursor: opts.cursor ?? undefined,
++ q: opts.q?.trim() ? opts.q.trim() : undefined,
++ scope: opts.scope && opts.scope !== "all" ? opts.scope : undefined,
++ })}`,
++ { cache: "no-store" },
++ );
if (!res.ok) throw new Error(`sessions → ${res.status}`);
- const body = (await res.json()) as { sessions?: StoredSession[] };
- return body.sessions ?? [];
+ const body = (await res.json()) as Partial<SessionPage>;
+ return {
+ cwd: body.cwd,
+ sessions: body.sessions ?? [],
+ nextCursor: body.nextCursor ?? null,
+ total: typeof body.total === "number" ? body.total : (body.sessions ?? []).length,
+ };
+ }
+
-export async function listSessions(): Promise<StoredSession[]> {
- const page = await listSessionsPage();
++/** Sessions saved under `<root>/.graff/sessions`; absent root = the default
++ * workspace. The first page only — the library pages the rest. */
++export async function listSessions(root?: string): Promise<StoredSession[]> {
++ const page = await listSessionsPage({ root });
+ return page.sessions;
}
-export async function loadSession(name: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {
- const res = await fetch(`${BASE}?name=${encodeURIComponent(name)}`, { cache: "no-store" });
+export async function loadSession(name: string, root?: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {
+ const res = await fetch(`${BASE}${withRoot({ name, root })}`, { cache: "no-store" });
if (!res.ok) {
const detail = await res.text().catch(() => "");
throw new Error(`session ${name} → ${res.status}: ${detail.slice(0, 200)}`);
diff --cc apps/native/package.json
index d81ac791,565c7cc4..972aa99a
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@@ -10,10 -10,9 +10,10 @@@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts"
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts"
++ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts"
},
"dependencies": {
+ "@streamdown/code": "^1.1.1",
"glimm": "^0.3.0",
"iconoir-react": "^7.11.1",
"liveline": "^0.0.7",