Files
bflatastic 428ebb70a5 Agent panel: ask before plugins, libraries and the share server; fmt
- The Ask gate missed `plugins.*` (runLast runs a plugin) and `libraries.*`
  (only `plugin.`/`library.` were matched), and `pref.publishServer`, which
  changes where shared files are sent.
- The Auto mode's doc said the automation roots confine file access; a
  window opened normally has none, so say when they apply.
- rustfmt the same-layer exceptions in xtask/src/layers.rs.
2026-12-01 20:55:56 +07:00

20 KiB
Raw Permalink Blame History

The in-app agent (harness)

FigCraft can run an AI agent inside the app: the Agent tab of the left sidebar, which edits the open document through the same commands and tools an external MCP client uses. This document is the module's contract: what it is made of, which lines it adds to the upstream tree, how to keep those lines rebasing cleanly, and what it deliberately does not do.

Opening it

The rail (the far-left icon column) has an Agent tab beside File and Assets (LeftTab::Agent). While it is selected the left panel holds the conversation alone: a header (New chat, Connections), the messages, and the composer pinned to the bottom. File and Assets bring Pages and Layers back. The window remembers whether it was left on the Agent tab (panel in agents.json) and opens on it next time; a build with no settings folder (the browser, tests) never does, so every test that measures the File tab is unchanged.

The conversation reads like a chat: the person's messages in bubbles on the right, the agent's answers as plain text, and each run of tool calls folded into one line ("5 steps", "Running frame.create") that opens to show every call. A failed turn is a card with a way to check the connection; a permission request is a card with Allow and Deny. With no conversation yet, the tab offers a few example requests, or the connection choices when nothing is connected.

Working with the canvas

  • Selection chips. The layers selected on the canvas show as chips above the composer (icon and name). A request carries them: its context is their inspect.designContext and the agent is told their names and ids. A chip's × leaves that layer out of the next request (a new selection brings it back); clicking a chip selects the layer. The sent message shows the layers it carried, and clicking one there selects it again.
  • @ names a layer. Typing @ at the start of a word lists the file's layers whose names hold what follows (components first, then pages, frames, instances, text, the rest; with nothing typed, only components, pages and frames). Arrows move, Enter or Tab picks, Escape closes. The pick replaces the typed word with @Name and joins the chips, so the layer goes with the request like a selected one, without selecting it.
  • Suggestions for the selection. With the composer empty, up to three requests for what is selected show above it (text: rewrite, translate, type hierarchy; a component: states, a check, a description; frames: spacing, auto layout, variations; instances and other layers their own). A click sends one.
  • Design system. A request carries the file's styles (style.list), variables (variable.list) and components (names and ids; a variant set once), with an instruction to build with them ({$var}, fillStyle, textStyle, effectStyle, instance.create) and to say when a raw value was needed. It goes once per conversation and again only when it changed (a hash of the text), so it does not cost tokens on every turn.
  • Screenshot to layers. With an image attached and the box empty, Rebuild as editable layers sends a short request; the model also gets fixed instructions (a new frame beside the content, nested auto layout, real text, the file's design system, then a screenshot to compare and fix) that the bubble does not show.
  • Time and tokens. Under each answer: how long it took and the tokens it used (the turn's difference in the provider's count; no count, time only).
  • Pages. A request carries the file's pages and the top-level frames on each (names and ids, which one is in front), once per conversation and again when they changed, with how to read one (design_context with its frames), open one (page.select, said aloud), add one (page.add) and move frames (object.moveToPage). The rules put the design system on 00 · Design System and screens on pages named by flow; the list says when that page is missing. A page named with @ stands for the frames on it. (The selection context also stopped sending a maxBytes that inspect.designContext refuses, which had left requests without it.)
  • The design system page. Every file's design system lives on the page 00 · Design System, first in the file. The agent's design_system tool (crates/agent/src/brief.rs) reads it (the page, its Design guidelines text, the variable collections) or, with a spec (product, platform, language; primary, secondary, accent, greys, status colours, light/dark; heading, body and code fonts and a type scale; spacing step, corners, shadows, border; an open-source icon set by name with style, stroke and size; tone, imagery, contrast, notes), makes or updates it: the page, moved first; through command.batch in one undo step the Primitives collection (ten-step OKLCH ramps), Theme (roles aliasing them, Light and Dark), Sizes (space, radius, border, icon), ten text styles, three shadow styles and FigCraft's design review settings (design.configure: grid, radii, brand colours, AA/AAA preset); and a Design guidelines text on the page with the choices tokens can't hold. Running it again updates them instead of making copies. Icons are never downloaded: the agent draws them in the named set's manner or the person imports them.
  • How the agent works. Its rules (app_rules in crates/agent/src/session.rs) let it read and change every page and layer (no approval for canvas, page, variable or style commands; only files and the network ask), and give a design request three steps. (1) Foundations first: the file must have 00 · Design System. Without it the agent proposes a design system in a few lines and waits for the person to confirm or change it, then calls design_system with the spec and lays out the foundations and base components on that page (Design system setup skill). With it, the agent reads it first. (2) Design with the system. (3) Before finishing, the Design review skill: design.audit, design.fix, design.audit again, then a screenshot for what no rule measures, with the score before and after. Small edits to existing layers skip step 1. The idea of starting from a design library with variables and themes comes from pen.dev's public documentation (docs.pencil.dev); nothing of its app was opened or copied (AGENTS.md, clean room).
  • Screenshot check. The agent can take a screenshot whenever it needs to. Always check with a screenshot in the composer's + menu (also Connections › Advanced) makes it take one after every answer that changed the canvas and fix what differs from the request.
  • Skills. Named instructions for a kind of work (crates/agent/src/skills.rs). Five come with the app (mobile app screen, landing page, design review, design system setup, dark mode); the person's own are Markdown files in agent-skills/ beside agents.json (--- header with name and description, then the instructions), and one with a built-in skill's name replaces it. The book icon in the header opens the Skills screen: the list, a read-only view of a built-in skill (Make a copy to edit), and an editor (name, when to use it, instructions; Save, Delete). Typing / at the start of a word lists the skills; the pick becomes a chip and its instructions go with the request (the bubble shows /Name). The model is told the list (names and descriptions, once per conversation and again when it changed) and loads one with the load_skill tool: the API-key loop answers it itself, and the loopback MCP endpoint adds it to FigCraft's tools for Claude Code, Codex and OpenCode.
  • Ask agent. The canvas's context menu, for a selection, starts with Ask agent… (open the tab with the selection attached and the composer focused) and Agent quick actions (tidy up, make a component with variants, three variations, a contrast check), which send at once. ⌘⇧M (Ctrl+Shift+M) does what Ask agent… does.
  • Images. The composer's + pastes an image from the clipboard or attaches a render of the selection (file.export PNG); ⌘V in the composer attaches a clipboard image; an image dropped on the Agent tab is attached instead of placed on the canvas. Images are scaled to 1568 px at most, sent as PNG, six per request at most. API-key models get them as image blocks (a model whose reads images is off is told they were left out); Claude Code reads them from a stream-json message on its input; Codex and OpenCode get files (--image, --file) written under agent-chats/cli/attachments/.
  • Messages. Copy under an answer, Edit under the last request (it goes back in the box), Try again on a failed turn. A request typed while the agent works is queued above the composer (removable) and sent when the turn ends; a failed turn holds the queue.
  • History. The clock in the header lists this file's chats; New chat keeps the last one there. Each chat is <slug>[-<time>].ui.json / .context.json, and <slug>.current names the one shown. Delete this chat removes its files.

What it is

Piece Crate Layer
Provider adapters, the tool-call loop, the bridge crates/agent (figcraft-agent) L6
The panel (composer, conversation, setup) crates/ui-egui/src/chat.rs (ours) L6
Tool surface figcraft-mcp's tool_definitions / call_tool (unchanged) L6
Command execution figcraft-ui-egui's control queue (unchanged) L6

The agent is not a second implementation of the tool set. It implements [figcraft_mcp::Backend] over a channel to the UI thread, so every tool call becomes the same control request figcraft-cli mcp --attach sends. Window routing, screenshot admission, automation roots and command behaviour are therefore identical for both.

chat panel (UI thread)
   │ send prompt
   ▼
Worker thread ──── HTTPS + SSE ────► provider (OpenAI Completions / Anthropic Messages)
   │  tool calls
   ▼
Remote (Backend) ── Call ──► Chat::take_bridge_calls ──► app.control_queue
                                                              │
                                              control::handle │ (UI thread)
                                                              ▼
                                                        FigCraft session

Connecting a model

The Connections screen (the … button in the header, or the empty tab) has two groups, and neither asks for an endpoint, a model id or token limits.

Use a subscription runs a command-line agent the person already installed and signed in to, so their own plan pays for it and FigCraft never holds that login:

Card Program Plan
Claude Code claude Claude Pro / Max
Codex codex ChatGPT
OpenCode opencode whatever OpenCode is signed in to (OpenCode Go, Zen, …)

cli::status looks for the program on PATH and in the folders installers use (~/.local/bin, ~/.opencode/bin, Homebrew, …) and asks it whether it is signed in. A card then shows Connect, or the install or sign-in command with a Copy button.

A turn runs the program once, non-interactively, and reads its JSON event stream (cli.rs): Claude Code with -p --output-format stream-json --include-partial-messages, Codex with exec --json, OpenCode with run --format json. The program keeps the conversation and the next turn resumes it by the session id it reported (kept in <slug>.context.json). Its built-in tools are left out (Claude Code: --tools "" --strict-mcp-config; OpenCode: an agent whose only tools are figcraft_*; Codex: a read-only sandbox) and FigCraft's tools are attached over MCP:

mcp_http.rs serves figcraft_mcp::Server on 127.0.0.1:<random port>/mcp for the length of the conversation (Streamable HTTP, JSON answers only). It needs the bearer token handed to the child, and refuses a request with an Origin header or a non-loopback Host. Its tool calls go through the same Ask/Auto gate and the same bridge as the in-app loop, and their cards reach the panel from there, so the conversation looks the same whichever way the model is reached. The model picker offers the program's own aliases (Claude Code: sonnet, opus, haiku; OpenCode: opencode models), with Default model leaving the choice to the program.

Use an API key opens a card with one key field: Anthropic, OpenAI, OpenCode Go, OpenCode Zen, OpenRouter, DeepSeek, and the local Ollama and LM Studio (no key). Connect lists the endpoint's models (GET {base}/models) as the check that the key works, then picks a model with config::pick_model: the preset's preferred family, newest first, skipping small and non-chat models. A refused key, an unreachable host and a missing local server each get a plain message.

Everything else — endpoint, key, model by hand, reasoning, reads images, prices, the review pass — is under Advanced on the Connections screen. Switching model or connection is the model chip in the composer.

Connections are stored in <settings folder>/agents.json, mode 0600 on Unix because the file holds API keys. A connection left with neither a key nor a model (an older, half-finished setup) is dropped when the file is read. Env vars are not read; a proxy environment variable is honoured by ureq as usual.

API-key dialects

  • OpenAI Completions — {base}/chat/completions: OpenAI, OpenCode Zen/Go, OpenRouter, DeepSeek, Ollama, LM Studio, any compatible gateway. Requests carry x-opencode-session for opencode.ai hosts (stable id per conversation, for prompt cache affinity).
  • Anthropic Messages — {base}/messages with x-api-key and anthropic-version: 2023-06-01.

A provider is ready when it has a base URL and a model id; a subscription is always ready (an empty model means the program's default).

Tools and permissions

The tool set is figcraft_mcp::tool_definitions() — run_command, batch, create_node, set_properties, inspect_document, design_context, screenshot, export, undo, and the rest. Tool results are translated to each dialect (OpenAI: tool messages plus a user message for images; Anthropic: tool_result blocks, images inside them).

Two permission modes, toggled in the composer:

Mode Canvas edits Files, network, plugins, fonts, the share server
Ask (default) run at once ask: a card names the tool and why
Auto run at once run at once

A denial is returned to the model as a tool error, so it can continue with what it may do. Even in Auto, a confined app (--automation-read-root) confines the agent's writes.

Every command runs with agent: "FigCraft Agent", so the app shows the agent's avatar and outline while it works and signs the comments it makes.

Self-review

When a turn changed the canvas and Look at the canvas after each change is on (Connections › Advanced, on by default), the agent takes one screenshot through the screenshot tool (a step named Checking the result), hands it back with a short instruction, and the model fixes what it sees or replies. One pass per turn, so the cost is one extra request with one image.

  • API key: the loop continues with the picture; skipped when the model's Reads images is off.
  • Command-line agent: the endpoint notes when a tool call changed the document; after the run, the same conversation is resumed once with the picture (--resume / --session). A failed check is a line in the answer, not a failed request.

Reasoning effort

Connections › Advanced has a Reasoning choice: Auto (nothing is sent), Low, Medium or High. For OpenAI-compatible endpoints it becomes reasoning_effort. The Anthropic adapter leaves the provider's own default alone in this version.

Variants

The composer's ×1 / ×2 / ×3 button makes one request build that many versions side by side: the first exactly as asked, the others as alternatives in their own frames, 96 px apart. One worker still does the work in one turn, so there is no concurrency to reconcile; the extra cost is the model's own tool calls.

Tokens and cost

The panel shows {input} in · {output} out after the first turn. Fill In $/1M and Out $/1M in Connections › Advanced and it adds ≈ $… at API rates — an estimate from the provider's own usage numbers, not an invoice. With the prices empty, no amount is guessed.

Stop

Stop interrupts the stream (or ends the command-line agent's process), denies any permission request still waiting for an answer, and leaves the edits already made. If the agent thread ever ends unexpectedly (a panic), the panel says so and starts a fresh worker on the next request instead of staying "working" forever.

Chat history

Each document keeps its conversation under <settings folder>/agent-chats/:

File Holds
<slug>.ui.json what the panel shows: messages, tool cards, notes (the last 200 lines)
<slug>.context.json the model's own messages and token usage, so a request after a restart continues the conversation

<slug> is a readable part of the file path (or the document's name while unsaved) plus a hash of the whole string. New chat starts a new pair of files and keeps the old one in the history. Switching tabs switches the conversation; a running turn keeps the one it started with, and its edits stay pinned to the document and window it began in.

Context

Each request carries a short inspect.designContext of the selection (or the page when nothing is selected), so "make this bigger" applies to what the person is looking at. The model reads more with the tools. Older tool output is shortened once the conversation passes 600 000 characters.

What an answer changed

The panel keeps the document as each turn found it and as each step left it, and compares them (changed_layers): a new layer counts once (not each child), an edited child counts without the frame that only holds it, pages and library copies are left out.

  • Each step in the opened N steps list has Show N layers: it selects them (on the page of the first) and zooms to them.
  • After an answer that changed the canvas, a line says Changed N layers with Show and Undo. Undo walks back every undo step the answer made at once, and is offered only for the last answer, made in this run of the app, on the document in front, while nothing else changed since (otherwise its hint points to Edit › Undo). After it, Redo brings the changes back on the same terms.

The seams: every line this module adds to upstream files

File Change
Cargo.toml figcraft-agent workspace member and ureq
crates/agent/** new crate (ours entirely)
crates/ui-egui/Cargo.toml depends on figcraft-agent
crates/ui-egui/src/lib.rs pub mod chat; and FigApp.chat
crates/ui-egui/src/state.rs LeftTab::Agent
crates/ui-egui/src/app.rs initialise chat; read agents.json on the first frame and open on the Agent tab; ⌘⇧M (chat::shortcut); the panel's accessible name for the tab
crates/ui-egui/src/panels/layers.rs the Agent tab in the rail, remembering it, and the tab's arm in left_panel
crates/ui-egui/locales/en.toml the panel's English strings (English only, as feature PRs do)
crates/ui-egui/src/control.rs drain bridge calls, pump replies (two call sites); ui.set {leftTab: "agent"}
crates/ui-egui/src/menus.rs the canvas context menu's Agent entries (one call, for a selection)
crates/ui-egui/src/services.rs agent_config_path (defaulted method, no breakage)
apps/figcraft/src/services.rs the desktop path for agents.json
xtask/src/layers.rs table entry and two same-layer pairs

Everything else lives in files upstream does not touch. Keep the table above current: it is the checklist for a git rebase.

Browser build

The Agent tab is not in the browser build's rail (an Agent left tab falls back to File there); no keys are stored in a page. Provider calls from the browser would also face CORS, so the browser build is out of scope for now.

Adding a provider dialect

Implement a module beside openai.rs / anthropic.rs:

  1. payload(...) — the request body from system, messages, tools.
  2. stream(...) — send it, read SSE with sse::Sse, call on_text per delta, return a Step (text, Invocations, stop reason, usage).
  3. Translate neutral::Block both ways; do not leak the dialect into session.rs.
  4. Add a case to ApiKind and to Agent::stream.

Tests are fixture-based: no network in CI.