# Code editor

An editor window: files, tabs over the code, a terminal and problems panel, source control with a diff, a command palette and an assistant that proposes a fix.

A whole app screen built only from this system's components and token utilities; the layout is Tailwind.

A rounded app: its page has `<html data-shape="rounded">`, so its buttons, toggles and segmented controls name no shape.

## App.tsx

```tsx
/* A code editor (VS Code, Zed): an activity bar and a side view (explorer or source control), open
 * files as attached tabs over the code, a terminal and problems panel below, an assistant on the
 * right, a command palette on Ctrl/⌘ K or P and a status bar. Dense like the product: 24px tree
 * and list rows, 28px tabs, 32px pane headers, 13px code that never wraps. Panels are a Splitter
 * (drag, or arrow keys on a handle); a panel is open while its size is above zero, so the toggles
 * and the handles share one state. Below 720px the app shows one view at a time, picked at the
 * bottom. Shortcuts are bound on the app's root, so they work while the app has focus and leave
 * the page's own keys alone.
 *
 * A rounded app: the page that hosts it has <html data-shape="rounded"> (index.json tells the
 * docs site), so no button, toggle or switcher here names a shape, and its dialogs follow. */
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { CheckCircle, Eye, File, FileText, Folder, GitBranch, MagnifyingGlass, Play, Sparkle, Terminal, Warning, XCircle } from "@phosphor-icons/react";
import {
  Button, CodeView, CommandPalette, Count, EmptyState, Kbd, ScrollArea, SegmentedControl, Splitter, Tabs, Toggle, TreeView,
  type CommandPaletteItem, type TreeViewNode,
} from "@fndn/react";
import { Assistant } from "./Assistant";
import { SourceControl } from "./SourceControl";
import { BRANCH, CHANGES, FILES, PROBLEMS, PROJECT, RATE_LIMIT_FIXED, TREE, lineDiff, testRun, type Change } from "./data";

const RATE_LIMIT = "src/middleware/rate-limit.ts";
/** An open diff is a tab of its own, next to the file's: its value is the path with this prefix. */
const DIFF = "diff:";
const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.userAgent) ? "⌘" : "Ctrl";
/** A pane's title row: 32px, the height of the tab strip beside it, quiet small text. */
const PANE_TITLE = "flex h-8 shrink-0 items-center px-3 text-xs font-medium text-ink-2";

/** The size of an element (a callback ref: the element may come and go), measured before the
 * first paint and on every change. */
function useSize() {
  const [size, setSize] = useState({ width: 0, height: 0 });
  const observer = useRef<ResizeObserver>(null);
  const ref = useCallback((el: HTMLElement | null) => {
    observer.current?.disconnect();
    if (!el) return;
    setSize({ width: el.clientWidth, height: el.clientHeight });
    observer.current = new ResizeObserver(([e]) => e && setSize({ width: e.contentRect.width, height: e.contentRect.height }));
    observer.current.observe(el);
  }, []);
  return [ref, size] as const;
}

const fileIcon = (path: string) => (path.endsWith(".md") ? <FileText data-slot="icon" /> : <File data-slot="icon" />);
const withIcons = (nodes: TreeViewNode[]): TreeViewNode[] =>
  nodes.map((n) => (n.children
    ? { ...n, icon: <Folder />, children: withIcons(n.children) }
    : { ...n, icon: n.value.endsWith(".md") ? <FileText /> : <File /> }));
const FILE_TREE = withIcons(TREE);
const nameOf = (path: string) => path.split("/").pop()!;
const pathOf = (tab: string) => (tab.startsWith(DIFF) ? tab.slice(DIFF.length) : tab);
const language = (path: string) => (path.endsWith(".ts") ? "TypeScript" : path.endsWith(".json") ? "JSON" : "Markdown");

/** A terminal line in vitest's colours: counts of failed red, passed green, marks in their tone;
 * what vitest dims (labels, a file's test count, timings, the path) is ink-2 beside the ink of
 * the output: two levels, and both are read, so neither is fainter than ink-2. PARTS also cuts
 * out the labels and a file's test count, so a "1 failed" inside "(3 tests | 1 failed)" is
 * dimmed with its count. */
const TONES: [RegExp, string][] = [
  [/^(\d+ failed|×|FAIL)$/, "text-red"],
  [/^(\d+ passed|✓)$/, "text-green"],
  [/^❯$/, "text-orange"],
  [/^(Test Files|Tests|Duration|RUN|\(\d+(?: tests?)?(?: \| \d+ failed)?\)|\d+ms|\/home\/[\w/-]+)$/, "text-ink-2"],
];
const PARTS = /(\d+ failed|\d+ passed|×|✓|❯|FAIL|Test Files|Tests|Duration|RUN|\(\d+(?: tests?)?(?: \| \d+ failed)?\)|\d+ms|\/home\/[\w/-]+)/;
function TerminalLine({ line }: { line: string }) {
  if (line.startsWith("$ ")) return <div className="ps-[1ch] text-ink">{line}</div>;
  if (!line) return <div>{" "}</div>;
  return (
    <div className="text-ink">
      {line.split(PARTS).map((part, i) => {
        const tone = TONES.find(([re]) => re.test(part))?.[1];
        return tone ? <span key={i} className={tone}>{part}</span> : part;
      })}
    </div>
  );
}

/** The terminal: opens at the start of the newest run (the first frame never scrolls), and a run
 * added later is brought in at its first line, once the terminal is in view (it may be a hidden
 * tab when the run is added). */
function TerminalOutput({ lines }: { lines: string[] }) {
  const output = useRef<HTMLPreElement>(null);
  const shown = useRef(lines.length);
  useLayoutEffect(() => {
    const el = output.current;
    const view = el?.closest<HTMLElement>("[data-slot=scroll-area-viewport]");
    if (!el || !view) return;
    const reveal = () => {
      const count = el.children.length;
      if (count === shown.current || !el.offsetHeight) return;
      shown.current = count;
      const rows = [...el.children] as HTMLElement[];
      const start = rows.map((row) => row.textContent?.startsWith("$ ")).lastIndexOf(true);
      view.scrollTop = start > 0 ? rows[start]!.offsetTop : 0;
    };
    reveal();
    const ro = new ResizeObserver(reveal);
    ro.observe(el);
    return () => ro.disconnect();
  }, [lines]);
  return (
    /* left to right on a right-to-left page too; long lines wrap at the pane's width, as a terminal
     * wraps at its columns, so a line's start is never cut and nothing scrolls sideways */
    <pre ref={output} className="relative px-3 py-2 font-mono text-xs leading-5 whitespace-pre-wrap wrap-anywhere [direction:ltr] [text-size-adjust:100%]">
      {lines.map((line, i) => <TerminalLine key={i} line={line} />)}
    </pre>
  );
}

/** One panel open: the sizes it takes, the others sharing the rest. */
const sideSizes = (side: boolean, assistant: boolean) => [side ? 23 : 0, 100 - (side ? 23 : 0) - (assistant ? 28 : 0), assistant ? 28 : 0];

export default function App() {
  const [root, { width }] = useSize();
  const phone = width > 0 && width < 720;

  /* the project */
  const [files, setFiles] = useState(FILES);
  const [changes, setChanges] = useState<Change[]>(CHANGES);
  const [problems, setProblems] = useState(PROBLEMS);
  const [terminal, setTerminal] = useState(() => testRun(false));
  const [passing, setPassing] = useState(false);
  const [ahead, setAhead] = useState(0);

  /* the editor: open tabs (a path, or DIFF + path) and the active one */
  const [open, setOpen] = useState([RATE_LIMIT, "test/rate-limit.test.ts", "src/routes/invoices.ts"]);
  const [active, setActive] = useState(RATE_LIMIT);
  const activePath = pathOf(active);
  const diffOf = active.startsWith(DIFF) ? activePath : null;
  /* the line the caret is on in each file, marked as the code block's current line */
  const [caret, setCaret] = useState<Record<string, number>>({});
  const [expanded, setExpanded] = useState(["src", "src/middleware", "test"]);

  /* the layout */
  const [side, setSide] = useState<"explorer" | "changes">("explorer");
  const [sizes, setSizes] = useState(() => sideSizes(true, true));
  const [rows, setRows] = useState([68, 32]);
  const [panelTab, setPanelTab] = useState("terminal");
  const [phoneView, setPhoneView] = useState("code");
  const [palette, setPalette] = useState(false);
  const sideOpen = sizes[0]! > 0, assistantOpen = sizes[2]! > 0, panelOpen = rows[1]! > 0;

  const openTab = (tab: string) => {
    setOpen((o) => (o.includes(tab) ? o : [...o, tab]));
    setActive(tab);
    setPhoneView("code");
  };
  const openFile = (path: string, line?: number) => {
    openTab(path);
    if (line) setCaret((c) => ({ ...c, [path]: line }));
  };
  const openDiff = (path: string) => { openTab(DIFF + path); setSide("changes"); };
  const closeTab = (tab: string) => setOpen((o) => o.filter((t) => t !== tab));
  const showSide = (view: "explorer" | "changes" | null) => {
    if (view) setSide(view);
    setSizes(sideSizes(!!view, assistantOpen));
    if (view) setPhoneView(view === "explorer" ? "files" : "changes");
  };
  const showPanel = (show: boolean, tab?: string) => {
    if (tab) setPanelTab(tab);
    setRows(show ? [68, 32] : [100, 0]);
    if (show) setPhoneView("panel");
  };
  const runTests = (fixed = files[RATE_LIMIT] === RATE_LIMIT_FIXED) => {
    setTerminal((t) => [...t, "", ...testRun(fixed)]);
    setPassing(fixed);
    showPanel(true, "terminal");
  };
  const applyFix = (andTest: boolean) => {
    setFiles((f) => ({ ...f, [RATE_LIMIT]: RATE_LIMIT_FIXED }));
    /* appended, so the rows already there do not move */
    setChanges((c) => (c.some((x) => x.path === RATE_LIMIT) ? c : [...c, { path: RATE_LIMIT, status: "modified", before: FILES[RATE_LIMIT]! }]));
    setProblems((p) => p.filter((x) => x.fixedBy !== "rate-limit"));
    openDiff(RATE_LIMIT);
    if (andTest) runTests(true);
  };
  /* committed changes have no diff left: their tabs close, and the file's own tab takes over */
  const commit = () => {
    setChanges([]);
    setOpen((o) => { const kept = o.filter((t) => !t.startsWith(DIFF)); return diffOf && !kept.includes(diffOf) ? [...kept, diffOf] : kept; });
    if (diffOf) setActive(diffOf);
    setAhead((n) => n + 1);
  };

  /* files are found by name or path; commands show their own shortcut */
  const commands = useMemo((): CommandPaletteItem[] => [
    ...Object.keys(files).map((path) => ({
      value: `file:${path}`, label: nameOf(path), meta: path, group: "Files", keywords: [path],
      icon: path.endsWith(".md") ? <FileText data-slot="icon" weight="bold" /> : <File data-slot="icon" weight="bold" />,
    })),
    { value: "run-tests", label: "Run tests", meta: "pnpm test", group: "Commands", icon: <Play data-slot="icon" weight="bold" /> },
    { value: "explorer", label: "Show explorer", group: "View", shortcut: [mod, "B"], icon: <Eye data-slot="icon" weight="bold" /> },
    { value: "changes", label: "Show source control", group: "View", keywords: ["git", "diff"], icon: <GitBranch data-slot="icon" weight="bold" /> },
    { value: "terminal", label: "Show terminal", group: "View", shortcut: [mod, "J"], icon: <Terminal data-slot="icon" weight="bold" /> },
    { value: "problems", label: "Show problems", group: "View", keywords: ["errors", "warnings"], icon: <Warning data-slot="icon" weight="bold" /> },
    { value: "assistant", label: "Show assistant", group: "View", keywords: ["ai", "chat"], icon: <Sparkle data-slot="icon" weight="bold" /> },
  ], [files]);
  /* Quick Open's order: what was picked here first, then the open files (VS Code lists the
   * recently opened files before the rest of the workspace) */
  const [recent, setRecent] = useState<string[]>([]);
  const recentShown = [...new Set([...recent, ...open.filter((t) => !t.startsWith(DIFF)).map((t) => `file:${t}`)])].slice(0, 5);
  const run = (value: string) => {
    setRecent((r) => [value, ...r.filter((v) => v !== value)].slice(0, 3));
    if (value.startsWith("file:")) openFile(value.slice(5));
    else if (value === "run-tests") runTests();
    else if (value === "explorer" || value === "changes") showSide(value);
    else if (value === "terminal" || value === "problems") showPanel(true, value);
    else if (value === "assistant") { setSizes(sideSizes(sideOpen, true)); setPhoneView("assistant"); }
  };
  const onKeyDown = (e: KeyboardEvent) => {
    if (!(e.ctrlKey || e.metaKey) || e.altKey) return;
    const key = e.key.toLowerCase();
    if (key === "k" || key === "p") { e.preventDefault(); e.stopPropagation(); setPalette(true); }
    else if (key === "j") { e.preventDefault(); showPanel(!panelOpen); }
    else if (key === "b") { e.preventDefault(); showSide(sideOpen ? null : side); }
  };

  /* ── the views ─────────────────────────────────────────── */

  /* the pane is titled by its view; the project is the tree's own label, as VS Code's section */
  const explorer = (
    <div className="flex h-full min-w-0 flex-col bg-canvas" data-editor="explorer">
      <div className={PANE_TITLE}>Explorer</div>
      <ScrollArea className="min-h-0 flex-1">
        <TreeView
          className="px-1 pb-2" size="xs" label={PROJECT} items={FILE_TREE}
          expandedValue={expanded} onExpandedValueChange={setExpanded}
          selectedValue={diffOf ? [] : [activePath]}
          onSelectedValueChange={(v) => v[0] && v[0] in files && openFile(v[0])}
        />
      </ScrollArea>
    </div>
  );

  const sourceControl = (
    <SourceControl changes={changes} selected={diffOf} branch={BRANCH} onSelect={openDiff} onCommit={commit} />
  );

  /* the editor: closable pill tabs in the pane's 32px header over a code view (no frame, no copy,
   * no path; lines never wrap and the gutter stays while the code scrolls sideways). A strip with
   * more files than room scrolls, fades its cut edge and lists every file in its menu */
  const editorOf = (tab: string) => {
    const path = pathOf(tab);
    if (tab.startsWith(DIFF)) {
      const change = changes.find((c) => c.path === path);
      return <CodeView fill wrap={false} label={`${path} (working tree)`} diff={lineDiff(change?.before ?? files[path]!, files[path]!)} />;
    }
    return <CodeView fill wrap={false} label={path} value={files[path]!.join("\n")} currentLine={caret[path]} />;
  };
  const code = (
    <div className="h-full bg-surface" data-editor="code">
      {open.length ? (
        <Tabs
          variant="pill" closable fill inHeader headerClass="h-8 border-b border-line px-1" aria-label="Open files"
          value={open.includes(active) ? active : open[0]} onValueChange={setActive} onClose={closeTab}
          items={open.map((tab) => ({
            value: tab,
            label: tab.startsWith(DIFF) ? `${nameOf(pathOf(tab))} (working tree)` : nameOf(tab),
            icon: tab.startsWith(DIFF) ? <GitBranch data-slot="icon" /> : fileIcon(tab),
            content: editorOf(tab),
          }))}
        />
      ) : (
        <EmptyState className="h-full bg-surface" size="block" icon="file" title="No open files" hint={`${mod}+P opens one by name.`} />
      )}
    </div>
  );

  const errors = problems.filter((p) => p.severity === "error").length;
  const warnings = problems.length - errors;
  const problemTree: TreeViewNode[] = [...new Set(problems.map((p) => p.path))].map((path) => ({
    value: path, label: nameOf(path), icon: <File />,
    children: problems.filter((p) => p.path === path).map((p) => ({
      value: p.value, label: `${p.message} [Ln ${p.line}, Col ${p.col}]`,
      icon: p.severity === "error" ? <XCircle weight="fill" className="text-red" /> : <Warning className="text-orange" />,
    })),
  }));
  const bottom = (
    <div className="h-full bg-surface" data-editor="panel">
      {/* fill: the panel under the strip takes the rest of the pane's height */}
      <Tabs
        fill variant="underline" inHeader headerClass="h-8 border-b border-line px-3 text-xs" aria-label="Panel"
        value={panelTab} onValueChange={setPanelTab}
        items={[
          {
            value: "terminal", label: "Terminal",
            content: (
              <ScrollArea className="h-full" data-editor="terminal">
                <TerminalOutput lines={terminal} />
              </ScrollArea>
            ),
          },
          {
            value: "problems",
            label: <span className="flex items-center gap-1.5">Problems <Count size="sm">{String(problems.length)}</Count></span>,
            content: (
              <ScrollArea className="h-full" data-editor="problems">
                {problems.length ? (
                  <TreeView
                    className="px-1 py-1" size="xs" aria-label="Problems" items={problemTree} expandedValue={problemTree.map((n) => n.value)}
                    selectedValue={[]}
                    onSelectedValueChange={(v) => { const p = problems.find((x) => x.value === v[0]); if (p) openFile(p.path, p.line); }}
                  />
                ) : (
                  <EmptyState size="row" title="No problems in the workspace" />
                )}
              </ScrollArea>
            ),
          },
        ]}
      />
    </div>
  );

  const assistant = <Assistant file={activePath} onApply={applyFix} onOpenDiff={openDiff} />;

  /* the system's command palette; Ctrl/⌘ K and P are bound on the app's root (onKeyDown), so they
   * work while the app has focus and leave the page's own ⌘K alone */
  const paletteDialog = (
    <CommandPalette
      items={commands} recent={recentShown} limit={8} hotkey={false}
      open={palette} onOpenChange={setPalette} onSelect={run}
      label="Go to a file or run a command" placeholder="Go to a file or run a command…"
      emptyTitle="Nothing matches" emptyHint="Try a file name, or a command such as Run tests."
    />
  );

  /* ── phone: one view at a time ──────────────────────────── */
  const views: Record<string, ReactNode> = { files: explorer, code, changes: sourceControl, panel: bottom, assistant };
  const phoneLayout = (
    <>
      <header className="flex h-11 shrink-0 items-center gap-2 border-b border-line ps-3 pe-1.5">
        <span className="min-w-0 flex-1 truncate text-sm font-semibold" title={`${PROJECT} · ${BRANCH}`}>{PROJECT}</span>
        <Button variant="ghost" size="sm" square muted aria-label="Go to a file or run a command" icon={<MagnifyingGlass data-slot="icon" weight="bold" />} onClick={() => setPalette(true)} />
      </header>
      <div className="min-h-0 flex-1">{views[phoneView]}</div>
      <nav aria-label="Views" className="shrink-0 border-t border-line p-2">
        <SegmentedControl
          fill size="md" aria-label="View" value={phoneView} onValueChange={setPhoneView}
          options={[{ value: "files", label: "Files" }, { value: "code", label: "Code" }, { value: "changes", label: "Git" }, { value: "panel", label: "Terminal" }, { value: "assistant", label: "AI" }]}
        />
      </nav>
    </>
  );

  /* ── desktop ───────────────────────────────────────────── */
  const sideViews = [
    { value: "explorer" as const, label: `Explorer (${mod}+B)`, Icon: Folder },
    { value: "changes" as const, label: `Source control, ${changes.length === 1 ? "1 change" : `${changes.length} changes`}`, Icon: GitBranch },
  ];
  const desktopLayout = (
    <>
      {/* the title bar: the command center in the middle, the layout toggles at the end */}
      <header className="grid h-9 shrink-0 grid-cols-[1fr_minmax(0,18rem)_1fr] items-center gap-3 border-b border-line bg-canvas px-2">
        <span />
        <span className="relative flex">
          <Button variant="outline" size="sm" className="w-full justify-start pe-16 text-ink-3" icon={<MagnifyingGlass data-slot="icon" weight="bold" />} aria-keyshortcuts="Control+K Meta+K Control+P Meta+P" onClick={() => setPalette(true)} data-editor="palette-button">
            Go to file or command
          </Button>
          <span className="pointer-events-none absolute inset-y-0 end-1.5 flex items-center" aria-hidden><Kbd keys={[mod, "K"]} /></span>
        </span>
        <span className="flex justify-end gap-0.5">
          <Toggle variant="ghost" size="sm" square muted tooltip={`Panel (${mod}+J)`} pressed={panelOpen} onPressedChange={(on) => showPanel(on)} icon={<Terminal data-slot="icon" weight="bold" />} />
          <Toggle variant="ghost" size="sm" square muted tooltip="Assistant" pressed={assistantOpen} onPressedChange={(on) => setSizes(sideSizes(sideOpen, on))} icon={<Sparkle data-slot="icon" weight="bold" />} />
        </span>
      </header>

      <div className="flex min-h-0 flex-1">
        {/* the activity bar: muted ghost toggles; the open view keeps the pressed fill */}
        <nav aria-label="Side views" className="flex w-11 shrink-0 flex-col items-center gap-1 border-e border-line bg-canvas py-1.5">
          <div role="toolbar" aria-orientation="vertical" aria-label="Side view" className="flex flex-col items-center gap-1">
            {sideViews.map(({ value, label, Icon }) => (
              <Toggle
                key={value} data-value={value} variant="ghost" size="md" square muted tooltip={label}
                pressed={sideOpen && side === value}
                onPressedChange={(on) => showSide(on ? value : null)}
                icon={<Icon data-slot="icon" weight="bold" />}
              />
            ))}
          </div>
        </nav>
        <Splitter
          className="min-w-0 flex-1" handleLabel="Resize the side views" size={sizes} onSizeChange={setSizes}
          panels={[
            { id: "side", minSize: 14, maxSize: 40, collapsible: true, content: sideOpen && (side === "explorer" ? explorer : sourceControl) },
            {
              id: "main", minSize: 30,
              content: (
                <Splitter
                  orientation="vertical" handleLabel="Resize the panel" size={rows} onSizeChange={setRows}
                  panels={[
                    { id: "editor", minSize: 30, content: code },
                    { id: "bottom", minSize: 15, collapsible: true, content: panelOpen && bottom },
                  ]}
                />
              ),
            },
            { id: "assistant", minSize: 22, maxSize: 45, collapsible: true, content: assistantOpen && assistant },
          ]}
        />
      </div>

      <footer className="flex h-6 shrink-0 items-center gap-3 border-t border-line bg-canvas px-2 text-xs text-ink-2" data-editor="status">
        <span className="flex items-center gap-1"><GitBranch weight="bold" aria-hidden />{BRANCH}{ahead > 0 && ` ↑${ahead}`}</span>
        <Button variant="ghost" size="xs" muted onClick={() => showPanel(true, "problems")} aria-label={`${errors} errors, ${warnings} warnings: show problems`}>
          <span className="flex items-center gap-1 tabular-nums"><XCircle weight="fill" className={errors ? "text-red" : undefined} aria-hidden />{errors}<Warning weight="bold" className="ms-1.5" aria-hidden />{warnings}</span>
        </Button>
        {/* the test result as VS Code's status bar shows it: ink text after a glyph in its tone (a
          * pill belongs in content); a press shows the run in the terminal */}
        <Button variant="ghost" size="xs" muted onClick={() => showPanel(true, "terminal")} aria-label={`${passing ? "Tests passing" : "1 test failing"}: show the terminal`}>
          <span className="flex items-center gap-1">
            {passing ? <CheckCircle weight="fill" className="text-green" aria-hidden /> : <XCircle weight="fill" className="text-red" aria-hidden />}
            {passing ? "Tests passing" : "1 test failing"}
          </span>
        </Button>
        <span className="ms-auto flex items-center gap-3">
          <span className="[unicode-bidi:plaintext]">{caret[activePath] ? `Ln ${caret[activePath]}` : `${(files[activePath] ?? []).length} lines`}</span>
          <span className="[unicode-bidi:plaintext]">Spaces: 2</span>
          <span>UTF-8</span>
          <span>{language(activePath)}</span>
        </span>
      </footer>
    </>
  );

  return (
    <div ref={root} tabIndex={-1} onKeyDown={onKeyDown} className="flex h-full flex-col bg-page text-ink outline-none" data-editor="root" data-layout={phone ? "phone" : "desktop"}>
      {phone ? phoneLayout : desktopLayout}
      {paletteDialog}
    </div>
  );
}
```

## Assistant.tsx

```tsx
/* The assistant side panel (Cursor, Claude Code): a conversation of Messages (the question as the
 * person's bubble; the answer holds the agent blocks: tool chips for what the agent did, streaming
 * text for its answer) and the prompt bar to ask. A decision the agent waits for is an approval
 * card docked above the prompt bar, so it is always in sight; once decided it leaves, and the
 * next turn says what happened. Replies are canned and streamed word by word; nothing streams or
 * scrolls on first paint: the panel opens at the start of the conversation, and a turn added
 * later is brought in at its start, never scrolled to the bottom. */
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { ApprovalCard, Message, PromptBar, ScrollArea, StreamingText, ToolChips, type StreamingToken, type ToolDiff, type ToolStep } from "@fndn/react";

/* live: the turn was added by this session (a reply to the person), so its blocks enter; the
 * conversation the panel opens with is history and is simply there */
type Turn = { id: number; prompt?: string; steps?: ToolStep[]; diffs?: ToolDiff[]; reply: StreamingToken[]; done: boolean; live?: boolean };

const words = (text: string): StreamingToken[] => text.split(" ").map((w) => ({ text: w }));

const FIRST: Turn = {
  id: 0,
  prompt: "The rate-limit test fails after the first minute. Why?",
  steps: [
    { icon: "read", label: "Read", chip: "rate-limit.ts", mono: true, detail: [{ text: "25 lines, one bucket per API key" }] },
    { icon: "run", label: "Run tests", chip: "pnpm test", mono: true, detailMono: true, detail: [{ text: "× refills the bucket after the window" }, { text: "1 failed | 10 passed" }] },
  ],
  reply: words("windowStart is set when a key makes its first call and never again, so the count never goes back to zero: after 120 calls that key is refused for good. Reset the count and the window once a minute has passed, before the call is counted."),
  done: true,
};

const MODELS = [
  { value: "standard", label: "Standard", meta: "Balanced" },
  { value: "deep", label: "Deep", meta: "Slower, more careful" },
];
const COMMANDS = [
  { value: "explain", description: "Explain the open file" },
  { value: "fix", description: "Fix the selected problem" },
  { value: "test", description: "Write tests for the open file" },
  { value: "review", description: "Review the uncommitted changes" },
];

function answer(prompt: string, file: string): string {
  const name = file.split("/").pop();
  if (/commit|message/i.test(prompt)) return "Reset the rate-limit window once it has passed. The change only touches rate-limit.ts; the invoices work can go in a commit of its own.";
  if (/test/i.test(prompt)) return `The suite has 11 tests in two files. ${name} is covered by rate-limit.test.ts, which checks the 429 on the 121st call and the refill after a minute.`;
  return `${name} is open. It is short and does one thing; ask me to explain a part of it, fix a problem from the panel below, or review what is uncommitted.`;
}

export function Assistant({ file, onApply, onOpenDiff }: { file: string; onApply: (runTests: boolean) => void; onOpenDiff: (path: string) => void }) {
  const [turns, setTurns] = useState<Turn[]>([FIRST]);
  const [target, setTarget] = useState<string[] | null>(null);
  /* the fix waits for a decision until it is approved or declined */
  const [asking, setAsking] = useState(true);
  const busy = target !== null;
  const scroller = useRef<HTMLDivElement>(null);

  /* stream the pending reply into the last turn, a word every 45ms */
  useEffect(() => {
    if (!target) return;
    const timer = window.setInterval(() => setTurns((all) => {
      const last = all.at(-1)!;
      const n = Math.min(last.reply.length + 1, target.length);
      return [...all.slice(0, -1), { ...last, reply: target.slice(0, n).map((text) => ({ text })), done: n === target.length }];
    }), 45);
    return () => clearInterval(timer);
  }, [target]);
  useEffect(() => { if (target && turns.at(-1)?.done) setTarget(null); }, [turns, target]);

  /* a turn added after first paint is brought in at its start (inside the panel only, never the
   * page); the first frame shows the conversation from the top */
  const count = useRef(turns.length);
  useLayoutEffect(() => {
    if (turns.length === count.current) return;
    count.current = turns.length;
    const view = scroller.current?.querySelector<HTMLElement>("[data-slot=scroll-area-viewport]");
    const turn = scroller.current?.querySelector<HTMLElement>(`[data-turn="${turns.at(-1)!.id}"]`);
    if (view && turn) view.scrollTop = turn.getBoundingClientRect().top - view.getBoundingClientRect().top + view.scrollTop - 12;
  }, [turns]);

  const reply = (turn: Omit<Turn, "id" | "reply" | "done">, text: string) => {
    setTurns((all) => [...all, { ...turn, id: all.length, reply: [], done: false, live: true }]);
    setTarget(text.split(" "));
  };

  const apply = (runTests: boolean) => {
    onApply(runTests);
    reply(
      {
        steps: [
          { icon: "write", label: "Edit", chip: "rate-limit.ts", mono: true, detailMono: true, detail: [{ text: "+ if (now - bucket.windowStart >= WINDOW_MS) {", tone: "add" }, { text: "+   bucket.count = 0;", tone: "add" }] },
          ...(runTests ? [{ icon: "run", label: "Run tests", chip: "pnpm test", mono: true, detailMono: true, detail: [{ text: "✓ 11 passed" }] } satisfies ToolStep] : []),
        ],
        diffs: [{ file: "rate-limit.ts", add: 5, del: 0 }],
      },
      runTests
        ? "Done. The window now starts again once a minute has passed, and all 11 tests pass. The change is in Source control, ready to commit."
        : "Done. The window now starts again once a minute has passed. Run the tests from the command palette when you are ready.",
    );
  };

  return (
    <div className="flex h-full min-w-0 flex-col bg-surface" data-editor="assistant">
      <div className="flex h-8 shrink-0 items-center px-3 text-xs font-medium text-ink-2">Assistant</div>
      <div ref={scroller} className="flex min-h-0 flex-1 flex-col">
        <ScrollArea className="min-h-0 flex-1">
          <div className="flex flex-col gap-4 p-3">
            {turns.map((t) => (
              <div key={t.id} data-turn={t.id} className="flex flex-col gap-3">
                {t.prompt && <Message role="user" text={t.prompt} actions={["copy"]} />}
                {/* the answer's actions are the streaming text's own (copy, retry, thumbs); no author
                  * line: the pane is titled Assistant already (Cursor's) */}
                <Message role="assistant" streaming={!t.done}>
                  {(t.steps || t.reply.length > 0) && <div className="flex flex-col gap-3">
                    {t.steps && (
                      <ToolChips
                        appear={t.live}
                        steps={t.steps}
                        diffs={t.diffs}
                        labels={{ header: `${t.steps.length} tool ${t.steps.length === 1 ? "call" : "calls"}` }}
                        onDiffClick={() => onOpenDiff("src/middleware/rate-limit.ts")}
                      />
                    )}
                    {t.reply.length > 0 && <StreamingText fill appear={t.live} content={t.reply} done={t.done} />}
                  </div>}
                </Message>
              </div>
            ))}
          </div>
        </ScrollArea>
      </div>
      <div className="flex shrink-0 flex-col gap-2 p-2">
        {asking && (
          <ApprovalCard
            resettable={false}
            action={{
              title: "Apply the fix to rate-limit.ts?",
              description: "+5 lines, then runs the tests.",
            }}
            labels={{ approve: "Apply", deny: "Not now" }}
            onDismiss={() => setAsking(false)}
            onDecision={(decision) => {
              setAsking(false);
              if (decision === "approve") apply(true);
              else reply({}, "Left rate-limit.ts as it is. Ask me again when you want the fix.");
            }}
          />
        )}
        <PromptBar
          aria-label="Ask the assistant"
          placeholder="Ask about this code…"
          defaultModel="standard"
          models={MODELS}
          commands={COMMANDS}
          busy={busy}
          onStop={() => { setTarget(null); setTurns((all) => [...all.slice(0, -1), { ...all.at(-1)!, done: true }]); }}
          onSubmit={({ value }) => reply({ prompt: value }, answer(value, file))}
        />
      </div>
    </div>
  );
}
```

## data.ts

```tsx
/* The project the editor has open: a small billing API with one failing test. Plain data, so the
 * app's files read as layout and state only. */
import type { CodeDiffRow, TreeViewNode } from "@fndn/react";

export const PROJECT = "billing-api";
export const BRANCH = "fix/rate-limit";

const rateLimit = [
  'import type { NextFunction, Request, Response } from "express";',
  "",
  "const WINDOW_MS = 60_000;",
  "const LIMIT = 120;",
  "",
  "type Bucket = { count: number; windowStart: number };",
  "const buckets = new Map<string, Bucket>();",
  "",
  "export function rateLimit(req: Request, res: Response, next: NextFunction) {",
  '  const key = req.header("x-api-key") ?? req.ip ?? "anonymous";',
  "  const now = Date.now();",
  "  let bucket = buckets.get(key);",
  "  if (!bucket) {",
  "    bucket = { count: 0, windowStart: now };",
  "    buckets.set(key, bucket);",
  "  }",
  "",
  "  bucket.count += 1;",
  "  if (bucket.count > LIMIT) {",
  "    const retryAfter = Math.ceil((bucket.windowStart + WINDOW_MS - now) / 1000);",
  '    res.set("Retry-After", String(Math.max(retryAfter, 1)));',
  '    return res.status(429).json({ error: "rate_limited", retryAfter });',
  "  }",
  "  next();",
  "}",
];

/** rate-limit.ts once the assistant's fix is applied: the window resets when it has passed. */
export const RATE_LIMIT_FIXED = [
  ...rateLimit.slice(0, 16),
  "",
  "  if (now - bucket.windowStart >= WINDOW_MS) {",
  "    bucket.count = 0;",
  "    bucket.windowStart = now;",
  "  }",
  ...rateLimit.slice(16),
];

const invoicesBefore = [
  'import { Router } from "express";',
  'import { db } from "../lib/db";',
  "",
  "export const invoices = Router();",
  "",
  'invoices.get("/", async (req, res) => {',
  "  const rows = await db.invoice.findMany({",
  "    where: { customerId: String(req.query.customer) },",
  '    orderBy: { issuedAt: "desc" },',
  "  });",
  "  res.json(rows);",
  "});",
  "",
  'invoices.get("/:id", async (req, res) => {',
  "  const row = await db.invoice.findUnique({ where: { id: req.params.id } });",
  '  if (!row) return res.status(404).json({ error: "not_found" });',
  "  res.json(row);",
  "});",
];

const invoices = [
  'import { Router } from "express";',
  'import { formatAmount } from "../lib/currency";',
  'import { db } from "../lib/db";',
  "",
  "export const invoices = Router();",
  "",
  'invoices.get("/", async (req, res) => {',
  "  const limit = Math.min(Number(req.query.limit ?? 50), 200);",
  "  const rows = await db.invoice.findMany({",
  "    where: { customerId: String(req.query.customer) },",
  '    orderBy: { issuedAt: "desc" },',
  "    take: limit,",
  "  });",
  "  const total = rows.reduce((sum, r) => sum + r.amountCents, 0);",
  "  res.json(rows.map((r) => ({ ...r, amount: formatAmount(r.amountCents, r.currency) })));",
  "});",
  "",
  'invoices.get("/:id", async (req, res) => {',
  "  const row = await db.invoice.findUnique({ where: { id: req.params.id } });",
  '  if (!row) return res.status(404).json({ error: "not_found" });',
  "  res.json({ ...row, amount: formatAmount(row.amountCents, row.currency) });",
  "});",
];

const currency = [
  "const formatters = new Map<string, Intl.NumberFormat>();",
  "",
  "/** 12345, \"EUR\" → \"€123.45\". Formatters are cached per currency. */",
  "export function formatAmount(cents: number, currency: string, locale = \"en-US\") {",
  "  const key = `${locale}:${currency}`;",
  "  let format = formatters.get(key);",
  "  if (!format) {",
  '    format = new Intl.NumberFormat(locale, { style: "currency", currency });',
  "    formatters.set(key, format);",
  "  }",
  "  return format.format(cents / 100);",
  "}",
];

/** Every file of the project, by path. */
export const FILES: Record<string, string[]> = {
  "src/server.ts": [
    'import express from "express";',
    'import { auth } from "./middleware/auth";',
    'import { rateLimit } from "./middleware/rate-limit";',
    'import { customers } from "./routes/customers";',
    'import { invoices } from "./routes/invoices";',
    "",
    "export const app = express();",
    "",
    "app.use(express.json());",
    "app.use(auth, rateLimit);",
    'app.use("/v1/customers", customers);',
    'app.use("/v1/invoices", invoices);',
    "",
    "const port = Number(process.env.PORT ?? 8080);",
    "app.listen(port, () => console.log(`billing-api on :${port}`));",
  ],
  "src/middleware/auth.ts": [
    'import type { NextFunction, Request, Response } from "express";',
    'import { db } from "../lib/db";',
    "",
    "export async function auth(req: Request, res: Response, next: NextFunction) {",
    '  const key = req.header("x-api-key");',
    '  if (!key) return res.status(401).json({ error: "missing_api_key" });',
    "  const account = await db.apiKey.findUnique({ where: { key } });",
    '  if (!account?.active) return res.status(403).json({ error: "inactive_key" });',
    "  res.locals.accountId = account.accountId;",
    "  next();",
    "}",
  ],
  "src/middleware/rate-limit.ts": rateLimit,
  "src/routes/customers.ts": [
    'import { Router } from "express";',
    'import { z } from "zod";',
    'import { db } from "../lib/db";',
    "",
    "export const customers = Router();",
    "",
    'customers.get("/:id", async (req, res) => {',
    "  const row = await db.customer.findUnique({ where: { id: req.params.id } });",
    '  if (!row) return res.status(404).json({ error: "not_found" });',
    "  res.json(row);",
    "});",
  ],
  "src/routes/invoices.ts": invoices,
  "src/lib/currency.ts": currency,
  "src/lib/db.ts": [
    'import { PrismaClient } from "@prisma/client";',
    "",
    "/** One client per process; Prisma pools the connections. */",
    "export const db = new PrismaClient({",
    '  log: process.env.NODE_ENV === "production" ? ["warn", "error"] : ["query"],',
    "});",
  ],
  "test/rate-limit.test.ts": [
    'import request from "supertest";',
    'import { afterEach, describe, expect, it, vi } from "vitest";',
    'import { app } from "../src/server";',
    "",
    'const call = () => request(app).get("/v1/invoices").set("x-api-key", "test_key");',
    "",
    'describe("rate limit", () => {',
    "  afterEach(() => vi.useRealTimers());",
    "",
    '  it("refuses the 121st call in a minute", async () => {',
    "    for (let i = 0; i < 120; i++) await call();",
    "    expect((await call()).status).toBe(429);",
    "  });",
    "",
    '  it("refills the bucket after the window", async () => {',
    "    vi.useFakeTimers();",
    "    for (let i = 0; i < 121; i++) await call();",
    "    vi.advanceTimersByTime(60_000);",
    "    expect((await call()).status).toBe(200);",
    "  });",
    "});",
  ],
  "package.json": [
    "{",
    '  "name": "billing-api",',
    '  "private": true,',
    '  "type": "module",',
    '  "scripts": {',
    '    "dev": "tsx watch src/server.ts",',
    '    "test": "vitest run",',
    '    "typecheck": "tsc --noEmit"',
    "  },",
    '  "dependencies": { "@prisma/client": "^6.4.0", "express": "^5.1.0", "zod": "^3.24.2" },',
    '  "devDependencies": { "supertest": "^7.1.0", "tsx": "^4.19.3", "vitest": "^3.2.4" }',
    "}",
  ],
  "README.md": [
    "# billing-api",
    "",
    "Invoices and customers for the dashboard, behind an API key.",
    "",
    "- `pnpm dev` starts the server on :8080",
    "- `pnpm test` runs the suite (vitest + supertest)",
    "- Every key may make 120 calls a minute; the 121st gets a 429 and a Retry-After header.",
  ],
};

const node = (path: string): TreeViewNode => ({ value: path, label: path.split("/").pop()! });

/** The explorer's tree. Icons are added by the app. */
export const TREE: TreeViewNode[] = [
  {
    value: "src", label: "src",
    children: [
      { value: "src/lib", label: "lib", children: [node("src/lib/currency.ts"), node("src/lib/db.ts")] },
      { value: "src/middleware", label: "middleware", children: [node("src/middleware/auth.ts"), node("src/middleware/rate-limit.ts")] },
      { value: "src/routes", label: "routes", children: [node("src/routes/customers.ts"), node("src/routes/invoices.ts")] },
      node("src/server.ts"),
    ],
  },
  { value: "test", label: "test", children: [node("test/rate-limit.test.ts")] },
  node("package.json"),
  node("README.md"),
];

/** A whole-file unified diff (both sides are short): the longest common run of lines stays as
 * context, the rest is removed or added. */
export function lineDiff(before: string[], after: string[]): CodeDiffRow[] {
  const n = before.length, m = after.length;
  const lcs = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
  for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) lcs[i]![j] = before[i] === after[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
  const rows: CodeDiffRow[] = [];
  let i = 0, j = 0;
  while (i < n || j < m) {
    if (i < n && j < m && before[i] === after[j]) { rows.push({ old: i + 1, cur: j + 1, type: "ctx", pieces: [{ text: before[i]! }] }); i++; j++; }
    else if (j < m && (i === n || lcs[i]![j + 1]! >= lcs[i + 1]![j]!)) { rows.push({ old: null, cur: j + 1, type: "add", pieces: [{ text: after[j]! }] }); j++; }
    else { rows.push({ old: i + 1, cur: null, type: "del", pieces: [{ text: before[i]! }] }); i++; }
  }
  return rows;
}

export type Change = { path: string; status: "modified" | "added"; before: string[] };

/** Uncommitted work when the editor opens. */
export const CHANGES: Change[] = [
  { path: "src/routes/invoices.ts", status: "modified", before: invoicesBefore },
  { path: "src/lib/currency.ts", status: "added", before: [] },
];

export type Problem = { value: string; path: string; line: number; col: number; severity: "error" | "warning"; message: string; fixedBy?: "rate-limit" };

export const PROBLEMS: Problem[] = [
  { value: "p1", path: "test/rate-limit.test.ts", line: 19, col: 38, severity: "error", fixedBy: "rate-limit", message: "rate limit › refills the bucket after the window: expected 429 to be 200" },
  { value: "p2", path: "src/routes/invoices.ts", line: 14, col: 9, severity: "warning", message: "'total' is declared but its value is never read. ts(6133)" },
  { value: "p3", path: "src/routes/customers.ts", line: 2, col: 10, severity: "warning", message: "'z' is defined but never used. eslint(no-unused-vars)" },
];

/** What `pnpm test` prints, before and after the fix. */
export function testRun(fixed: boolean): string[] {
  return [
    "$ pnpm test",
    "",
    " RUN  v3.2.4 /home/dev/billing-api",
    "",
    " ✓ test/invoices.test.ts (9 tests) 48ms",
    fixed ? " ✓ test/rate-limit.test.ts (2 tests) 31ms" : " ❯ test/rate-limit.test.ts (2 tests | 1 failed) 29ms",
    ...(fixed ? [] : [
      "   × rate limit > refills the bucket after the window",
      "     → expected 429 to be 200 // Object.is equality",
      "",
      " FAIL  test/rate-limit.test.ts > rate limit > refills the bucket after the window",
      "  ❯ test/rate-limit.test.ts:19:38",
    ]),
    "",
    fixed ? " Test Files  2 passed (2)" : " Test Files  1 failed | 1 passed (2)",
    fixed ? "      Tests  11 passed (11)" : "      Tests  1 failed | 10 passed (11)",
    "   Duration  1.42s",
    "",
  ];
}
```

## SourceControl.tsx

```tsx
/* The source-control side view (VS Code's): a commit message, Commit, and the changed files as
 * dense rows of a flush list (part of the pane, no box): the name, its folder dimmed, a status letter at the end in its tone (M modified,
 * A added). Choosing a file opens its diff as a tab in the editor. */
import { useState } from "react";
import { CheckCircle } from "@phosphor-icons/react";
import { Button, Count, EmptyState, Listbox, ScrollArea, Textarea } from "@fndn/react";
import type { Change } from "./data";

const LETTER = { modified: { meta: "M", metaTone: "orange" }, added: { meta: "A", metaTone: "green" } } as const;

export function SourceControl({ changes, selected, branch, onSelect, onCommit }: {
  changes: Change[];
  selected: string | null;
  branch: string;
  onSelect: (path: string) => void;
  onCommit: (message: string) => void;
}) {
  const [message, setMessage] = useState("");
  const [invalid, setInvalid] = useState(false);
  const [last, setLast] = useState<string | null>(null);
  const commit = () => {
    if (!message.trim()) return setInvalid(true);
    onCommit(message.trim());
    setLast(message.trim());
    setMessage("");
  };

  return (
    <div className="flex h-full min-w-0 flex-col bg-canvas" data-editor="source-control">
      <div className="flex h-8 shrink-0 items-center px-3 text-xs font-medium text-ink-2">Source control</div>
      {changes.length ? (
        <ScrollArea className="min-h-0 flex-1">
          <div className="flex flex-col gap-2 px-2 pb-1">
            <Textarea
              size="sm" rows={2} aria-label="Commit message" placeholder={`Message (Ctrl+Enter to commit on ${branch})`}
              value={message} invalid={invalid}
              onChange={(e) => { setMessage(e.target.value); setInvalid(false); }}
              onKeyDown={(e) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); commit(); } }}
            />
            <Button size="sm" variant="accent" onClick={commit}>Commit</Button>
            <h3 className="mt-1 flex items-center gap-1.5 text-xs font-medium text-ink-2" aria-hidden>Changes <Count size="sm">{String(changes.length)}</Count></h3>
          </div>
          {/* flush: the rows are part of the pane, edge to edge, their text on the pane's 8px inset */}
          <Listbox
            variant="flush" size="xs" className="w-full pb-2" aria-label={`Changes, ${changes.length}`}
            items={changes.map((c) => {
              const folder = c.path.split("/").slice(0, -1).join("/");
              return { value: c.path, label: c.path.split("/").pop()!, ...(folder ? { description: folder } : {}), ...LETTER[c.status] };
            })}
            value={selected ? [selected] : []}
            onValueChange={(v) => v[0] && onSelect(v[0])}
          />
        </ScrollArea>
      ) : (
        <EmptyState className="p-6" size="block" icon={<CheckCircle weight="fill" />} title="No changes" hint={last ? `Committed “${last}” to ${branch}.` : "The working tree is clean."} />
      )}
    </div>
  );
}
```
