SLOPSHOPPER

leaf

Generative UI: the agent builds the page your task needs, writes new widgets when the project calls for them, and answers your comments and edits over a…

bandrowsguardtoastprocess
★ 6v?MITupdated 2026-10-26max-sixty/leaf
A shopper browsing a rack in a slop shop
README

leaf

maintained with tend

Experimental software; not ready for general use.

Leaf is generative UI for Claude Code and Codex. Review a plan, make a decision, or follow live work in a page you can comment on and change. The agent responds by revising the page.

<img alt="A Leaf page with an anchored comment, the agent's reply, and a revised plan" src="https://raw.githubusercontent.com/max-sixty/leaf-assets/32c04adf7de760ed573454224db6d7458b1b2c14/demo/session-light.png">

A Leaf page receiving a comment, revising the work, and preserving a moved card

Try Leaf on the home page, where a small demo agent responds in your private copy, or explore the examples.

Install

You need uv, jq 1.6 or newer on PATH, and a browser that can reach the machine the agent runs on. No Leaf account or configuration is required. Users and package authors never need to build Leaf or run a package manager; custom widgets are ordinary browser JavaScript.

Install the Leaf plugin, which includes the application, harness integration and the Leaf skill. The skill supplies the agent's instructions; copying its directory alone does not install the application.

Claude Code:

/plugin marketplace add max-sixty/leaf
/plugin install leaf@leaf

Codex:

codex plugin marketplace add max-sixty/leaf
codex plugin add leaf@leaf

Pi (a highly experimental trial, which the rest of these docs don't cover yet):

pi install git:github.com/max-sixty/leaf

Then ask: “Use Leaf to write up the options for this change.” The explicit skill is /leaf [topic] in Claude Code, $leaf [topic] in Codex, and /skill:leaf [topic] in Pi; without a topic, it presents the work already under discussion. The result opens in a browser page; its comments return to the same agent task.

Known functional limitations and accepted visual differences in current browsers are recorded in Browser support gaps.

The first run syncs the plugin's uv environment through your configured package index. Render checks use the executable named by LEAF_BROWSER_EXECUTABLE, CHROME_PATH, or CHROME_BIN, then installed Google Chrome, then the first google-chrome, google-chrome-stable, chrome, chromium, or chromium-browser on PATH.

Leaf needs Claude Code 2.1.196 or later, the first release whose hooks name the turn they run in. On an earlier one, an update handed into a prompt you interrupt waits until that turn ends before it is offered again.

In Claude Code, a background Stop hook watches the session's pages between turns, and Leaf's hooks module shows a line above the prompt for each page the session holds: a link to the page, what is On you, its open threads with how many have replies you haven't read, and what the agent is doing or waiting for. Ctrl+X Tab then Enter opens the first page in your browser, or, in a session you reached over SSH, copies its link to your clipboard. Hooks modules are an early-access Claude Code feature.

A page messages its session when input arrives while nothing watches it, as can happen after you interrupt a turn. A session that bypasses permissions holds that message for your approval unless Claude Code's crossSessionInbound setting is "accept".

Leaf's hooks run outside an agent's sandbox, but leaf commands run wherever the agent's shell commands do, and a sandbox refuses them what they need: writes to Leaf's state in ~/.local/state/leaf, a port on localhost for the page server, and a browser for render checks.

In Claude Code, Leaf's hook starts a bridge outside the sandbox before the first leaf command, and each sandboxed leaf command hands itself to the bridge through the sandbox's network proxy. The first time in a session, Claude Code asks whether to allow that connection. To allow it without asking, add 127.0.0.1 to Claude Code's settings, such as ~/.claude/settings.json:

{ "sandbox": { "network": { "allowedDomains": ["127.0.0.1"] } } }

Allowing 127.0.0.1 lets every sandboxed command reach any server listening on this machine's loopback, Leaf's bridge among them, and through the bridge run leaf commands with your own access, as Leaf's hooks already run.

Codex's sandbox gives a command no such route, so Leaf's Codex plugin adds an MCP server, leaf, which Codex starts outside the sandbox. In the sandbox the agent runs leaf commands with the server's run tool. The first time, Codex asks whether to allow the tool, for the session or always. Allowing it lets the agent run any leaf command with your own access, including a package's scripts, with arguments it chooses. To allow it without being asked, add this to ~/.codex/config.toml:

[plugins."leaf@leaf".mcp_servers.leaf]
default_tools_approval_mode = "approve"

The agent's own edits to a page's files still run in Codex's sandbox, which lets them write only the task's directory and the temporary directories. So Codex refuses each edit to a page in Leaf's state home, or asks you to approve it. To let the agent edit pages there, add the state home's pages directory to the sandbox's writable roots in ~/.codex/config.toml, inside the [sandbox_workspace_write] table if you already have one:

[sandbox_workspace_write]
writable_roots = ["~/.local/state/leaf/pages"]

If you set XDG_STATE_HOME, the directory is $XDG_STATE_HOME/leaf/pages. Every command the sandbox runs can then write every page's files, as it can the task's directory. Where a task's sandbox lacks the line, the MCP server's first answer in that task gives it to the agent to pass on.

Explore and extend

  • How it works: comments, decisions, live revisions, and the widgets a page can use.
  • Examples: proposals, editable drafts, release workspaces, and code reviews.
  • Extending: choose between page-local changes, reusable packages, and Leaf's shared kernel. Your agent can build a widget a task needs and use it in later pages.
  • Public contracts: authoring, serving, and continuing a Leaf page.
Source 1 files
hooks/claude-code.ts 364 lines
1/**
2 * Leaf's Claude Code hooks module: the band above the prompt that shows the
3 * session's pages, and the drawing of Leaf's own rows in the conversation. Claude
4 * Code loads it from the installed plugin (measured at 2.1.305). It neither
5 * watches nor wakes the session: `hooks.json`'s background Stop registration
6 * keeps the watch between turns. A watch here would wake with a prompt, which
7 * Claude Code drops from an Escape until the user next types, so every wake after
8 * an Escape became a cross-session nudge (measured at 2.1.307 with the
9 * claude-code journey).
10 *
11 * Starting an idle turn always draws a row, and no hook or exit code wakes the
12 * session without one (read in 2.1.307's source). The watch's wake is a task
13 * notification whose summary `hooks.json` names (`rewakeSummary`, an internal
14 * field of Claude Code's hook schema), and the module draws that row as nothing,
15 * leaving the band to show the agent at work; a nudge, which comes as another
16 * session's message, it draws as one dim line. The model reads both whole, and
17 * ctrl+o shows them as Claude Code draws them.
18 *
19 * A module's processes inherit Claude Code's own environment, which names no
20 * session of its own, so every call states the session and Claude Code's process
21 * as a hook's environment does. That process is the parent of every process the
22 * module starts (measured at Claude Code 2.1.291). A follower that fails reports
23 * its diagnostics through Claude Code's UI log.
24 *
25 * The band has a line for each live page the session holds: the word Leaf in the
26 * tone the page's Leaf panel gives its leaf, a link to the page, what is On the
27 * user, and its open threads with how many hold words the user hasn't read, the
28 * counts the panel marks, then the agent's status. It goes above whatever other
29 * plugins draw there. Claude Code keeps an empty row between the band and the
30 * prompt (measured at 2.1.306); a negative margin to close it hides the band.
31 * `leaf-dev claude-code-session` runs a session that draws it from this tree.
32 *
33 * In the terminal a click on the link opens the page wherever the terminal runs,
34 * SSH included. No escape sequence makes a terminal open a URL without a click,
35 * and no `$` call reaches the user's browser, so each line ends with a button for
36 * the keyboard, the first focused once ctrl+x tab takes the band, for Enter to
37 * press. Where the user sits at this machine, which Leaf's server judges by
38 * SSH_CONNECTION (`page_access`), it opens the page in the browser; over SSH a
39 * browser started here would open on the wrong machine, so it copies the link to
40 * the user's own clipboard, which OSC 52 reaches. Other surfaces draw the link as
41 * an anchor their keyboard reaches.
42 *
43 * In the terminal one link runs from the word Leaf through the title. The desktop
44 * app draws a `Link` as plain text unless it goes to https or localhost, but links
45 * any http URL in `Markdown`, which takes no color, so there the title alone is a
46 * markdown link (measured at the app's Claude Code 2.1.304). Linking to localhost
47 * instead would open the page at another origin than every other link to it,
48 * with its own cookie jar and drafts, and send the host key's cookie to whatever
49 * else the user serves on localhost.
50 *
51 * A follower (`bin/leaf hook --harness claude-code
52 * --if-claimed --pages`) prints that list whenever it changes and exits once the
53 * session holds no page; the launcher answers it without starting uv in a session
54 * holding none. The session takes a page only through a `leaf` command, so the
55 * module starts the follower as the session starts, after each Bash call that
56 * runs `leaf`, and as a turn starts or a main-loop turn ends, once none is
57 * running; a request while one runs starts another once it exits.
58 */
59
60import type {
61  EngineInterface,
62  Register,
63  RenderElement,
64  RenderSurface,
65  UiPressArgument,
66} from "claude-code";
67
68// Claude Code's process, read once by `sessionOf`.
69let claudePid = "";
70// Whether the user reached this machine over SSH, read once by the band.
71let remote: boolean | undefined;
72
73// The summary `hooks.json` gives the background watch's wake, which Claude Code
74// draws as a task notification's row, and the words of the nudge Leaf sends
75// through session messaging (`ClaudeCodeHarness.nudge`).
76const WAKE_SUMMARY = "Leaf: new input";
77const NUDGE_WORDS = "has new input, which arrives with this message.";
78
79// A live page the session holds, as the follower prints it (`hooks.cmd_pages`).
80type Leaf = {
81  page_key: string;
82  url: string;
83  title: string;
84  on_user: number;
85  threads: { open: number; unread: number };
86  activity: { kind: string; detail: string };
87};
88
89// The color the word Leaf wears for each activity kind, in Claude Code's theme: the
90// tone the page's Leaf panel paints its leaf (`.lf-dot` in chrome.css), muted for the
91// rest.
92const TONES: Record<string, string> = {
93  working: "suggestion",
94  listening: "success",
95  stalled: "warning",
96  away: "warning",
97};
98
99/** What a line says of the agent's work, in the words of an All pages row
100 * (`leafRow` in activity-words.js), less its bare Listening and Awaits, since
101 * listening is the usual case. */
102function statusOf({ kind, detail }: Leaf["activity"]) {
103  const stated = (word: string) => (detail ? `${word} — ${detail}` : word);
104  if (kind === "working") return stated("Working");
105  if (kind === "stalled") return stated("Quiet");
106  if (kind === "away") return "Away";
107  return "";
108}
109
110// The follower's last list, how to stop the follower while one runs, and whether
111// something asked for one while it ran, which may have outlived its last read.
112let leaves: Leaf[] = [];
113let following: { stop: () => unknown } | undefined;
114let followAgain = false;
115
116/** The session's id, once Claude Code's process is known. A module loaded or reloaded
117 * mid-session sees no session.start, so whichever hook comes first reads it. */
118async function sessionOf($: EngineInterface) {
119  if (!claudePid)
120    claudePid = (await $.process.run(["/bin/sh", "-c", "echo $PPID"])).stdout.trim();
121  return $.session.id();
122}
123
124function environment(session: string) {
125  return { CLAUDE_CODE_SESSION_ID: session, CLAUDE_PID: claudePid };
126}
127
128function launcher($: EngineInterface) {
129  return `${$.plugin.root}/bin/leaf`;
130}
131
132/** Log the follower's failure, to the conversation unless a signal from outside
133 * the module ended it, which the launcher's shell reports as 128 plus the signal:
134 * as SIGTERM ends it while a session sits idle, or SIGHUP as its terminal closes.
135 * That ending is no failure of Leaf's to show the user. */
136function report($: EngineInterface, text: string, code: number | null) {
137  $.ui.log(text, code !== null && code > 128 ? { to: "debug" } : undefined);
138}
139
140// The command that opens its first argument in this machine's browser.
141const OPENER = '[ "$(uname)" = Darwin ] && exec open "$1"; exec xdg-open "$1"';
142
143/** What a line's button does: open the page here, or over SSH copy its link to
144 * the clipboard of the surface pressed on. */
145async function openPage(
146  $: EngineInterface,
147  { url, title }: Leaf,
148  surface: RenderSurface,
149) {
150  try {
151    if (remote) {
152      const copied = await $.ui.copy({ text: url, surface });
153      if (copied.isCopied) $.ui.toast(`Copied the link to ${title}`);
154      else $.ui.log(`Leaf: the link to ${title} was not copied (${copied.reason})`);
155      return;
156    }
157    const ran = await $.process.run(["/bin/sh", "-c", OPENER, "sh", url]);
158    if (ran.exitCode !== 0)
159      $.ui.log(
160        `Leaf: opening ${title} exited with code ${ran.exitCode}${ran.stderr.trim() ? `: ${ran.stderr.trim()}` : ""}`,
161      );
162  } catch (error) {
163    $.ui.log(`Leaf: opening ${title} failed: ${error}`);
164  }
165}
166
167function show($: EngineInterface, listed: Leaf[]) {
168  leaves = listed;
169  $.ui.invalidate("ui.render");
170}
171
172/** Start the follower of the session's pages, or once the running one exits. */
173function follow($: EngineInterface, session: string) {
174  if (following) {
175    followAgain = true;
176    return;
177  }
178  followAgain = false;
179  let stream: ReturnType<EngineInterface["process"]["spawn"]>;
180  try {
181    stream = $.process.spawn({
182      argv: [
183        launcher($),
184        "hook",
185        "--harness",
186        "claude-code",
187        "--if-claimed",
188        "--pages",
189      ],
190      env: environment(session),
191      input: JSON.stringify({ hook_event_name: "Pages", session_id: session }),
192    });
193  } catch (error) {
194    $.ui.log(`Leaf: the pages follower could not start: ${error}`);
195    return;
196  }
197  const current = { stop: () => stream.return(undefined as never) };
198  following = current;
199  void (async () => {
200    let line = "";
201    let stderr = "";
202    try {
203      for await (const chunk of stream) {
204        if (chunk.stream === "stderr") {
205          stderr += chunk.text;
206          continue;
207        }
208        const lines = (line + chunk.text).split("\n");
209        line = lines.pop() ?? "";
210        const last = lines.at(-1);
211        if (last !== undefined && following === current) show($, JSON.parse(last));
212      }
213      const result = await stream.result;
214      if (result.code !== 0 && following === current)
215        report(
216          $,
217          `Leaf: the pages follower exited with code ${result.code}${stderr.trim() ? `: ${stderr.trim()}` : ""}`,
218          result.code,
219        );
220    } catch (error) {
221      if (following === current) $.ui.log(`Leaf: the pages follower failed: ${error}`);
222    } finally {
223      // It exits once the session holds no page, or never starts in one holding none.
224      if (following === current) {
225        following = undefined;
226        if (followAgain) follow($, session);
227        else show($, []);
228      }
229    }
230  })();
231}
232
233export const register: Register = (on) => {
234  on("session.start", async ($, e, next) => {
235    const started = await next(e);
236    const session = await sessionOf($);
237    follow($, session);
238    return started;
239  });
240
241  // A call that runs `leaf`, as `hooks.json`'s PreToolUse registrations match one.
242  on(
243    "tool.call",
244    { tool: "Bash", command: /(^|[\s;&|(/])leaf(\s|$)/ },
245    async ($, e, next) => {
246      const result = await next(e);
247      // A gate on the tool's own call: nothing after its result may fail it.
248      void sessionOf($).then((session) => follow($, session));
249      return result;
250    },
251  );
252
253  // A resumed or cleared session raises no session.start, so its first turn follows.
254  on("turn.start", ($, e, next) => {
255    if (e.agentId !== undefined) return next(e);
256    void sessionOf($).then((session) => follow($, session));
257    return next(e);
258  });
259
260  on("turn.complete", async ($, e, next) => {
261    const completed = await next(e);
262    if (e.agentId !== undefined) return completed;
263    follow($, await sessionOf($));
264    return completed;
265  });
266
267  // The band is shared: Leaf's lines go above whatever the plugins beneath draw.
268  // Leaf's own rows in the conversation stay quiet, unless ctrl+o expands them; the
269  // model reads them whole either way.
270  on("ui.render", { component: "UserMessage" }, async ($, e, next) => {
271    if (e.props.isExpanded) return next(e);
272    const { origin, text } = e.props;
273    const { Box, Text } = $.ui.resolve(e);
274    if (origin.kind === "task-notification" && text === WAKE_SUMMARY)
275      return h(Box, {}) as RenderElement;
276    if (origin.kind === "peer" && text.includes(NUDGE_WORDS))
277      return h(Text, { dimColor: true }, "Leaf: new input") as RenderElement;
278    return next(e);
279  });
280
281  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
282    const beneath = await next(e);
283    if (leaves.length === 0 || e.props.hasSurvey) return beneath;
284    const { Box, Text, Link, Markdown, Button } = $.ui.resolve(e);
285    if (e.surface === "terminal") remote ??= Boolean(await $.env.get("SSH_CONNECTION"));
286    // What JSX would type; the module stays `.ts` for Node, which runs it in tests.
287    const dim = (text: string) => h(Text, { dimColor: true }, text);
288    // A line keeps one row, its status cut first; only the counts that aren't zero
289    // show, and what waits on the user takes a color.
290    const line = (page: Leaf, index: number) => {
291      const { url, title, on_user, threads, activity } = page;
292      const status = statusOf(activity);
293      const leaf = h(
294        Text,
295        { color: TONES[activity.kind] ?? "inactive", weight: "semibold" },
296        "Leaf",
297      );
298      const counts = [
299        ...(on_user
300          ? [dim(" · "), h(Text, { color: "warning" }, `On me ${on_user}`)]
301          : []),
302        // A resolved thread can still hold unread words.
303        ...(threads.open || threads.unread ? [dim(` · Threads ${threads.open}`)] : []),
304        ...(threads.unread
305          ? [dim(", "), h(Text, { color: "suggestion" }, `${threads.unread} new`)]
306          : []),
307        ...(status ? [dim(` · ${status}`)] : []),
308      ];
309      if (e.surface === "terminal") {
310        // The button stays whole at the line's end while the text before it is cut.
311        return h(
312          Box,
313          { gap: 1 },
314          h(
315            Text,
316            { wrap: "truncate-end" },
317            h(Link, { href: url }, leaf, " ", h(Text, { underline: true }, title)),
318            ...counts,
319          ),
320          h(
321            Box,
322            { flexShrink: 0 },
323            h(Button, {
324              key: page.page_key,
325              label: remote ? "copy link" : "open",
326              plain: true,
327              dimColor: true,
328              ...(index === 0 ? { autoFocus: true } : {}),
329              onPress: (press: UiPressArgument) =>
330                void openPage($, page, press.surface),
331            }),
332          ),
333        );
334      }
335      // The title keeps its width and the counts are cut, as the terminal's
336      // truncation cuts them.
337      const escaped = title.replace(/[!-/:-@[-`{-~]/g, "\\$&");
338      return h(
339        Box,
340        { flexDirection: "row", overflow: "hidden" },
341        h(Box, { flexShrink: 0 }, h(Text, {}, leaf, " ")),
342        h(Box, { flexShrink: 0 }, h(Markdown, { text: `[${escaped}](${url})` })),
343        ...(counts.length
344          ? [h(Box, { minWidth: 0 }, h(Text, { wrap: "truncate-end" }, ...counts))]
345          : []),
346      );
347    };
348    return h(
349      Box,
350      { flexDirection: "column" },
351      ...leaves.map(line),
352      beneath,
353    ) as RenderElement;
354  });
355
356  on("session.end", async ($, e, next) => {
357    const current = following;
358    following = undefined;
359    show($, []);
360    await current?.stop();
361    return next(e);
362  });
363};
364