SKILL.md
SKILL.mdBrowse 4 files
4,009 tokens
14,991 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: tldraw-offline3description: Drive and script tldraw offline canvases with an agent.4version: 1.0.05author: Teknium + Hermes Agent6license: MIT7platforms: [linux, macos, windows]8metadata:9 hermes:10 tags: [tldraw, canvas, whiteboard, document-script, diagramming]11 category: creative12 related_skills: []13---14 15# tldraw offline Skill16 17Work with the tldraw offline desktop app (offline.tldraw.com): read the open18canvas, make edits, and write **document scripts** — JavaScript embedded in a19`.tldraw` file that runs on load and gives the file durable behavior. The app20runs a **local HTTP API** (default `localhost:7236`) that a coding agent drives21with plain `curl` from its terminal — this is exactly how the app's own homepage22demo (Codex editing a canvas live) works. The agent does NOT use computer-use /23GUI clicking, and does NOT hand-edit the `.tldraw` file directly. Keep tldraw24offline open while you work.25 26## When to Use27 28- The user has tldraw offline open and asks you to build or modify a canvas29 (diagrams, wireframes, layouts).30- You want to add durable behavior to a drawing (reactive shapes, interactive31 buttons, animation, connection logic) via an embedded document script.32 33Do NOT hand-place shapes to imitate a drawing — write the code that generates34them. Agents are far better at scripting the canvas than at drawing on it.35 36## Prerequisites37 38- **tldraw offline installed and running**, with a document open. Releases:39 https://github.com/tldraw/tldraw-offline/releases/latest (macOS DMG, Windows40 x64/Arm64, Linux `x86_64`/`arm64` AppImage or amd64/arm64 `.deb`).41- **Agent skills installed in the app**: `Develop → Install Agent Skills`. The42 app writes its own tldraw skill into `~/.codex/skills/`, `~/.claude/skills/`,43 `~/.cursor/skills/`, and `~/.gemini/skills/` — teaching that agent the `curl`44 recipes below. (This Hermes skill mirrors that guidance for Hermes.)45- **The local control API.** On launch the app writes `server.json` to its config46 dir (Linux `~/.config/tldraw/`, macOS `~/Library/Application Support/tldraw/`,47 Windows `%APPDATA%\tldraw\`) with `port` (default `7236`), a bearer `token`,48 `pid`, and `startedAt`. Every request except `GET /` needs49 `Authorization: Bearer <token>`. A clean quit removes `server.json`; if it's50 present but the port doesn't answer, the app quit uncleanly — treat as not51 running.52- **Re-read port + token on EVERY shell call.** Each terminal call is a fresh53 shell, so an `export`ed token does not persist — "export once and reuse" sends54 an empty token and 401s. Read both inline at the top of each call:55 `PORT=$(jq -r .port <server.json>); TOKEN=$(jq -r .token <server.json>)`.56- No account or network needed for local editing.57 58## How to Run59 60Two distinct workflows. Pick by whether the change must survive a reload.61 62**A. One-off canvas edits (`/exec`)** — layout, generating shapes, cleanup. This63is a live edit, not saved script:64 65```bash66BASE=http://localhost:723667TOKEN=$(python -c "import json;print(json.load(open('$HOME/.config/tldraw/server.json'))['token'])")68# find the focused document id69DOC=$(curl -s "$BASE/api/search" -X POST -H 'content-type: application/json' \70 -H "Authorization: Bearer $TOKEN" \71 -d '{"code":"return (await api.getFocusedDoc()).id"}' | python -c "import sys,json;print(json.load(sys.stdin)['result'])")72# run code with the live `editor` + `helpers` in scope73curl -s "$BASE/api/doc/$DOC/exec" -X POST -H 'content-type: application/json' \74 -H "Authorization: Bearer $TOKEN" \75 -d '{"code":"const {createShapeId,toRichText}=await import(\"tldraw\"); editor.createShape({id:createShapeId(),type:\"geo\",x:0,y:0,props:{geo:\"rectangle\",w:200,h:100,color:\"blue\",fill:\"solid\",richText:toRichText(\"hello\")}}); return editor.getCurrentPageShapes().length"}'76```77 78**B. Durable behavior (`script/main.js`)** — reactive/interactive logic that must79survive reload. Edit the file on disk; the app's watcher applies it:80 81```bash82# get the live script file path for the doc83curl -s "$BASE/api/doc/$DOC/script-workspace" -X POST \84 -H "Authorization: Bearer $TOKEN" # -> result.mainJsPath, result.isDefaultScript85# edit result.mainJsPath with read_file / patch / write_file (see scripts/main.js)86# then confirm the watcher applied it:87curl -s "$BASE/api/doc/$DOC/script-status" -H "Authorization: Bearer $TOKEN"88```89 90The ready-to-adapt document script is `scripts/main.js`.91 92## Quick Reference93 94The document-script contract (verified against the app's bundled95`script-context.d.ts`):96 97```js98import { createShapeId, toRichText } from 'tldraw' // primitives: import, not globals99 100export default function ({ editor, helpers, signal }) {101 editor.run(() => { // batch = one undo step102 helpers.createShapeIfMissing({ // idempotent furniture103 id: createShapeId('node-1'), type: 'geo', x: 0, y: 0,104 props: { geo: 'rectangle', w: 200, h: 100, richText: toRichText('hi') },105 })106 })107 108 const stop = editor.store.listen(() => { /* react */ }) // fires the tick AFTER a commit109 signal.addEventListener('abort', () => stop()) // REQUIRED cleanup on rerun/close110}111```112 113- `ctx.editor` — the live `Editor` (`createShape`, `updateShape`, `deleteShapes`,114 `getCurrentPageShapes`, `getShape`, `getBindingsFromShape`, `zoomToFit`,115 `on('tick'|'event', fn)`, `run(fn, { history: 'ignore' })`).116- `ctx.helpers` — `createShapeIfMissing`, `createShapesIfMissing`,117 `createArrowBetweenShapes(from, to, { arrowheadEnd })`, `translateShapes`,118 `onShapeTranslate(id, fn, { signal })`, `richTextToPlainText`, `boxShapes`,119 `getLints`.120- `ctx.signal` — `AbortSignal`; attach every listener/interval teardown to it.121- `config.js` (separate file) registers custom shape/tool/component utils and122 runs before mount; `main.js` runs against the mounted editor and reruns on save.123 124## Interactive UI (clickable buttons that drive state)125 126Drawn shapes can behave like a real app — the thing a static whiteboard can't do.127Full example: `scripts/counter.js` (a number display + MINUS/RESET/PLUS buttons).128 129Verification boundary — read this before claiming interaction works or doesn't.130The app's OWN agent playbook says to verify a clickable-UI script with "one131simulated click and one state read" via `/exec` (`editor.dispatch` a pointer132event, await a tick, read the shape's state) — NOT by driving a real mouse. By133that standard the counter is verified: dispatched clicks stepped it134`0 → 1 → 2 → 1 → 0`. Two caveats worth writing down:135- **The script only runs once the app's file-watcher applies it.** On Linux that136 watcher uses inotify; a host with an exhausted `fs.inotify.max_user_instances`137 logs `inotify_add_watch ... No space left on device`, `script-status` shows138 `state: "not-watching"` / `hasEntry: false`, and the script never executes.139 This is a host limit, not a script bug — a normal desktop is unaffected.140- **Driving the canvas with computer-use needs FOREGROUND delivery, not141 background.** cua-driver's default `background` delivery returns142 `background_unavailable` against Electron's occluded renderer — but that is the143 first rung, not a wall. cua-driver returns an `escalation: "foreground"` hint;144 set `delivery_mode: "foreground"` (pair with `bring_to_front`) and its X11 XTest145 path (`x11_xtest_fg`) clicks land — this dismisses the "Run Script" consent146 dialog and clicks the canvas. Verified by the Cua team on this exact v1.11.0147 AppImage (Linux/X11). Do NOT conclude "Electron rejects synthetic clicks" and148 give up in background mode — climb to foreground. (The real product path is149 still `/exec`, not clicks; this note is for computer-use-driven testing.)150 151The pattern:152 153```js154export default function ({ editor, helpers, signal }) {155 // 1. Build buttons idempotently; tag each with meta so the handler finds them.156 // Give buttons a visible label AND a meta.action.157 // 2. Hit-test pointer_down in PAGE coordinates against the button bounds:158 const inside = (b, p) => p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h159 function onEvent(info) {160 if (!info || info.name !== 'pointer_down') return161 let p = null162 try { if (info.point && editor.screenToPage) p = editor.screenToPage(info.point) } catch {}163 p = p ?? editor.inputs?.currentPagePoint164 if (!p) return165 const hit = editor.getCurrentPageShapes().find(166 (s) => s.meta?.ui === 'button' &&167 inside({ x: s.x, y: s.y, w: s.props.w, h: s.props.h }, p)168 )169 if (hit) runAction(hit.meta.action) // mutate state; store it in a shape's meta170 }171 editor.on('event', onEvent)172 signal.addEventListener('abort', () => editor.off('event', onEvent)) // REQUIRED173}174```175 176- Find buttons by `meta` (or visible label via `helpers.richTextToPlainText`),177 not by hard-coded coordinates.178- **One script owns both build and read.** If the shapes are created by one code179 path (with `meta.action: 'inc'`) and the handler reads another convention180 (`meta.action === 'PLUS'`), clicks silently do nothing. Ship the buttons built181 by the same script that handles them, or ship an empty canvas so the script182 builds them fresh — never pre-bake mismatched shapes into the file's db.183- Keep app state in a shape's `meta` (e.g. `meta.count`) and render it as that184 shape's `richText` label, so it survives save and is readable for verification.185- **Detach the listener on `signal` abort.** Skipping this is not cosmetic: on186 the next save the old `onEvent` stays attached alongside the new one, so every187 click fires twice and a counter jumps by 2 instead of 1.188- For continuous motion use `editor.on('tick', fn)`; for a moving anchor with189 attached pieces use `helpers.onShapeTranslate(id, fn, { signal })`.190 191### Shipping a self-running scripted `.tldraw`192 193A `.tldraw` is a zip of `metadata.json` + `session.json` + `db.sqlite` + `assets/`194+ `script/` (only those entries are packable). For the script to auto-run without195the "This document contains a script → Run Script" consent dialog:196 197- `metadata.json` must carry a `script` manifest: `{ "sha256": "<digest>" }`, where198 the digest is `sha256` over each sorted `script/` path as `` `${path}\0${sha256hex(bytes)}\n` ``.199 A mismatch is rejected as tampered.200- Pre-trust the digest by adding it to `~/.tldraw/script-trust.json`201 (`{ "trusted": ["<digest>"] }`, or `$TLDRAW_SCRIPT_TRUST`). The app skips consent202 when `isScriptTrusted(digest)` is true.203 204## Procedure205 2061. Read the current token/port from `server.json`. Find the target doc with207 `api.getFocusedDoc()` (or `api.getDocs()`); name it explicitly if several are208 open.2092. For layout/generation, use `/exec`. For durable behavior, edit210 `script/main.js` via `/script-workspace`.2113. Make scripts idempotent: create durable shapes with `helpers.createShapeIfMissing`212 and stable `createShapeId('name')` ids. Scripts rerun on every load.2134. Keep script-owned writes out of the user's undo stack:214 `editor.run(fn, { history: 'ignore' })` (or `helpers.translateShapes`, which215 already does).2165. For reactivity, `editor.store.listen(cb)` and tear it down on `signal` abort.217 For interaction, `editor.on('event', h)` (hit-test `pointer_down` in page218 coords); for animation, `editor.on('tick', h)`.2196. For a single moving anchor + attached internals, prefer220 `helpers.onShapeTranslate(anchorId, fn, { signal })` over a broad store221 listener — a broad listener can turn your own writes into feedback loops.222 223## Shape props (validated against tldraw SDK v5 schema)224 225`editor.createShape` / `createShapeIfMissing` accept partial props (shape utils226fill defaults). When building **raw records** for a file snapshot, every prop227below is required (run `scripts/validate_shapes.mjs`):228 229| Shape | Required props |230|-------|----------------|231| `note` | `richText`, `color`, `labelColor`, `size`, `font`, `align`, `verticalAlign`, `growY`, `fontSizeAdjustment`, `url`, `scale`, `textLastEditedBy` |232| `text` | `richText`, `color`, `size`, `font`, `textAlign`, `w`, `scale`, `autoSize` |233| `frame` | `w`, `h`, `name`, `color` |234| `geo` | `geo`, `w`, `h`, `color`, `fill`, `richText` (+ dash/size/etc. defaulted) |235 236`richText` must be `toRichText('...')` — a bare string is rejected. `color` enum:237`black grey light-violet violet blue light-blue yellow orange green light-green238light-red red white`. `font` enum: `draw sans serif mono`.239 240## Pitfalls241 242- **`store.listen` fires on the tick AFTER a commit, not synchronously.** If you243 write a shape and immediately read state expecting the listener to have run, it244 hasn't. Verified live: an in-turn read shows 0 fires; after one `setTimeout`245 tick it shows 1. Same reason the app notes `editor.dispatch` is async — await a246 tick before verifying.247- **`ctx`, not globals.** The entry is `export default function ({ editor,248 helpers, signal })`. There is no bare `editor` global in a document script.249 `createShapeId` / `toRichText` / `Vec` come from `import ... from 'tldraw'`.250- **`richText`, not `text`.** Text/note/geo labels use `richText: toRichText(s)`.251- **Raw records need every prop; `createShape` does not.** In-app pass only the252 props you care about; a hand-built `.tldraw` snapshot needs the full set (table).253- **Scripts rerun on every load — be idempotent.** Use `createShapeIfMissing`254 with stable ids or you duplicate content and clobber user edits.255- **Clean up on `signal`.** `signal.addEventListener('abort', () => stop())` for256 every `store.listen` / `editor.on` / `setInterval`; the signal fires before257 rerun and on close.258- **Keep script writes out of undo:** `editor.run(fn, { history: 'ignore' })`.259- **`editor.on('tick')` pauses when the window is hidden** (it is a RAF loop);260 `setInterval` keeps firing but Electron throttles it to ~1/s in the background.261- **The API needs the bearer token** from `server.json`; the port can be non-default262 (`server.listen(0)` picks one) — always read the file, don't hardcode `7236`.263- **Only `tldraw` / `react` / `react-dom` import** — not a Node project.264 265## Verification266 267- **Shape schema (offline, no app):** `node scripts/validate_shapes.mjs` — builds268 the real tldraw schema and validates note/text/frame. Passing prints `3/3`.269- **Live canvas edits:** after `/exec`, read back with `/api/search` →270 `api.getShapes(docId)` (returns `{ page, viewport, shapes }`) and271 `api.getBindings(docId)` (array). Confirm expected shapes/bindings exist. Grab272 `api.getScreenshot(docId)` (returns `{ filePath, ... }`) and inspect the PNG/JPEG273 with `vision_analyze`.274- **Durable script applied:** `GET /api/doc/:id/script-status`. Success is275 `state: "applied"` (`currentDiskDigest === lastAppliedDigest === manifestSha256`,276 `pendingApply === false`, `lastApplyError === null`). If it stays `"pending"`277 after a short retry, report that instead of claiming success; `"error"` means278 the apply failed — read `errorLogPath`.279 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.