graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(native): paginated conversation library
Cursor Agentd2a6617902fc
diff --git a/apps/native/README.md b/apps/native/README.mdindex 84f85e36..07b6de50 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -67,12 +67,13 @@ and re-reads `current` after every respawn, so the picker reflects whatgraff'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.The workspace itself is walkable: `/api/fs` (list/read, plus macOS`open`/`open -R` passthroughs) is sandboxed to the agent's cwd and backsdiff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.tsindex 80e3e4de..f656a485 100644--- a/apps/native/app/api/sessions/route.ts+++ b/apps/native/app/api/sessions/route.ts@@ -1,6 +1,17 @@-import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";+import { existsSync, readFileSync, statSync } from "node:fs";import path from "node:path";import { NextRequest } from "next/server";+import {+ MAX_FULL_BYTES,+ NAME_RE,+ clampLimit,+ findSessionFile,+ homeDir,+ listSessionRows,+ pageSessions,+ peekHeader,+ type ListScope,+} from "@/lib/session-store";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -14,90 +25,35 @@ function workspaceRoot(): string {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";-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;-};-function str(v: unknown): string | null {return typeof v === "string" && v.length > 0 ? v : null;}-function peekHeader(file: string, size: number): Header | null {- const fd = openSync(file, "r");- try {- const want = Math.min(size, PEEK_BYTES);- const buf = Buffer.alloc(want);- const n = readSync(fd, buf, 0, want, 0);- const text = buf.toString("utf8", 0, n);- // Quotes inside string values are escaped in the file, so the raw needle- // only matches the real top-level key.- const idx = text.indexOf('"messages":');- if (idx < 0) return null;- let head = text.slice(0, idx).trimEnd();- if (head.endsWith(",")) head = head.slice(0, -1);- return JSON.parse(`${head}}`) as Header;- } catch {- return null;- } finally {- closeSync(fd);- }-}--function rowFor(dir: string, entry: string): StoredSessionRow | null {- const name = entry.slice(0, -EXT.length);- if (!NAME_RE.test(name)) return null;- const file = path.join(dir, entry);- let size = 0;- let mtimeMs = 0;- try {- const st = statSync(file);- if (!st.isFile()) return null;- size = st.size;- mtimeMs = st.mtimeMs;- } catch {- return null;- }- const header = size > 0 ? peekHeader(file, size) : null;- const updated = typeof header?.updated_ms === "number" && header.updated_ms > 0 ? header.updated_ms : Math.round(mtimeMs);- return {- name,- title: str(header?.title),- updatedMs: updated,- model: str(header?.model),- provider: str(header?.provider),- size,- };+function parseScope(raw: string | null): ListScope {+ if (raw === "local" || raw === "elsewhere") return raw;+ return "all";}export async function GET(req: NextRequest) {const root = workspaceRoot();- 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 });- const file = path.join(dir, `${name}${EXT}`);- if (!existsSync(file)) return Response.json({ error: "no such session" }, { status: 404 });- const st = statSync(file);+ const found = findSessionFile(root, name, home);+ if (!found) return Response.json({ error: "no such session" }, { status: 404 });+ const st = statSync(found.file);if (st.size > MAX_FULL_BYTES) return Response.json({ error: "session too large to open" }, { status: 413 });try {- const parsed = JSON.parse(readFileSync(file, "utf8")) as Header & { messages?: unknown };+ const parsed = JSON.parse(readFileSync(found.file, "utf8")) as {+ title?: unknown;+ updated_ms?: unknown;+ model?: unknown;+ provider?: unknown;+ workspace?: unknown;+ messages?: unknown;+ };+ const header = peekHeader(found.file, st.size);return Response.json({name,title: str(parsed.title),@@ -105,19 +61,19 @@ export async function GET(req: NextRequest) {provider: str(parsed.provider),updatedMs: typeof parsed.updated_ms === "number" ? parsed.updated_ms : Math.round(st.mtimeMs),size: st.size,+ workspace: str(parsed.workspace) ?? str(header?.workspace) ?? found.workspace,+ local: found.local,messages: Array.isArray(parsed.messages) ? parsed.messages : [],});} catch (err) {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 });}diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsxindex ddcf2116..8ed1e634 100644--- a/apps/native/components/primitives/SidebarNav.tsx+++ b/apps/native/components/primitives/SidebarNav.tsx@@ -11,6 +11,7 @@ import {IconFolder,IconHome,IconMagnifyingGlass,+ IconChat,IconPlusMedium,IconPopsicle2,IconSettingsGear1,@@ -30,6 +31,7 @@ const WORKSPACE = { key: "graff", name: "Codegraff", monogram: "G" };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} /> },];@@ -66,11 +68,14 @@ type SidebarNavProps = {footerIcon?: ReactNode;onFooterClick?: () => void;recents?: SidebarRecent[];+ /** How many saved sessions exist (sidebar only shows a preview). */+ recentsTotal?: number;+ onSeeAll?: () => void;variant?: string;};const SIDEBAR_MOTION = {- expandedWidth: 224,+ expandedWidth: 248,collapsedWidth: 52,duration: 280,copyDuration: 180,@@ -217,6 +222,8 @@ export default function SidebarNav({footerIcon,onFooterClick,recents = DEFAULT_RECENTS,+ recentsTotal,+ onSeeAll,}: SidebarNavProps) {const [collapsed, setCollapsed] = useState(false);const [internalNav, setInternalNav] = useState("chats");@@ -273,7 +280,7 @@ export default function SidebarNav({"--sidebar-easing": SIDEBAR_MOTION.easing,} as CSSProperties}>- <div className="flex min-h-0 w-[224px] shrink-0 flex-col">+ <div className="flex min-h-0 w-[248px] shrink-0 flex-col"><div className="relative mb-2.5 h-10 shrink-0"><buttonref={workspaceButtonRef}@@ -289,7 +296,7 @@ export default function SidebarNav({}setWorkspaceOpen((open) => !open);}}- className="sidebar-workspace-control absolute left-2 top-1 flex h-8 w-[164px] items-center rounded-[8px] px-2 text-left transition-[background-color,transform] duration-100 hover:bg-hover-2 active:scale-[0.99]"+ className="sidebar-workspace-control absolute left-2 top-1 flex h-8 w-[188px] items-center rounded-[8px] px-2 text-left transition-[background-color,transform] duration-100 hover:bg-hover-2 active:scale-[0.99]"><span className="sidebar-logo flex size-5 shrink-0 items-center justify-center text-ink"><IconPopsicle2 size={18} />@@ -341,7 +348,7 @@ export default function SidebarNav({key={item.key}icon={item.icon}label={item.label}- count={item.count}+ count={item.key === "conversations" && recentsTotal != null ? String(recentsTotal) : item.count}active={currentNav === item.key}onClick={() => selectNav(item.key)}/>@@ -425,16 +432,21 @@ export default function SidebarNav({type="button"title={item.hint ? `${item.label} — ${item.hint}` : item.label}onClick={() => {- selectNav("chats");+ selectNav("home");if (activeTitle === undefined) setDemoActiveTitle(item.label);onPick?.(item.id, item.label, item.prompt);}}- className={`sidebar-row relative z-10 mx-2 flex h-8 items-center rounded-[8px] px-2 text-left transition-[width,background-color,color,transform] duration-150 active:scale-[0.98] ${+ className={`sidebar-row relative z-10 mx-2 flex min-h-10 items-center rounded-[8px] px-2 py-1.5 text-left transition-[width,background-color,color,transform] duration-150 active:scale-[0.98] ${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></Fragment>@@ -443,10 +455,23 @@ export default function SidebarNav({{query && visibleRecents.length === 0 && (<div className="sidebar-copy mx-2 px-2 py-2 text-[12.5px] text-ink-3">No chats found</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 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"><buttontype="button"onClick={onFooterClick ?? onNewChat}diff --git a/apps/native/components/site/ConversationsPane.tsx b/apps/native/components/site/ConversationsPane.tsxnew file mode 100644index 00000000..d966ca5b--- /dev/null+++ b/apps/native/components/site/ConversationsPane.tsx@@ -0,0 +1,219 @@+"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,+}: {+ activeId?: string | null;+ onPick: (name: string) => void;+ onNewChat?: () => void;+}) {+ 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 })+ .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]);++ 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 })+ .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 --git a/apps/native/components/site/EmptyState.tsx b/apps/native/components/site/EmptyState.tsxnew file mode 100644index 00000000..a8f80440--- /dev/null+++ b/apps/native/components/site/EmptyState.tsx@@ -0,0 +1,121 @@+"use client";++import { useEffect, useState, type CSSProperties } from "react";+import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";+import { STARTER_PROMPTS, type Health } from "@/lib/acp-client";++function greeting(): string {+ const hour = new Date().getHours();+ if (hour < 5) return "Up late";+ if (hour < 12) return "Good morning";+ if (hour < 18) return "Good afternoon";+ return "Good evening";+}++const HOME_REVEAL = {+ offsetY: 23,+ blur: 17,+ duration: 800,+ easing: "cubic-bezier(0.16, 1, 0.3, 1)",+};++function homeRevealStyle(visible: boolean): CSSProperties {+ return {+ opacity: visible ? 1 : 0,+ transform: visible ? "translate3d(0, 0, 0)" : `translate3d(0, ${HOME_REVEAL.offsetY}px, 0)`,+ filter: visible ? "blur(0px)" : `blur(${HOME_REVEAL.blur}px)`,+ transition: ["opacity", "transform", "filter"]+ .map((property) => `${property} ${HOME_REVEAL.duration}ms ${HOME_REVEAL.easing}`)+ .join(", "),+ };+}++export default function EmptyState({+ onSend,+ health,+ models,+ modelKey,+ onModelChange,+}: {+ onSend: (text: string) => void;+ health: Health | null;+ models: PromptModel[];+ modelKey?: string;+ onModelChange: (key: string) => void;+}) {+ 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 = [+ setTimeout(() => setStage(1), 170),+ setTimeout(() => setStage(2), 330),+ setTimeout(() => setStage(3), 400),+ setTimeout(() => setStage(4), 550),+ ];+ return () => timers.forEach(clearTimeout);+ }, []);++ return (+ <div className="mx-auto flex min-h-full max-w-[720px] flex-col justify-center px-4 py-10 sm:px-8">+ <h1 className="text-[26px] font-normal tracking-[-0.02em] text-ink">+ <span className="home-reveal block text-ink-3" style={homeRevealStyle(stage >= 1)}>+ {greeting()}+ </span>+ <span className="home-reveal block" style={homeRevealStyle(stage >= 2)}>+ What should graff work on?+ </span>+ </h1>++ <div className="home-reveal relative mt-7" style={homeRevealStyle(stage >= 3)}>+ <PromptBar+ demo={false}+ tall+ placeholder="Ask graff to read, edit, or review this workspace…"+ models={models}+ modelKey={modelKey}+ onModelChange={onModelChange}+ onSend={onSend}+ disabled={health !== null && !health.ok}+ />+ {health && !health.ok && (+ <p className="mt-3 text-[12.5px] text-orange">+ graff acp is not reachable. From the repo root run{" "}+ <span className="font-mono text-ink">zig build</span>+ {health.detail ? ` — ${health.detail}` : ""}.+ </p>+ )}+ </div>++ <div className="home-reveal mt-6 flex flex-col" style={homeRevealStyle(stage >= 4)}>+ {shown.map((item) => (+ <button+ key={item.id}+ type="button"+ onClick={() => onSend(item.prompt)}+ className="-mx-2 flex items-center gap-3 rounded-control px-2 py-2.5 text-left text-[14px] text-ink transition-colors duration-150 hover:bg-hover"+ >+ <span className="text-ink-3">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <path d="M8 6l-5 6 5 6M16 6l5 6-5 6" />+ </svg>+ </span>+ <span className="min-w-0 truncate">{item.label}</span>+ </button>+ ))}+ <div className="mt-1 flex items-center gap-5 pl-0.5 text-[13px] text-ink-3">+ <span className="flex items-center gap-2 py-1" title={health?.cwd}>+ <span className={`size-1.5 rounded-full ${health?.ok ? "bg-green" : "bg-orange"}`} />+ {health?.ok+ ? `Connected · ${health.cwd ? (health.cwd.split("/").pop() ?? health.cwd) : "over ACP"}`+ : "Waiting for graff acp"}+ </span>+ <button type="button" onClick={shuffle} className="flex items-center gap-2 py-1 transition-colors duration-150 hover:text-ink">+ Shuffle suggestions+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex de8d2a7e..105045fe 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -1,18 +1,19 @@"use client";-import { useEffect, useRef, useState, type CSSProperties, type RefObject } from "react";+import { useEffect, useRef, useState, type RefObject } from "react";import Markdown from "@/components/primitives/Markdown";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 { IconFolder } from "@/lib/icons";+import { IconChat, IconFolder } from "@/lib/icons";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 {MODELS,- STARTER_PROMPTS,cancel,chatHandle,checkHealth,@@ -24,17 +25,7 @@ import {type Health,} from "@/lib/acp-client";import { applyAcpUpdate, emptyTurn, finishAcpTurn, turnBlocks, type AssistantTurn } from "@/lib/acp";-import { dateGroup, listSessions, loadSession, relativeTime, type StoredSession } from "@/lib/sessions";--const NAME = "there";--function greeting(): string {- const hour = new Date().getHours();- if (hour < 5) return "Up late";- if (hour < 12) return "Good morning";- if (hour < 18) return "Good afternoon";- return "Good evening";-}+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@@ -89,24 +80,6 @@ function pinScrollerTail(el: HTMLElement | null): void {if (fromBottom < 240) el.scrollTop = el.scrollHeight;}-const HOME_REVEAL = {- offsetY: 23,- blur: 17,- duration: 800,- easing: "cubic-bezier(0.16, 1, 0.3, 1)",-};--function homeRevealStyle(visible: boolean): CSSProperties {- return {- opacity: visible ? 1 : 0,- transform: visible ? "translate3d(0, 0, 0)" : `translate3d(0, ${HOME_REVEAL.offsetY}px, 0)`,- filter: visible ? "blur(0px)" : `blur(${HOME_REVEAL.blur}px)`,- transition: ["opacity", "transform", "filter"]- .map((property) => `${property} ${HOME_REVEAL.duration}ms ${HOME_REVEAL.easing}`)- .join(", "),- };-}-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" }}>@@ -292,102 +265,9 @@ function newSessionName(): string {return `native-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;}-function EmptyState({- onSend,- health,- offset,- shuffle,- models,- modelKey,- onModelChange,-}: {- onSend: (text: string) => void;- health: Health | null;- offset: number;- shuffle: () => void;- models: PromptModel[];- modelKey?: string;- onModelChange: (key: string) => void;-}) {- const shown = [0, 1, 2].map((i) => STARTER_PROMPTS[(offset + i) % STARTER_PROMPTS.length]);- const [stage, setStage] = useState(0);- useEffect(() => {- const timers = [- setTimeout(() => setStage(1), 170),- setTimeout(() => setStage(2), 330),- setTimeout(() => setStage(3), 400),- setTimeout(() => setStage(4), 550),- ];- return () => timers.forEach(clearTimeout);- }, []);-- return (- <div className="mx-auto flex min-h-full max-w-[720px] flex-col justify-center px-4 py-10 sm:px-8">- <h1 className="text-[26px] font-normal tracking-[-0.02em] text-ink">- <span className="home-reveal block text-ink-3" style={homeRevealStyle(stage >= 1)}>- {greeting()}- </span>- <span className="home-reveal block" style={homeRevealStyle(stage >= 2)}>- What should graff work on?- </span>- </h1>-- <div className="home-reveal relative mt-7" style={homeRevealStyle(stage >= 3)}>- <PromptBar- demo={false}- tall- placeholder="Ask graff to read, edit, or review this workspace…"- models={models}- modelKey={modelKey}- onModelChange={onModelChange}- onSend={onSend}- disabled={health !== null && !health.ok}- />- {health && !health.ok && (- <p className="mt-3 text-[12.5px] text-orange">- graff acp is not reachable. From the repo root run{" "}- <span className="font-mono text-ink">zig build</span>- {health.detail ? ` — ${health.detail}` : ""}.- </p>- )}- </div>-- <div className="home-reveal mt-6 flex flex-col" style={homeRevealStyle(stage >= 4)}>- {shown.map((item) => (- <button- key={item.id}- type="button"- onClick={() => onSend(item.prompt)}- className="-mx-2 flex items-center gap-3 rounded-control px-2 py-2.5 text-left text-[14px] text-ink transition-colors duration-150 hover:bg-hover"- >- <span className="text-ink-3">- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden>- <path d="M8 6l-5 6 5 6M16 6l5 6-5 6" />- </svg>- </span>- <span className="min-w-0 truncate">{item.label}</span>- </button>- ))}- <div className="mt-1 flex items-center gap-5 pl-0.5 text-[13px] text-ink-3">- <span className="flex items-center gap-2 py-1" title={health?.cwd}>- <span className={`size-1.5 rounded-full ${health?.ok ? "bg-green" : "bg-orange"}`} />- {health?.ok- ? `Connected · ${health.cwd ? (health.cwd.split("/").pop() ?? health.cwd) : "over ACP"}`- : "Waiting for graff acp"}- </span>- <button type="button" onClick={shuffle} className="flex items-center gap-2 py-1 transition-colors duration-150 hover:text-ink">- Shuffle suggestions- </button>- </div>- </div>- </div>- );-}-export default function GraffHarness() {const [chats, setChats] = useState<Chat[]>([{ id: 1, title: null, messages: [] }]);const [activeId, setActiveId] = useState(1);- const [offset, setOffset] = useState(0);const [health, setHealth] = useState<Health | null>(null);// Every tab owns a `graff acp` child (the agent keeps one session per// process), so sessions, busy state and the spawned model are all per chat.@@ -397,12 +277,14 @@ export default function GraffHarness() {const sessionNamesRef = useRef(new Map<number, string>());const [sessionIds, setSessionIds] = useState<Record<number, string>>({});const [stored, setStored] = useState<StoredSession[]>([]);+ const [storedTotal, setStoredTotal] = useState(0);const [busyIds, setBusyIds] = useState<ReadonlySet<number>>(() => new Set());// No hardcoded default: until graff/models answers, the agent's own model// 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 [filesOpen, setFilesOpen] = useState(false);+ const [pane, setPane] = useState<"chat" | "workspace" | "conversations">("chat");+ const filesOpen = pane === "workspace";const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);const fileReqRef = useRef(0);const chatIdRef = useRef(1);@@ -491,11 +373,12 @@ export default function GraffHarness() {/** Re-read graff's session directory; tabs adopt the titles graff saved. */const refreshStored = async () => {try {- const list = await listSessions();- setStored(list);+ const page = await listSessionsPage({ limit: 12 });+ setStored(page.sessions);+ setStoredTotal(page.total);setChats((current) =>current.map((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;}),);@@ -505,12 +388,12 @@ export default function GraffHarness() {};const openPath = (path: string) => {- setFilesOpen(true);+ setPane("workspace");setFileRequest({ path, n: (fileReqRef.current += 1) });};const openChanges = () => {- setFilesOpen(true);+ setPane("workspace");setFileRequest({ path: "", n: (fileReqRef.current += 1), changes: true });};@@ -589,7 +472,7 @@ export default function GraffHarness() {sessionNamesRef.current.set(id, session);setChats((current) => [...current, { id, title: null, messages: [], model: model ?? undefined, session }]);setActiveId(id);- setFilesOpen(false);+ setPane("chat");// Spawn eagerly so the first send is not stuck behind agent + MCP boot.void requireSession(id).catch(() => undefined);};@@ -600,7 +483,7 @@ export default function GraffHarness() {const existing = chats.find((c) => c.session === name);if (existing) {setActiveId(existing.id);- setFilesOpen(false);+ setPane("chat");return;}let loaded: Awaited<ReturnType<typeof loadSession>>;@@ -618,7 +501,7 @@ export default function GraffHarness() {{ id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name },]);setActiveId(id);- setFilesOpen(false);+ setPane("chat");void requireSession(id, false, loaded.meta.model ?? undefined).catch(() => undefined);};@@ -666,14 +549,8 @@ export default function GraffHarness() {pinScrollerTail(scrollRef.current);}, [active, lastAssistant?.turn.text, lastAssistant?.turn.reasoning, lastAssistant?.turn.tools.length]);- // The sidebar is graff's session directory, newest first, bucketed by day.- const now = Date.now();- const recents = stored.map((s) => ({- id: s.name,- label: s.title ?? s.name,- group: dateGroup(s.updatedMs, now),- hint: [s.model, relativeTime(s.updatedMs, now)].filter(Boolean).join(" · "),- }));+ // Sidebar preview: first page of the session index, newest first.+ const recents = stored.map((s) => toSidebarRecent(s));const workspaceName = health?.cwd ? (health.cwd.split("/").pop() || health.cwd) : "workspace";@@ -693,7 +570,7 @@ export default function GraffHarness() {aria-label="Working"/>)}- <button type="button" aria-pressed={c.id === activeId} onClick={() => setActiveId(c.id)} title={c.title ?? "New chat"} className="min-w-0 flex-1 text-left">+ <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"><span className="block truncate">{c.title ?? "New chat"}</span></button><button@@ -719,10 +596,22 @@ export default function GraffHarness() {</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"))}+ 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"+ }`}+ >+ <IconChat size={14} />+ <span className="hidden sm:inline">Chats</span>+ </button><buttontype="button"aria-pressed={filesOpen}- onClick={() => setFilesOpen((open) => !open)}+ 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 ${filesOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"@@ -744,12 +633,18 @@ export default function GraffHarness() {fillclassName="hidden lg:flex"recents={recents}+ recentsTotal={storedTotal}activeTitle={chatThread.title}activeId={chatThread.session ?? null}onPick={pickRecent}onNewChat={newChat}- activeNav={filesOpen ? "workspace" : "chats"}- onNavigate={(key) => setFilesOpen(key === "workspace")}+ onSeeAll={() => setPane("conversations")}+ activeNav={pane === "workspace" ? "workspace" : pane === "conversations" ? "conversations" : "home"}+ onNavigate={(key) => {+ if (key === "workspace") setPane("workspace");+ else if (key === "conversations") setPane("conversations");+ else setPane("chat");+ }}footerLabel={sessionId ? `Session ${sessionId.slice(0, 8)}` : "Connecting…"}onFooterClick={() => undefined}/>@@ -758,7 +653,13 @@ export default function GraffHarness() {<div className="flex min-h-0 flex-1 gap-2.5"><section className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">{tabBar}- {active ? (+ {pane === "conversations" ? (+ <ConversationsPane+ activeId={chatThread.session ?? null}+ onPick={pickRecent}+ onNewChat={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">@@ -796,8 +697,6 @@ export default function GraffHarness() {<EmptyStateonSend={send}health={health}- offset={offset}- shuffle={() => setOffset((current) => (current + 3) % STARTER_PROMPTS.length)}models={models}modelKey={chatModel}onModelChange={changeModel}@@ -806,9 +705,9 @@ export default function GraffHarness() {)}</section>- {filesOpen && <FilesPane requested={fileRequest} onClose={() => setFilesOpen(false)} />}+ {filesOpen && <FilesPane requested={fileRequest} onClose={() => setPane("chat")} />}- {!filesOpen && active && paneTodos.length > 0 && (+ {pane === "chat" && active && paneTodos.length > 0 && (<asideclassName="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 --git a/apps/native/lib/icons.tsx b/apps/native/lib/icons.tsxindex 78fe025e..fbb0ddf7 100644--- a/apps/native/lib/icons.tsx+++ b/apps/native/lib/icons.tsx@@ -142,3 +142,11 @@ export function IconFolder(p: IconProps) {</Svg>);}++export function IconChat(p: IconProps) {+ return (+ <Svg {...p}>+ <path d="M5 6.5A2.5 2.5 0 0 1 7.5 4h9A2.5 2.5 0 0 1 19 6.5v7A2.5 2.5 0 0 1 16.5 16H12l-4.2 3.2A.6.6 0 0 1 7 18.7V16H7.5A2.5 2.5 0 0 1 5 13.5z" />+ </Svg>+ );+}diff --git a/apps/native/lib/session-store.test.ts b/apps/native/lib/session-store.test.tsnew file mode 100644index 00000000..8d8eebd1--- /dev/null+++ b/apps/native/lib/session-store.test.ts@@ -0,0 +1,119 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import {+ decodeCursor,+ displayWorkspace,+ encodeCursor,+ filterRows,+ findSessionFile,+ listSessionRows,+ pageSessions,+ sameWorkspace,+ SESSIONS_DIR,+} from "./session-store.ts";++function writeSession(root: string, name: string, body: Record<string, unknown>): void {+ const dir = path.join(root, SESSIONS_DIR);+ mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, `${name}.session.json`), `${JSON.stringify({ ...body, messages: [] })}\n`);+}++describe("displayWorkspace / sameWorkspace", () => {+ it("tilts home and treats a trailing slash as the same tree", () => {+ assert.equal(displayWorkspace("/Users/me", "/Users/me"), "~");+ assert.equal(displayWorkspace("/Users/me/proj", "/Users/me"), "~/proj");+ assert.equal(displayWorkspace("/tmp/other", "/Users/me"), "/tmp/other");+ assert.equal(sameWorkspace("/Users/me", "/Users/me/"), true);+ assert.equal(sameWorkspace("/Users/me", "/tmp/proj"), false);+ });+});++describe("listSessionRows", () => {+ it("lists cwd, then home, and cwd wins on the same name", () => {+ const cwd = mkdtempSync(path.join(tmpdir(), "graff-cwd-"));+ const home = mkdtempSync(path.join(tmpdir(), "graff-home-"));+ writeSession(cwd, "here", { title: "Repo chat", updated_ms: 30, model: "glm-5" });+ writeSession(cwd, "shared", { title: "Cwd copy", updated_ms: 20, model: "glm-5" });+ writeSession(home, "shared", { title: "Home copy", updated_ms: 90, model: "kimi" });+ writeSession(home, "notes", { title: "Kitchen notes", updated_ms: 10, model: "kimi", workspace: home });+ const rows = listSessionRows(cwd, home);+ assert.deepEqual(+ rows.map((r) => r.name),+ ["here", "shared", "notes"],+ );+ const shared = rows.find((r) => r.name === "shared");+ assert.equal(shared?.title, "Cwd copy");+ assert.equal(shared?.local, true);+ const notes = rows.find((r) => r.name === "notes");+ assert.equal(notes?.local, false);+ assert.equal(notes?.origin, "~");+ });+});++describe("pageSessions", () => {+ it("pages newest-first and resumes after the cursor", () => {+ const rows = [40, 30, 20, 10].map((ms, i) => ({+ name: `s${i}`,+ title: `Chat ${i}`,+ updatedMs: ms,+ model: "glm-5",+ provider: null,+ size: 12,+ workspace: "/tmp",+ origin: null,+ local: true,+ }));+ const first = pageSessions(rows, { limit: 2 });+ assert.equal(first.total, 4);+ assert.deepEqual(+ first.sessions.map((s) => s.name),+ ["s0", "s1"],+ );+ assert.equal(first.nextCursor, encodeCursor(30, "s1"));+ const second = pageSessions(rows, { limit: 2, cursor: first.nextCursor });+ assert.deepEqual(+ second.sessions.map((s) => s.name),+ ["s2", "s3"],+ );+ assert.equal(second.nextCursor, null);+ });++ it("filters by query and scope before paging", () => {+ const rows = [+ { name: "a", title: "Fix login", updatedMs: 3, model: "glm-5", provider: null, size: 1, workspace: "/repo", origin: null, local: true },+ { name: "b", title: "Home notes", updatedMs: 2, model: "kimi", provider: null, size: 1, workspace: "/Users/me", origin: "~", local: false },+ { name: "c", title: "Fix tests", updatedMs: 1, model: "glm-5", provider: null, size: 1, workspace: "/repo", origin: null, local: true },+ ];+ const login = filterRows(rows, "login");+ assert.deepEqual(+ login.map((r) => r.name),+ ["a"],+ );+ const elsewhere = pageSessions(rows, { scope: "elsewhere", limit: 10 });+ assert.equal(elsewhere.total, 1);+ assert.equal(elsewhere.sessions[0]?.name, "b");+ });+});++describe("cursors", () => {+ it("round-trips and rejects junk", () => {+ assert.deepEqual(decodeCursor(encodeCursor(99, "native-abc")), { updatedMs: 99, name: "native-abc" });+ assert.equal(decodeCursor("nope"), null);+ assert.equal(decodeCursor("12:"), null);+ });+});++describe("findSessionFile", () => {+ it("prefers cwd and falls back to home", () => {+ const cwd = mkdtempSync(path.join(tmpdir(), "graff-find-cwd-"));+ const home = mkdtempSync(path.join(tmpdir(), "graff-find-home-"));+ writeSession(cwd, "here", { title: "Here", updated_ms: 1 });+ writeSession(home, "away", { title: "Away", updated_ms: 2 });+ assert.equal(findSessionFile(cwd, "here", home)?.local, true);+ assert.equal(findSessionFile(cwd, "away", home)?.local, false);+ assert.equal(findSessionFile(cwd, "missing", home), null);+ });+});diff --git a/apps/native/lib/session-store.ts b/apps/native/lib/session-store.tsnew file mode 100644index 00000000..101df6dd--- /dev/null+++ b/apps/native/lib/session-store.ts@@ -0,0 +1,225 @@+import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";+import os from "node:os";+import path from "node:path";++/** Same layout `src/session_index.zig` owns. Header fields land before+ * `messages`, so a list peeks the prefix instead of parsing whole files. */+export const SESSIONS_DIR = ".graff/sessions";+export const SESSION_EXT = ".session.json";+export const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+export const PEEK_BYTES = 64 * 1024;+export const MAX_FULL_BYTES = 16 * 1024 * 1024;+export const PAGE_DEFAULT = 24;+export const PAGE_MAX = 80;++export type StoredSessionRow = {+ name: string;+ title: string | null;+ updatedMs: number;+ model: string | null;+ provider: string | null;+ size: number;+ workspace: string | null;+ /** `~/…` (or the path) when the save is not in the current cwd. */+ origin: string | null;+ local: boolean;+};++type Header = {+ title?: unknown;+ updated_ms?: unknown;+ model?: unknown;+ provider?: unknown;+ workspace?: unknown;+};++export type SessionPage = {+ sessions: StoredSessionRow[];+ nextCursor: string | null;+ total: number;+};++export type ListScope = "all" | "local" | "elsewhere";++function str(v: unknown): string | null {+ return typeof v === "string" && v.length > 0 ? v : null;+}++export function sameWorkspace(a: string, b: string): boolean {+ const left = a.replace(/\/+$/, "");+ const right = b.replace(/\/+$/, "");+ return left === right;+}++/** `~/…` when `dir` is under home; otherwise the path as-is. */+export function displayWorkspace(dir: string, home: string): string {+ if (!home) return dir;+ const root = home.replace(/\/+$/, "");+ if (dir === root || dir === home) return "~";+ if (dir.startsWith(`${root}/`)) return `~${dir.slice(root.length)}`;+ return dir;+}++export function clampLimit(raw: string | null | undefined, fallback = PAGE_DEFAULT): number {+ const n = raw == null || raw === "" ? fallback : Number.parseInt(raw, 10);+ if (!Number.isFinite(n) || n < 1) return fallback;+ return Math.min(PAGE_MAX, Math.floor(n));+}++export function encodeCursor(updatedMs: number, name: string): string {+ return `${updatedMs}:${name}`;+}++export function decodeCursor(cursor: string): { updatedMs: number; name: string } | null {+ const split = cursor.indexOf(":");+ if (split <= 0) return null;+ const updatedMs = Number.parseInt(cursor.slice(0, split), 10);+ const name = cursor.slice(split + 1);+ if (!Number.isFinite(updatedMs) || !NAME_RE.test(name)) return null;+ return { updatedMs, name };+}++export function homeDir(override?: string | null): string {+ const raw = override ?? process.env.HOME ?? os.homedir();+ return raw.replace(/\/+$/, "");+}++type HeaderPeek = Header | null;++export function peekHeader(file: string, size: number): HeaderPeek {+ const fd = openSync(file, "r");+ try {+ const want = Math.min(size, PEEK_BYTES);+ const buf = Buffer.alloc(want);+ const n = readSync(fd, buf, 0, want, 0);+ const text = buf.toString("utf8", 0, n);+ const idx = text.indexOf('"messages":');+ if (idx < 0) return null;+ let head = text.slice(0, idx).trimEnd();+ if (head.endsWith(",")) head = head.slice(0, -1);+ return JSON.parse(`${head}}`) as Header;+ } catch {+ return null;+ } finally {+ closeSync(fd);+ }+}++function rowFor(dir: string, entry: string, fallbackWorkspace: string, local: boolean, home: string, cwd: string): StoredSessionRow | null {+ const name = entry.slice(0, -SESSION_EXT.length);+ if (!NAME_RE.test(name)) return null;+ const file = path.join(dir, entry);+ let size = 0;+ let mtimeMs = 0;+ try {+ const st = statSync(file);+ if (!st.isFile()) return null;+ size = st.size;+ mtimeMs = st.mtimeMs;+ } catch {+ return null;+ }+ const header = size > 0 ? peekHeader(file, size) : null;+ const updated = typeof header?.updated_ms === "number" && header.updated_ms > 0 ? header.updated_ms : Math.round(mtimeMs);+ const workspace = str(header?.workspace) ?? fallbackWorkspace;+ const here = local || sameWorkspace(workspace, cwd);+ return {+ name,+ title: str(header?.title),+ updatedMs: updated,+ model: str(header?.model),+ provider: str(header?.provider),+ size,+ workspace,+ origin: here ? null : displayWorkspace(workspace, home),+ local: here,+ };+}++function readDir(dir: string, workspace: string, local: boolean, home: string, cwd: string): StoredSessionRow[] {+ if (!existsSync(dir)) return [];+ const rows: StoredSessionRow[] = [];+ for (const entry of readdirSync(dir)) {+ if (!entry.endsWith(SESSION_EXT)) continue;+ const row = rowFor(dir, entry, workspace, local, home, cwd);+ if (row) rows.push(row);+ }+ return rows;+}++function newerFirst(a: StoredSessionRow, b: StoredSessionRow): number {+ if (a.updatedMs !== b.updatedMs) return b.updatedMs - a.updatedMs;+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;+}++/** Cwd saves first (they win on the same base name), then `~/.graff/sessions`+ * when that tree is a different workspace. ADR 0059 / #712. */+export function listSessionRows(cwd: string, home = homeDir()): StoredSessionRow[] {+ const cwdDir = path.join(cwd, SESSIONS_DIR);+ const rows = readDir(cwdDir, cwd, true, home, cwd);+ const seen = new Set(rows.map((r) => r.name));+ if (home && !sameWorkspace(home, cwd)) {+ for (const row of readDir(path.join(home, SESSIONS_DIR), home, false, home, cwd)) {+ if (seen.has(row.name)) continue;+ rows.push(row);+ seen.add(row.name);+ }+ }+ rows.sort(newerFirst);+ return rows;+}++export function matchesQuery(row: StoredSessionRow, q: string): boolean {+ const needle = q.trim().toLowerCase();+ if (!needle) return true;+ const hay = [row.title, row.name, row.model, row.provider, row.origin, row.workspace]+ .filter((v): v is string => typeof v === "string" && v.length > 0)+ .join("\n")+ .toLowerCase();+ return hay.includes(needle);+}++export function filterRows(rows: StoredSessionRow[], q?: string | null, scope: ListScope = "all"): StoredSessionRow[] {+ return rows.filter((row) => {+ if (scope === "local" && !row.local) return false;+ if (scope === "elsewhere" && row.local) return false;+ return matchesQuery(row, q ?? "");+ });+}++export function pageSessions(+ rows: StoredSessionRow[],+ opts: { limit?: number; cursor?: string | null; q?: string | null; scope?: ListScope } = {},+): SessionPage {+ const filtered = filterRows(rows, opts.q, opts.scope ?? "all");+ const limit = opts.limit && opts.limit > 0 ? Math.min(PAGE_MAX, Math.floor(opts.limit)) : PAGE_DEFAULT;+ let start = 0;+ if (opts.cursor) {+ const cur = decodeCursor(opts.cursor);+ if (cur) {+ const idx = filtered.findIndex((r) => r.updatedMs === cur.updatedMs && r.name === cur.name);+ if (idx >= 0) start = idx + 1;+ else {+ const older = filtered.findIndex(+ (r) => r.updatedMs < cur.updatedMs || (r.updatedMs === cur.updatedMs && r.name > cur.name),+ );+ start = older < 0 ? filtered.length : older;+ }+ }+ }+ const slice = filtered.slice(start, start + limit);+ const last = slice[slice.length - 1];+ const nextCursor = start + limit < filtered.length && last ? encodeCursor(last.updatedMs, last.name) : null;+ return { sessions: slice, nextCursor, total: filtered.length };+}++export function findSessionFile(cwd: string, name: string, home = homeDir()): { file: string; local: boolean; workspace: string } | null {+ if (!NAME_RE.test(name)) return null;+ const localFile = path.join(cwd, SESSIONS_DIR, `${name}${SESSION_EXT}`);+ if (existsSync(localFile)) return { file: localFile, local: true, workspace: cwd };+ if (home && !sameWorkspace(home, cwd)) {+ const homeFile = path.join(home, SESSIONS_DIR, `${name}${SESSION_EXT}`);+ if (existsSync(homeFile)) return { file: homeFile, local: false, workspace: home };+ }+ return null;+}diff --git a/apps/native/lib/sessions.test.ts b/apps/native/lib/sessions.test.tsindex 0682e6eb..b2c262bc 100644--- a/apps/native/lib/sessions.test.ts+++ b/apps/native/lib/sessions.test.ts@@ -1,6 +1,6 @@import { describe, it } from "node:test";import assert from "node:assert/strict";-import { dateGroup, transcriptFromMessages } from "./sessions.ts";+import { dateGroup, groupSessions, sessionHint, transcriptFromMessages } from "./sessions.ts";describe("transcriptFromMessages", () => {it("folds assistant + tool messages into one turn per user message", () => {@@ -87,3 +87,24 @@ describe("dateGroup", () => {assert.match(dateGroup(now - 90 * day, now), /2026/);});});++describe("groupSessions / sessionHint", () => {+ it("keeps date buckets consecutive and names an elsewhere origin", () => {+ const now = new Date(2026, 7, 30, 15, 0, 0).getTime();+ const rows = [+ { name: "a", title: "Today one", updatedMs: now, model: "glm-5", provider: null, size: 1, local: true },+ { name: "b", title: "Today two", updatedMs: now - 1_000, model: "kimi", provider: null, size: 1, local: false, origin: "~/notes" },+ { name: "c", title: "Older", updatedMs: now - 3 * 86_400_000, model: "glm-5", provider: null, size: 1, local: true },+ ];+ const groups = groupSessions(rows, now);+ assert.deepEqual(+ groups.map((g) => [g.group, g.items.length]),+ [+ ["Today", 2],+ ["Previous 7 days", 1],+ ],+ );+ assert.equal(sessionHint(rows[0], now), "glm-5 · just now");+ assert.equal(sessionHint(rows[1], now), "~/notes · kimi · just now");+ });+});diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.tsindex f1c1a3d3..bb5d908d 100644--- a/apps/native/lib/sessions.ts+++ b/apps/native/lib/sessions.ts@@ -17,19 +17,53 @@ export type StoredSession = {model: string | null;provider: string | null;size: number;+ workspace?: string | null;+ /** Set when the save is not in the current cwd (ADR 0059). */+ origin?: string | null;+ local?: boolean;};+export type SessionPage = {+ cwd?: string;+ sessions: StoredSession[];+ nextCursor: string | null;+ total: number;+};++export type SessionScope = "all" | "local" | "elsewhere";+export type TranscriptMsg =| { role: "user"; text: string }| { role: "assistant"; turn: AssistantTurn };const BASE = "/api/sessions";-export async function listSessions(): Promise<StoredSession[]> {- const res = await fetch(BASE, { cache: "no-store" });+export async function listSessionsPage(opts: {+ limit?: number;+ cursor?: string | null;+ q?: string;+ scope?: SessionScope;+} = {}): 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" });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();+ return page.sessions;}export async function loadSession(name: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {@@ -67,6 +101,37 @@ export function relativeTime(ms: number, now = Date.now()): string {return new Date(ms).toLocaleDateString();}+export function sessionHint(s: StoredSession, now = Date.now()): string {+ const where = s.local === false ? (s.origin ?? "elsewhere") : null;+ return [where, s.model, relativeTime(s.updatedMs, now)].filter(Boolean).join(" · ");+}++export function toSidebarRecent(s: StoredSession, now = Date.now()): {+ id: string;+ label: string;+ group: string;+ hint: string;+} {+ return {+ id: s.name,+ label: s.title ?? s.name,+ group: dateGroup(s.updatedMs, now),+ hint: sessionHint(s, now),+ };+}++/** Consecutive rows that share a date bucket, newest buckets first. */+export function groupSessions(rows: StoredSession[], now = Date.now()): { group: string; items: StoredSession[] }[] {+ const out: { group: string; items: StoredSession[] }[] = [];+ for (const row of rows) {+ const group = dateGroup(row.updatedMs, now);+ const last = out[out.length - 1];+ if (last && last.group === group) last.items.push(row);+ else out.push({ group, items: [row] });+ }+ return out;+}+type RawCall = { id?: unknown; function?: { name?: unknown; arguments?: unknown } };type RawMsg = { role?: unknown; content?: unknown; tool_calls?: unknown; tool_call_id?: unknown };diff --git a/apps/native/package.json b/apps/native/package.jsonindex f0569552..565c7cc4 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -10,7 +10,7 @@"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"+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts"},"dependencies": {"glimm": "^0.3.0",