# Figma setup for codedesign

`codedesign`'s Figma write path (`figma_execute`) runs arbitrary Figma Plugin API JavaScript inside a Desktop session. This requires one‑time setup of a **Personal Access Token** and the **Desktop Bridge plugin**. Everything here is optional — the agent falls back to text‑only advice if Figma is unavailable.

## What you get once it's wired

| capability | without setup | with setup |
|---|---|---|
| `ds import <figma-url>` | ❌ 401 | ✅ distills 6‑role palette + fonts from any Figma file you can read |
| `figma_distill_ds` (REPL tool) | ❌ | ✅ same as above, mid‑conversation |
| `figma_execute` (write to canvas) | ❌ | ✅ creates/edits frames, components, styles in your live Desktop session |

---

## 1. Install Figma Desktop

Download: <https://www.figma.com/downloads>

Browser Figma does not expose a plugin runtime we can reach from outside the browser — **Desktop is required** for write paths. Read‑only REST calls (`ds import`, `ds pull`) do not need Desktop, only the token.

## 2. Create a Personal Access Token (PAT)

1. Go to <https://www.figma.com/settings> → **Security** → **Personal access tokens**
2. Click **Generate new token**
3. Give it a recognisable name (e.g. `codedesign-cli`)
4. Scopes needed:
   - `File content: Read` — for `ds import` / `figma_distill_ds`
   - `Variables: Read` (optional) — unlocks Variables API priors for Enterprise files; gracefully falls back to named styles + sampling on lower plans
5. Copy the `figd_…` string. It is shown **once**.

Store it:

```bash
codedesign auth set figma_token figd_your_token_here
codedesign auth show            # verify — will be masked
```

## 3. Install the Desktop Bridge plugin

The plugin is vendored in this repo at `figma-desktop-bridge/` (sourced from `figma-console-mcp` v1.23.0, MIT).

1. Open Figma Desktop → open **any** design file
2. **Plugins** (top menu) → **Development** → **Import plugin from manifest…**
3. Select `figma-desktop-bridge/manifest.json` from your local clone
4. The plugin now appears under **Plugins → Development → Figma Desktop Bridge**

## 4. Start the bridge before each session

Every time you want `figma_execute` to work:

1. Open (any) Figma Desktop file
2. **Plugins → Development → Figma Desktop Bridge**
3. The plugin window shows **"MCP ready"** with a green dot — leave that window open
4. In another terminal, run `codedesign`

If the bridge window is closed mid‑session, `figma_execute` calls will return a structured error and the agent will say so.

---

## Troubleshooting

**"`figma_execute` returned: bridge not running"**
- The plugin window is closed or Figma Desktop was quit. Re‑run **Plugins → Development → Figma Desktop Bridge**.

**"`ds import` returns 403 / 404"**
- Your PAT can't read that file. Confirm you have **view** access in Figma (open the URL in your browser while logged into the same account).
- Enterprise‑only Variables endpoints may 403 on lower plans — that's fine, the distiller falls back to named styles and sampling.

**"`ds import` exits with `Variable aliases were not resolved`"**
- A style points to a variable in a separate library file you don't have access to. The import still proceeds; check the provenance column in the distill preview — roles resolved via sampling will be marked `sample`.

**"Plugin doesn't show up in Figma after importing"**
- Figma caches plugin manifests aggressively. Restart Figma Desktop.

**"I regenerated my PAT — now what?"**
- `codedesign auth set figma_token figd_new_token_value` overwrites the old one in `auth.toml`.

---

## Security notes

- `auth.toml` is written with `chmod 600` (user‑readable only).
- The PAT has the same access your account does — store it like a password. Rotate via Figma Settings if it leaks.
- `figma_execute` runs **arbitrary JS** the agent authors inside your Figma session. Review the code it shows before letting it run destructive operations on production files. Use a scratch file for early experiments.

---

## Binding a Component Library

CodeDesign can reproduce DS components 1:1 by walking your Figma DS file via
the REST API and rebuilding each component as native Plugin API nodes on the
target canvas.

### One-time setup

In the REPL, run:

```
library_add({ "url": "https://www.figma.com/design/<KEY>/<name>" })
```

This walks every COMPONENT and COMPONENT_SET in the file, downloads SVG
exports for vector children, and writes everything under
`~/.codedesign/libraries/<slug>/`. The default slug is the slugified file
name; pass `slug:"<name>"` to override.

Re-run with `overwrite:true` to refresh after DS updates.

### Using the library

```
list_components({ "query": "按钮" })
list_components({ "page": "导航菜单" })
```

returns matching components with their `key`, page (category), and (for
COMPONENT_SET) the variant axes.

```
place_component({
  "library": "ruliu-mobile",
  "key": "13:47945",
  "x": 100, "y": 100,
  "variant": { "Property 1": "默认" }
})
```

drops a 1:1 reconstruction at the given coordinates on the current Figma
canvas. Requires the Desktop Bridge Plugin to be running.

### Limitations

- Variables (Figma's design tokens) require the `file_variables:read` OAuth
  scope which is gated to Enterprise plans. Without it, all paints are
  serialized as RGB; updates to your DS color tokens won't auto-propagate
  to placed components — re-run `place_component` to pick up new values.
- Components referenced via `remote:true` from a published Team Library
  can't be reconstructed (their children aren't accessible). They appear
  as red-bordered placeholders.
- Smoke script for end-to-end validation: `scripts/library-smoke.sh`.
