Showcase
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.
Source
Only the system's components and token utilities; the layout is Tailwind.
showcases/code-editor/App.tsx
1
/* A code editor (VS Code, Zed): an activity bar and a side view (explorer or source control), open2
* files as attached tabs over the code, a terminal and problems panel below, an assistant on the3
* right, a command palette on Ctrl/⌘ K or P and a status bar. Dense like the product: 24px tree4
* and list rows, 28px tabs, 32px pane headers, 13px code that never wraps. Panels are a Splitter5
* (drag, or arrow keys on a handle); a panel is open while its size is above zero, so the toggles6
* and the handles share one state. Below 720px the app shows one view at a time, picked at the7
* bottom. Shortcuts are bound on the app's root, so they work while the app has focus and leave8
* the page's own keys alone.9
*10
* A rounded app: the page that hosts it has <html data-shape="rounded"> (index.json tells the11
* docs site), so no button, toggle or switcher here names a shape, and its dialogs follow. */12
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";13
import { CheckCircle, Eye, File, FileText, Folder, GitBranch, MagnifyingGlass, Play, Sparkle, Terminal, Warning, XCircle } from "@phosphor-icons/react";14
import {15
Button, CodeView, CommandPalette, Count, EmptyState, Kbd, ScrollArea, SegmentedControl, Splitter, Tabs, Toggle, TreeView,16
type CommandPaletteItem, type TreeViewNode,17
} from "@fndn/react";18
import { Assistant } from "./Assistant";19
import { SourceControl } from "./SourceControl";20
import { BRANCH, CHANGES, FILES, PROBLEMS, PROJECT, RATE_LIMIT_FIXED, TREE, lineDiff, testRun, type Change } from "./data";21
22
const RATE_LIMIT = "src/middleware/rate-limit.ts";23
/** An open diff is a tab of its own, next to the file's: its value is the path with this prefix. */24
const DIFF = "diff:";25
const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.userAgent) ? "⌘" : "Ctrl";26
/** A pane's title row: 32px, the height of the tab strip beside it, quiet small text. */27
const PANE_TITLE = "flex h-8 shrink-0 items-center px-3 text-xs font-medium text-ink-2";28
29
/** The size of an element (a callback ref: the element may come and go), measured before the30
* first paint and on every change. */31
function useSize() {32
const [size, setSize] = useState({ width: 0, height: 0 });33
const observer = useRef<ResizeObserver>(null);34
const ref = useCallback((el: HTMLElement | null) => {35
observer.current?.disconnect();36
if (!el) return;37
setSize({ width: el.clientWidth, height: el.clientHeight });38
observer.current = new ResizeObserver(([e]) => e && setSize({ width: e.contentRect.width, height: e.contentRect.height }));39
observer.current.observe(el);40
}, []);41
return [ref, size] as const;42
}43
44
const fileIcon = (path: string) => (path.endsWith(".md") ? <FileText data-slot="icon" /> : <File data-slot="icon" />);45
const withIcons = (nodes: TreeViewNode[]): TreeViewNode[] =>46
nodes.map((n) => (n.children47
? { ...n, icon: <Folder />, children: withIcons(n.children) }48
: { ...n, icon: n.value.endsWith(".md") ? <FileText /> : <File /> }));49
const FILE_TREE = withIcons(TREE);50
const nameOf = (path: string) => path.split("/").pop()!;51
const pathOf = (tab: string) => (tab.startsWith(DIFF) ? tab.slice(DIFF.length) : tab);52
const language = (path: string) => (path.endsWith(".ts") ? "TypeScript" : path.endsWith(".json") ? "JSON" : "Markdown");53
54
/** A terminal line in vitest's colours: counts of failed red, passed green, marks in their tone;55
* what vitest dims (labels, a file's test count, timings, the path) is ink-2 beside the ink of56
* the output: two levels, and both are read, so neither is fainter than ink-2. PARTS also cuts57
* out the labels and a file's test count, so a "1 failed" inside "(3 tests | 1 failed)" is58
* dimmed with its count. */59
const TONES: [RegExp, string][] = [60
[/^(\d+ failed|×|FAIL)$/, "text-red"],61
[/^(\d+ passed|✓)$/, "text-green"],62
[/^❯$/, "text-orange"],63
[/^(Test Files|Tests|Duration|RUN|\(\d+(?: tests?)?(?: \| \d+ failed)?\)|\d+ms|\/home\/[\w/-]+)$/, "text-ink-2"],64
];65
const PARTS = /(\d+ failed|\d+ passed|×|✓|❯|FAIL|Test Files|Tests|Duration|RUN|\(\d+(?: tests?)?(?: \| \d+ failed)?\)|\d+ms|\/home\/[\w/-]+)/;66
function TerminalLine({ line }: { line: string }) {67
if (line.startsWith("$ ")) return <div className="ps-[1ch] text-ink">{line}</div>;68
if (!line) return <div>{" "}</div>;69
return (70
<div className="text-ink">71
{line.split(PARTS).map((part, i) => {72
const tone = TONES.find(([re]) => re.test(part))?.[1];73
return tone ? <span key={i} className={tone}>{part}</span> : part;74
})}75
</div>76
);77
}78
79
/** The terminal: opens at the start of the newest run (the first frame never scrolls), and a run80
* added later is brought in at its first line, once the terminal is in view (it may be a hidden81
* tab when the run is added). */82
function TerminalOutput({ lines }: { lines: string[] }) {83
const output = useRef<HTMLPreElement>(null);84
const shown = useRef(lines.length);85
useLayoutEffect(() => {86
const el = output.current;87
const view = el?.closest<HTMLElement>("[data-slot=scroll-area-viewport]");88
if (!el || !view) return;89
const reveal = () => {90
const count = el.children.length;91
if (count === shown.current || !el.offsetHeight) return;92
shown.current = count;93
const rows = [...el.children] as HTMLElement[];94
const start = rows.map((row) => row.textContent?.startsWith("$ ")).lastIndexOf(true);95
view.scrollTop = start > 0 ? rows[start]!.offsetTop : 0;96
};97
reveal();98
const ro = new ResizeObserver(reveal);99
ro.observe(el);100
return () => ro.disconnect();101
}, [lines]);102
return (103
/* left to right on a right-to-left page too; long lines wrap at the pane's width, as a terminal104
* wraps at its columns, so a line's start is never cut and nothing scrolls sideways */105
<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%]">106
{lines.map((line, i) => <TerminalLine key={i} line={line} />)}107
</pre>108
);109
}110
111
/** One panel open: the sizes it takes, the others sharing the rest. */112
const sideSizes = (side: boolean, assistant: boolean) => [side ? 23 : 0, 100 - (side ? 23 : 0) - (assistant ? 28 : 0), assistant ? 28 : 0];113
114
export default function App() {115
const [root, { width }] = useSize();116
const phone = width > 0 && width < 720;117
118
/* the project */119
const [files, setFiles] = useState(FILES);120
const [changes, setChanges] = useState<Change[]>(CHANGES);121
const [problems, setProblems] = useState(PROBLEMS);122
const [terminal, setTerminal] = useState(() => testRun(false));123
const [passing, setPassing] = useState(false);124
const [ahead, setAhead] = useState(0);125
126
/* the editor: open tabs (a path, or DIFF + path) and the active one */127
const [open, setOpen] = useState([RATE_LIMIT, "test/rate-limit.test.ts", "src/routes/invoices.ts"]);128
const [active, setActive] = useState(RATE_LIMIT);129
const activePath = pathOf(active);130
const diffOf = active.startsWith(DIFF) ? activePath : null;131
/* the line the caret is on in each file, marked as the code block's current line */132
const [caret, setCaret] = useState<Record<string, number>>({});133
const [expanded, setExpanded] = useState(["src", "src/middleware", "test"]);134
135
/* the layout */136
const [side, setSide] = useState<"explorer" | "changes">("explorer");137
const [sizes, setSizes] = useState(() => sideSizes(true, true));138
const [rows, setRows] = useState([68, 32]);139
const [panelTab, setPanelTab] = useState("terminal");140
const [phoneView, setPhoneView] = useState("code");141
const [palette, setPalette] = useState(false);142
const sideOpen = sizes[0]! > 0, assistantOpen = sizes[2]! > 0, panelOpen = rows[1]! > 0;143
144
const openTab = (tab: string) => {145
setOpen((o) => (o.includes(tab) ? o : [...o, tab]));146
setActive(tab);147
setPhoneView("code");148
};149
const openFile = (path: string, line?: number) => {150
openTab(path);151
if (line) setCaret((c) => ({ ...c, [path]: line }));152
};153
const openDiff = (path: string) => { openTab(DIFF + path); setSide("changes"); };154
const closeTab = (tab: string) => setOpen((o) => o.filter((t) => t !== tab));155
const showSide = (view: "explorer" | "changes" | null) => {156
if (view) setSide(view);157
setSizes(sideSizes(!!view, assistantOpen));158
if (view) setPhoneView(view === "explorer" ? "files" : "changes");159
};160
const showPanel = (show: boolean, tab?: string) => {161
if (tab) setPanelTab(tab);162
setRows(show ? [68, 32] : [100, 0]);163
if (show) setPhoneView("panel");164
};165
const runTests = (fixed = files[RATE_LIMIT] === RATE_LIMIT_FIXED) => {166
setTerminal((t) => [...t, "", ...testRun(fixed)]);167
setPassing(fixed);168
showPanel(true, "terminal");169
};170
const applyFix = (andTest: boolean) => {171
setFiles((f) => ({ ...f, [RATE_LIMIT]: RATE_LIMIT_FIXED }));172
/* appended, so the rows already there do not move */173
setChanges((c) => (c.some((x) => x.path === RATE_LIMIT) ? c : [...c, { path: RATE_LIMIT, status: "modified", before: FILES[RATE_LIMIT]! }]));174
setProblems((p) => p.filter((x) => x.fixedBy !== "rate-limit"));175
openDiff(RATE_LIMIT);176
if (andTest) runTests(true);177
};178
/* committed changes have no diff left: their tabs close, and the file's own tab takes over */179
const commit = () => {180
setChanges([]);181
setOpen((o) => { const kept = o.filter((t) => !t.startsWith(DIFF)); return diffOf && !kept.includes(diffOf) ? [...kept, diffOf] : kept; });182
if (diffOf) setActive(diffOf);183
setAhead((n) => n + 1);184
};185
186
/* files are found by name or path; commands show their own shortcut */187
const commands = useMemo((): CommandPaletteItem[] => [188
...Object.keys(files).map((path) => ({189
value: `file:${path}`, label: nameOf(path), meta: path, group: "Files", keywords: [path],190
icon: path.endsWith(".md") ? <FileText data-slot="icon" weight="bold" /> : <File data-slot="icon" weight="bold" />,191
})),192
{ value: "run-tests", label: "Run tests", meta: "pnpm test", group: "Commands", icon: <Play data-slot="icon" weight="bold" /> },193
{ value: "explorer", label: "Show explorer", group: "View", shortcut: [mod, "B"], icon: <Eye data-slot="icon" weight="bold" /> },194
{ value: "changes", label: "Show source control", group: "View", keywords: ["git", "diff"], icon: <GitBranch data-slot="icon" weight="bold" /> },195
{ value: "terminal", label: "Show terminal", group: "View", shortcut: [mod, "J"], icon: <Terminal data-slot="icon" weight="bold" /> },196
{ value: "problems", label: "Show problems", group: "View", keywords: ["errors", "warnings"], icon: <Warning data-slot="icon" weight="bold" /> },197
{ value: "assistant", label: "Show assistant", group: "View", keywords: ["ai", "chat"], icon: <Sparkle data-slot="icon" weight="bold" /> },198
], [files]);199
/* Quick Open's order: what was picked here first, then the open files (VS Code lists the200
* recently opened files before the rest of the workspace) */201
const [recent, setRecent] = useState<string[]>([]);202
const recentShown = [...new Set([...recent, ...open.filter((t) => !t.startsWith(DIFF)).map((t) => `file:${t}`)])].slice(0, 5);203
const run = (value: string) => {204
setRecent((r) => [value, ...r.filter((v) => v !== value)].slice(0, 3));205
if (value.startsWith("file:")) openFile(value.slice(5));206
else if (value === "run-tests") runTests();207
else if (value === "explorer" || value === "changes") showSide(value);208
else if (value === "terminal" || value === "problems") showPanel(true, value);209
else if (value === "assistant") { setSizes(sideSizes(sideOpen, true)); setPhoneView("assistant"); }210
};211
const onKeyDown = (e: KeyboardEvent) => {212
if (!(e.ctrlKey || e.metaKey) || e.altKey) return;213
const key = e.key.toLowerCase();214
if (key === "k" || key === "p") { e.preventDefault(); e.stopPropagation(); setPalette(true); }215
else if (key === "j") { e.preventDefault(); showPanel(!panelOpen); }216
else if (key === "b") { e.preventDefault(); showSide(sideOpen ? null : side); }217
};218
219
/* ── the views ─────────────────────────────────────────── */220
221
/* the pane is titled by its view; the project is the tree's own label, as VS Code's section */222
const explorer = (223
<div className="flex h-full min-w-0 flex-col bg-canvas" data-editor="explorer">224
<div className={PANE_TITLE}>Explorer</div>225
<ScrollArea className="min-h-0 flex-1">226
<TreeView227
className="px-1 pb-2" size="xs" label={PROJECT} items={FILE_TREE}228
expandedValue={expanded} onExpandedValueChange={setExpanded}229
selectedValue={diffOf ? [] : [activePath]}230
onSelectedValueChange={(v) => v[0] && v[0] in files && openFile(v[0])}231
/>232
</ScrollArea>233
</div>234
);235
236
const sourceControl = (237
<SourceControl changes={changes} selected={diffOf} branch={BRANCH} onSelect={openDiff} onCommit={commit} />238
);239
240
/* the editor: closable pill tabs in the pane's 32px header over a code view (no frame, no copy,241
* no path; lines never wrap and the gutter stays while the code scrolls sideways). A strip with242
* more files than room scrolls, fades its cut edge and lists every file in its menu */243
const editorOf = (tab: string) => {244
const path = pathOf(tab);245
if (tab.startsWith(DIFF)) {246
const change = changes.find((c) => c.path === path);247
return <CodeView fill wrap={false} label={`${path} (working tree)`} diff={lineDiff(change?.before ?? files[path]!, files[path]!)} />;248
}249
return <CodeView fill wrap={false} label={path} value={files[path]!.join("\n")} currentLine={caret[path]} />;250
};251
const code = (252
<div className="h-full bg-surface" data-editor="code">253
{open.length ? (254
<Tabs255
variant="pill" closable fill inHeader headerClass="h-8 border-b border-line px-1" aria-label="Open files"256
value={open.includes(active) ? active : open[0]} onValueChange={setActive} onClose={closeTab}257
items={open.map((tab) => ({258
value: tab,259
label: tab.startsWith(DIFF) ? `${nameOf(pathOf(tab))} (working tree)` : nameOf(tab),260
icon: tab.startsWith(DIFF) ? <GitBranch data-slot="icon" /> : fileIcon(tab),261
content: editorOf(tab),262
}))}263
/>264
) : (265
<EmptyState className="h-full bg-surface" size="block" icon="file" title="No open files" hint={`${mod}+P opens one by name.`} />266
)}267
</div>268
);269
270
const errors = problems.filter((p) => p.severity === "error").length;271
const warnings = problems.length - errors;272
const problemTree: TreeViewNode[] = [...new Set(problems.map((p) => p.path))].map((path) => ({273
value: path, label: nameOf(path), icon: <File />,274
children: problems.filter((p) => p.path === path).map((p) => ({275
value: p.value, label: `${p.message} [Ln ${p.line}, Col ${p.col}]`,276
icon: p.severity === "error" ? <XCircle weight="fill" className="text-red" /> : <Warning className="text-orange" />,277
})),278
}));279
const bottom = (280
<div className="h-full bg-surface" data-editor="panel">281
{/* fill: the panel under the strip takes the rest of the pane's height */}282
<Tabs283
fill variant="underline" inHeader headerClass="h-8 border-b border-line px-3 text-xs" aria-label="Panel"284
value={panelTab} onValueChange={setPanelTab}285
items={[286
{287
value: "terminal", label: "Terminal",288
content: (289
<ScrollArea className="h-full" data-editor="terminal">290
<TerminalOutput lines={terminal} />291
</ScrollArea>292
),293
},294
{295
value: "problems",296
label: <span className="flex items-center gap-1.5">Problems <Count size="sm">{String(problems.length)}</Count></span>,297
content: (298
<ScrollArea className="h-full" data-editor="problems">299
{problems.length ? (300
<TreeView301
className="px-1 py-1" size="xs" aria-label="Problems" items={problemTree} expandedValue={problemTree.map((n) => n.value)}302
selectedValue={[]}303
onSelectedValueChange={(v) => { const p = problems.find((x) => x.value === v[0]); if (p) openFile(p.path, p.line); }}304
/>305
) : (306
<EmptyState size="row" title="No problems in the workspace" />307
)}308
</ScrollArea>309
),310
},311
]}312
/>313
</div>314
);315
316
const assistant = <Assistant file={activePath} onApply={applyFix} onOpenDiff={openDiff} />;317
318
/* the system's command palette; Ctrl/⌘ K and P are bound on the app's root (onKeyDown), so they319
* work while the app has focus and leave the page's own ⌘K alone */320
const paletteDialog = (321
<CommandPalette322
items={commands} recent={recentShown} limit={8} hotkey={false}323
open={palette} onOpenChange={setPalette} onSelect={run}324
label="Go to a file or run a command" placeholder="Go to a file or run a command…"325
emptyTitle="Nothing matches" emptyHint="Try a file name, or a command such as Run tests."326
/>327
);328
329
/* ── phone: one view at a time ──────────────────────────── */330
const views: Record<string, ReactNode> = { files: explorer, code, changes: sourceControl, panel: bottom, assistant };331
const phoneLayout = (332
<>333
<header className="flex h-11 shrink-0 items-center gap-2 border-b border-line ps-3 pe-1.5">334
<span className="min-w-0 flex-1 truncate text-sm font-semibold" title={`${PROJECT} · ${BRANCH}`}>{PROJECT}</span>335
<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)} />336
</header>337
<div className="min-h-0 flex-1">{views[phoneView]}</div>338
<nav aria-label="Views" className="shrink-0 border-t border-line p-2">339
<SegmentedControl340
fill size="md" aria-label="View" value={phoneView} onValueChange={setPhoneView}341
options={[{ value: "files", label: "Files" }, { value: "code", label: "Code" }, { value: "changes", label: "Git" }, { value: "panel", label: "Terminal" }, { value: "assistant", label: "AI" }]}342
/>343
</nav>344
</>345
);346
347
/* ── desktop ───────────────────────────────────────────── */348
const sideViews = [349
{ value: "explorer" as const, label: `Explorer (${mod}+B)`, Icon: Folder },350
{ value: "changes" as const, label: `Source control, ${changes.length === 1 ? "1 change" : `${changes.length} changes`}`, Icon: GitBranch },351
];352
const desktopLayout = (353
<>354
{/* the title bar: the command center in the middle, the layout toggles at the end */}355
<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">356
<span />357
<span className="relative flex">358
<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">359
Go to file or command360
</Button>361
<span className="pointer-events-none absolute inset-y-0 end-1.5 flex items-center" aria-hidden><Kbd keys={[mod, "K"]} /></span>362
</span>363
<span className="flex justify-end gap-0.5">364
<Toggle variant="ghost" size="sm" square muted tooltip={`Panel (${mod}+J)`} pressed={panelOpen} onPressedChange={(on) => showPanel(on)} icon={<Terminal data-slot="icon" weight="bold" />} />365
<Toggle variant="ghost" size="sm" square muted tooltip="Assistant" pressed={assistantOpen} onPressedChange={(on) => setSizes(sideSizes(sideOpen, on))} icon={<Sparkle data-slot="icon" weight="bold" />} />366
</span>367
</header>368
369
<div className="flex min-h-0 flex-1">370
{/* the activity bar: muted ghost toggles; the open view keeps the pressed fill */}371
<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">372
<div role="toolbar" aria-orientation="vertical" aria-label="Side view" className="flex flex-col items-center gap-1">373
{sideViews.map(({ value, label, Icon }) => (374
<Toggle375
key={value} data-value={value} variant="ghost" size="md" square muted tooltip={label}376
pressed={sideOpen && side === value}377
onPressedChange={(on) => showSide(on ? value : null)}378
icon={<Icon data-slot="icon" weight="bold" />}379
/>380
))}381
</div>382
</nav>383
<Splitter384
className="min-w-0 flex-1" handleLabel="Resize the side views" size={sizes} onSizeChange={setSizes}385
panels={[386
{ id: "side", minSize: 14, maxSize: 40, collapsible: true, content: sideOpen && (side === "explorer" ? explorer : sourceControl) },387
{388
id: "main", minSize: 30,389
content: (390
<Splitter391
orientation="vertical" handleLabel="Resize the panel" size={rows} onSizeChange={setRows}392
panels={[393
{ id: "editor", minSize: 30, content: code },394
{ id: "bottom", minSize: 15, collapsible: true, content: panelOpen && bottom },395
]}396
/>397
),398
},399
{ id: "assistant", minSize: 22, maxSize: 45, collapsible: true, content: assistantOpen && assistant },400
]}401
/>402
</div>403
404
<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">405
<span className="flex items-center gap-1"><GitBranch weight="bold" aria-hidden />{BRANCH}{ahead > 0 && ` ↑${ahead}`}</span>406
<Button variant="ghost" size="xs" muted onClick={() => showPanel(true, "problems")} aria-label={`${errors} errors, ${warnings} warnings: show problems`}>407
<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>408
</Button>409
{/* the test result as VS Code's status bar shows it: ink text after a glyph in its tone (a410
* pill belongs in content); a press shows the run in the terminal */}411
<Button variant="ghost" size="xs" muted onClick={() => showPanel(true, "terminal")} aria-label={`${passing ? "Tests passing" : "1 test failing"}: show the terminal`}>412
<span className="flex items-center gap-1">413
{passing ? <CheckCircle weight="fill" className="text-green" aria-hidden /> : <XCircle weight="fill" className="text-red" aria-hidden />}414
{passing ? "Tests passing" : "1 test failing"}415
</span>416
</Button>417
<span className="ms-auto flex items-center gap-3">418
<span className="[unicode-bidi:plaintext]">{caret[activePath] ? `Ln ${caret[activePath]}` : `${(files[activePath] ?? []).length} lines`}</span>419
<span className="[unicode-bidi:plaintext]">Spaces: 2</span>420
<span>UTF-8</span>421
<span>{language(activePath)}</span>422
</span>423
</footer>424
</>425
);426
427
return (428
<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"}>429
{phone ? phoneLayout : desktopLayout}430
{paletteDialog}431
</div>432
);433
}1
/* The assistant side panel (Cursor, Claude Code): a conversation of Messages (the question as the2
* person's bubble; the answer holds the agent blocks: tool chips for what the agent did, streaming3
* text for its answer) and the prompt bar to ask. A decision the agent waits for is an approval4
* card docked above the prompt bar, so it is always in sight; once decided it leaves, and the5
* next turn says what happened. Replies are canned and streamed word by word; nothing streams or6
* scrolls on first paint: the panel opens at the start of the conversation, and a turn added7
* later is brought in at its start, never scrolled to the bottom. */8
import { useEffect, useLayoutEffect, useRef, useState } from "react";9
import { ApprovalCard, Message, PromptBar, ScrollArea, StreamingText, ToolChips, type StreamingToken, type ToolDiff, type ToolStep } from "@fndn/react";10
11
/* live: the turn was added by this session (a reply to the person), so its blocks enter; the12
* conversation the panel opens with is history and is simply there */13
type Turn = { id: number; prompt?: string; steps?: ToolStep[]; diffs?: ToolDiff[]; reply: StreamingToken[]; done: boolean; live?: boolean };14
15
const words = (text: string): StreamingToken[] => text.split(" ").map((w) => ({ text: w }));16
17
const FIRST: Turn = {18
id: 0,19
prompt: "The rate-limit test fails after the first minute. Why?",20
steps: [21
{ icon: "read", label: "Read", chip: "rate-limit.ts", mono: true, detail: [{ text: "25 lines, one bucket per API key" }] },22
{ 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" }] },23
],24
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."),25
done: true,26
};27
28
const MODELS = [29
{ value: "standard", label: "Standard", meta: "Balanced" },30
{ value: "deep", label: "Deep", meta: "Slower, more careful" },31
];32
const COMMANDS = [33
{ value: "explain", description: "Explain the open file" },34
{ value: "fix", description: "Fix the selected problem" },35
{ value: "test", description: "Write tests for the open file" },36
{ value: "review", description: "Review the uncommitted changes" },37
];38
39
function answer(prompt: string, file: string): string {40
const name = file.split("/").pop();41
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.";42
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.`;43
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.`;44
}45
46
export function Assistant({ file, onApply, onOpenDiff }: { file: string; onApply: (runTests: boolean) => void; onOpenDiff: (path: string) => void }) {47
const [turns, setTurns] = useState<Turn[]>([FIRST]);48
const [target, setTarget] = useState<string[] | null>(null);49
/* the fix waits for a decision until it is approved or declined */50
const [asking, setAsking] = useState(true);51
const busy = target !== null;52
const scroller = useRef<HTMLDivElement>(null);53
54
/* stream the pending reply into the last turn, a word every 45ms */55
useEffect(() => {56
if (!target) return;57
const timer = window.setInterval(() => setTurns((all) => {58
const last = all.at(-1)!;59
const n = Math.min(last.reply.length + 1, target.length);60
return [...all.slice(0, -1), { ...last, reply: target.slice(0, n).map((text) => ({ text })), done: n === target.length }];61
}), 45);62
return () => clearInterval(timer);63
}, [target]);64
useEffect(() => { if (target && turns.at(-1)?.done) setTarget(null); }, [turns, target]);65
66
/* a turn added after first paint is brought in at its start (inside the panel only, never the67
* page); the first frame shows the conversation from the top */68
const count = useRef(turns.length);69
useLayoutEffect(() => {70
if (turns.length === count.current) return;71
count.current = turns.length;72
const view = scroller.current?.querySelector<HTMLElement>("[data-slot=scroll-area-viewport]");73
const turn = scroller.current?.querySelector<HTMLElement>(`[data-turn="${turns.at(-1)!.id}"]`);74
if (view && turn) view.scrollTop = turn.getBoundingClientRect().top - view.getBoundingClientRect().top + view.scrollTop - 12;75
}, [turns]);76
77
const reply = (turn: Omit<Turn, "id" | "reply" | "done">, text: string) => {78
setTurns((all) => [...all, { ...turn, id: all.length, reply: [], done: false, live: true }]);79
setTarget(text.split(" "));80
};81
82
const apply = (runTests: boolean) => {83
onApply(runTests);84
reply(85
{86
steps: [87
{ 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" }] },88
...(runTests ? [{ icon: "run", label: "Run tests", chip: "pnpm test", mono: true, detailMono: true, detail: [{ text: "✓ 11 passed" }] } satisfies ToolStep] : []),89
],90
diffs: [{ file: "rate-limit.ts", add: 5, del: 0 }],91
},92
runTests93
? "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."94
: "Done. The window now starts again once a minute has passed. Run the tests from the command palette when you are ready.",95
);96
};97
98
return (99
<div className="flex h-full min-w-0 flex-col bg-surface" data-editor="assistant">100
<div className="flex h-8 shrink-0 items-center px-3 text-xs font-medium text-ink-2">Assistant</div>101
<div ref={scroller} className="flex min-h-0 flex-1 flex-col">102
<ScrollArea className="min-h-0 flex-1">103
<div className="flex flex-col gap-4 p-3">104
{turns.map((t) => (105
<div key={t.id} data-turn={t.id} className="flex flex-col gap-3">106
{t.prompt && <Message role="user" text={t.prompt} actions={["copy"]} />}107
{/* the answer's actions are the streaming text's own (copy, retry, thumbs); no author108
* line: the pane is titled Assistant already (Cursor's) */}109
<Message role="assistant" streaming={!t.done}>110
{(t.steps || t.reply.length > 0) && <div className="flex flex-col gap-3">111
{t.steps && (112
<ToolChips113
appear={t.live}114
steps={t.steps}115
diffs={t.diffs}116
labels={{ header: `${t.steps.length} tool ${t.steps.length === 1 ? "call" : "calls"}` }}117
onDiffClick={() => onOpenDiff("src/middleware/rate-limit.ts")}118
/>119
)}120
{t.reply.length > 0 && <StreamingText fill appear={t.live} content={t.reply} done={t.done} />}121
</div>}122
</Message>123
</div>124
))}125
</div>126
</ScrollArea>127
</div>128
<div className="flex shrink-0 flex-col gap-2 p-2">129
{asking && (130
<ApprovalCard131
resettable={false}132
action={{133
title: "Apply the fix to rate-limit.ts?",134
description: "+5 lines, then runs the tests.",135
}}136
labels={{ approve: "Apply", deny: "Not now" }}137
onDismiss={() => setAsking(false)}138
onDecision={(decision) => {139
setAsking(false);140
if (decision === "approve") apply(true);141
else reply({}, "Left rate-limit.ts as it is. Ask me again when you want the fix.");142
}}143
/>144
)}145
<PromptBar146
aria-label="Ask the assistant"147
placeholder="Ask about this code…"148
defaultModel="standard"149
models={MODELS}150
commands={COMMANDS}151
busy={busy}152
onStop={() => { setTarget(null); setTurns((all) => [...all.slice(0, -1), { ...all.at(-1)!, done: true }]); }}153
onSubmit={({ value }) => reply({ prompt: value }, answer(value, file))}154
/>155
</div>156
</div>157
);158
}1
/* The project the editor has open: a small billing API with one failing test. Plain data, so the2
* app's files read as layout and state only. */3
import type { CodeDiffRow, TreeViewNode } from "@fndn/react";4
5
export const PROJECT = "billing-api";6
export const BRANCH = "fix/rate-limit";7
8
const rateLimit = [9
'import type { NextFunction, Request, Response } from "express";',10
"",11
"const WINDOW_MS = 60_000;",12
"const LIMIT = 120;",13
"",14
"type Bucket = { count: number; windowStart: number };",15
"const buckets = new Map<string, Bucket>();",16
"",17
"export function rateLimit(req: Request, res: Response, next: NextFunction) {",18
' const key = req.header("x-api-key") ?? req.ip ?? "anonymous";',19
" const now = Date.now();",20
" let bucket = buckets.get(key);",21
" if (!bucket) {",22
" bucket = { count: 0, windowStart: now };",23
" buckets.set(key, bucket);",24
" }",25
"",26
" bucket.count += 1;",27
" if (bucket.count > LIMIT) {",28
" const retryAfter = Math.ceil((bucket.windowStart + WINDOW_MS - now) / 1000);",29
' res.set("Retry-After", String(Math.max(retryAfter, 1)));',30
' return res.status(429).json({ error: "rate_limited", retryAfter });',31
" }",32
" next();",33
"}",34
];35
36
/** rate-limit.ts once the assistant's fix is applied: the window resets when it has passed. */37
export const RATE_LIMIT_FIXED = [38
...rateLimit.slice(0, 16),39
"",40
" if (now - bucket.windowStart >= WINDOW_MS) {",41
" bucket.count = 0;",42
" bucket.windowStart = now;",43
" }",44
...rateLimit.slice(16),45
];46
47
const invoicesBefore = [48
'import { Router } from "express";',49
'import { db } from "../lib/db";',50
"",51
"export const invoices = Router();",52
"",53
'invoices.get("/", async (req, res) => {',54
" const rows = await db.invoice.findMany({",55
" where: { customerId: String(req.query.customer) },",56
' orderBy: { issuedAt: "desc" },',57
" });",58
" res.json(rows);",59
"});",60
"",61
'invoices.get("/:id", async (req, res) => {',62
" const row = await db.invoice.findUnique({ where: { id: req.params.id } });",63
' if (!row) return res.status(404).json({ error: "not_found" });',64
" res.json(row);",65
"});",66
];67
68
const invoices = [69
'import { Router } from "express";',70
'import { formatAmount } from "../lib/currency";',71
'import { db } from "../lib/db";',72
"",73
"export const invoices = Router();",74
"",75
'invoices.get("/", async (req, res) => {',76
" const limit = Math.min(Number(req.query.limit ?? 50), 200);",77
" const rows = await db.invoice.findMany({",78
" where: { customerId: String(req.query.customer) },",79
' orderBy: { issuedAt: "desc" },',80
" take: limit,",81
" });",82
" const total = rows.reduce((sum, r) => sum + r.amountCents, 0);",83
" res.json(rows.map((r) => ({ ...r, amount: formatAmount(r.amountCents, r.currency) })));",84
"});",85
"",86
'invoices.get("/:id", async (req, res) => {',87
" const row = await db.invoice.findUnique({ where: { id: req.params.id } });",88
' if (!row) return res.status(404).json({ error: "not_found" });',89
" res.json({ ...row, amount: formatAmount(row.amountCents, row.currency) });",90
"});",91
];92
93
const currency = [94
"const formatters = new Map<string, Intl.NumberFormat>();",95
"",96
"/** 12345, \"EUR\" → \"€123.45\". Formatters are cached per currency. */",97
"export function formatAmount(cents: number, currency: string, locale = \"en-US\") {",98
" const key = `${locale}:${currency}`;",99
" let format = formatters.get(key);",100
" if (!format) {",101
' format = new Intl.NumberFormat(locale, { style: "currency", currency });',102
" formatters.set(key, format);",103
" }",104
" return format.format(cents / 100);",105
"}",106
];107
108
/** Every file of the project, by path. */109
export const FILES: Record<string, string[]> = {110
"src/server.ts": [111
'import express from "express";',112
'import { auth } from "./middleware/auth";',113
'import { rateLimit } from "./middleware/rate-limit";',114
'import { customers } from "./routes/customers";',115
'import { invoices } from "./routes/invoices";',116
"",117
"export const app = express();",118
"",119
"app.use(express.json());",120
"app.use(auth, rateLimit);",121
'app.use("/v1/customers", customers);',122
'app.use("/v1/invoices", invoices);',123
"",124
"const port = Number(process.env.PORT ?? 8080);",125
"app.listen(port, () => console.log(`billing-api on :${port}`));",126
],127
"src/middleware/auth.ts": [128
'import type { NextFunction, Request, Response } from "express";',129
'import { db } from "../lib/db";',130
"",131
"export async function auth(req: Request, res: Response, next: NextFunction) {",132
' const key = req.header("x-api-key");',133
' if (!key) return res.status(401).json({ error: "missing_api_key" });',134
" const account = await db.apiKey.findUnique({ where: { key } });",135
' if (!account?.active) return res.status(403).json({ error: "inactive_key" });',136
" res.locals.accountId = account.accountId;",137
" next();",138
"}",139
],140
"src/middleware/rate-limit.ts": rateLimit,141
"src/routes/customers.ts": [142
'import { Router } from "express";',143
'import { z } from "zod";',144
'import { db } from "../lib/db";',145
"",146
"export const customers = Router();",147
"",148
'customers.get("/:id", async (req, res) => {',149
" const row = await db.customer.findUnique({ where: { id: req.params.id } });",150
' if (!row) return res.status(404).json({ error: "not_found" });',151
" res.json(row);",152
"});",153
],154
"src/routes/invoices.ts": invoices,155
"src/lib/currency.ts": currency,156
"src/lib/db.ts": [157
'import { PrismaClient } from "@prisma/client";',158
"",159
"/** One client per process; Prisma pools the connections. */",160
"export const db = new PrismaClient({",161
' log: process.env.NODE_ENV === "production" ? ["warn", "error"] : ["query"],',162
"});",163
],164
"test/rate-limit.test.ts": [165
'import request from "supertest";',166
'import { afterEach, describe, expect, it, vi } from "vitest";',167
'import { app } from "../src/server";',168
"",169
'const call = () => request(app).get("/v1/invoices").set("x-api-key", "test_key");',170
"",171
'describe("rate limit", () => {',172
" afterEach(() => vi.useRealTimers());",173
"",174
' it("refuses the 121st call in a minute", async () => {',175
" for (let i = 0; i < 120; i++) await call();",176
" expect((await call()).status).toBe(429);",177
" });",178
"",179
' it("refills the bucket after the window", async () => {',180
" vi.useFakeTimers();",181
" for (let i = 0; i < 121; i++) await call();",182
" vi.advanceTimersByTime(60_000);",183
" expect((await call()).status).toBe(200);",184
" });",185
"});",186
],187
"package.json": [188
"{",189
' "name": "billing-api",',190
' "private": true,',191
' "type": "module",',192
' "scripts": {',193
' "dev": "tsx watch src/server.ts",',194
' "test": "vitest run",',195
' "typecheck": "tsc --noEmit"',196
" },",197
' "dependencies": { "@prisma/client": "^6.4.0", "express": "^5.1.0", "zod": "^3.24.2" },',198
' "devDependencies": { "supertest": "^7.1.0", "tsx": "^4.19.3", "vitest": "^3.2.4" }',199
"}",200
],201
"README.md": [202
"# billing-api",203
"",204
"Invoices and customers for the dashboard, behind an API key.",205
"",206
"- `pnpm dev` starts the server on :8080",207
"- `pnpm test` runs the suite (vitest + supertest)",208
"- Every key may make 120 calls a minute; the 121st gets a 429 and a Retry-After header.",209
],210
};211
212
const node = (path: string): TreeViewNode => ({ value: path, label: path.split("/").pop()! });213
214
/** The explorer's tree. Icons are added by the app. */215
export const TREE: TreeViewNode[] = [216
{217
value: "src", label: "src",218
children: [219
{ value: "src/lib", label: "lib", children: [node("src/lib/currency.ts"), node("src/lib/db.ts")] },220
{ value: "src/middleware", label: "middleware", children: [node("src/middleware/auth.ts"), node("src/middleware/rate-limit.ts")] },221
{ value: "src/routes", label: "routes", children: [node("src/routes/customers.ts"), node("src/routes/invoices.ts")] },222
node("src/server.ts"),223
],224
},225
{ value: "test", label: "test", children: [node("test/rate-limit.test.ts")] },226
node("package.json"),227
node("README.md"),228
];229
230
/** A whole-file unified diff (both sides are short): the longest common run of lines stays as231
* context, the rest is removed or added. */232
export function lineDiff(before: string[], after: string[]): CodeDiffRow[] {233
const n = before.length, m = after.length;234
const lcs = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));235
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]!);236
const rows: CodeDiffRow[] = [];237
let i = 0, j = 0;238
while (i < n || j < m) {239
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++; }240
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++; }241
else { rows.push({ old: i + 1, cur: null, type: "del", pieces: [{ text: before[i]! }] }); i++; }242
}243
return rows;244
}245
246
export type Change = { path: string; status: "modified" | "added"; before: string[] };247
248
/** Uncommitted work when the editor opens. */249
export const CHANGES: Change[] = [250
{ path: "src/routes/invoices.ts", status: "modified", before: invoicesBefore },251
{ path: "src/lib/currency.ts", status: "added", before: [] },252
];253
254
export type Problem = { value: string; path: string; line: number; col: number; severity: "error" | "warning"; message: string; fixedBy?: "rate-limit" };255
256
export const PROBLEMS: Problem[] = [257
{ 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" },258
{ 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)" },259
{ value: "p3", path: "src/routes/customers.ts", line: 2, col: 10, severity: "warning", message: "'z' is defined but never used. eslint(no-unused-vars)" },260
];261
262
/** What `pnpm test` prints, before and after the fix. */263
export function testRun(fixed: boolean): string[] {264
return [265
"$ pnpm test",266
"",267
" RUN v3.2.4 /home/dev/billing-api",268
"",269
" ✓ test/invoices.test.ts (9 tests) 48ms",270
fixed ? " ✓ test/rate-limit.test.ts (2 tests) 31ms" : " ❯ test/rate-limit.test.ts (2 tests | 1 failed) 29ms",271
...(fixed ? [] : [272
" × rate limit > refills the bucket after the window",273
" → expected 429 to be 200 // Object.is equality",274
"",275
" FAIL test/rate-limit.test.ts > rate limit > refills the bucket after the window",276
" ❯ test/rate-limit.test.ts:19:38",277
]),278
"",279
fixed ? " Test Files 2 passed (2)" : " Test Files 1 failed | 1 passed (2)",280
fixed ? " Tests 11 passed (11)" : " Tests 1 failed | 10 passed (11)",281
" Duration 1.42s",282
"",283
];284
}1
/* The source-control side view (VS Code's): a commit message, Commit, and the changed files as2
* 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,3
* A added). Choosing a file opens its diff as a tab in the editor. */4
import { useState } from "react";5
import { CheckCircle } from "@phosphor-icons/react";6
import { Button, Count, EmptyState, Listbox, ScrollArea, Textarea } from "@fndn/react";7
import type { Change } from "./data";8
9
const LETTER = { modified: { meta: "M", metaTone: "orange" }, added: { meta: "A", metaTone: "green" } } as const;10
11
export function SourceControl({ changes, selected, branch, onSelect, onCommit }: {12
changes: Change[];13
selected: string | null;14
branch: string;15
onSelect: (path: string) => void;16
onCommit: (message: string) => void;17
}) {18
const [message, setMessage] = useState("");19
const [invalid, setInvalid] = useState(false);20
const [last, setLast] = useState<string | null>(null);21
const commit = () => {22
if (!message.trim()) return setInvalid(true);23
onCommit(message.trim());24
setLast(message.trim());25
setMessage("");26
};27
28
return (29
<div className="flex h-full min-w-0 flex-col bg-canvas" data-editor="source-control">30
<div className="flex h-8 shrink-0 items-center px-3 text-xs font-medium text-ink-2">Source control</div>31
{changes.length ? (32
<ScrollArea className="min-h-0 flex-1">33
<div className="flex flex-col gap-2 px-2 pb-1">34
<Textarea35
size="sm" rows={2} aria-label="Commit message" placeholder={`Message (Ctrl+Enter to commit on ${branch})`}36
value={message} invalid={invalid}37
onChange={(e) => { setMessage(e.target.value); setInvalid(false); }}38
onKeyDown={(e) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); commit(); } }}39
/>40
<Button size="sm" variant="accent" onClick={commit}>Commit</Button>41
<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>42
</div>43
{/* flush: the rows are part of the pane, edge to edge, their text on the pane's 8px inset */}44
<Listbox45
variant="flush" size="xs" className="w-full pb-2" aria-label={`Changes, ${changes.length}`}46
items={changes.map((c) => {47
const folder = c.path.split("/").slice(0, -1).join("/");48
return { value: c.path, label: c.path.split("/").pop()!, ...(folder ? { description: folder } : {}), ...LETTER[c.status] };49
})}50
value={selected ? [selected] : []}51
onValueChange={(v) => v[0] && onSelect(v[0])}52
/>53
</ScrollArea>54
) : (55
<EmptyState className="p-6" size="block" icon={<CheckCircle weight="fill" />} title="No changes" hint={last ? `Committed “${last}” to ${branch}.` : "The working tree is clean."} />56
)}57
</div>58
);59
}