46 Commits

Author SHA1 Message Date
Marcos Paulo 87c9c3a151 fix: repair release test failures
site / publish (push) Has been cancelled
release / site (push) Has been cancelled
release / test (push) Has been cancelled
release / windows (push) Has been cancelled
release / macos (push) Has been cancelled
release / linux (push) Has been cancelled
release / publish (push) Has been cancelled
2026-10-29 15:55:21 -03:00
Marcos Paulo ddd6fd96b8 Merge pull request #1 from nxtime/claude/affectionate-euler-blm40d
feat(site): add a landing page published to the pages branch
2026-10-29 15:40:10 -03:00
Claude 944311cba1 feat(site): add a landing page published to the pages branch
The page in site/ reads the latest GitHub release from release.json, offers
the build for the visitor's system, and shows the demo tour, a live agent
run and the feature set on the app's acrylic look. site.yml builds it with
the newest release and commits the result to the pages branch; release.yml
calls it after publishing, and a daily run catches releases made by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J9PiV8m3jnQjxY1skZUJfF
2026-10-29 18:23:31 +00:00
Marcos Paulo bc0c3c1a1b chore(release): 0.9.1
release / test (push) Has been cancelled
release / windows (push) Has been cancelled
release / macos (push) Has been cancelled
release / linux (push) Has been cancelled
release / publish (push) Has been cancelled
2026-10-29 14:37:34 -03:00
Marcos Paulo 23e0571b2c feat: expand agent chat and design handoff 2026-10-29 10:28:15 -03:00
Marcos Paulo 24c2c2ad5f chore(release): 0.9.0
release / test (push) Has been cancelled
release / windows (push) Has been cancelled
release / macos (push) Has been cancelled
release / linux (push) Has been cancelled
release / publish (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:12 -03:00
Marcos Paulo 1b056f0f01 perf: cut chat and image memory, wrap long answer chips
Chat screenshots move to files (kept 14 days), the history list holds no
messages, thumbnails stay small, canvas images decode only for the GPU and
leave it when idle, and long answer options wrap instead of widening the chat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 13503d4c19 feat(mcp): wire the new tools and document them
export_presentation, critique_design, design_lessons, claim_nodes,
release_claims, list_claims and undo/redo scope; 94 tools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo a9a719f1ef feat(ui): page icons, a searchable pages list, sliding layer buttons
Pages can carry an icon, the pages popover filters by name, a layer row's eye
and lock slide in only while shown, and agent outlines fade sooner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo e4639054e7 feat(mcp): let several agents share one project safely
Named CLI agents (--as, --parent), conflict reports and ifRev on writes,
claims that fence layers off, delegate build scopes and per-agent undo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 264629ed47 feat(mcp): critique designs through reviewer personas and keep approved lessons
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 5428122609 feat(screens): keep a screen's device height and add sections
A screen made at a device width keeps that device's height and scrolls what
does not fit. Sections group screens on the canvas, drawn as a faint outline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 8d3306ea1f feat(ui-kits): add shadcn, MUI, Mantine, Bootstrap and Chakra kits
The four derived kits reuse the shadcn markup with their own tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo b64a779619 feat(mcp): make write_html follow the browser more closely
Rewrites common unsupported CSS into what the canvas has, makes room when a
frame grows into the ones below it, keeps growing text in hugging rows at its
width, and lints what still differs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 975dcfe023 feat(io): export the screens as a presentation deck
A PDF with a cover, contents and a slide per screen, from the File menu, the
palette, the inspector's Export section and `--format presentation`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 74ba94b66f fix(web): give config_dir a wasm variant so the web build compiles
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:47:02 -03:00
Marcos Paulo 580fa9ecc3 docs(skills): teach the incremental check loop in the papercraft skill
The skill's lint step now says to lint only what changed between edits
(rev, changedOnly, since), to read geometry with get_bounds and changes with
get_changes, and to finish with one full lint and a screenshot per mode. The
several-agents section uses get_changes {exclude: "self"}, and the cheat
sheet lists both new tools and the overflow rule. This replaces the pending
snippet file.

The reference and docs/agents.md now match the tools as merged: lint_design
reports coverage under `covered`, and get_bounds returns columns and rows
with continueWith when truncated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:53:27 -03:00
Marcos Paulo 27e6765a43 docs: mind the build machine and keep full test runs on CI
RULES.md gains "The machine you build on": check memory, load and running
builds first, cap Cargo jobs and test threads, run at low priority, one heavy
job at a time, stop when the person says the machine is slow, and clean up
scratch targets. Locally only the test targets a change touches run; the full
suite runs on GitHub before a release. AGENTS.md, CONTRIBUTING.md and the PR
checklist say the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:50:31 -03:00
Marcos Paulo 9de7c4d8ae ci: run the full test suite before every release
test.yml runs cargo test and the wasm check on a Windows runner. The release
workflow calls it and publishes only when it passes; it can also be run on
its own with `gh workflow run test.yml -f ref=<branch>`. Like the release
jobs, it only runs on github.com.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:50:31 -03:00
Marcos Paulo a98bed0da7 test: pass tool arguments to log_agent in the UI smoke test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:50:07 -03:00
Marcos Paulo e876035fc6 fix: reset the change log on every project switch
Editor::load replaced the change log with a fresh one, so rev restarted at 0
when a project was opened from the app. Once the new project caught up, an
agent's old `since` looked current and get_changes reported a partial list
instead of `truncated`. The log now carries across load and resets there,
which covers the app, the session and MCP alike.

The MCP-only reset after create_file goes: that tool creates a project
without opening it. Tests now open the project with open_file and read the
rev before writing instead of assuming the log starts at 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:50:07 -03:00
Marcos Paulo f4fd3a8607 docs: count 88 tools after get_changes and get_bounds
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 18:10:05 -03:00
Marcos Paulo 83c644d2bf Merge branch 'worktree-agent-a8158d642a885966f' into integration/incremental-lint 2026-10-28 18:09:56 -03:00
Marcos Paulo 1d4eb97d98 Merge branch 'worktree-agent-aaa0fa0d394a3b41c' into integration/incremental-lint 2026-10-28 18:09:55 -03:00
Marcos Paulo a7302326f2 Merge branch 'worktree-agent-afce846aed3239911' into integration/incremental-lint
# Conflicts:
#	PROGRESS.md
2026-10-28 18:09:55 -03:00
Marcos Paulo 72931c5220 Merge branch 'worktree-agent-ae1f23fd3f4aeb50f' into integration/incremental-lint 2026-10-28 18:09:46 -03:00
Marcos Paulo b848eabdf3 feat: incremental lint with a change log and get_changes
A bounded log (10000 layer changes, each tagged with the client that made it)
records what every commit, undo and redo touched; variable edits count as
touching the layers bound to them. Write tools return rev, get_basic_info
reports it, get_changes lists changes (exclude: self, by), and lint_design
takes since / changedOnly to check only changed layers plus what they affect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 18:09:27 -03:00
Marcos Paulo cd2913d6f7 feat: add the overflow lint rule and the get_bounds tool
lint_design flags layers past their artboard or clipping parent and text
taller than its box (scrolling frames exempt). get_bounds returns the
rects of whole subtrees in one read.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 18:05:54 -03:00
Marcos Paulo ec6da1d383 fix: treat agent reads as reads in the pill, outlines and follow camera
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 17:43:14 -03:00
Marcos Paulo ccc6da2e8c docs(specs): design swarm safety for concurrent agents
Identity, optimistic concurrency, soft claims, per-client undo, offline multi-process locking, test harness and phases.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 17:42:45 -03:00
Marcos Paulo 39933d3c74 docs: add incremental checks workflow (rev, get_changes, scoped lint, get_bounds)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 17:34:24 -03:00
Marcos Paulo 5ee037a7c3 docs: add an AI usage policy, AGENTS.md and CODEOWNERS
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 16:33:24 -03:00
Marcos Paulo d97b889455 docs: add contributing guide, project rules, code of conduct and security policy
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 16:19:19 -03:00
Marcos Paulo 65d160af3b ci: install libdbus and the Apple silicon target for release builds
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 16:01:32 -03:00
Marcos Paulo 837c4448b0 ci: build and publish releases on GitHub only
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 14:27:54 -03:00
Marcos Paulo db650b3ea6 docs: bring the README status and known limits up to date
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 14:20:08 -03:00
Marcos Paulo 76afc98890 docs: drop the paper-rs fork credit and upstream references
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 12:40:25 -03:00
Marcos Paulo 8d46a01a10 chore(release): 0.8.4
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 12:30:22 -03:00
Marcos Paulo 7a6d664c42 docs(readme): add demo video and refresh screenshots
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 12:25:45 -03:00
Marcos Paulo 70830478d9 fix(ui): read the performance overlay's prefs from the project config dir
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 12:25:44 -03:00
Marcos Paulo c575b7e7a7 feat(ui): menu icons and offsets, panel grips, / to hide panels, narrow-window fixes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 10:04:38 -03:00
Marcos Paulo ec7f1f8a14 feat(ui): refresh-rate frame cap, Task Manager-accurate RAM/CPU, menu toggle and themed close button
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 08:55:37 -03:00
Marcos Paulo 24f6c797f2 chore(release): 0.8.1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:16:28 -03:00
Marcos Paulo a2885a3283 perf(ui): cache the Design tab's lint and feedback until the document changes
The tab ran the design lint over every node, and scanned every node for open
comments, on every frame. On a 12.6k-node page that cost hundreds of ms per
frame (377 ms worst) while the tab was open. Both results are now kept per
(doc_stamp, active page); the open-feedback count of other pages refreshes once
a second.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:14:34 -03:00
Marcos Paulo 0143f1e465 feat(perf): RAM and CPU on Windows; refresh rates up to 360 Hz
The performance overlay showed n/a for RAM and CPU on Windows: the readings
existed only for macOS and Linux. They now come from GetProcessMemoryInfo
(working set) and GetProcessTimes (kernel plus user time).

The "Warn below" chips become "Refresh rate" and now go up to 144, 165, 240
and 360, for high-refresh monitors. The default stays 60.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 01:14:34 -03:00
Marcos Paulo dc57f9af20 feat(ui): window buttons in the toolbar on Windows/Linux; controls and acrylic from craft-ui
- Drop the separate title bar: minimize/maximize/close sit at the toolbar's right,
  its empty middle drags the window (double-click maximizes). Home gets the same.
- Linux is undecorated too, with edge resize.
- Settings pages fill the modal height and scroll (Appearance rendered empty).
- Checkbox, toggle, select and the acrylic material now come from craft-ui.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:44:02 -03:00
164 changed files with 14856 additions and 1554 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
# Upstream (michaelshimeles/paper-rs) carries no ArtCraft/Discord branding; keep it that way. Run: perl tools/craft-skills/skills/debrand/debrand.pl --check .
# The tree carries no ArtCraft/Discord branding; keep it that way. Run: perl tools/craft-skills/skills/debrand/debrand.pl --check .
keep ^(LICENSE-(MIT|APACHE)|\.debrand)$
forbid (?i)artcraft
forbid (?i)discord
+1
View File
@@ -0,0 +1 @@
* @nxtime
+19
View File
@@ -0,0 +1,19 @@
---
name: Bug report
about: Something does not work as expected
labels: bug
---
**What happened**
**What you expected**
**Steps to reproduce**
1.
2.
**Version and platform**
PaperCraft version (the release you installed), OS, and the GPU if it is a rendering problem.
**Screenshot, recording or project**
Attach one if you can. Remove anything private first.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Security vulnerability
url: https://github.com/nxtime/papercraft/security/advisories/new
about: Report security problems privately, not as an issue.
+14
View File
@@ -0,0 +1,14 @@
---
name: Feature request
about: Suggest an idea or a missing capability
labels: enhancement
---
**The problem**
What are you trying to do, and what gets in the way?
**What you would like**
**Alternatives you considered**
**Is it already in ROADMAP.md?**
+24
View File
@@ -0,0 +1,24 @@
## What and why
<!-- What changed, and the problem it solves. Link the issue: Fixes #123 -->
## How I tested it
<!-- Tests added, commands run, platforms tried. -->
## AI assistance
<!-- Which tool helped and how much, or "none". See AI_POLICY.md. You must understand every line. -->
## Screenshots
<!-- For UI changes: before and after, at scale 2, in each theme. -->
## Checklist
- [ ] Tests first; new code is covered, error paths included
- [ ] `cargo fmt --all`, `cargo clippy --all-targets` and the affected `cargo test --test` targets pass
- [ ] Follows [RULES.md](../RULES.md) (no overflow, data safety, one undo step per tool call)
- [ ] Docs, tool descriptions and `PROGRESS.md` updated where needed
- [ ] Conventional commit messages
- [ ] I read and understand every line of this change (AI-assisted or not)
+101
View File
@@ -0,0 +1,101 @@
# Builds Windows, macOS and Linux on GitHub's runners when a v* tag is pushed, then publishes a
# GitHub release with the files once the full test suite (test.yml) passes, then refreshes the
# landing page (site.yml). Gitea reads .github/workflows too, so every job is gated on the
# server URL: this pipeline only ever runs on github.com.
name: release
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: Existing tag to build and release (e.g. v0.8.4)
required: true
permissions:
contents: write
env:
CARGO_TERM_COLOR: always
TAG: ${{ inputs.tag || github.ref_name }}
jobs:
test:
uses: ./.github/workflows/test.yml
with: { ref: "${{ inputs.tag || github.ref }}" }
windows:
if: github.server_url == 'https://github.com'
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
with: { ref: "${{ inputs.tag || github.ref }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build and zip
shell: pwsh
run: |
cargo build --release --locked --bins
$v = $env:TAG.TrimStart('v')
New-Item -ItemType Directory -Force dist | Out-Null
$exes = 'papercraft','papercraft-cli','papercraft-mcp','papercraft-relay' | ForEach-Object { "target/release/$_.exe" }
Compress-Archive -Path $exes -DestinationPath "dist/papercraft-$v-windows-x86_64.zip"
- uses: actions/upload-artifact@v4
with: { name: windows, path: dist/* }
macos:
if: github.server_url == 'https://github.com'
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
with: { ref: "${{ inputs.tag || github.ref }}" }
- uses: dtolnay/rust-toolchain@stable
with: { targets: aarch64-apple-darwin }
- uses: Swatinem/rust-cache@v2
- name: Package (Apple silicon, ad-hoc signed, not notarized)
run: packaging/macos/package.sh --arch aarch64
- uses: actions/upload-artifact@v4
with: { name: macos, path: dist/release/* }
linux:
if: github.server_url == 'https://github.com'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { ref: "${{ inputs.tag || github.ref }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build dependencies
run: |
sudo apt-get update
sudo apt-get install -y pkg-config libssl-dev libxkbcommon-x11-dev libxcb-xkb-dev libx11-xcb-dev libwayland-dev libvulkan-dev libdbus-1-dev
- name: Build and tar
run: |
cargo build --release --locked --bins
v="${TAG#v}"
mkdir -p dist stage
cp target/release/papercraft target/release/papercraft-cli target/release/papercraft-mcp target/release/papercraft-relay stage/
tar -C stage -czf "dist/papercraft-$v-linux-x86_64.tar.gz" .
tar -C stage -czf "dist/papercraft-cli-$v-linux-x86_64.tar.gz" papercraft-cli papercraft-mcp
- uses: actions/upload-artifact@v4
with: { name: linux, path: dist/* }
publish:
if: github.server_url == 'https://github.com'
needs: [test, windows, macos, linux]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with: { path: files, merge-multiple: true }
- name: Create the release
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release create "$TAG" files/* --repo "$GITHUB_REPOSITORY" --title "PaperCraft ${TAG#v}" \
--generate-notes --verify-tag || gh release upload "$TAG" files/* --repo "$GITHUB_REPOSITORY" --clobber
site:
if: github.server_url == 'https://github.com'
needs: publish
uses: ./.github/workflows/site.yml
+69
View File
@@ -0,0 +1,69 @@
# Builds the landing page (site/) with the latest GitHub release and commits it to the `pages`
# branch, which GitHub Pages serves (Settings → Pages → Deploy from a branch → pages, / (root)).
# release.yml calls it after publishing, a daily run catches releases made by hand, and pushes to
# the page's sources rebuild it. Nothing is committed when the result is unchanged. Gitea reads
# .github/workflows too, so the job is gated on the server URL.
name: site
on:
workflow_call:
workflow_dispatch:
schedule:
- cron: "23 5 * * *"
push:
branches: [main]
paths:
- site/**
- docs/demo.mp4
- docs/screenshots/readme/**
- assets/app-icon/papercraft.svg
- assets/agents/**
- .github/workflows/site.yml
permissions:
contents: write
concurrency:
group: site
cancel-in-progress: false
jobs:
publish:
if: github.server_url == 'https://github.com'
runs-on: ubuntu-latest
steps:
# The page comes from the default branch even when a release tag calls this workflow.
- uses: actions/checkout@v4
with: { ref: "${{ github.event.repository.default_branch }}" }
- name: Install ffmpeg
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends ffmpeg
- name: Check out the pages branch
run: |
echo "PAGES=$RUNNER_TEMP/pages" >> "$GITHUB_ENV"
PAGES="$RUNNER_TEMP/pages"
if git ls-remote --exit-code --heads origin pages > /dev/null; then
git fetch --depth 1 origin pages:refs/remotes/origin/pages
git worktree add --detach "$PAGES" origin/pages
else
git worktree add --orphan -b pages "$PAGES"
fi
- name: Build
env:
GH_TOKEN: ${{ github.token }}
run: sh site/build.sh dist/site "$PAGES"
- name: Commit and push
run: |
cd "${PAGES:?}"
# Clearing through git drops files the new build no longer has, and only tracked ones.
git rm -rqf --ignore-unmatch .
cp -a "$GITHUB_WORKSPACE/dist/site/." .
git add -A
if git diff --cached --quiet; then
echo "The page is already up to date."
exit 0
fi
tag="$(jq -r .tag release.json)"
git -c user.name="github-actions[bot]" \
-c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
commit -q -m "chore(site): publish the page for $tag"
git push origin HEAD:refs/heads/pages
+34
View File
@@ -0,0 +1,34 @@
# The full test suite. Local runs cover only the targets a change touches (RULES.md, "The machine
# you build on"); this is where everything runs, before a release can publish. Run it alone with
# `gh workflow run test.yml -f ref=<branch or tag>`. Gitea reads .github/workflows too, so the job
# is gated on the server URL.
name: test
on:
workflow_call:
inputs:
ref:
type: string
required: false
workflow_dispatch:
inputs:
ref:
description: Branch or tag to test (default the one you run from)
required: false
env:
CARGO_TERM_COLOR: always
jobs:
test:
if: github.server_url == 'https://github.com'
# Windows: the platform the app is developed on, and its runners render with a software GPU.
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
with: { ref: "${{ inputs.ref || github.ref }}" }
- uses: dtolnay/rust-toolchain@stable
with: { targets: wasm32-unknown-unknown }
- uses: Swatinem/rust-cache@v2
- run: cargo test --locked --no-fail-fast
- run: cargo check --locked --lib --target wasm32-unknown-unknown
+77
View File
@@ -0,0 +1,77 @@
# Guidance for coding agents
PaperCraft is a native Rust design and whiteboard canvas (egui, wgpu, winit) that AI agents drive
over MCP and a CLI. Read [CONTRIBUTING.md](CONTRIBUTING.md) and [RULES.md](RULES.md) first; this
file is the short version for agents, and [AI_POLICY.md](AI_POLICY.md) says what the person using
you is accountable for.
## Commands
```sh
cargo build --release
cargo fmt --all
cargo clippy --all-targets
cargo test --test incremental # only the targets your change touches
cargo test --lib editor::changes # unit tests of one module
cargo check --lib --target wasm32-unknown-unknown
```
Do not run the full suite locally: it builds dozens of test binaries. It runs on GitHub before
each release (`.github/workflows/test.yml`). `tests/update.rs` cannot run on Windows outside CI
(it needs elevation); that failure is known.
Builds run on the person's own machine, so mind its resources (RULES.md, "The machine you build
on"): check free memory and running builds first, cap jobs at no more than half the cores
(`cargo test -j 8 -- --test-threads=8` on 16 cores), run at low priority, run one heavy job at a
time, and stop at once if they say it is slow.
## Running the app safely
Never run a test copy against the person's real projects or MCP port, and never close or restart
their running PaperCraft. Give yours its own folder and port, and keep its PID so you can stop only
your own process:
```sh
PAPERCRAFT_HOME=/tmp/pc PAPERCRAFT_MCP_PORT=29998 ./target/release/papercraft
```
Do not stop processes by name.
## Layout
`src/model` (document), `src/editor` (tools and edits), `src/render` (wgpu), `src/mcp` (tools,
HTML/CSS mapping, lint), `src/ui` (egui panels), `src/io` (import and export), `src/project`
(store and formats), `tests/` (scenario tests), `specs/` (feature specs), `skills/` (agent
skills). The README's project layout lists the rest.
## Conventions
* Tests first; match the style of the tests next to yours, and check the behaviour is not already
covered.
* Changes to the document go through `Editor::edit`: one transaction, one undo step.
* Handle errors; do not `unwrap` user data and do not discard errors with `let _ =`.
* Comments explain *why*, never summarise the code. No dead code, debug prints or
commented-out blocks.
* Files stay under about 800 lines; split by feature.
* Reuse the shared UI kit and theme instead of one-off values. Nothing may overflow its container.
* Writes to projects are atomic and format changes ship a migration (see RULES.md, "Data safety").
* Adding or removing an MCP tool means a test in `tests/mcp.rs`, a precise description, and the
tool count updated in the README and ROADMAP.
* Commits are conventional (`feat(scope): summary`) and focused. Do not commit, push or tag unless
the person asked you to.
## Designing with PaperCraft (skills, examples, screenshots)
* Themes are modes, never copies: one artboard per screen, a value per mode on each variable, and
`set_variable_mode` to switch. Never duplicate artboards for light and dark.
* Every colour on a themed screen is a variable.
* Check each artboard for overflow, programmatically and by screenshot in each mode, and run
`lint_design`.
* Release design locks when you finish.
## Avoid
* Creative additions nobody asked for; stay inside the task.
* Trivial tests, wide or optional types added to appease the compiler, and swallowed errors.
* Editing generated files, lockfiles or release artifacts by hand, or touching files unrelated to
the task. Leave other people's uncommitted work alone.
+40
View File
@@ -0,0 +1,40 @@
# AI usage policy
PaperCraft is built to be driven by AI agents, and many of its contributors use them too. AI tools
are welcome here. What we ask is that a person stays accountable for everything submitted.
## For contributors
* **You own what you submit.** Read every line of your pull request before asking for review. If
you cannot explain what a change does and how it fits the rest of the system without asking an
AI, do not submit it yet.
* **Disclose meaningful AI help.** Say which tool you used and roughly how much it wrote in the
pull request description (for example "drafted with Claude Code, reviewed and tested by me").
Autocomplete and spell-checking do not need a note.
* **Write issues yourself.** An agent can help you research, but the report should be in your own
words, trimmed to what matters, with reproduction steps you ran. Long generated text that nobody
checked puts the burden on maintainers.
* **Think before you generate.** Agents jump to code and make their own job easy: trivial tests,
wide or optional types, swallowed errors, redundant comments, copied local patterns that do not
fit. Push back on all of it. [RULES.md](RULES.md) lists the standards to hold the output to.
* **Verify.** Run the checks in [CONTRIBUTING.md](CONTRIBUTING.md), use the app, and attach
screenshots for UI changes. "The agent said it works" is not a test result.
* **Answer automated review.** If a bot reviews your pull request, fix its findings or reply with
a one-line reason a finding does not apply.
* **No bulk or drive-by pull requests.** Many small generated changes across the tree, or changes
to something nobody asked for, will be closed. Open an issue first for anything beyond a small
fix.
Pull requests that clearly skip these steps may be closed without a detailed review. Repeated
low-effort submissions can lead to a block, under the [Code of Conduct](CODE_OF_CONDUCT.md).
## For coding agents
Read [AGENTS.md](AGENTS.md). It holds the commands, conventions and guardrails an agent working in
this repository should follow.
## Why
Every issue and pull request is read by a person. Review time is the scarce resource, and a change
nobody understood costs more than it saves. AI that is reviewed, tested and understood by the
person submitting it is a good way to build PaperCraft; AI used to skip that work is not.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+31
View File
@@ -0,0 +1,31 @@
# Code of Conduct
PaperCraft is built by people with different backgrounds and experience. We want everyone to be
able to contribute without harassment.
## Our standard
Be respectful and constructive. Assume good intent, give specific and kind feedback, and accept
it the same way. Disagree about the work, not the person.
Not acceptable:
* harassment, insults, slurs, or personal or political attacks;
* sexualised language or imagery, or unwelcome attention;
* threats, doxxing, or publishing someone's private information;
* sustained disruption of discussions, or pressure to merge or answer;
* anything else a reasonable person would consider inappropriate in a professional setting.
## Scope
This applies in issues, pull requests, discussions, commit messages and any space where someone
represents the project.
## Enforcement
Maintainers may edit or remove comments, close or lock threads, and block people who break these
rules. To report a problem, use GitHub's "Report content" on the comment, or contact a maintainer
through a private channel on their GitHub profile. Reports are handled privately and in good
faith, and retaliation against a reporter is itself a violation.
The spirit of this text follows the [Contributor Covenant](https://www.contributor-covenant.org).
+129
View File
@@ -0,0 +1,129 @@
# Contributing to PaperCraft
Thanks for wanting to help. PaperCraft is an alpha, so there is plenty to do and the bar for a
first contribution is low: a typo fix, a clearer error message, a missing test or a one-line bug
fix are all welcome.
Please read [RULES.md](RULES.md) before writing code: it holds the standards a change is judged by.
By taking part you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). Using an AI tool is fine;
the [AI usage policy](AI_POLICY.md) says what you stay responsible for, and coding agents should read
[AGENTS.md](AGENTS.md).
## Ways to help
* **Report a bug** or **suggest a feature** with an [issue](https://github.com/nxtime/papercraft/issues/new/choose).
A screenshot or a short recording helps; so does the project folder (or a page of it) that
triggers the bug.
* **Pick something from [ROADMAP.md](ROADMAP.md).** Rows marked `todo` or `partial` are open. Say
which one you are taking in an issue first, so two people do not build the same thing.
* **Improve the docs, skills or screenshots.** [docs/](docs), [skills/](skills) and the README are
as important as code.
* **Review a pull request.** A second pair of eyes is always useful.
Security problems do not go in public issues: see [SECURITY.md](SECURITY.md).
## Before you start
For anything bigger than a small fix, open an issue (or comment on one) describing the problem and
how you plan to solve it. Large features start as a short spec in [specs/](specs): a `spec.md`
(why, what, what is out of scope) and a `plan.md`. [specs/component-props](specs/component-props)
shows the shape. A spec agreed up front saves a rewrite later.
## Set up
You need Rust 1.95 or newer (`rust-version` in `Cargo.toml`) and the platform libraries listed in
the README's [Build from source](README.md#build-from-source).
```sh
git clone https://github.com/nxtime/papercraft
cd papercraft
cargo build --release
```
Run a test copy next to your own PaperCraft so it cannot touch your real projects or collide with
the running app's MCP port:
```sh
PAPERCRAFT_HOME=/tmp/pc PAPERCRAFT_MCP_PORT=29998 ./target/release/papercraft
```
`PAPERCRAFT_HOME` moves the project root and the config folder; `PAPERCRAFT_MCP_PORT` moves the
MCP server. Always set both when developing.
The code depends on [`craft-ui`](https://git.marcospaulo.dev.br/masi/craft-libs), which Cargo
fetches from a public git repository at the revision pinned in `Cargo.toml`.
## Make the change
1. Fork the repository and branch from `main` (`fix/short-name`, `feat/short-name`).
2. **Write the test first.** Fix a bug by adding a test that fails, then make it pass. See
[Tests](#tests).
3. Keep the change focused. One concern per pull request; unrelated cleanups go in their own.
4. Run the checks below and fix what they report.
5. Update the docs the change touches: the README, `docs/`, the tool description for an MCP tool,
the skills if agents should now behave differently.
6. Add a short entry to [PROGRESS.md](PROGRESS.md) for user-visible changes.
### Checks
```sh
cargo fmt --all
cargo clippy --all-targets
cargo test --test <target> # the targets your change touches
cargo check --lib --target wasm32-unknown-unknown # the web build
```
Each file in `tests/` is its own binary linking the whole app, so the full suite is slow and heavy
on a desktop. It runs on GitHub instead: before every release (`.github/workflows/test.yml`), or
on demand with `gh workflow run test.yml -f ref=<branch>`.
Keep the tree free of the third-party branding patterns listed in `.debrand`.
### Tests
* Unit tests sit next to the code in `#[cfg(test)]` modules.
* Scenario tests live in [tests/](tests). They drive the editor with synthetic pointer and
keyboard events; `tests/mcp.rs` covers every MCP tool on a headless session.
* Aim for **80% coverage** on code you add or change, including the error paths.
* GPU-dependent tests skip when no adapter exists. Set `PAPERCRAFT_REQUIRE_GPU=1` to make them
fail instead.
* `tests/update.rs` cannot run on Windows (it needs elevation); that failure is known and not
yours.
* For UI work, run the app, look at it, and attach a screenshot. Headless rendering needs no
display: `papercraft --screenshot ui.png --demo --size 1440x900 --scale 2`.
## Commits
[Conventional commits](https://www.conventionalcommits.org): `type(scope): summary`, with the
types `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `perf` and `ci`.
```
fix(ui): keep the review row's revert button off the hover edge
feat(mcp): add set_screens
docs(readme): add the demo video
```
Write the summary in the imperative, under about 72 characters, and use the body to say *why*.
Reference the issue (`Fixes #123`).
## Pull requests
* Fill in the template: what changed, why, how you tested it, screenshots for UI changes.
* Keep it reviewable. If it grows past a few hundred lines of non-generated code, split it.
* The branch must be up to date with `main`; rebase rather than merge.
* Expect review comments; they are about the code, not you. Push fixes as new commits and we
squash on merge.
* A maintainer merges once a review is approved.
## Releases
Maintainers cut releases. A `v*` tag pushed to GitHub builds Windows, macOS and Linux and
publishes them (`.github/workflows/release.yml`). Contributors do not need to bump versions.
## Licensing
PaperCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE). Unless you
state otherwise, anything you submit is licensed under the same terms, with no extra conditions.
Only submit work you wrote or have the right to submit. Code ported from another project needs a
compatible license and an entry in [THIRD_PARTY.md](THIRD_PARTY.md); bundled assets go in
[ATTRIBUTION.md](ATTRIBUTION.md).
Generated
+3 -2
View File
@@ -784,7 +784,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://git.marcospaulo.dev.br/masi/craft-libs?rev=22544b6d619d4f16779b8bdfa3f0b642a86fc065#22544b6d619d4f16779b8bdfa3f0b642a86fc065"
source = "git+https://git.marcospaulo.dev.br/masi/craft-libs?rev=9c470aa935c4ce48f2ba4f0a17f9410c0c8660fb#9c470aa935c4ce48f2ba4f0a17f9410c0c8660fb"
dependencies = [
"egui",
]
@@ -3128,7 +3128,7 @@ dependencies = [
[[package]]
name = "papercraft"
version = "0.8.0"
version = "0.9.1"
dependencies = [
"arboard",
"axum",
@@ -3175,6 +3175,7 @@ dependencies = [
"web-sys",
"web-time",
"wgpu",
"windows-sys 0.61.2",
"winit",
"winresource",
"zstd",
+6 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "papercraft"
version = "0.8.0"
version = "0.9.1"
edition = "2024"
rust-version = "1.95"
description = "A native infinite-canvas app for planning, working and sketching"
@@ -44,7 +44,7 @@ env_logger = "0.11"
rfd = "0.17"
fastrand = "2"
dirs = "6"
craft-ui = { version = "0.1.0", git = "https://git.marcospaulo.dev.br/masi/craft-libs", rev = "22544b6d619d4f16779b8bdfa3f0b642a86fc065" }
craft-ui = { version = "0.1.0", git = "https://git.marcospaulo.dev.br/masi/craft-libs", rev = "9c470aa935c4ce48f2ba4f0a17f9410c0c8660fb" }
i_overlay = "9.0.1"
miniz_oxide = "0.9.1"
usvg = "0.48"
@@ -101,6 +101,10 @@ libc = "0.2"
zstd = "0.13"
# Browser build (`src/web.rs`): canvas + WebGPU/WebGL surface, DOM events instead of winit.
# Process RAM and CPU readings for the performance overlay (`ui::perf`).
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_ProcessStatus", "Win32_System_Threading"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wgpu = { version = "30", features = ["webgl"] }
wasm-bindgen = "0.2"
+55
View File
@@ -76,6 +76,50 @@ are credited in `THIRD_PARTY.md`.
* **Not carried over**: comments, design tokens, AI image generation, video export, teams;
moving layers between pages; remote image URLs (see README Known gaps).
### 2026-10-28: overflow lint rule and `get_bounds`
* `lint_design` has an `overflow` rule (`src/mcp/lint_overflow.rs`): layers past their artboard or clipping parent, and text taller than its box. Scrolling frames and what is pinned in them are exempt; it is never auto-fixed. It is a pure function over a node set, so a scope filter can pass any subset.
* New tool `get_bounds {nodeIds?, pageId?, depth?}` (`src/mcp/bounds.rs`): every layer's rect in one read (about 2000 rows per call, then `continueWith`). Tool count is now 87 (one more than before; if another branch also adds a tool, recount). Tests: `tests/mcp_bounds.rs`.
### 2026-10-28: agent reads no longer look like edits
* Read-only tool calls (`get_node_info`, `get_children`, ...) have honest verbs ("Looking at the design") and light the "Working" pill for 1.5 s instead of 6 s, so it goes out right after a sweep ends.
* A sweep of reads draws at most one layer outline (a read outlines only when no other read ran in the last 2 s) and no longer pans the follow-agent camera; edits behave as before. "Is this a read" comes from `mcp::tools::edits_doc`.
### 2026-10-28: 0.9.0 (presentations, critique, several agents, lighter chats)
* Export the screens as a presentation PDF: cover, contents and a slide per screen (File menu, palette, `--format presentation`, `export_presentation`).
* `critique_design` reviews finished work through personas (vision, UX, flow, QA, visual, accessibility, copy, end-user); `design_lessons` keeps the findings the person approved for every later design.
* Several agents on one project: named CLI agents (`--as`), conflict reports and `ifRev` on writes, `claim_nodes` / `release_claims` / `list_claims`, scoped delegate builds and per-agent undo. 94 tools.
* Screens keep their device height and scroll what does not fit; sections group screens on the canvas; pages can carry icons.
* UI kits for shadcn, MUI, Mantine, Bootstrap and Chakra; `write_html` follows the browser more closely.
* Memory: chat screenshots move to files (kept 14 days), thumbnails stay small, canvas images decode only for the GPU. A long chat dropped from about 1 GB to about 400 MB.
* Fix: long answer options in a question card wrap instead of widening the whole chat.
### 2026-10-28: 0.8.4 (demo video, fresh screenshots)
* README opens with a time-lapse of designing a habit-tracker app (`docs/demo.gif`, full video `docs/demo.mp4`), and every screenshot is retaken from that design.
* Fix: the Performance overlay reads its settings from the project config folder, so `PAPERCRAFT_HOME` isolates it too.
### 2026-10-28: 0.8.3 (menus, panel grips, narrow windows)
* Menus open 6 px below their button, are at least 180 px wide and show an icon beside each item. Below 1100 px the hamburger opens every menu in one popup.
* Side panels: a slim rounded grip in the gap resizes them (double click resets) and `/` hides or shows both. Panels size to their content and step aside when the window is too narrow for the canvas.
* Sharper window buttons (pixel-snapped glyphs); the hamburger morphs into a back arrow while the File / Edit strip slides open and shut.
* Fixes: lint Fix buttons no longer cover the issue text; review rows keep their badge and revert button off the hover edge; the Export button stays on one line.
### 2026-10-28: 0.8.2 (refresh-rate cap, accurate RAM/CPU, toolbar)
* Settings > Performance > Refresh rate is now a real frame cap applied live (30 to 360 Hz, 60 by default); **Auto** draws as fast as the display allows and is the default on macOS.
* Performance Monitor: RAM is the private working set and CPU is divided by logical cores on Windows, so both match Task Manager.
* Windows and Linux toolbar: a hamburger button shows or hides the File / Edit strip (remembered); the close button uses the theme's danger colour on the acrylic surface, with hover animation and a pointing-hand cursor.
### 2026-10-28: 0.8.1 (Performance Monitor on Windows, Design tab speed)
* Performance Monitor: RAM (working set) and CPU now show on Windows; before they were `n/a` there. The overlay and slow-frame badge judge frames against a refresh rate you pick in Settings > Performance: 30 to 360 Hz (144, 165 and 240 included), 60 by default.
* Design tab: the lint and the open-feedback scan are kept until the document changes instead of walking every node each frame; a 12.6k-node page no longer drops to a few FPS while the tab is open.
* Windows and Linux: window buttons in the toolbar; controls and acrylic come from craft-ui.
### 2026-10-27: 0.8.0 (screens, packed pages, canvas performance)
* Screens (`specs/screens`): a frame can be declared a screen or an overlay (drawer, modal, sheet) with `set_screens`, inspector toggles, or Declare N screens on the page. Agent edits to layers hidden behind an overlay or opaque layer in their screen are refused unless `allowHidden`; partly covered ones are reported with their visible share. `get_basic_info` lists screens, `get_node_info` tells a layer's visibility, `lint_design` skips hidden layers, On click lists screens, nested screens get canvas labels.
@@ -207,6 +251,17 @@ are credited in `THIRD_PARTY.md`.
* Agent view lists runs and supports review, whole-run revert, per-change undo and accept all. Review adds canvas outlines and a finish toast; palette commands review or revert the last run.
* Id-paired page diffs power review; History version compare UI remains todo. Completed with full restore (including variables, modes and tokens), tool edit classification, and wasm support.
### 2026-10-28: Incremental lint
Agents re-linted whole pages after every edit. A bounded change log (`src/editor/changes.rs`, the
last 10000 layer changes, each with the client that made it) now records which layers every
commit, undo and redo touched; variable edits count as touching the layers bound to them. Write
tools return `rev`, `get_basic_info` reports it, `get_changes {since, page?, exclude?, by?}` lists
the changes, and `lint_design {since | changedOnly}` checks only those layers plus their
ancestors, descendants and siblings (`src/mcp/incremental.rs`), with `covered` saying what ran.
Tests: `tests/incremental.rs`, unit tests next to the code, the attribution check in
`tests/mcp.rs::parallel_sessions_get_their_own_runs`.
### 2026-10-21: Design libraries and offline CLI
* Variables are now collections with modes, slash groups, four types and aliases, stored in `design.json` (project version 2; 0.4.0 refuses migrated projects). Each page keeps a derived cache; every edit is one undo step per page, and the page-only removals are gone. Per-page active mode per collection.
+59 -18
View File
@@ -12,9 +12,17 @@
</p>
<p align="center">
<img src="docs/screenshots/readme/hero.png" alt="PaperCraft with the Redesign page of its own design file open: layers on the left, the canvas in the middle, the inspector on the right" width="100%">
<a href="docs/demo.mp4">
<img src="docs/demo.gif" alt="PaperCraft's editor breaking apart into its panels on a 3D stage, then chat mode with an agent, annotations pinned to a sign-in screen, the variables and libraries modals, and the home screen" width="100%">
</a>
<br>
<sub>PaperCraft editing its own design file (the Redesign page).</sub>
<sub>A 40-second tour: the editor, chat mode, annotations and design systems. <a href="docs/demo.mp4">Watch it in full quality</a> (MP4, 1080p60). Rendered from the app's own design with <a href="tools/showcase/README.md">tools/showcase</a>, not screen-recorded.</sub>
</p>
<p align="center">
<img src="docs/screenshots/readme/hero.png" alt="PaperCraft with the Pulse habit-tracker design open: layers on the left, three annotated screens on the canvas, the inspector on the right" width="100%">
<br>
<sub>The finished design: three screens, a component library and annotations.</sub>
</p>
<p align="center">
@@ -25,6 +33,7 @@
<a href="#keyboard-shortcuts">Shortcuts</a> ·
<a href="#status-and-known-limits">Status</a> ·
<a href="#project-layout">Layout</a> ·
<a href="#contributing">Contributing</a> ·
<a href="#license-and-credits">License</a>
</p>
@@ -54,11 +63,11 @@ It is an alpha. It is good for building screens, design systems and sketches, an
<table>
<tr>
<td width="50%" valign="top">
<img src="docs/screenshots/readme/variables.png" alt="The Variables modal listing the Colors collection with four Catppuccin modes" width="100%">
<br><sub>Variables modal: collections, modes, groups and types.</sub>
<img src="docs/screenshots/readme/variables.png" alt="The Variables modal listing the Colors collection with Light and Dark values for brand, foreground and background" width="100%">
<br><sub>Variables modal: collections, modes (Light and Dark here), groups and types.</sub>
</td>
<td width="50%" valign="top">
<img src="docs/screenshots/readme/assets.png" alt="The Assets side view with components grouped into Banner, Button, Checkbox and Chip" width="100%">
<img src="docs/screenshots/readme/assets.png" alt="The Assets side view with the Habit row component and the shadcn Button kit" width="100%">
<br><sub>Assets view: components grouped by name, from this file and enabled libraries.</sub>
</td>
</tr>
@@ -68,12 +77,32 @@ It is an alpha. It is good for building screens, design systems and sketches, an
<br><sub>Libraries modal: publish this file, enable libraries from the store.</sub>
</td>
<td width="50%" valign="top">
<img src="docs/screenshots/readme/agent-review.png" alt="Agent run review: a list of changes on the left and green, yellow and red outlines on the canvas" width="100%">
<br><sub>Review of an agent run, with the changes outlined on the canvas.</sub>
<img src="docs/screenshots/readme/agent-review.png" alt="The Agent side view: a finished run with Review and Revert, above the list of earlier runs" width="100%">
<br><sub>The Agent view: runs, with Review and Revert for the latest.</sub>
</td>
</tr>
</table>
<table>
<tr>
<td width="50%" valign="top">
<img src="docs/screenshots/readme/toolbar-panels.png" alt="The toolbar with the menu button folded into a back arrow, the File to Theme strip, and the floating left panel with a slim grip beside it" width="100%">
<br><sub>Toolbar and panels: the menu button shows or hides the File / Edit strip, and the slim grip between a panel and the canvas resizes it (double click resets). <kbd>/</kbd> hides both side panels.</sub>
</td>
<td width="50%" valign="top">
<img src="docs/screenshots/readme/menus.png" alt="The Tools menu open below its button, each tool with an icon and its shortcut" width="100%">
<br><sub>Menus open a little below their button, are never narrower than 180 px, and carry an icon next to each item.</sub>
</td>
</tr>
<tr>
<td width="50%" valign="top">
<img src="docs/screenshots/readme/annotations.png" alt="The Annotations side view listing five notes grouped by screen, with their category chips" width="100%">
<br><sub>Annotations: rule, behaviour, content and data notes, kept with the layers they describe.</sub>
</td>
<td width="50%" valign="top"></td>
</tr>
</table>
**Prototyping and review**
* Prototype links between frames and a **Present** mode that follows them with a camera glide.
* **Version history:** named and automatic saved versions per page; rename, restore, delete.
@@ -90,11 +119,11 @@ Projects live in `~/Documents/papercraft/<name>/` (`project.json`, one JSON file
## Agents
PaperCraft exposes **70 tools** (`src/mcp/tools.rs`) three ways. They run the same code inside the app.
PaperCraft exposes **98 tools** (`src/mcp/tools.rs`) three ways. They run the same code inside the app.
| Way | Notes |
|---|---|
| MCP over HTTP | Built into the app: `http://127.0.0.1:29980/mcp`. Loopback only; browser requests (with an `Origin` header) and foreign `Host` headers are rejected. `PAPERCRAFT_MCP_PORT` changes the port, `PAPERCRAFT_MCP=0` turns it off. |
| MCP over HTTP | Built into the app: `http://127.0.0.1:29980/mcp`. Loopback only; browser requests (with an `Origin` header) and foreign `Host` headers are rejected. `?tools=core` lists 33 common tools in full plus `search_tools` and `call_tool`, which reach the rest (about a third of the schema size); lean chat agents use it. `PAPERCRAFT_MCP_PORT` changes the port, `PAPERCRAFT_MCP=0` turns it off. |
| MCP over stdio | `papercraft-mcp` relays stdio to the running app. It lists tools even when the app is closed. |
| Shell | `papercraft-cli` calls the same tools, so an agent with a terminal needs no schemas in its context. |
@@ -138,10 +167,10 @@ EOF
### Chat
Chat mode (⌘J, or `Design | Chat` in the top bar) puts a conversation next to the canvas. It runs Claude Code and Codex through their CLIs, any agent that speaks the Agent Client Protocol (ACP, such as OpenCode, Gemini CLI or Cursor) found on your PATH, or the Anthropic API with your own key. It shows tool calls, checkpoints and run review in the thread. Chats are saved in the project's `chats/` folder. See [docs/chat.md](docs/chat.md).
Chat mode (⌘J, or `Design | Chat` in the top bar) puts a conversation next to the canvas. It runs Claude Code and Codex through their CLIs, any agent that speaks the Agent Client Protocol (ACP, such as OpenCode, Cursor or Goose) found on your PATH, or the Anthropic API with your own key. It shows tool calls, checkpoints and run review in the thread. Chats are saved in the project's `chats/` folder. See [docs/chat.md](docs/chat.md).
<p align="center">
<img src="docs/screenshots/readme/chat.png" alt="Chat mode: the chat column on the left shows a finished agent run with its Review, Revert and Accept actions, and the canvas on the right" width="100%">
<img src="docs/screenshots/readme/chat.png" alt="Chat mode: the chat column on the left with its starter prompts and input, and the annotated habit-tracker screens on the canvas" width="100%">
<br>
<sub>Chat mode with a finished agent run: review, revert or accept from the thread.</sub>
</p>
@@ -162,12 +191,13 @@ Releases are at [git.marcospaulo.dev.br/masi/papercraft/releases](https://git.ma
| Build | File |
|---|---|
| Windows (x86_64) | `papercraft-<version>-windows-x86_64.zip`: `papercraft.exe`, `papercraft-cli.exe`, `papercraft-mcp.exe` and `papercraft-relay.exe` |
| macOS app (Apple silicon) | `papercraft-<version>-macos-aarch64.dmg`, containing PaperCraft.app |
| Linux (x86_64) | `papercraft-<version>-linux-x86_64.tar.gz` |
| CLI tools, macOS | `papercraft-cli-<version>-macos-aarch64.zip` (`papercraft-cli` and `papercraft-mcp`) |
| CLI tools, Linux | `papercraft-cli-<version>-linux-x86_64.tar.gz` |
macOS builds are ad-hoc signed and not notarized: on another Mac, open the app with right-click, Open the first time. Other platforms: build from source.
The Windows zip is unsigned: SmartScreen may ask you to confirm the first run. macOS builds are ad-hoc signed and not notarized: on another Mac, open the app with right-click, Open the first time. Other platforms: build from source.
### Build from source
@@ -179,9 +209,10 @@ cargo build --release
./target/release/papercraft ~/Documents/papercraft/Plan # open a project folder
./target/release/papercraft --demo # sample board, not saved
packaging/macos/package.sh # PaperCraft.app on a DMG, plus the CLI zip
pwsh packaging/windows/package.ps1 -Arch x64 # Windows MSI, portable zip and CLI zip
```
**macOS:** `xcode-select --install` for the linker. It renders with Metal through wgpu. **Linux:** install the runtime libraries (`sudo apt install libxkbcommon-x11-0 libxcb-xkb1 libvulkan1 mesa-vulkan-drivers` on Debian or Ubuntu); it runs on X11 and Wayland through Vulkan, with GL as a fallback, and file dialogs use the XDG desktop portal.
**Windows:** the MSVC build tools (Visual Studio Build Tools with the C++ workload); it renders through wgpu on Direct3D 12 or Vulkan. **macOS:** `xcode-select --install` for the linker. It renders with Metal through wgpu. **Linux:** install the runtime libraries (`sudo apt install libxkbcommon-x11-0 libxcb-xkb1 libvulkan1 mesa-vulkan-drivers` on Debian or Ubuntu); it runs on X11 and Wayland through Vulkan, with GL as a fallback, and file dialogs use the XDG desktop portal.
To run a test copy next to your own PaperCraft, give it its own folder and port: `PAPERCRAFT_HOME=/tmp/pc PAPERCRAFT_MCP_PORT=29998 ./target/release/papercraft`.
@@ -228,24 +259,32 @@ The scenario tests drive the editor with synthetic pointer and keyboard events;
| PageUp / PageDown | Previous / next page | ⌘\\ | Show / hide UI |
| ⌘J | Design / Chat mode | ⌘L | Add selection to chat (Chat mode) |
| N | Annotate tool | ⌘⇧A | Annotations: full, badges, hidden |
| / | Show / hide the side panels | | |
Draw a frame around existing shapes and it adopts them; dragging a layer into or out of a frame re-parents it. Hold ⌘ while dragging to suspend snapping.
## Status and known limits
> [!IMPORTANT]
> PaperCraft is an alpha. [ROADMAP.md](ROADMAP.md) lists what is missing, in priority order; [PROGRESS.md](PROGRESS.md) is the milestone history.
> PaperCraft is an alpha (0.8.x). It is used daily on Windows, macOS and Linux, and its project format migrates forward, but expect rough edges. [ROADMAP.md](ROADMAP.md) lists what is missing, in priority order; [PROGRESS.md](PROGRESS.md) is the milestone history.
**What works today:** local projects with pages and an infinite canvas; vector, text, auto layout, constraints, components with properties and variants, variables with modes, shared libraries and screens; annotations, lint and Present mode with prototype links; PNG, SVG and PDF export, Figma, Excalidraw and SVG import; the MCP server, CLI (online and offline) and in-app Chat mode; versions, agent runs with review and revert; optional relay sync.
**Known limits:**
* **No rotation.** Nodes are axis-aligned boxes; rotated imports are baked into paths.
* **Text** is Inter only, with no shaping (no ligatures, complex scripts or RTL) and no font picker. IME preedit is not displayed.
* **Rendering approximations.** Frame clipping is a rectangle, so rounded frames do not clip their corners. Overlay, dodge, burn, light, difference, exclusion and the HSL blend modes draw as Normal on the canvas (they are exact in SVG and PDF export). There is no layer or background blur yet.
* **Variables:** gradients keep fixed colors; there are no text styles and no component variants or properties.
* **Variables:** gradients keep fixed colors, and there are no text styles (named type styles that update every text layer).
* **Components:** properties (text, bool, icon, enum) and `merge_variants` cover variants, but there are no variant sets with several axes, and no responsive per-breakpoint variants or breakpoint preview.
* **Prototyping:** links and flows work in Present mode; smart transitions and hover states do not exist yet.
* **Booleans are destructive:** the result is a new vector path with flattened curves.
* **`write_html`** ignores margin, tables and transforms (it reports them as `ignoredStyles`) and does not fetch remote images; pass a local path or a `data:` URI.
* **Agents:** one project is open at a time in the app, and `move_nodes` stays on one page. The in-app Chat mode runs Claude Code, Codex, ACP agents or your own Anthropic key. Agents that are not in Chat connect over MCP or the CLI.
* **Sharing** has no live presence (cursors, selections) yet.
* **Scale:** cached frames take about 3 ms at 10k visible nodes; it is not tuned for 100k.
* **Pen pressure** is simulated from stroke velocity on macOS tablets, because winit 0.30 does not expose it for mouse-like pen events.
* **Releases** cover macOS (Apple silicon) and Linux x86_64. Windows packaging scripts exist but are not part of releases.
* **Releases:** the Gitea releases ship Windows x86_64. macOS (Apple silicon) and Linux x86_64 builds come from the packaging scripts or from source; the Linux build is not part of the current releases.
* **PDF** text is outlined, not selectable.
## Project layout
@@ -280,12 +319,14 @@ analysis/ behaviour studies and design notes
docs/ guides and screenshots
```
## Contributing
Bug reports, ideas, docs and code are welcome. Start with [CONTRIBUTING.md](CONTRIBUTING.md) (setup, checks, commits, pull requests) and [RULES.md](RULES.md) (the standards a change is reviewed against). AI tools are welcome under the [AI usage policy](AI_POLICY.md), and coding agents should read [AGENTS.md](AGENTS.md). Security problems go through [SECURITY.md](SECURITY.md), and everyone follows the [Code of Conduct](CODE_OF_CONDUCT.md).
## License and credits
Dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
Bundled fonts, icons and other assets keep their own licenses, listed in [ATTRIBUTION.md](ATTRIBUTION.md); Inter is © The Inter Project Authors under the SIL Open Font License 1.1. Some algorithms are ported from MIT-licensed projects (rough.js, hachure-fill, Excalidraw), with their notices in [THIRD_PARTY.md](THIRD_PARTY.md).
PaperCraft started as a fork of [storytold/paper-rs](https://git.marcospaulo.dev.br/storytold/paper-rs); thanks to its contributors.
PaperCraft is not affiliated with Paper or Figma. Only the behavior of other tools was studied (see `analysis/`); no code, shaders, icons, fonts or assets from them are used.
+5 -4
View File
@@ -22,7 +22,7 @@ Agents can already build a design system through the tools; people cannot yet ma
| 7 | Number variables (spacing, radius, font size) | **done** | Typed number, string and boolean variables in collections with groups and aliases; fields bind (size, gap, padding, radius, font size, line height, opacity, visible) in the inspector and `bind_variable`. |
| 8 | Stroke and gradient variables | partial | Strokes and text color bind to variables. Gradients keep fixed colors. |
| 9 | Text styles | todo | Named type styles (Heading / L, Body / M) that update every text layer using them. |
| 10 | Component variants and properties | todo | Variants are separate components named `Button / Primary`. No variant sets, boolean or text properties. |
| 10 | Component variants and properties | partial | Main components carry text, bool, icon and enum properties; `merge_variants` folds per-state components into one. Multi-axis variant sets todo. |
| 11 | Swap instance, detach by tool | **done** | `swap_instance` and `detach_instance` MCP tools + UI controls in Design tab and Inspector. |
| 12 | Cross-page and shared libraries | **done** | Instances of a main on any page; publish a project as a library, enable, update and disable it in other projects (Libraries modal, `*_library` tools). |
| 13 | Export design tokens | **done** | `get_variables` with `format: "css"`, `"json"` (W3C DTCG + modes), or `"tailwind"` (`@theme`), plus Copy CSS / Copy JSON in Design tab. |
@@ -32,7 +32,7 @@ Agents can already build a design system through the tools; people cannot yet ma
| # | Item | Status | Notes |
|---|---|---|---|
| 15 | MCP and CLI tool surface | **done** | 67 tools, one undo step per call, `papercraft-cli list / schema / call`. |
| 15 | MCP and CLI tool surface | **done** | 98 tools, one undo step per call, `papercraft-cli list / schema / call`. |
| 16 | Agent skills | **done** | `skills/papercraft` and `skills/papercraft-design`. |
| 17 | Accessibility annotations | todo | Reading order, roles and alt text on layers, checked by the linter. |
| 18 | Code export from frames | **done** | `get_jsx` supports `format: "inline"`, `"tailwind"` (Tailwind utility classes), and `"html"` (HTML + CSS rules with `:root` variables). |
@@ -63,7 +63,7 @@ Agents can already build a design system through the tools; people cannot yet ma
| 32 | Version history | **done** | Named and automatic saved versions per page: rename, restore, delete (`src/versions.rs`). Restore now includes variables and tokens; compare todo. |
| 33 | Figma import | **done** | `.fig` binary (Kiwi wire decoder + zip container) and Figma REST API JSON import in `src/io/fig.rs`. |
| 34 | Multiplayer and cloud sync | partial | Optional shared projects through the relay, with merge of concurrent edits to one page. Presence (cursors, selections) todo. Stays optional. |
| 35 | Release builds for Windows and Linux | todo | The code targets them (wgpu, winit); packaging today is the macOS DMG and the `papercraft-cli` zip. |
| 35 | Release builds for Windows and Linux | partial | Windows x86_64 zips are released and `packaging/windows` builds an MSI; Linux x86_64 is not in the current releases. |
## 5. Quality
@@ -92,4 +92,5 @@ Spec: [specs/agent-runs/spec.md](specs/agent-runs/spec.md), tasks: [specs/agent-
| # | Item | Status | Notes |
|---|---|---|---|
| 47 | Design annotations | **done** | Notes with leader lines and categories, templates per project and page, view modes (⌘⇧A), Annotate tool (N), side view, inspector section, six MCP tools; see `docs/annotations.md`. |
| 48 | ACP agents in Chat | **done** | Any ACP agent on the PATH (OpenCode works; Gemini CLI refuses ACP clients for now; Cursor needs `cursor-agent login`), npx agents after enabling, custom agents; see `docs/chat.md`. |
| 48 | ACP agents in Chat | **done** | Any ACP agent on the PATH (OpenCode works; Cursor needs `cursor-agent login`), npx agents after enabling, custom agents; see `docs/chat.md`. |
| 48b | Free agents | **done** | OpenCode and Pi on free models with `Free (auto)` rotation, Pi provider keys, an install dialog per OS; see `specs/free-agents`. |
+124
View File
@@ -0,0 +1,124 @@
# Project rules
The standards a change to PaperCraft is reviewed against. [CONTRIBUTING.md](CONTRIBUTING.md) says
*how* to contribute; this file says what "good" means once you do.
## Code
* **Immutability by default.** Return new values rather than mutating shared ones. The document
changes only through `Editor::edit` transactions, so every change is one undo step and is
logged for the renderer's cache.
* **Small, cohesive files.** 200 to 400 lines is typical, 800 is the ceiling. Split a module
when it grows past that. Organise by feature, not by type.
* **Small functions** (under about 50 lines) and **shallow nesting** (4 levels at most); prefer
early returns.
* **Handle errors explicitly.** No `unwrap` or `expect` on user data, file contents or network
responses; return an error with context. User-facing messages are plain language. Never swallow
an error silently.
* **Validate at the boundaries**: MCP and CLI arguments, imported files (Figma, Excalidraw, SVG),
project folders and anything from the relay. Treat all of it as untrusted.
* **No magic numbers.** Name thresholds, sizes and delays as constants; UI measures come from
the theme, not literals.
* **No dead code, debug prints or commented-out blocks.**
* **Match the surrounding code**: naming, comment density and idiom. Comments say *why*, not
*what*.
* **Cross-platform.** Code must build on Windows, macOS and Linux and for the web build. Gate
platform code with `cfg`, never assume a path separator, and keep
`cargo check --lib --target wasm32-unknown-unknown` passing.
* **No new heavy dependencies** without discussion. Licenses must be compatible with
MIT OR Apache-2.0.
## Data safety
PaperCraft stores people's work. Treat that as the top priority.
* Writes to projects are **atomic** (`src/io/atomic.rs`); never write a page in place.
* A format change bumps the project format version and ships a **migration**. Older data must
keep loading; if a newer build writes something an older build cannot read, the older build
must refuse it rather than corrupt it.
* Agent and sync paths must never silently drop a layer. If a merge cannot keep something, it
says so.
* Destructive operations are undoable or confirmed.
## The machine you build on
A full build links dozens of test binaries and can take every core and most of the memory of a
desktop. The person is still using that machine, often with PaperCraft open.
* **Look before you start a heavy job.** Check free memory, CPU load and what is already running
(the person's app, another build, other agents) before a build, a test run or clippy. If memory
is short or another build is running, wait or ask.
* **Leave room.** Cap Cargo at no more than half the logical cores (`-j 8` on a 16-core machine,
or `CARGO_BUILD_JOBS`) and the test harness too (`-- --test-threads=8`); go lower when memory is
tight, since linking is the peak. Run heavy jobs at low priority (`nice` on Unix, Below Normal
on Windows).
* **One heavy job at a time.** Never run two builds side by side; each target folder is a full
build's worth of compiling and linking. Parallel agents share one build slot.
* **Run only what your change touches**: `cargo check` before `cargo build`, and the test
targets that cover the change (`cargo test --test incremental`). The full suite runs on GitHub
before a release (`.github/workflows/test.yml`), not on a desktop.
* **Stop at once when the person says the machine is slow**, then check that no compiler, linker
or test process of yours is left over.
* **Clean up.** Delete scratch target folders and worktrees when the work is merged; they grow to
tens of gigabytes.
## UI
* **Use the shared kit.** Controls, spacing, radii and colours come from `craft-ui`,
`src/ui/kit.rs` and the theme, not one-off values.
* **Themes are modes.** Never branch on a theme to pick a colour; read it from the palette.
* **Nothing overflows.** Text truncates with an ellipsis, rows keep their controls inside, and
panels step aside when the window is narrow. Test a narrow window and a long name.
* **Targets are at least 44 px** where a person taps or clicks something primary, and everything
stays reachable from the keyboard.
* **Animation is quick**: eased and under about 200 ms.
* **Look at it.** Run the app or take a headless screenshot at scale 2 in each theme before
asking for review.
## MCP tools and the CLI
* Every tool has a precise one-paragraph description, a JSON schema, and a test in
`tests/mcp.rs`. Descriptions are what agents read; write them for that reader.
* One tool call is **one undo step**.
* Names follow the existing style (`verb_noun`); reuse Paper-compatible names and argument shapes
where a tool has an equivalent.
* Reads are cheap and bounded. Apply limits, say when you truncated, and never dump the whole
document by default.
* The server listens on `127.0.0.1` only and rejects browser origins. Do not weaken that.
* Update the tool count in the README and ROADMAP when you add or remove tools.
## Designs made with PaperCraft
These apply to example projects, templates, screenshots and skill content, and are what the
skills teach agents.
* **Themes are modes, never copies.** One artboard per screen. Give each variable a value per
mode and switch with `set_variable_mode`. Do not duplicate artboards as light and dark
versions, and do not rebuild a screen with other hex values.
* **Every colour on a themed screen is a variable** (`var(--name)` on fills and text,
`bind_variable` for strokes, opacity and visibility).
* **No overflow.** Nothing extends past its artboard or clipping parent. Scrolling content is
clipped inside its viewport and ends above floating bars with a fade and enough bottom padding.
Check each artboard programmatically *and* by screenshot in each mode.
* Run `lint_design` and fix what it finds: contrast, the 4 px grid, type scale and 44 px targets.
* Release design locks when you are done so the next person can inspect.
## Skills and docs
* Skills in [skills/](skills) are instructions for agents: keep them short, concrete and tested
against a real agent run.
* Docs describe what exists. Do not document a feature that is not built; put plans in `specs/`
and `ROADMAP.md`.
* Screenshots come from the real app, in a generic project (no personal data, local paths or
real names), at scale 2.
## Branding
The tree carries no third-party product branding; `.debrand` lists the forbidden patterns and
the check runs in review. Describe PaperCraft on its own terms.
## Review
A pull request is approved when it has no unresolved **critical** (security, data loss) or
**high** (bug, significant quality) issues. Medium and low comments are suggestions the author
may take or decline with a reason.
+29
View File
@@ -0,0 +1,29 @@
# Security policy
## Supported versions
PaperCraft is an alpha. Security fixes go into the latest release and `main`.
## Reporting a vulnerability
**Do not open a public issue.** Use GitHub's private reporting: the repository's **Security** tab,
then **Report a vulnerability**. Include what you found, how to reproduce it, the version and
platform, and the impact you see.
A maintainer will acknowledge the report as soon as they can and keep you updated until it is
fixed. Please give us reasonable time to ship a fix before you disclose it.
## What counts
Examples of in-scope problems:
* the MCP server (`127.0.0.1:29980`) or the relay accepting requests it should reject (browser
origins, DNS rebinding, another user);
* path traversal or code execution from a project folder, a design-system or library package, or
an imported Figma, Excalidraw or SVG file;
* the updater or the agent integrations running something the person did not approve;
* secrets (an Anthropic key, relay tokens) written to disk unprotected or sent anywhere
unexpected.
PaperCraft is local-first: it opens no network port beyond the loopback MCP server unless you
share a project through a relay you run.
-1
View File
@@ -1 +0,0 @@
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Gemini</title><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z"></path></svg>

Before

Width:  |  Height:  |  Size: 651 B

+13 -1
View File
@@ -1,6 +1,6 @@
# Driving PaperCraft with agents
PaperCraft exposes one set of 70 tools three ways. They all run the same code inside the app, so an agent sees what you see and every call is one undo step.
PaperCraft exposes one set of 88 tools three ways. They all run the same code inside the app, so an agent sees what you see and every call is one undo step.
| Way | Use it when | Needs the app running |
|---|---|---|
@@ -108,6 +108,18 @@ write_html {
EOF
```
## Checking only what changed
On a big page a full `lint_design` after every edit repeats the same output, and a `get_node_info` call per layer is slow (about 53 s for 397 layers). Check the change, then check everything once.
* Every write tool result includes `rev`, the document revision after the call. `get_basic_info` reports the current `rev`. Reads never change it.
* `get_changes {since, page?}` returns `{rev, since, truncated, changes: [{page, ids}]}`: what the edits since `since` touched. `truncated: true` means the log no longer reaches that far back, so do a full pass.
* `lint_design {changedOnly: true}` lints since this client's last lint; `{since: rev}` lints since a revision you name. A scoped lint checks the touched layers plus their ancestors, descendants, siblings and every layer bound to a changed variable, and reports its coverage in `covered`, for example `{checked: 12, total: 397, since: 40, partial: true}`. Plain `lint_design` is a full pass (`partial: false`). The `overflow` rule flags a layer that extends past its parent or clipping artboard (scroll frames are excluded).
* `get_bounds {nodeIds?, pageId?, depth?}` returns `columns` `[id, parent, x, y, w, h, absX, absY, clip]` and one row per layer for a subtree in one call (at most 2000 rows; then `truncated` and `continueWith`, the nodeIds for the next call). Use it instead of looping `get_node_info`.
* Always finish with one full `lint_design` (no arguments) and a screenshot per artboard in each theme mode before reporting. A partial lint speeds up the loop; it does not replace that pass.
In the app, read-only calls no longer draw per-layer outlines or keep the "Working" pill lit for long. The agent workflow, with an example, is in [incremental-checks.md](../skills/papercraft/references/incremental-checks.md).
## Design-system tools
* Variables: `get_variables` and `set_variables` take collections, groups (`color/brand/primary`), types (`color`, `number`, `string`, `boolean`), `mode`, `alias`, `description` and `hidden`; the old `{"name":"#hex"}` call still works and lands in the first collection. `create_collection` makes a collection with modes, `delete_variables` removes by name (refuses aliased ones unless `force`), `bind_variable` binds or detaches a field of layers (`stroke`, `text-color`, `width`, `height`, `gap`, `padding`, `radius`, `font-size`, `line-height`, `opacity`, `visible`).
+5 -4
View File
@@ -18,15 +18,16 @@ Chat drives the same tools as an agent connected over MCP, so the edits, runs, u
The ACP agents PaperCraft knows about, and what was checked on the development Mac:
* **OpenCode** (`opencode acp`): works.
* **Gemini CLI** (`gemini --acp`): found and started, but its server currently refuses ACP clients, so turns fail with the agent's error until Google changes that.
* **OpenCode** (`opencode acp`): works. Its free models (`opencode/*-free`, Big Pickle) need no key.
* **Cursor** (`cursor-agent acp`): sign in first with `cursor-agent login`.
* **Pi** (`pi-acp`, an adapter run through `npx`): enable it once in the agent panel or Settings, then it works like the others.
* **Pi** (`pi-acp`, an adapter run through `npx`): enable it once in the agent panel or Settings. `pi-acp` does not pass MCP servers on to Pi, so a lean Pi gets its own folder (`PI_CODING_AGENT_DIR`) whose only package is `pi-mcp-adapter`, connected to PaperCraft. Pi runs on the providers you add a key for in Settings → Chat → Pi: OpenRouter (`:free` models, 50 requests a day without credits), Groq, Gemini, NVIDIA NIM and Cerebras. Keys live in the OS secret store and reach Pi only as environment variables.
* **Goose, Kimi, Devin, Junie, Mistral Vibe, Hermes, OpenHands, Stakpak, VT Code, Poolside, Droid**: started with the command their own docs give. They are not all verified here.
* **Claude Code and Codex ACP adapters** (`npx`): listed under Enable via npx. Claude Code and Codex themselves use the direct backends above.
Agents that run through `npx` are off until you enable them, because enabling runs code that npx fetches from npm.
**Free models.** For OpenCode and Pi the model list starts on free models (`Free only`) and offers `Free (auto)`, the default for new chats on them. It starts on the free model with the largest context. When a model fails with a rate limit, quota, overload or "gone" error before any tool ran, the turn moves to the next free one (at most two more) and the thread says so. A model that failed is skipped for 15 minutes. A failure after a tool ran is not retried, because the design may already have changed.
ACP permissions: PaperCraft's own tools run without asking, except the destructive ones listed under Approval below. Any other tool the agent asks to run (its own shell or file tools, for example) shows an approval card with Approve or Deny in the thread, and Deny is sent back to the agent.
**Custom agents** are your own ACP agents: a name, a command (a program name on the resolved `PATH`, or a full path) and arguments. The arguments are split on spaces, with no quoting. Custom agents appear under Custom in the agent panel and in Settings → Chat.
@@ -68,7 +69,7 @@ Settings → Chat has the same list, so an agent can also be hidden from the pan
### Setup card
A chat with no backend chosen shows one card, "Connect an agent". It lists the agents detected on this computer, up to four, with `Show all agents` for the rest. Below them are `Add an API endpoint` and `Add custom agent`. The card never lists install steps.
A chat with no backend chosen shows one card, "Connect an agent". It lists the agents detected on this computer, up to four, with `Show all agents` for the rest. Below them are `Add an API endpoint` and `Add custom agent`. When OpenCode or Pi is not found, its row has `Install…`. The dialog offers the install methods that work on this OS (Homebrew, Scoop, npm, Nix or the agent's install script; on Linux also the distribution's own). It shows the exact command and runs it only after you click Install, streaming the output. Methods that need `sudo` or an admin shell, and npm when Node is missing or too old, are shown with the reason and a command to copy instead.
### Sign-in
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 MiB

BIN
View File
Binary file not shown.
+2
View File
@@ -93,6 +93,8 @@ Fill-based sets (Phosphor, Material) follow variables; Lucide is stroke-based an
| `layer-name` | warning | default names (Frame, Rectangle, Group...) on layers with children |
| `hard-coded-color` | warning, info | a literal color that equals a variable (warning), or a literal used repeatedly when variables exist (info) |
| `overflow` | error | a layer extending past its artboard or clipping parent (by how many px, on which side), or text taller than its box. Scrolling frames and layers pinned in them are exempt. Never auto-fixed by `fix: true`: resize, move or let the parent grow. `get_bounds` returns every rect in one call |
Instances are skipped (their main component is linted). The rules are conventions, not law: pass `scale` to match your own type scale and ignore `info` items you disagree with. Lint does not judge taste; always look at `get_screenshot` too.
## Libraries
Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 385 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 355 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 209 KiB

After

Width:  |  Height:  |  Size: 303 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 356 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 416 KiB

+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Build the landing page into a folder ready for GitHub Pages:
# sh site/build.sh <out-dir> [<previous-build-dir>]
# Needs curl, jq and ffmpeg. GH_TOKEN, when set, authenticates the GitHub API call.
# RELEASE_JSON=<file> uses that file instead of asking the API. The demo video is re-encoded only
# when docs/demo.mp4 changed since <previous-build-dir>, so a release-only update stays cheap.
# <out-dir> must be new or empty.
set -eu
cd "$(dirname "$0")/.."
OUT="${1:?usage: sh site/build.sh <out-dir> [<previous-build-dir>]}"
PREV="${2:-}"
REPO="${GITHUB_REPOSITORY:-nxtime/papercraft}"
if [ -n "$(ls -A "$OUT" 2>/dev/null)" ]; then
echo "$OUT is not empty; pass a new folder." >&2
exit 1
fi
mkdir -p "$OUT/media/agents"
cp site/index.html site/site.css site/site.js "$OUT/"
cp assets/app-icon/papercraft.svg "$OUT/media/icon.svg"
for agent in claude openai cursor goose kimi mistral qwen cline githubcopilot nousresearch; do
cp "assets/agents/$agent.svg" "$OUT/media/agents/"
done
for shot in hero chat annotations variables; do
cp "docs/screenshots/readme/$shot.png" "$OUT/media/"
done
# GitHub Pages runs Jekyll otherwise, which is slower and has nothing to do here.
touch "$OUT/.nojekyll"
# The page reads this shape; site.js maps the API's own shape onto it the same way.
if [ -n "${RELEASE_JSON:-}" ]; then
cp "$RELEASE_JSON" "$OUT/release.json"
else
set -- -fsSL -H "Accept: application/vnd.github+json"
if [ -n "${GH_TOKEN:-}" ]; then
set -- "$@" -H "Authorization: Bearer $GH_TOKEN"
fi
curl "$@" "https://api.github.com/repos/$REPO/releases/latest" | jq '{
tag: .tag_name,
name: .name,
publishedAt: .published_at,
url: .html_url,
assets: [.assets[] | {name, size, url: .browser_download_url, digest}]
}' > "$OUT/release.json"
fi
jq -e '.tag and (.assets | length > 0)' "$OUT/release.json" > /dev/null
SRC_SUM="$(sha256sum docs/demo.mp4 | cut -d' ' -f1)"
if [ -n "$PREV" ] && [ -f "$PREV/media/demo.mp4" ] && [ "$(cat "$PREV/media/demo.source" 2>/dev/null)" = "$SRC_SUM" ]; then
cp "$PREV/media/demo.mp4" "$PREV/media/poster.jpg" "$OUT/media/"
else
# 720p30 without audio keeps the tour near 2 MB, against 26 MB for the 1080p60 source.
ffmpeg -loglevel error -y -i docs/demo.mp4 -vf "scale=1280:-2,fps=30" -c:v libx264 -crf 28 \
-preset slow -pix_fmt yuv420p -an -movflags +faststart "$OUT/media/demo.mp4"
ffmpeg -loglevel error -y -ss 1.5 -i docs/demo.mp4 -frames:v 1 -vf scale=1280:-2 -q:v 4 \
"$OUT/media/poster.jpg"
fi
echo "$SRC_SUM" > "$OUT/media/demo.source"
echo "Built $(jq -r .tag "$OUT/release.json") into $OUT"
+375
View File
@@ -0,0 +1,375 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>PaperCraft</title>
<meta name="claude:viewport-fit-sides" content="cover">
<meta name="description" content="A native, local-first design and whiteboard canvas that AI agents can drive over MCP and a CLI.">
<meta name="theme-color" content="#11111b">
<meta property="og:title" content="PaperCraft">
<meta property="og:description" content="A native canvas that AI agents can drive. Local-first, no account, open source.">
<meta property="og:image" content="media/poster.jpg">
<link rel="icon" href="media/icon.svg" type="image/svg+xml">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Geist:wght@400;500;600&family=Geist+Mono:wght@400;500&display=swap">
<link rel="stylesheet" href="site.css">
</head>
<body>
<div class="stage" aria-hidden="true"><div class="glow a"></div><div class="glow b"></div><div class="glow c"></div><div class="spot"></div></div>
<header class="nav" id="nav">
<div class="wrap">
<div class="nav-bar acrylic">
<a class="brand" href="#top"><img src="media/icon.svg" alt="">PaperCraft</a>
<nav class="nav-links" aria-label="Sections">
<a href="#live">Agents</a>
<a href="#features">Features</a>
<a href="#local">Local-first</a>
<a href="#download">Download</a>
<a href="https://github.com/nxtime/papercraft">GitHub</a>
</nav>
<a class="btn btn-primary btn-sm" href="#download">Download <span class="ver" data-version>latest</span></a>
<span class="progress" aria-hidden="true"></span>
</div>
</div>
</header>
<main id="top">
<section class="hero wrap">
<img class="hero-mark rise" src="media/icon.svg" alt="PaperCraft app icon" width="76" height="76">
<div class="eyebrow rise d1">Rust · egui · wgpu · MCP</div>
<h1 class="serif" id="headline">A native canvas that <em>AI agents</em> can drive.</h1>
<p class="lede rise d2">PaperCraft is an infinite-canvas design tool and whiteboard. It runs on your desktop with no account and no cloud, and it serves the Model Context Protocol so Claude Code, Codex and other agents can edit the open canvas, screenshot it and lint it, one undo step per call.</p>
<div class="cta rise d3">
<a class="btn btn-primary" id="hero-dl" href="#download">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12m0 0-5-5m5 5 5-5M4 21h16"/></svg>
<span id="hero-dl-label">Download</span> <span class="ver" data-version>latest</span>
</a>
<a class="btn btn-ghost" href="https://github.com/nxtime/papercraft">
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5a11.5 11.5 0 0 0-3.64 22.41c.58.1.79-.25.79-.56v-2c-3.2.7-3.88-1.37-3.88-1.37-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.69 1.25 3.35.96.1-.75.4-1.25.73-1.54-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.17 1.18a11 11 0 0 1 5.77 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.8 1.19 1.83 1.19 3.09 0 4.42-2.7 5.39-5.26 5.68.41.36.78 1.06.78 2.14v3.17c0 .31.21.67.8.56A11.5 11.5 0 0 0 12 .5Z"/></svg>
Source on GitHub
</a>
</div>
<div class="facts rise d3"><span>Local-first, no account</span><span>98 MCP tools</span><span>Windows · macOS · Linux</span><span>MIT or Apache-2.0</span></div>
</section>
<section class="showcase wrap" aria-label="Product tour">
<div class="window acrylic" id="window">
<div class="chrome" aria-hidden="true"><i></i><i></i><i></i><span>PaperCraft · Landing page</span></div>
<video src="media/demo.mp4" poster="media/poster.jpg" autoplay muted loop playsinline preload="metadata" aria-label="A 40-second tour of the editor, chat mode, annotations and design systems"></video>
</div>
<p class="caption">A 40-second tour, rendered from the app's own design rather than screen-recorded.</p>
</section>
<section class="marquee" aria-label="Agents that work with PaperCraft">
<p class="eyebrow wrap">Chat mode runs the agents you already use</p>
<div class="track">
<div class="belt">
<span class="chip acrylic"><i style="--logo:url(media/agents/claude.svg)"></i>Claude Code</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/openai.svg)"></i>Codex</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/cursor.svg)"></i>Cursor</span>
<span class="chip acrylic"><i class="none"></i>OpenCode</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/goose.svg)"></i>Goose</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/kimi.svg)"></i>Kimi</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/mistral.svg)"></i>Mistral Vibe</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/qwen.svg)"></i>Qwen Code</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/cline.svg)"></i>Cline</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/githubcopilot.svg)"></i>Copilot CLI</span>
<span class="chip acrylic"><i style="--logo:url(media/agents/nousresearch.svg)"></i>Hermes</span>
<span class="chip acrylic"><i class="none"></i>Any ACP agent</span>
</div>
</div>
</section>
<section class="block wrap" id="live">
<div class="section-head reveal">
<div class="eyebrow">For agents</div>
<h2 class="serif">Watch an agent <em>build a screen.</em></h2>
<p>Each tool call is one undo step. The agent writes HTML that becomes real layers, switches the theme by changing a variable mode, takes a screenshot and lints the result.</p>
</div>
<div class="live acrylic reveal" id="live-demo">
<div class="log">
<div class="log-head"><span class="dot" aria-hidden="true"></span>Agent run · Sign in<span class="undo" id="undo-count">0 undo steps</span></div>
<ol class="calls" id="calls">
<li class="call"><span class="st"></span><b>create_artboard</b><span class="ms">9 ms</span><span class="arg">{"name": "Sign in", "width": 360, "height": 480}</span></li>
<li class="call"><span class="st"></span><b>set_variables</b><span class="ms">4 ms</span><span class="arg">{"bg", "surface", "text", "accent"} with Dark and Light modes</span></li>
<li class="call"><span class="st"></span><b>write_html</b><span class="ms">18 ms</span><span class="arg">&lt;div style="display:flex; flex-direction:column; gap:12px"&gt; → 6 layers</span></li>
<li class="call"><span class="st"></span><b>update_styles</b><span class="ms">3 ms</span><span class="arg">{"#submit": {"background": "var(--accent)"}}</span></li>
<li class="call"><span class="st"></span><b>set_variable_mode</b><span class="ms">2 ms</span><span class="arg">{"collection": "Colors", "mode": "Light"}</span></li>
<li class="call"><span class="st"></span><b>get_screenshot</b><span class="ms">41 ms</span><span class="arg">sign-in@2x.png</span></li>
<li class="call"><span class="st"></span><b>lint_design</b><span class="ms">7 ms</span><span class="arg">contrast, 4px grid, type scale, touch targets</span></li>
</ol>
</div>
<div class="board-area" aria-hidden="true">
<span class="board-label">Sign in</span>
<span class="mode-pill" id="mode-pill">Mode: Dark</span>
<div class="board" id="board">
<div class="a-logo"></div>
<div class="a-title">Welcome back</div>
<div class="a-sub">Sign in to continue to your workspace.</div>
<div class="a-field"></div>
<div class="a-field"></div>
<div class="a-btn">Sign in</div>
</div>
<span class="lint" id="lint">✓ lint_design · 0 issues</span>
<span class="flash" id="flash"></span>
</div>
</div>
</section>
<section class="block wrap" id="features">
<div class="section-head reveal">
<div class="eyebrow">What you get</div>
<h2 class="serif">A real design tool, <em>not a chat window</em> with a canvas bolted on.</h2>
<p>Frames, auto layout, components, variables and a hand-drawn whiteboard on one GPU-rendered canvas.</p>
</div>
<div class="features">
<article class="feature reveal">
<div class="copy">
<div class="eyebrow">The editor</div>
<h3 class="serif">Layers, canvas, inspector. <em>One native window.</em></h3>
<p>Built in Rust on egui and wgpu. Cached frames take about 3 ms with ten thousand visible layers.</p>
<ul class="ticks">
<li>Auto layout with gap, padding, hug, fill, wrap and constraints</li>
<li>Pen and Bézier editing, boolean operations, gradients and blend modes</li>
<li>A command palette over every action, page and layer</li>
</ul>
</div>
<div class="tilt"><div class="shot acrylic"><img src="media/hero.png" alt="PaperCraft with a habit-tracker design open: layers on the left, three annotated screens on the canvas, the inspector on the right" loading="lazy"></div></div>
</article>
<article class="feature reveal">
<div class="copy">
<div class="eyebrow">Chat mode</div>
<h3 class="serif">Pick an agent. <em>Describe the screen.</em></h3>
<p>A conversation sits next to the canvas. Point at layers with @ mentions or a picked area, and the agent gets a crop with your notes drawn on it.</p>
<ul class="ticks">
<li>Claude Code and Codex through their CLIs, with your own logins</li>
<li>Any ACP agent on your PATH, or the Anthropic API with your key</li>
<li>Every run can be reviewed, reverted one change at a time, or accepted</li>
</ul>
</div>
<div class="tilt"><div class="shot acrylic"><img src="media/chat.png" alt="Chat mode: a conversation with an agent beside the canvas" loading="lazy"></div></div>
</article>
<article class="feature reveal">
<div class="copy">
<div class="eyebrow">Annotations</div>
<h3 class="serif">Annotate <em>in place.</em> Agents read the notes.</h3>
<p>Pin typed notes for rules, behaviour, content and data to any layer, with a template per project. They travel with the design into the handoff spec.</p>
</div>
<div class="tilt"><div class="shot acrylic"><img src="media/annotations.png" alt="The Annotations view listing notes grouped by screen, with their category chips" loading="lazy"></div></div>
</article>
<article class="feature reveal">
<div class="copy">
<div class="eyebrow">Design systems</div>
<h3 class="serif">Tokens out as CSS, DTCG or Tailwind. <em>Code out as JSX.</em></h3>
<p>Variables with modes and aliases, components that work across projects, and shared libraries you publish, enable and update.</p>
<ul class="ticks">
<li>Light and dark are modes on one artboard, never copies</li>
<li>Lint for contrast, the 4px grid, type scale and touch targets, with auto-fix</li>
</ul>
</div>
<div class="tilt"><div class="shot acrylic"><img src="media/variables.png" alt="The Variables modal with Light and Dark values for brand, foreground and background" loading="lazy"></div></div>
</article>
</div>
</section>
<section class="block wrap" aria-labelledby="more-title">
<div class="section-head reveal">
<div class="eyebrow">And the rest</div>
<h2 class="serif" id="more-title">Sketch it, <em>present it,</em> ship it.</h2>
</div>
<div class="bento stagger">
<article class="tile wide acrylic lit reveal">
<div class="art">
<svg class="sketch" viewBox="0 0 360 92" width="100%" height="92" preserveAspectRatio="xMinYMid meet" aria-hidden="true">
<path d="M12 18 C60 12 110 16 140 19 C143 40 141 60 138 76 C96 79 50 78 14 74 C11 55 13 36 12 18Z"/>
<path d="M146 46 C180 44 210 46 236 47 M226 38 L238 47 L226 56"/>
<rect class="note" x="252" y="14" width="78" height="64" rx="4" transform="rotate(3 291 46)"/>
</svg>
</div>
<h3>Whiteboard mode</h3>
<p>Hand-drawn shapes, arrows bound to shapes, elbow connectors, sticky notes, freehand ink and a laser pointer, on the same canvas as your screens.</p>
</article>
<article class="tile acrylic lit reveal">
<div class="art"><span class="fmt in">.fig</span><span class="fmt in">.excalidraw</span><span class="arrow-dash"></span><span class="fmt out">PDF</span></div>
<h3>Import and export</h3>
<p>Figma, Excalidraw and SVG in. PNG at 1 to 4x, SVG and vector PDF out, for a selection, a frame or a page.</p>
</article>
<article class="tile acrylic lit reveal">
<div class="art"><div class="versions"><div>Agent run · Sign in</div><div>Auto-version · 14:02</div><div>Before handoff</div></div></div>
<h3>Versions and runs</h3>
<p>Named and automatic versions per page. An agent run saves one before its first edit, so you can always go back.</p>
</article>
<article class="tile acrylic lit reveal">
<div class="art"><span class="fmt">Welcome</span><span class="arrow-dash"></span><span class="fmt">Today</span></div>
<h3>Present mode</h3>
<p>Prototype links between frames, followed with a camera glide.</p>
</article>
<article class="tile acrylic lit reveal">
<div class="art"><div class="peers"><span style="background:var(--mauve)">M</span><span style="background:var(--blue)">A</span><span style="background:var(--green)">J</span></div></div>
<h3>Shared projects</h3>
<p>An optional relay merges concurrent edits to a page. Without one, nothing leaves your machine.</p>
</article>
<article class="tile wide acrylic lit reveal">
<div class="art">
<div class="swatches" aria-hidden="true">
<span style="background:#eff1f5"></span><span style="background:#303446"></span><span style="background:#24273a"></span><span style="background:#1e1e2e"></span><span style="background:#11111b"></span>
</div>
</div>
<h3>Themes</h3>
<p>System, Light and Dark, plus the four Catppuccin flavours: Latte, Frappé, Macchiato and Mocha.</p>
</article>
<article class="tile acrylic lit reveal">
<div class="art"><span class="fmt">wasm32</span><span class="arrow-dash"></span><span class="fmt out">browser</span></div>
<h3>Web build</h3>
<p>The same editor compiled to WebAssembly, served by <code>papercraft-relay</code>.</p>
</article>
</div>
</section>
<section class="block wrap" id="local">
<div class="section-head reveal">
<div class="eyebrow">Local-first</div>
<h2 class="serif">Your project is <em>a folder on your disk.</em></h2>
<p>Plain JSON you can back up, diff and commit. No account to make and no server to trust.</p>
</div>
<div class="local">
<div class="tree acrylic reveal">
<pre><span class="path">~/Documents/papercraft/</span><span class="d">Pulse/</span>
├── project.json <span class="c"># manifest, variables, components</span>
├── <span class="d">pages/</span> <span class="c"># one JSON file per page</span>
├── <span class="d">versions/</span> <span class="c"># named and automatic versions</span>
├── <span class="d">runs/</span> <span class="c"># agent runs, for review and revert</span>
└── <span class="d">chats/</span> <span class="c"># chat threads with their tool calls</span></pre>
</div>
<div class="points stagger">
<div class="point acrylic lit reveal"><h3>Atomic autosave</h3><p>Every write is atomic, and older files are migrated forward when they load.</p></div>
<div class="point acrylic lit reveal"><h3>Works with the app closed</h3><p><code>papercraft-cli --offline</code> runs the same tools on the project store, screenshots included.</p></div>
<div class="point acrylic lit reveal"><h3>Keys stay in your OS</h3><p>API keys live in the system credential store and never in a project file, chat or log.</p></div>
</div>
</div>
</section>
<section class="block wrap" id="agents">
<div class="section-head reveal">
<div class="eyebrow">Connect</div>
<h2 class="serif">Same tools, <em>three ways in.</em></h2>
<p>The MCP server is built into the app and listens on loopback only. Browser requests and foreign hosts are rejected.</p>
</div>
<div class="agents stagger">
<div class="card acrylic lit reveal">
<div class="stat" id="tool-count" data-to="98">98</div>
<h3>MCP tools, one undo step each</h3>
<div class="ways">
<div class="way"><b>MCP over HTTP</b><span>Built into the app at <code>127.0.0.1:29980/mcp</code>.</span></div>
<div class="way"><b>MCP over stdio</b><span><code>papercraft-mcp</code> relays to the running app.</span></div>
<div class="way"><b>Shell</b><span><code>papercraft-cli</code> calls the same tools, so the agent needs no schemas in context.</span></div>
</div>
</div>
<div class="card acrylic lit reveal">
<h3>Register it once</h3>
<p>Start PaperCraft, then add it to your agent.</p>
<div class="code">
<button class="copy-btn" type="button" data-copy="claude mcp add --transport http --scope user papercraft http://127.0.0.1:29980/mcp">Copy</button>
<pre><span class="c"># Claude Code</span>
<span class="k">claude</span> mcp add --transport http --scope user \
papercraft http://127.0.0.1:29980/mcp</pre>
</div>
<div class="code">
<button class="copy-btn" type="button" data-copy="codex mcp add papercraft --url http://127.0.0.1:29980/mcp">Copy</button>
<pre><span class="c"># Codex</span>
<span class="k">codex</span> mcp add papercraft --url http://127.0.0.1:29980/mcp</pre>
</div>
<div class="code">
<button class="copy-btn" type="button" data-copy="papercraft-cli call get_screenshot '{&quot;nodeId&quot;:&quot;abc123:1&quot;}' --project Demo -o card.png">Copy</button>
<pre><span class="c"># No app running</span>
<span class="k">papercraft-cli</span> call get_screenshot '{"nodeId":"abc123:1"}' \
--project Demo -o card.png</pre>
</div>
</div>
</div>
</section>
<section class="block wrap" aria-labelledby="keys-title">
<div class="section-head reveal">
<div class="eyebrow">Keyboard first</div>
<h2 class="serif" id="keys-title">The shortcuts <em>you'll use daily.</em></h2>
</div>
<div class="keys stagger">
<div class="key acrylic lit reveal"><kbd data-keys="mod K"></kbd><span>Command palette</span></div>
<div class="key acrylic lit reveal"><kbd data-keys="mod J"></kbd><span>Design or Chat mode</span></div>
<div class="key acrylic lit reveal"><kbd data-keys="mod alt shift V"></kbd><span>Variables</span></div>
<div class="key acrylic lit reveal"><kbd data-keys="N"></kbd><span>Annotate</span></div>
<div class="key acrylic lit reveal"><kbd data-keys="/"></kbd><span>Hide the side panels</span></div>
</div>
</section>
<section class="block wrap" id="download">
<div class="dl-head reveal">
<div class="section-head">
<div class="eyebrow">Download</div>
<h2 class="serif">Get the <em>latest build.</em></h2>
</div>
<a class="release-pill acrylic" id="release-link" href="https://github.com/nxtime/papercraft/releases/latest">
<span class="pulse" aria-hidden="true"></span>
<span><b data-version>latest</b> · <span id="release-date">GitHub releases</span></span>
</a>
</div>
<div class="platforms stagger" id="platforms">
<article class="platform acrylic">
<h3>Loading the latest release</h3>
<p class="note">All builds are also on the <a href="https://github.com/nxtime/papercraft/releases/latest">GitHub releases page</a>.</p>
</article>
</div>
<div class="dl-foot">
<div class="card acrylic reveal">
<h3>First run</h3>
<p>The Windows zip is unsigned, so SmartScreen may ask you to confirm. macOS builds are ad-hoc signed and not notarized: open the app with right-click, Open the first time.</p>
</div>
<div class="card acrylic reveal">
<h3>Build from source</h3>
<p>Rust 1.95 or newer, then <code>cargo build --release</code>. Linux needs Vulkan or GL and the usual X11 or Wayland libraries.</p>
</div>
</div>
</section>
<section class="wrap">
<div class="status acrylic reveal">
<div>
<div class="eyebrow">Status</div>
<h2 class="serif">Alpha, <em>and used daily.</em></h2>
<p>PaperCraft is good for screens, design systems and sketches, and it is not yet a replacement for a mature design tool. The roadmap lists what is missing, in priority order.</p>
</div>
<div class="actions">
<a class="btn btn-ghost" href="https://github.com/nxtime/papercraft/blob/main/ROADMAP.md">Roadmap</a>
<a class="btn btn-ghost" href="https://github.com/nxtime/papercraft#status-and-known-limits">Known limits</a>
</div>
</div>
</section>
</main>
<footer>
<div class="wrap foot">
<span>PaperCraft is open source, licensed MIT or Apache-2.0.</span>
<nav aria-label="Links">
<a href="https://github.com/nxtime/papercraft">GitHub</a>
<a href="https://github.com/nxtime/papercraft/releases">Releases</a>
<a href="https://github.com/nxtime/papercraft/blob/main/docs/agents.md">Agent guide</a>
<a href="https://github.com/nxtime/papercraft/blob/main/CONTRIBUTING.md">Contributing</a>
</nav>
</div>
</footer>
<div class="toast acrylic" id="toast" role="status" aria-live="polite"></div>
<script src="site.js"></script>
</body>
</html>
+484
View File
@@ -0,0 +1,484 @@
/* The landing page sits on the app's own dark canvas: acrylic panels over a dot grid lit by
lavender glows, with the palette of the app icon (Catppuccin Mocha). */
:root {
color-scheme: dark;
--crust: #11111b;
--base: #181825;
--mantle: #1e1e2e;
--surface: #313244;
--overlay: #45475a;
--text: #cdd6f4;
--subtext: #a6adc8;
--muted: #7f849c;
--mauve: #cba6f7;
--mauve-hi: #d9bcfa;
--mauve-deep: #b48ef0;
--on-mauve: #1e1e2e;
--green: #a6e3a1;
--blue: #89b4fa;
--peach: #fab387;
--glass: rgb(30 30 46 / 0.55);
--glass-strong: rgb(30 30 46 / 0.8);
--glass-edge: rgb(205 214 244 / 0.09);
--glass-hi: rgb(255 255 255 / 0.06);
--glow: rgb(203 166 247 / 0.32);
--dot: rgb(205 214 244 / 0.07);
--well: rgb(17 17 27 / 0.6);
--display: "Instrument Serif", "Iowan Old Style", Georgia, serif;
--sans: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
--r-panel: 22px;
--r-control: 12px;
--wrap: 1180px;
--ease: cubic-bezier(.2, .7, .2, 1);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
background: var(--crust);
color: var(--text);
font-family: var(--sans);
font-size: 16px;
line-height: 1.6;
-webkit-font-smoothing: antialiased;
overflow-x: hidden;
}
body::before {
content: ""; position: fixed; inset: 0 0 auto; height: env(safe-area-inset-top, 0px);
z-index: 30; background: var(--crust);
}
img { max-width: 100%; }
code { font-family: var(--mono); font-size: .92em; }
a { color: inherit; }
:focus-visible { outline: 2px solid var(--mauve); outline-offset: 3px; border-radius: 6px; }
/* The canvas behind everything: dot grid, drifting glows and a spotlight that follows the pointer */
.stage { position: fixed; inset: 0; z-index: -1; pointer-events: none; background: var(--crust); overflow: hidden; }
.stage::before {
content: ""; position: absolute; inset: 0;
background: radial-gradient(circle at 1px 1px, var(--dot) 1px, transparent 0) 0 0 / 22px 22px;
mask-image: radial-gradient(70rem 50rem at 50% 0%, #000 30%, transparent 85%);
}
.glow { position: absolute; border-radius: 50%; filter: blur(80px); opacity: .55; }
.glow.a { width: 52rem; height: 34rem; left: 50%; top: -18rem; margin-left: -26rem; background: rgb(203 166 247 / .32); }
.glow.b { width: 34rem; height: 26rem; right: -10rem; top: 45%; background: rgb(137 180 250 / .12); }
.glow.c { width: 30rem; height: 24rem; left: -10rem; bottom: -6rem; background: rgb(203 166 247 / .14); }
.spot {
position: absolute; inset: 0;
background: radial-gradient(28rem 28rem at var(--mx, 50%) var(--my, -20%), rgb(203 166 247 / .07), transparent 70%);
}
.wrap {
width: 100%; max-width: var(--wrap); margin-inline: auto;
padding-left: max(20px, env(safe-area-inset-left, 0px));
padding-right: max(20px, env(safe-area-inset-right, 0px));
}
/* Acrylic: translucent fill, backdrop blur, a hairline edge and a top highlight */
.acrylic {
position: relative;
background: linear-gradient(180deg, var(--glass-hi), transparent 40%), var(--glass);
backdrop-filter: blur(22px) saturate(160%);
-webkit-backdrop-filter: blur(22px) saturate(160%);
border: 1px solid var(--glass-edge);
box-shadow: 0 1px 0 var(--glass-hi) inset, 0 24px 60px -24px rgb(0 0 0 / .6);
}
/* Cards light up under the pointer, like a hovered panel in the app */
.lit::after {
content: ""; position: absolute; inset: -1px; border-radius: inherit; pointer-events: none;
background: radial-gradient(22rem 22rem at var(--lx, 50%) var(--ly, 50%), rgb(203 166 247 / .14), transparent 60%);
opacity: 0; transition: opacity .4s;
}
.lit:hover::after { opacity: 1; }
.eyebrow {
font-family: var(--mono); font-size: 12px; letter-spacing: .18em;
text-transform: uppercase; color: var(--muted);
}
.serif { font-family: var(--display); font-weight: 400; letter-spacing: -.01em; }
em { font-style: italic; color: var(--mauve); }
/* Nav */
header.nav { position: sticky; top: env(safe-area-inset-top, 0px); z-index: 20; padding-block: 14px; }
.nav-bar {
display: flex; align-items: center; gap: 16px; padding: 8px 8px 8px 14px; border-radius: 999px;
transition: background .3s, box-shadow .3s;
}
.scrolled .nav-bar { background: var(--glass-strong); }
.brand { display: flex; align-items: center; gap: 10px; text-decoration: none; font-weight: 600; }
.brand img { width: 28px; height: 28px; }
.nav-links { display: flex; gap: 4px; margin-left: auto; }
.nav-links a {
text-decoration: none; color: var(--subtext); font-size: 14px;
padding: 6px 12px; border-radius: 999px; transition: color .2s, background .2s;
}
.nav-links a:hover, .nav-links a.active { color: var(--text); background: var(--glass-hi); }
.progress {
position: absolute; left: 24px; right: 24px; bottom: -1px; height: 1px; border-radius: 1px;
background: linear-gradient(90deg, transparent, var(--mauve), transparent);
transform-origin: 0 50%; transform: scaleX(var(--p, 0)); opacity: .7;
}
/* Buttons */
.btn {
position: relative; overflow: hidden;
display: inline-flex; align-items: center; gap: 10px; text-decoration: none;
font: 500 15px/1 var(--sans); padding: 13px 20px; border-radius: 999px;
border: 1px solid transparent; cursor: pointer; white-space: nowrap;
transition: transform .25s var(--ease), box-shadow .25s, background .25s;
}
.btn-primary {
background: linear-gradient(180deg, var(--mauve-hi), var(--mauve-deep)); color: var(--on-mauve);
box-shadow: 0 0 0 1px rgb(255 255 255 / .25) inset, 0 10px 30px -8px var(--glow);
}
.btn-primary::before {
content: ""; position: absolute; inset: 0; transform: translateX(-120%);
background: linear-gradient(100deg, transparent 30%, rgb(255 255 255 / .45) 50%, transparent 70%);
}
.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 0 0 1px rgb(255 255 255 / .3) inset, 0 16px 40px -8px var(--glow); }
.btn-primary:hover::before { transition: transform .8s var(--ease); transform: translateX(120%); }
.btn-ghost { background: var(--glass); border-color: var(--glass-edge); color: var(--text); backdrop-filter: blur(12px); }
.btn-ghost:hover { background: var(--glass-strong); transform: translateY(-2px); }
.btn-sm { padding: 9px 14px; font-size: 14px; }
.btn svg { width: 16px; height: 16px; flex: none; }
.ver { font-family: var(--mono); font-size: 12px; opacity: .7; }
/* Hero */
.hero { text-align: center; padding-block: clamp(48px, 9vw, 104px) 36px; }
.hero-mark { width: 76px; height: 76px; margin: 0 auto 22px; display: block; filter: drop-shadow(0 12px 30px var(--glow)); }
.hero h1 { font-size: clamp(44px, 7.4vw, 92px); line-height: 1; margin: 18px auto 0; max-width: 14ch; text-wrap: balance; }
.hero h1 .w { display: inline-block; }
.lede { max-width: 58ch; margin: 22px auto 0; color: var(--subtext); font-size: clamp(16px, 1.6vw, 18px); text-wrap: pretty; }
.cta { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; margin-top: 32px; }
.facts {
display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 22px; margin-top: 26px;
font-family: var(--mono); font-size: 12px; color: var(--muted); letter-spacing: .04em;
}
.facts span::before { content: ""; display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--green); margin-right: 8px; vertical-align: 2px; }
/* Video window: tilted back until it scrolls into view */
.showcase { padding-block: 24px 24px; perspective: 1600px; }
.window {
border-radius: var(--r-panel); padding: 10px;
transform: rotateX(var(--tilt, 10deg)) scale(var(--zoom, .96)); transform-origin: 50% 0;
box-shadow: 0 0 0 1px var(--glass-edge), 0 40px 120px -30px var(--glow), 0 30px 80px -30px rgb(0 0 0 / .8);
}
.chrome { display: flex; align-items: center; gap: 8px; padding: 4px 6px 10px; }
.chrome i { width: 11px; height: 11px; border-radius: 50%; background: var(--surface); }
.chrome span { margin-inline: auto; font-family: var(--mono); font-size: 12px; color: var(--muted); }
.window video { display: block; width: 100%; aspect-ratio: 16 / 9; border-radius: 14px; background: var(--base); }
.caption { text-align: center; color: var(--muted); font-size: 14px; margin: 18px 0 0; }
/* Agents marquee */
.marquee { padding-block: 40px 8px; }
.marquee p { text-align: center; margin: 0 0 18px; }
.track {
display: flex; overflow: hidden;
mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
}
.belt { display: flex; gap: 12px; padding-right: 12px; flex: none; animation: belt 48s linear infinite; }
.track:hover .belt { animation-play-state: paused; }
.chip {
display: inline-flex; align-items: center; gap: 9px; padding: 9px 14px; border-radius: 999px;
font-size: 14px; color: var(--subtext); white-space: nowrap;
}
.chip i {
width: 16px; height: 16px; flex: none; background: currentColor;
-webkit-mask: var(--logo) center / contain no-repeat; mask: var(--logo) center / contain no-repeat;
}
.chip i.none { -webkit-mask: none; mask: none; border-radius: 4px; background: var(--overlay); }
@keyframes belt { to { transform: translateX(-100%); } }
/* Sections */
section.block { padding-block: clamp(56px, 8vw, 96px); }
.section-head { max-width: 720px; margin-bottom: 44px; }
.section-head h2 { font-size: clamp(36px, 5vw, 60px); line-height: 1.04; margin: 14px 0 0; text-wrap: balance; }
.section-head p { color: var(--subtext); margin: 16px 0 0; max-width: 60ch; }
/* Live agent demo */
.live { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); gap: 0; border-radius: var(--r-panel); overflow: hidden; }
.log { padding: 22px; border-right: 1px solid var(--glass-edge); min-width: 0; display: flex; flex-direction: column; }
.log-head { display: flex; align-items: center; gap: 10px; font-size: 13px; color: var(--subtext); margin-bottom: 14px; }
.log-head .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--green); animation: pulse 2.4s infinite; }
.log-head .undo { margin-left: auto; font-family: var(--mono); font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; }
.calls { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; font: 13px/1.5 var(--mono); }
.call {
display: grid; grid-template-columns: 14px minmax(0, 1fr) auto; gap: 4px 10px; align-items: start;
padding: 9px 11px; border-radius: 10px; background: var(--well); border: 1px solid var(--glass-edge);
opacity: .28; transition: opacity .4s, border-color .4s, transform .4s var(--ease);
}
.call .st { width: 14px; height: 14px; margin-top: 3px; border-radius: 50%; border: 1.5px solid var(--overlay); }
.call b { font-weight: 500; color: var(--text); }
.call .arg { grid-column: 2 / span 2; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
.call .ms { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
.call.run { opacity: 1; border-color: rgb(203 166 247 / .5); transform: translateX(4px); }
.call.run .st { border-color: var(--mauve); border-top-color: transparent; animation: spin .7s linear infinite; }
.call.done { opacity: 1; }
.call.done .st { border: 0; background: var(--green) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='%231e1e2e' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 12px no-repeat; }
.call:not(.done) .ms { visibility: hidden; }
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgb(166 227 161 / .6); } 70%, 100% { box-shadow: 0 0 0 8px rgb(166 227 161 / 0); } }
.board-area {
position: relative; min-width: 0; display: grid; place-items: center; padding: 40px 24px;
background: radial-gradient(circle at 1px 1px, var(--dot) 1px, transparent 0) 0 0 / 18px 18px, rgb(17 17 27 / .35);
}
.board-label { position: absolute; top: 16px; left: 20px; font: 12px var(--mono); color: var(--muted); }
.mode-pill {
position: absolute; top: 12px; right: 16px; font: 500 12px var(--mono); padding: 4px 10px; border-radius: 999px;
background: var(--well); border: 1px solid var(--glass-edge); color: var(--subtext); transition: color .4s;
}
.board {
--a-bg: #1e1e2e; --a-surface: #313244; --a-text: #cdd6f4; --a-sub: #a6adc8; --a-accent: #cba6f7; --a-on: #1e1e2e;
width: min(100%, 300px); aspect-ratio: 3 / 4; border-radius: 18px; padding: 26px 22px;
display: flex; flex-direction: column; gap: 12px;
outline: 1.5px dashed transparent; outline-offset: 6px;
background: transparent; transition: background .6s, outline-color .4s, box-shadow .6s;
}
.board.light { --a-bg: #eff1f5; --a-surface: #dce0e8; --a-text: #4c4f69; --a-sub: #6c6f85; --a-accent: #8839ef; --a-on: #eff1f5; }
.board.s1 { outline-color: rgb(203 166 247 / .6); }
.board.s2 { background: var(--a-bg); box-shadow: 0 30px 60px -30px rgb(0 0 0 / .8); }
.board > * { opacity: 0; transform: translateY(8px); transition: opacity .45s var(--ease), transform .45s var(--ease), background .6s, color .6s; }
.board.s3 > * { opacity: 1; transform: none; }
.board.s3 > *:nth-child(2) { transition-delay: .06s; } .board.s3 > *:nth-child(3) { transition-delay: .12s; }
.board.s3 > *:nth-child(4) { transition-delay: .18s; } .board.s3 > *:nth-child(5) { transition-delay: .24s; }
.board.s3 > *:nth-child(6) { transition-delay: .3s; }
.a-logo { width: 34px; height: 34px; border-radius: 10px; background: var(--a-surface); }
.a-title { font: 600 22px/1.2 var(--sans); color: var(--a-text); }
.a-sub { font-size: 12px; color: var(--a-sub); margin-top: -6px; }
.a-field { height: 36px; border-radius: 9px; background: var(--a-surface); }
.a-btn {
height: 38px; border-radius: 10px; margin-top: auto; display: grid; place-items: center;
font: 600 13px var(--sans); background: var(--a-surface); color: var(--a-sub);
}
.board.s4 .a-btn { background: var(--a-accent); color: var(--a-on); }
.board.s4 .a-logo { background: var(--a-accent); }
.flash { position: absolute; inset: 0; background: #fff; opacity: 0; pointer-events: none; }
.flash.on { animation: flash .5s ease-out; }
@keyframes flash { 0% { opacity: .35; } 100% { opacity: 0; } }
.lint {
position: absolute; bottom: 16px; left: 50%; display: inline-flex; align-items: center; gap: 8px;
padding: 7px 12px; border-radius: 999px; font: 500 12px var(--mono); color: var(--green);
background: var(--glass-strong); border: 1px solid rgb(166 227 161 / .35);
opacity: 0; transform: translate(-50%, 10px); transition: opacity .4s, transform .4s var(--ease);
}
.lint.on { opacity: 1; transform: translate(-50%, 0); }
/* Feature rows */
.features { display: grid; gap: 24px; }
.feature {
display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: clamp(24px, 4vw, 56px);
align-items: center; padding-block: 28px;
}
.feature:nth-child(even) { grid-template-columns: minmax(0, 7fr) minmax(0, 5fr); }
.feature:nth-child(even) .copy { order: 2; }
.feature h3 { font-size: clamp(30px, 3.6vw, 44px); line-height: 1.06; margin: 12px 0 0; text-wrap: balance; }
.feature p { color: var(--subtext); margin: 14px 0 0; }
.ticks { margin: 16px 0 0; padding: 0; list-style: none; display: grid; gap: 8px; color: var(--subtext); font-size: 15px; }
.ticks li { display: flex; gap: 10px; }
.ticks li::before { content: ""; flex: none; width: 6px; height: 6px; margin-top: 10px; border-radius: 2px; background: var(--mauve); }
.tilt { perspective: 1200px; }
.shot {
border-radius: var(--r-panel); padding: 8px;
transform: rotateX(var(--rx, 0deg)) rotateY(var(--ry, 0deg)); transition: transform .5s var(--ease);
}
.shot img { display: block; width: 100%; height: auto; border-radius: 15px; }
/* Bento grid */
.bento { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
.tile { border-radius: var(--r-panel); padding: 24px; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
.tile.wide { grid-column: span 2; }
.tile h3 { margin: 0; font-size: 17px; font-weight: 600; }
.tile p { margin: 0; color: var(--subtext); font-size: 15px; }
.tile .art { height: 92px; margin-bottom: 8px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.fmt {
font: 500 12px var(--mono); padding: 6px 10px; border-radius: 8px; background: var(--well);
border: 1px solid var(--glass-edge); color: var(--subtext);
}
.fmt.in { color: var(--blue); } .fmt.out { color: var(--mauve); }
.arrow-dash { flex: 1; min-width: 30px; height: 1px; background: repeating-linear-gradient(90deg, var(--overlay) 0 6px, transparent 6px 12px); background-size: 24px 1px; animation: dash 1.2s linear infinite; }
@keyframes dash { to { background-position: 24px 0; } }
.swatches { display: flex; gap: 8px; }
.swatches span {
width: 40px; height: 56px; border-radius: 10px; border: 1px solid var(--glass-edge);
transition: transform .4s var(--ease);
}
.tile:hover .swatches span { transform: translateY(-6px); }
.tile:hover .swatches span:nth-child(2) { transition-delay: .04s; } .tile:hover .swatches span:nth-child(3) { transition-delay: .08s; }
.tile:hover .swatches span:nth-child(4) { transition-delay: .12s; } .tile:hover .swatches span:nth-child(5) { transition-delay: .16s; }
.sketch path { fill: none; stroke: var(--mauve); stroke-width: 2; stroke-linecap: round; stroke-dasharray: 340; stroke-dashoffset: 340; }
.sketch .note { fill: var(--peach); opacity: .85; }
.in-view .sketch path { animation: draw 1.6s var(--ease) forwards; }
.in-view .sketch path:nth-of-type(2) { animation-delay: .4s; }
@keyframes draw { to { stroke-dashoffset: 0; } }
.versions { display: grid; gap: 6px; width: 100%; font: 12px var(--mono); color: var(--muted); }
.versions div { display: flex; gap: 10px; align-items: center; }
.versions div::before { content: ""; width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--overlay); flex: none; }
.versions div:first-child { color: var(--text); }
.versions div:first-child::before { border-color: var(--mauve); background: var(--mauve); }
.peers { display: flex; align-items: center; }
.peers span {
width: 38px; height: 38px; border-radius: 50%; display: grid; place-items: center; font: 600 13px var(--sans);
color: var(--on-mauve); margin-left: -8px; border: 2px solid var(--mantle);
}
.peers span:first-child { margin-left: 0; }
/* Local-first */
.local { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
.tree { border-radius: var(--r-panel); padding: 22px 24px; font: 13px/2 var(--mono); color: var(--subtext); overflow-x: auto; min-width: 0; }
.tree .path { color: var(--muted); }
.tree .d { color: var(--mauve); }
.tree .c { color: var(--muted); }
.tree pre { margin: 0; }
.points { display: grid; gap: 14px; align-content: start; }
.point { border-radius: 16px; padding: 18px 20px; }
.point h3 { margin: 0; font-size: 16px; font-weight: 600; }
.point p { margin: 4px 0 0; color: var(--subtext); font-size: 15px; }
/* Agents */
.agents { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 20px; }
.card { border-radius: var(--r-panel); padding: 24px; min-width: 0; }
.card h3 { margin: 0; font-size: 17px; font-weight: 600; }
.card > p { color: var(--subtext); margin: 8px 0 0; font-size: 15px; }
.stat { font-family: var(--display); font-size: 72px; line-height: 1; color: var(--mauve); font-variant-numeric: tabular-nums; }
.ways { display: grid; gap: 14px; margin-top: 18px; }
.way { display: grid; grid-template-columns: 120px minmax(0, 1fr); gap: 12px; font-size: 14px; }
.way b { font-weight: 500; }
.way span { color: var(--subtext); }
.code {
position: relative; margin-top: 14px; border-radius: var(--r-control); background: var(--well);
border: 1px solid var(--glass-edge); font: 13px/1.7 var(--mono); color: var(--subtext);
}
.code pre { margin: 0; padding: 14px 16px; padding-right: 70px; overflow-x: auto; }
.code .c { color: var(--muted); }
.code .k { color: var(--mauve); }
.copy-btn {
position: absolute; top: 8px; right: 8px; font: 500 12px var(--sans); color: var(--subtext);
background: var(--glass-strong); border: 1px solid var(--glass-edge); border-radius: 8px;
padding: 5px 9px; cursor: pointer; transition: color .2s, border-color .2s;
}
.copy-btn:hover { color: var(--text); border-color: rgb(203 166 247 / .4); }
/* Shortcuts */
.keys { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; }
.key { border-radius: 16px; padding: 18px; display: grid; gap: 12px; justify-items: start; }
.key span { font-size: 14px; color: var(--subtext); }
kbd {
display: inline-flex; gap: 4px; font: 500 14px var(--mono); color: var(--text);
}
kbd b {
min-width: 30px; height: 30px; padding: 0 8px; display: grid; place-items: center; font-weight: 500;
border-radius: 8px; background: var(--well); border: 1px solid var(--glass-edge);
box-shadow: 0 2px 0 rgb(0 0 0 / .4); transition: transform .15s, box-shadow .15s;
}
.key:hover kbd b { transform: translateY(2px); box-shadow: 0 0 0 rgb(0 0 0 / .4); }
/* Download */
.dl-head { display: flex; flex-wrap: wrap; align-items: end; justify-content: space-between; gap: 16px; margin-bottom: 28px; }
.dl-head .section-head { margin: 0; }
.release-pill {
display: inline-flex; align-items: center; gap: 10px; padding: 8px 14px; border-radius: 999px;
font-family: var(--mono); font-size: 13px; color: var(--subtext); text-decoration: none;
}
.release-pill b { color: var(--text); font-weight: 500; }
.pulse { width: 8px; height: 8px; border-radius: 50%; background: var(--green); animation: pulse 2.4s infinite; }
.platforms { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
.platform { display: flex; flex-direction: column; gap: 12px; border-radius: var(--r-panel); padding: 22px; min-width: 0; }
.platform.mine { box-shadow: 0 0 0 1px rgb(203 166 247 / .55), 0 0 50px -10px var(--glow); }
.platform .tag {
position: absolute; top: 18px; right: 18px; font: 500 11px var(--mono); letter-spacing: .08em; text-transform: uppercase;
color: var(--on-mauve); background: var(--mauve); padding: 3px 8px; border-radius: 999px;
}
.platform .os { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
.platform .os svg { width: 28px; height: 28px; color: var(--text); flex: none; }
.platform h3 { margin: 0; font-size: 18px; font-weight: 600; }
.platform .arch { font-family: var(--mono); font-size: 12px; color: var(--muted); }
.file { display: grid; grid-template-columns: minmax(0, 1fr) auto; border-radius: var(--r-control); background: var(--well); border: 1px solid var(--glass-edge); transition: border-color .2s; }
.file:hover { border-color: rgb(203 166 247 / .5); }
.file a { display: grid; gap: 2px; padding: 12px 14px; text-decoration: none; min-width: 0; }
.file .fname { font: 500 14px var(--sans); }
.file .fmeta { font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; font-family: var(--mono); }
.file .sha {
align-self: center; margin-right: 8px; font: 500 11px var(--mono); color: var(--muted); cursor: pointer;
background: transparent; border: 1px solid var(--glass-edge); border-radius: 7px; padding: 5px 8px;
}
.file .sha:hover { color: var(--text); }
.platform .note { font-size: 13px; color: var(--muted); margin: auto 0 0; }
.dl-foot { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; margin-top: 16px; }
.dl-foot .card p { margin: 8px 0 0; color: var(--subtext); font-size: 14px; }
/* Status */
.status { border-radius: var(--r-panel); padding: clamp(24px, 4vw, 40px); display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 24px; align-items: center; }
.status h2 { font-size: clamp(30px, 4vw, 44px); line-height: 1.06; margin: 10px 0 0; }
.status p { color: var(--subtext); margin: 12px 0 0; max-width: 62ch; }
.status .actions { display: flex; gap: 12px; flex-wrap: wrap; }
footer { padding-block: 40px; border-top: 1px solid var(--glass-edge); margin-top: 56px; }
.foot { display: flex; flex-wrap: wrap; gap: 16px 28px; align-items: center; justify-content: space-between; color: var(--muted); font-size: 14px; }
.foot nav { display: flex; gap: 20px; flex-wrap: wrap; }
.foot a { text-decoration: none; }
.foot a:hover { color: var(--text); }
.toast {
position: fixed; left: 50%; bottom: calc(24px + env(safe-area-inset-bottom, 0px)); z-index: 40;
padding: 10px 16px; border-radius: 999px; font-size: 14px; transform: translate(-50%, 20px); opacity: 0;
transition: opacity .3s, transform .3s var(--ease); pointer-events: none;
}
.toast.on { opacity: 1; transform: translate(-50%, 0); }
/* Motion. Everything is readable at rest; motion only moves it into place. */
@media (prefers-reduced-motion: no-preference) {
.glow.a { animation: drift-a 22s ease-in-out infinite alternate; }
.glow.b { animation: drift-b 28s ease-in-out infinite alternate; }
.glow.c { animation: drift-c 26s ease-in-out infinite alternate; }
.hero-mark { animation: float 6s ease-in-out infinite; }
.rise { animation: rise .9s var(--ease) both; }
.hero h1 .w { animation: word .9s var(--ease) both; animation-delay: calc(var(--i) * 60ms + 120ms); }
.d1 { animation-delay: .1s; } .d2 { animation-delay: .45s; } .d3 { animation-delay: .6s; }
.js .reveal { opacity: .001; transform: translateY(24px); transition: opacity .8s var(--ease), transform .8s var(--ease); }
.js .reveal.in-view { opacity: 1; transform: none; }
.js .stagger > .reveal:nth-child(2) { transition-delay: .08s; }
.js .stagger > .reveal:nth-child(3) { transition-delay: .16s; }
.js .stagger > .reveal:nth-child(4) { transition-delay: .24s; }
.js .stagger > .reveal:nth-child(5) { transition-delay: .32s; }
.js .stagger > .reveal:nth-child(6) { transition-delay: .4s; }
@keyframes rise { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
@keyframes word { from { opacity: 0; transform: translateY(.4em); filter: blur(6px); } to { opacity: 1; transform: none; filter: none; } }
@keyframes float { 50% { transform: translateY(-6px); } }
@keyframes drift-a { to { transform: translate(6rem, 4rem) scale(1.1); } }
@keyframes drift-b { to { transform: translate(-8rem, -6rem) scale(1.15); } }
@keyframes drift-c { to { transform: translate(10rem, -4rem); } }
}
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
.window { --tilt: 0deg; --zoom: 1; }
.belt { animation: none; }
.track { overflow-x: auto; }
.pulse, .log-head .dot, .arrow-dash { animation: none; }
.sketch path { stroke-dashoffset: 0; }
}
@media (max-width: 960px) {
.feature, .feature:nth-child(even) { grid-template-columns: minmax(0, 1fr); }
.feature:nth-child(even) .copy { order: 0; }
.agents, .platforms, .local, .dl-foot, .live { grid-template-columns: minmax(0, 1fr); }
.log { border-right: 0; border-bottom: 1px solid var(--glass-edge); }
.bento { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.keys { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.status { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 640px) {
.nav-links { display: none; }
.nav-bar .btn { margin-left: auto; }
.way { grid-template-columns: minmax(0, 1fr); gap: 2px; }
.window { --tilt: 0deg; --zoom: 1; padding: 6px; }
.chrome { display: none; }
.bento { grid-template-columns: minmax(0, 1fr); }
.tile.wide { grid-column: auto; }
.keys { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
+347
View File
@@ -0,0 +1,347 @@
const REPO = 'nxtime/papercraft';
const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;
const ICONS = {
windows: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M3 5.5 10.5 4.4v7.1H3V5.5Zm0 13 7.5 1.1v-7H3v5.9Zm8.4 1.2L21 21V12.6h-9.6v7.1Zm0-15.4v7.2H21V3l-9.6 1.3Z"/></svg>',
macos: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M16.4 12.6c0-2.4 2-3.6 2.1-3.7-1.1-1.7-2.9-1.9-3.5-1.9-1.5-.2-2.9.9-3.7.9-.8 0-1.9-.9-3.2-.8-1.6 0-3.1 1-4 2.4-1.7 3-.4 7.3 1.2 9.7.8 1.2 1.8 2.5 3 2.4 1.2 0 1.7-.8 3.1-.8 1.5 0 1.9.8 3.2.8 1.3 0 2.2-1.2 3-2.4.9-1.4 1.3-2.7 1.3-2.8 0 0-2.5-1-2.5-3.8ZM14 5.4c.7-.8 1.1-1.9 1-3-.9 0-2.1.6-2.8 1.4-.6.7-1.2 1.9-1 2.9 1.1.1 2.1-.5 2.8-1.3Z"/></svg>',
linux: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2c-2 0-3.3 1.7-3.3 4.2 0 1.4.4 2.4-.4 3.7C7 12 5.5 14 5.5 16.3c0 .6.1 1.1.4 1.6-.9.4-2 .9-2 1.8 0 1.2 1.9 1.3 3.5 1.8 1.3.4 2 .5 2.6-.3.4.1 1.2.2 2 .2s1.6-.1 2-.2c.6.8 1.3.7 2.6.3 1.6-.5 3.5-.6 3.5-1.8 0-.9-1.1-1.4-2-1.8.3-.5.4-1 .4-1.6 0-2.3-1.5-4.3-2.8-6.4-.8-1.3-.4-2.3-.4-3.7C15.3 3.7 14 2 12 2Zm-1.4 4c.4 0 .7.5.7 1.1s-.3 1-.7 1-.7-.4-.7-1 .3-1.1.7-1.1Zm2.8 0c.4 0 .7.5.7 1.1s-.3 1-.7 1-.7-.4-.7-1 .3-1.1.7-1.1ZM12 9c.9 0 2 .6 2 1s-1.1 1-2 1-2-.6-2-1 1.1-1 2-1Z"/></svg>'
};
const PLATFORMS = [
{ key: 'windows', name: 'Windows', arch: 'x86_64', note: 'App, CLI, MCP bridge and relay in one zip.' },
{ key: 'macos', name: 'macOS', arch: 'Apple silicon', note: 'PaperCraft.app in a disk image, plus the CLI tools.' },
{ key: 'linux', name: 'Linux', arch: 'x86_64 · X11 and Wayland', note: 'Needs Vulkan or GL and the usual X11 libraries.' }
];
const OS = (() => {
const ua = navigator.userAgent;
if (/Windows/i.test(ua)) return 'windows';
if (/Macintosh|Mac OS X/i.test(ua) && !/iPhone|iPad/i.test(ua)) return 'macos';
if (/Linux/i.test(ua) && !/Android/i.test(ua)) return 'linux';
return null;
})();
const toast = message => {
const el = document.getElementById('toast');
el.textContent = message;
el.classList.add('on');
clearTimeout(toast.timer);
toast.timer = setTimeout(() => el.classList.remove('on'), 1800);
};
const copy = (text, label) => navigator.clipboard.writeText(text)
.then(() => toast(`${label} copied`))
.catch(() => toast('Copy was blocked. Select the text instead.'));
const escapeHtml = s => s.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
/* Release: release.json is written by the site workflow; the GitHub API is the fallback. */
const formatSize = bytes => `${(bytes / 1048576).toFixed(1)} MB`;
const formatDate = iso => new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
const fileType = name => (name.endsWith('.tar.gz') ? 'tar.gz' : name.split('.').pop());
const fileLabel = name => (name.includes('-cli-') ? 'CLI tools' : 'Desktop app');
const loadRelease = async () => {
try {
const res = await fetch('release.json', { cache: 'no-cache' });
if (res.ok) return await res.json();
} catch (err) {
console.warn('release.json is unavailable, asking the GitHub API', err);
}
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`);
if (!res.ok) throw new Error(`The GitHub API answered ${res.status}`);
const r = await res.json();
return {
tag: r.tag_name,
name: r.name,
publishedAt: r.published_at,
url: r.html_url,
assets: r.assets.map(a => ({ name: a.name, size: a.size, url: a.browser_download_url, digest: a.digest || null }))
};
};
const renderRelease = release => {
const grid = document.getElementById('platforms');
document.querySelectorAll('[data-version]').forEach(el => { el.textContent = release.tag; });
document.getElementById('release-date').textContent = formatDate(release.publishedAt);
document.getElementById('release-link').href = release.url;
grid.innerHTML = PLATFORMS.map(p => {
const files = release.assets.filter(a => a.name.includes(`-${p.key}-`));
const mine = p.key === OS;
const rows = files.map(a => `
<div class="file">
<a href="${escapeHtml(a.url)}">
<span class="fname">${fileLabel(a.name)}</span>
<span class="fmeta">${fileType(a.name)} · ${formatSize(a.size)}</span>
</a>
${a.digest ? `<button class="sha" type="button" data-digest="${escapeHtml(a.digest)}" title="Copy the SHA-256 checksum">SHA-256</button>` : ''}
</div>`).join('');
return `
<article class="platform acrylic lit reveal${mine ? ' mine' : ''}">
${mine ? '<span class="tag">Your system</span>' : ''}
<div class="os">${ICONS[p.key]}<div><h3>${p.name}</h3><div class="arch">${p.arch}</div></div></div>
${rows || '<p class="note">No build in this release. Build from source.</p>'}
<p class="note">${p.note}</p>
</article>`;
}).join('');
grid.querySelectorAll('.sha').forEach(btn => {
btn.addEventListener('click', () => copy(btn.dataset.digest.replace(/^sha256:/, ''), 'Checksum'));
});
grid.querySelectorAll('.reveal').forEach(el => revealer.observe(el));
grid.querySelectorAll('.lit').forEach(light);
const primary = OS && release.assets.find(a => a.name.includes(`-${OS}-`) && !a.name.includes('-cli-'));
if (primary) {
document.getElementById('hero-dl').href = primary.url;
document.getElementById('hero-dl-label').textContent = `Download for ${PLATFORMS.find(p => p.key === OS).name}`;
}
};
const showReleaseError = err => {
console.error(err);
document.getElementById('platforms').innerHTML = `
<article class="platform acrylic">
<h3>The release list did not load</h3>
<p class="note">Every build is on the GitHub releases page.</p>
<a class="btn btn-ghost" href="https://github.com/${REPO}/releases/latest">Open releases</a>
</article>`;
};
/* Motion */
const revealer = new IntersectionObserver(entries => {
entries.forEach(e => {
if (!e.isIntersecting) return;
e.target.classList.add('in-view');
revealer.unobserve(e.target);
});
}, { rootMargin: '0px 0px -8% 0px' });
const light = el => {
el.addEventListener('pointermove', e => {
const r = el.getBoundingClientRect();
el.style.setProperty('--lx', `${e.clientX - r.left}px`);
el.style.setProperty('--ly', `${e.clientY - r.top}px`);
});
};
const splitHeadline = () => {
const h1 = document.getElementById('headline');
let i = 0;
const wrap = node => {
if (node.nodeType === Node.TEXT_NODE) {
const frag = document.createDocumentFragment();
node.textContent.split(/(\s+)/).forEach(part => {
if (!part) return;
if (/^\s+$/.test(part)) { frag.append(part); return; }
const span = document.createElement('span');
span.className = 'w';
span.style.setProperty('--i', i++);
span.textContent = part;
frag.append(span);
});
node.replaceWith(frag);
return;
}
[...node.childNodes].forEach(wrap);
};
[...h1.childNodes].forEach(wrap);
};
const onScroll = () => {
const y = scrollY;
const max = document.documentElement.scrollHeight - innerHeight;
const win = document.getElementById('window');
const rect = win.getBoundingClientRect();
const t = Math.min(1, Math.max(0, 1 - rect.top / (innerHeight * 0.8)));
document.getElementById('nav').classList.toggle('scrolled', y > 24);
document.querySelector('.progress').style.setProperty('--p', max > 0 ? (y / max).toFixed(4) : 0);
if (!REDUCED && innerWidth > 640) {
win.style.setProperty('--tilt', `${(10 * (1 - t)).toFixed(2)}deg`);
win.style.setProperty('--zoom', (0.96 + 0.04 * t).toFixed(4));
}
};
const tiltShots = () => {
document.querySelectorAll('.tilt').forEach(box => {
const shot = box.querySelector('.shot');
box.addEventListener('pointermove', e => {
const r = box.getBoundingClientRect();
const x = (e.clientX - r.left) / r.width - 0.5;
const y = (e.clientY - r.top) / r.height - 0.5;
shot.style.setProperty('--ry', `${(x * 6).toFixed(2)}deg`);
shot.style.setProperty('--rx', `${(-y * 6).toFixed(2)}deg`);
});
box.addEventListener('pointerleave', () => {
shot.style.setProperty('--ry', '0deg');
shot.style.setProperty('--rx', '0deg');
});
});
};
const countUp = el => {
const to = Number(el.dataset.to);
const start = performance.now();
const step = now => {
const k = Math.min(1, (now - start) / 1200);
el.textContent = Math.round(to * (1 - Math.pow(1 - k, 3)));
if (k < 1) requestAnimationFrame(step);
};
requestAnimationFrame(step);
};
/* The live agent demo: each tool call lights up, then the artboard shows its effect. */
const runDemo = () => {
const calls = [...document.querySelectorAll('#calls .call')];
const board = document.getElementById('board');
const pill = document.getElementById('mode-pill');
const undo = document.getElementById('undo-count');
const flash = document.getElementById('flash');
const lint = document.getElementById('lint');
const effects = [
() => board.classList.add('s1'),
() => board.classList.add('s2'),
() => board.classList.add('s3'),
() => board.classList.add('s4'),
() => { board.classList.add('light'); pill.textContent = 'Mode: Light'; },
() => { flash.classList.remove('on'); void flash.offsetWidth; flash.classList.add('on'); },
() => lint.classList.add('on')
];
let step = 0;
let timer = null;
const reset = () => {
step = 0;
calls.forEach(c => c.classList.remove('run', 'done'));
board.className = 'board';
pill.textContent = 'Mode: Dark';
lint.classList.remove('on');
undo.textContent = '0 undo steps';
};
const tick = () => {
if (step === calls.length) {
timer = setTimeout(() => { reset(); tick(); }, 3200);
return;
}
const call = calls[step];
call.classList.add('run');
timer = setTimeout(() => {
call.classList.replace('run', 'done');
effects[step]();
step++;
undo.textContent = `${step} undo step${step === 1 ? '' : 's'}`;
timer = setTimeout(tick, 380);
}, 620);
};
if (REDUCED) {
calls.forEach((c, i) => { c.classList.add('done'); effects[i](); });
undo.textContent = `${calls.length} undo steps`;
return;
}
new IntersectionObserver(([e]) => {
if (e.isIntersecting && !timer) tick();
if (!e.isIntersecting && timer) { clearTimeout(timer); timer = null; reset(); }
}, { threshold: 0.35 }).observe(document.getElementById('live-demo'));
};
const keyLabels = () => {
const mac = OS === 'macos';
const names = mac ? { mod: '⌘', alt: '⌥', shift: '⇧' } : { mod: 'Ctrl', alt: 'Alt', shift: 'Shift' };
document.querySelectorAll('kbd[data-keys]').forEach(kbd => {
kbd.innerHTML = kbd.dataset.keys.split(' ').map(k => `<b>${names[k] || k}</b>`).join('');
});
};
const activeNav = () => {
const links = [...document.querySelectorAll('.nav-links a[href^="#"]')];
const spy = new IntersectionObserver(entries => {
entries.forEach(e => {
if (!e.isIntersecting) return;
links.forEach(a => a.classList.toggle('active', a.getAttribute('href') === `#${e.target.id}`));
});
}, { rootMargin: '-45% 0px -50% 0px' });
links.forEach(a => {
const target = document.querySelector(a.getAttribute('href'));
if (target) spy.observe(target);
});
};
/* Boot */
document.documentElement.classList.add('js');
splitHeadline();
keyLabels();
activeNav();
tiltShots();
runDemo();
document.querySelectorAll('.reveal').forEach(el => revealer.observe(el));
document.querySelectorAll('.lit').forEach(light);
document.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', () => copy(btn.dataset.copy, 'Command'));
});
const belt = document.querySelector('.belt');
const twin = belt.cloneNode(true);
// A second copy makes the loop seamless; screen readers only need the first.
twin.setAttribute('aria-hidden', 'true');
belt.after(twin);
const counter = document.getElementById('tool-count');
new IntersectionObserver(([e], obs) => {
if (!e.isIntersecting) return;
if (!REDUCED) countUp(counter);
obs.disconnect();
}, { threshold: 0.6 }).observe(counter);
addEventListener('scroll', onScroll, { passive: true });
addEventListener('resize', onScroll);
onScroll();
addEventListener('pointermove', e => {
const spot = document.querySelector('.spot');
spot.style.setProperty('--mx', `${e.clientX}px`);
spot.style.setProperty('--my', `${e.clientY}px`);
}, { passive: true });
loadRelease().then(renderRelease).catch(showReleaseError);
+83 -153
View File
@@ -1,180 +1,110 @@
---
name: papercraft-critique
description: Pre-emit critique gate for work built in PaperCraft. Five panels (designer, critic, brand, accessibility, copy) score a screen 0-10 against PaperCraft's own objective evidence (lint_design, verify_code, get_screenshot, get_design_spec, get_variables), the weighted composite must reach 8.0, and a failed gate ships the best round instead of the last one. Use when an agent is about to hand over a PaperCraft screen and wants a tool-backed review instead of a self-praise.
description: Critique finished PaperCraft work the way a design team does - against the person's objective, through independent reviewers (the person's vision, UX heuristics, flow across screens, QA states, visual, accessibility, copy, an end user from the audience), each finding rated 0-4 and backed by tool evidence, then fixed, reported and, when the person approves, kept as a lesson. Use when finish_working_on_nodes offers a critique, when asked to review or critique a design, or before handing over a screen or flow.
---
# papercraft-critique
A gate, not a compliment. Before a screen leaves the app it goes through five panels. Each panel is a rubric pass over the same artifact, and each panel may only cite what a PaperCraft tool actually returned. The panels produce five scores, the scores produce one composite, and the composite decides whether the work ships. Mechanics live in the `papercraft` skill, taste in `papercraft-design`; this skill is the gate.
A critique judges a design against what it is for, not against taste. The tool `critique_design`
hands you the evidence and the reviewers; this skill is how to run them. Mechanics live in the
`papercraft` skill, taste in `papercraft-design`. Per-reviewer checklists:
[personas.md](references/personas.md).
Reference: [panels.md](references/panels.md) (what each panel inspects, which tool backs it, its 0–10 bands).
## 1. When
## 1. When the gate runs
* `finish_working_on_nodes` returns `next`: ask the person (`ask_user`) whether to critique now.
* The person asks "review this", "is it ready?", "critique it".
* Before handing over a whole screen or flow. Not for one component, an early draft or a copy tweak.
Run it when the resolver (section 2) says on, or when the request is a review of finished work:
## 2. Objective first
* a whole screen is about to be handed over: landing page, dashboard, sign-in, settings, an onboarding flow, a whiteboard plan;
* a redesign of an existing screen, after the edits and a clean `lint_design`;
* the user asked "does this look right?", "review this", "critique it", "is it ready to ship?".
Critique without an objective is opinion. Before judging, have:
Do not run it for: a single component or icon, an exploratory draft before a direction is chosen (the `papercraft-design` section 0 step), or a one-line copy tweak. The gate costs a lint and a screenshot per round; spend it on work that is finished.
* **Objective**: what the work must achieve ("a returning customer reorders in two taps").
* **Audience**: who uses it, in what context (phone, in a hurry, first visit, low vision).
* **Top tasks**: the two to five things people come to do.
If the gate is on for a run, it must produce a status. Never skip it silently: report `Degraded` with the reason.
Take them from the brief, the spec, the person's notes (`get_feedback`) and references. Missing?
Ask with `ask_user` and pass them to `critique_design {objective, audience}`.
## 2. Enable resolver
## 3. The reviewers
Four levels, highest priority first. Take the first level that gives an explicit answer; "unset" falls through to the next one. A higher level saying *off* is final — a lower level cannot turn the gate back on.
| Order | Level | PaperCraft equivalent | How to read it |
|---|---|---|---|
| 1 | Per-task policy | the instruction the agent was given for this run | "run the critique gate before you finish", "review this screen" |
| 2 | Per-project setting | a toggle stored in the project's own metadata | **not implemented today** — PaperCraft has no project-level flag. Treat this level as unset and fall through to the environment flag or the per-task instruction |
| 3 | Environment flag | `PAPERCRAFT_CRITIQUE_ENABLED` | `1` / `true` / `always` = on, `0` / `false` / `never` = off, unset = fall through |
| 4 | Rollout phase | the release phase of the skill itself | off by default: the gate ships disabled until a run or a project turns it on |
So today the gate turns on in one of two ways: the user asks for it in the run's instructions, or `PAPERCRAFT_CRITIQUE_ENABLED=1` is in the environment. A future project setting — stored with the project, not with the user — would sit between those two and win over the environment, so a project could opt in permanently without an env var.
## 3. Order of operations
Objective checks first, subjective panels second. A panel never scores above evidence that contradicts it.
One round is: **evidence → repair → judge → score**.
1. **Snapshot.** Note the `pageId` and the artboard `nodeId` under review and keep them for the whole gate. A page switch between rounds invalidates the evidence.
2. **Evidence.** `lint_design` (`nodeId`, `pageId`, no `fix` yet) for the raw findings — the payload counts `errors`, `warnings` and `info`, groups them in `byRule`, and lists each issue with its `rule`, `severity`, `node`, `message` and `fix`; `get_screenshot` of the same node (`scale: 2` to read small text); `get_variables` for the token set and the active mode; `get_design_spec` (`nodeId`, `target`) when the design is headed for code. If there is code to check, `verify_code` (`nodeId`, `target`, `code`).
3. **Repair the hard evidence.** Fix every `lint_design` error and warning and re-run the lint until it is clean; fix every `verify_code` violation until `passed` is true. A panel cannot be scored on a design that still carries a lint error.
4. **Judge the five panels** on the evidence from steps 2–3 plus the screenshot. Every finding cites the tool result or the screenshot region behind it.
5. **Score.** Five scores 0–10, then the composite (section 5). Composite ≥ 8.0 → status `Shipped`, stop, `finish_working_on_nodes`.
6. **Otherwise fix and go again.** Take the findings in composite-impact order, fix them, run round N+1. Maximum 3 rounds.
7. **Ship the best round** if round 3 is still below the threshold (section 6).
The panels are rubric passes by the agent that holds the tools: one agent, five passes, five different rubrics. A runtime that can spawn subagents may run the panels in parallel, but the evidence vetoes, the composite and the round counter belong to the coordinator.
## 4. Hard evidence vetoes a panel
`lint_design` and `verify_code` are not suggestions. Each finding belongs to one panel, and that panel cannot score above the band its evidence forces.
| Evidence | Rule | Owner panel | Cap |
|---|---|---|---|
| `lint_design` error | `contrast` | Accessibility (the Critic reads it too) | 3.9 |
| `lint_design` warning | `text-size` (under 12px) | Accessibility | 6.9 |
| `lint_design` warning | `spacing-grid` (off the 4px grid) | Designer | 6.9 |
| `lint_design` warning | `touch-target` (under 44px) | Accessibility | 6.9 |
| `lint_design` warning | `layer-name` (default names) | Designer | 6.9 |
| `lint_design` warning | `hard-coded-color` | Brand | 6.9 |
| `lint_design` info | `type-scale` | Designer | none — must be listed |
| `verify_code` error | `missing-text` | Copy | 3.9 |
| `verify_code` error | `hardcoded-color` | Brand | 3.9 |
| `verify_code` error | `forbidden-absolute` | Designer | 3.9 |
| `verify_code` error | `missing-layout` | Designer | 3.9 |
| `verify_code` warning | `missing-component` | Brand | 6.9 |
| `verify_code` warning | `spacing-drift` | Designer | 6.9 |
An error caps the owning panel at 3.9 (Blocker band), a warning at 6.9 (Weak band), an `info` item caps nothing but must appear in the panel's notes. `hard-coded-color` arrives in both flavours: a warning when the color equals a variable that exists, an info when it is a literal used several times — the warning caps Brand, the info does not. The cap lifts as soon as the finding is gone; the next round re-scores the panel freely.
A finding is evidence for its owner and a hint for the others: `contrast` also informs the Critic, `spacing-grid` also informs the Brand (was it the token or the layout?), but only the owner is capped.
## 5. The panels and the composite
| Panel | Judges | Weight |
| Persona | Asks | Method |
|---|---|---|
| Designer | layout, composition, hierarchy, spacing rhythm, type scale in use | **0 in v1** — it still scores and its findings still drive the next round |
| Critic | does it meet the brief; contrast, weight, readability | 0.4 |
| Brand | token compliance, on-brand color, voice | 0.2 |
| Accessibility | WCAG, focus rings, semantic structure, alt text | 0.2 |
| Copy | voice, tone, terseness, error-message quality | 0.2 |
| `vision` | Does it achieve the objective, as the person imagined it? | Objective, element, effect, why (Connor and Irizarry) |
| `ux` | Can people use it without help? | Nielsen's 10 heuristics |
| `flow` | Do the screens make one coherent journey per task? | Task walkthrough across screens, 4 questions per step |
| `qa` | What breaks with real data and states? | State and edge-case matrix, pass/fail/n.a. |
| `visual` | Does the eye land right, does it hold together? | Hierarchy, balance, contrast, gestalt, rhythm, tokens |
| `accessibility` | Can everyone use it? | W3C POUR applied to a design |
| `copy` | Is every word clear and specific? | Plain language, labels, errors, empty states |
| `end-user` | Where would this user get stuck or give up? | Persona walkthrough of the top task |
```
composite = critic x 0.4 + brand x 0.2 + accessibility x 0.2 + copy x 0.2
```
`vision` always runs: the person's intent is the yardstick for the others. Pick the rest with
`personas` (default: all). The person's own words outrank any reviewer.
The weights sum to 1.0, so the composite is also 0–10. The Designer carries weight 0 in v1 on purpose: it is the panel most likely to argue with itself, so its score is reported and its findings are acted on, but it does not move the composite.
## 4. Independence
Each panel scores 0–10 in half-point steps. The composite is the weighted sum, rounded to two decimals.
Several reviewers find far more than one, but only when they work apart (Nielsen: one
evaluator finds about a third of the problems, three to five most of them). Reviewers who
discuss or debate converge and amplify each other's bias.
| Composite | Verdict |
* **With subagents**: one subagent per persona, given only its persona brief, the objective and
the evidence. No reviewer sees another's findings before rating.
* **Alone**: one pass per persona, in order, writing that persona's findings before reading the
next brief. Do not revise earlier personas' findings during later passes.
* **You coordinate**: you merge and judge; you never let reviewers argue a finding out.
## 5. Evidence
From `critique_design`: lint (fix every error and warning first), the `flow` graph (arrows between
screens, `deadEnds`, `unreached`), the lessons. Then `get_screenshot` each artboard at scale 1
(2 for small text) in every variable mode, `get_bounds` for overflow, `get_feedback` for the
person's notes. Every finding cites one of these: a tool result or a screenshot region. No
evidence, no finding.
## 6. A finding
`persona`, `heuristic or check`, `element` (layer name), `seen` (the observation), `effect` (on
the objective), `evidence`, `severity`, `suggestion`. Keep the observation and the suggestion
apart: critique is analysis, not brainstorming. Each persona also names at least one thing that
works and should stay.
Severity (Nielsen), from frequency, impact and persistence:
| | |
|---|---|
| ≥ 8.0 | Ship |
| < 8.0 | Not shippable as is: fix and re-run, or ship the best round after round 3 |
| 0 | not a problem |
| 1 | cosmetic: fix if time allows |
| 2 | minor: low priority |
| 3 | major: fix before handing over |
| 4 | catastrophe: blocks the task, fix now |
The band legend is the same for every panel:
Every broken lesson (`lessons`) is a finding of at least 3.
| Band | Range | Means |
|---|---|---|
| Blocker | 0.0–2.9 | Broken: the panel's own evidence is violated. Cannot ship |
| Poor | 3.0–4.9 | Works against the brief or the brand; ships visible damage |
| Weak | 5.0–6.9 | Passable but noticeably off; expect a second round |
| Acceptable | 7.0–7.9 | No blocker, but a reviewer would ask for one change |
| Good | 8.0–9.4 | Ships as is |
| Excellent | 9.5–10.0 | Reference quality for this project |
## 7. Merge, fix, report
What each panel inspects, which tool backs it and where its scores land: [panels.md](references/panels.md).
1. **Merge** into one list: join duplicates, count the personas that found each (two or more is
confirmed), severity is the mean of their independent ratings.
2. **Fix** every 3 and 4 with the smallest edit (`update_styles`, `set_text_content`), then check
that finding again with the same evidence. The work is ready when no 3 or 4 is open and lint is
clean. Three fix rounds at most; then hand over with the open findings stated.
3. **Report** to the person: what works, then findings by severity, each with what was seen, the
evidence, the suggestion and whether it was fixed. Phrase open ones as questions about the
objective ("How does a first-time user find Reorder from here?"), not verdicts.
## 6. Rounds and the fallback
## 8. Lessons
* At most **3 rounds** per gate. The counter is per gate, not per panel.
* A round ends when the composite is computed.
* Rounds 2 and 3 exist to fix what the panels found. Fix in composite-impact order: the panel with the largest `weight x (10 - score)` first.
* **`fallbackPolicy: ship_best`.** If the third round is still below 8.0, the status is `Below threshold` and what ships is the best round, not the last one. Best = highest composite; a tie goes to the earlier round (fewer changes). A later round edited the canvas, so put the canvas back into the best round's state before handing over — undo back to it, or re-apply that round's fix list in order.
* Ship the best round's artifact and report the failing score. `Below threshold` is a status, not a licence to hide the number.
Ask the person with `ask_user` which findings to remember, one question per finding: for every
project, for this project, or not. Save only what they approve, with
`design_lessons {add: {rule, why, scope}}`: the rule is one line written as an instruction
("Screens keep their device height; the main column scrolls"), `why` is what went wrong. Never
save a lesson the person did not approve, and never save praise. Lessons come back in
`get_basic_info` and in the next `critique_design`; `design_lessons {remove: "L3"}` drops one.
## 7. Status vocabulary
## Sources
Every gate ends with exactly one status.
| Status | When | What ships |
|---|---|---|
| `Shipped` | composite ≥ 8.0 | the reviewed artifact, unchanged |
| `Below threshold` | still < 8.0 after round 3 | the best-scoring round's artifact (`ship_best`), with the score reported |
| `Timed out` | the gate ran out of its budget (rounds or minutes) before a verdict | the best round so far, with the timeout stated |
| `Interrupted` | the user or the session stopped the gate mid-run | the last complete round's artifact |
| `Degraded` | a panel could not be judged properly (section 8) | the artifact, but the verdict is provisional and the reason is named |
`Degraded` outranks `Shipped`: a degraded panel is capped at 6.9, so a degraded run reports `Degraded`, not `Shipped`, even when the composite clears 8.0.
## 8. Degraded reasons
A panel that cannot be judged on real evidence is not scored as if it were fine. It is capped at 6.9, the composite is computed with the cap, and the run reports `Degraded` with the reason and the panel it hit.
| Reason | Cause | Handling |
|---|---|---|
| `malformed_block` | a tool returned something the gate could not parse (lint payload in an unexpected shape, a truncated screenshot answer) | retry the tool once; if it still fails, judge the panel on the evidence you do have and name the missing part |
| `oversize_block` | the evidence was too big to read whole (a screenshot scaled down past legibility, a tree deeper than the context, a lint payload whose `truncated` flag is set) | narrow the scope: screenshot or lint a subtree, split the screen into regions and judge region by region |
| `adapter_unsupported` | the requested target or format is not supported here (a `verify_code` target the project does not build) | drop that check; the panel falls back to the screenshot plus the design rules |
| `protocol_version_mismatch` | the MCP server exposes a different tool set than the gate expects (a tool renamed, an argument changed) | stop using the broken tool, finish what you can, report `Degraded`; do not guess the schema |
| `missing_artifact` | the thing under review is gone (artboard deleted, page switched, stale node id) | re-snapshot with `get_basic_info` and restart the gate; if the artifact is truly gone, report `Degraded` |
Degradation is a report, not an excuse: name the reason, the panel and the evidence you lost.
## 9. What the gate reports
End the gate with the status, the numbers and the findings, in that order:
```
Critique gate - Sign in (page p1, artboard 3fa9c1:7)
Round 2 of 3 - composite 8.44 / threshold 8.00 - status Shipped
Designer 7.5 (weight 0) | Critic 8.5 | Brand 8.5 | Accessibility 8.5 | Copy 8.2
Composite = 8.5x0.4 + 8.5x0.2 + 8.5x0.2 + 8.2x0.2 = 8.44
```
Then, per finding: the panel, what was seen, the evidence behind it (tool and finding, or the region of the screenshot), the fix, and whether it was fixed in this round or is still open.
Machine-readable form, when the caller wants JSON:
```json
{
"status": "Shipped",
"threshold": 8.0,
"composite": 8.44,
"round": 2,
"rounds": [{ "round": 1, "composite": 7.35 }, { "round": 2, "composite": 8.44 }],
"scores": { "designer": 7.5, "critic": 8.5, "brand": 8.5, "accessibility": 8.5, "copy": 8.2 },
"weights": { "designer": 0.0, "critic": 0.4, "brand": 0.2, "accessibility": 0.2, "copy": 0.2 },
"degraded": [],
"findings": [{ "panel": "critic", "evidence": "get_screenshot: headline at 16px over a photo", "severity": "warning", "state": "fixed" }]
}
```
## 10. Attribution
The five-panel critique contract — the roles, the weights, the composite, the 8.0 threshold, the three rounds and the `ship_best` fallback — is inspired by OpenDesign's Critique Theater (https://github.com/nexu-io/open-design, Apache-2.0). The contract is re-implemented here in PaperCraft's own words and against PaperCraft's own tools; no text was copied.
Adam Connor and Aaron Irizarry, *Discussing Design* (objective, element, effect, rationale);
Nielsen Norman Group: 10 usability heuristics, severity ratings, cognitive walkthroughs, design
critiques, visual design principles; W3C WAI accessibility principles (POUR); work on panels of
independent LLM judges (debate amplifies bias, a coordinating judge resists it).
@@ -1,182 +0,0 @@
# Panel rubrics
Five panels, one artifact, one set of evidence. A panel is a pass with a fixed rubric: what it inspects, which tool output backs it, what it does **not** judge, and the band each finding lands in. The panels share the band legend in [../SKILL.md](../SKILL.md) (Blocker 0–2.9, Poor 3–4.9, Weak 5–6.9, Acceptable 7–7.9, Good 8–9.4, Excellent 9.5–10).
## How to run one panel
1. Read the evidence you were handed: the lint payload, the screenshot, the design spec, the variables, the code result.
2. Write findings. Every finding cites its evidence — the lint rule and node, the region of the screenshot, the spec's MUST rule, the `verify_code` violation.
3. Score the panel 0–10. The score is the panel's verdict on the whole screen, not an average of its findings: two serious defects on one region cost more than two trivial ones on two regions, but a screen with three medium defects is not "Good" either.
4. Apply the caps. Hard evidence caps the owning panel (SKILL.md section 4); degraded evidence caps it at 6.9 (SKILL.md section 8).
Evidence a panel may not use: taste, guesses about a user's preferences, or a claim about something no tool showed. When a panel wants to judge what no tool exposes — whether an image is meaningful, whether a flow makes sense — it raises the question as an open item instead of scoring it as a defect.
Tool arguments used below are the current names. Note that `lint_design`'s `scale` is the list of allowed font sizes, not a zoom; the zoom argument of `get_screenshot` is `scale: 1 | 2`.
---
## Designer — weight 0 in v1
**Judges:** layout and composition, alignment, spacing rhythm, hierarchy, the type scale in use, how things are grouped, screen states, overflow, density.
**Evidence it uses**
| Tool | How |
|---|---|
| `get_screenshot` (`nodeId`, `scale: 2`) | the primary evidence: alignment, edges, rhythm, hierarchy, clipping, empty areas |
| `lint_design` (`nodeId`, `pageId`) | `spacing-grid`, `type-scale`, `layer-name` findings |
| `get_design_spec` (`nodeId`, `target`) | flow and sizing (`fixed`, `hug`, `fill`), grouping, where the spacing rules were broken |
| `get_tree_summary` (`nodeId`, `depth`) | structure depth, unnamed frames, accidental nesting |
**Does not judge:** contrast and WCAG (Accessibility), token and palette choices (Brand), wording (Copy).
**Bands**
| Band | What the Designer saw |
|---|---|
| 0.0–2.9 | Broken layout: frames overlap, content sits outside the artboard, text is clipped, the screen reads as a pile |
| 3.0–4.9 | Poor composition: everything on the default grid, equal weight everywhere, no grouping, ragged edges |
| 5.0–6.9 | Weak: spacing off the 4px grid in places, sizes off the type scale, mixed grouping (space *and* containers everywhere), a state missing |
| 7.0–7.9 | Acceptable: coherent, but one region is crowded or one rhythm is broken |
| 8.0–9.4 | Good: clear hierarchy, aligned to a few strong edges, consistent rhythm, states present |
| 9.5–10.0 | Excellent: deliberate rhythm, one memorable idea, whitespace used as a material |
**Fixes that move the score:** snap spacing to the 4/8 scale (`lint_design` with `fix: true`), pull one size step per level, give each group either a container or space — not both, align to one left edge, add the missing empty/loading/error state.
---
## Critic — weight 0.4
**Judges:** whether the screen meets the brief (the request this run is executing), whether visual weight matches the priority, readability as a human experiences it, and whether the real cases are covered.
**Evidence it uses**
| Tool | How |
|---|---|
| the brief | the user's request and the `papercraft-design` section 0 direction, read against the screenshot |
| `get_screenshot` (`nodeId`, `scale: 2`) | one primary action, reading order, what is above the fold, legibility by eye |
| `lint_design` (`nodeId`, `pageId`) | `contrast`, `text-size`, `type-scale` findings as the objective part of readability |
| `get_design_spec` (`nodeId`, `target`) | what the screen actually contains, against what was asked for |
| `verify_code` (`nodeId`, `target`, `code`) | when the design is code-bound: whether the implementation kept the intent |
**Does not judge:** which palette (Brand), line-level wording (Copy), implementation details beyond fidelity to the design.
**Bands**
| Band | What the Critic saw |
|---|---|
| 0.0–2.9 | Misses the brief: wrong screen or wrong content, the primary action is absent or ambiguous |
| 3.0–4.9 | Fights the brief: right elements, wrong order or emphasis, or hard to read (contrast errors, tiny type) |
| 5.0–6.9 | Weak: it does the job, but the weight is flat and something important sits below the fold or is buried |
| 7.0–7.9 | Acceptable: meets the brief; one area stays unclear or the priority is not obvious |
| 8.0–9.4 | Good: the brief is met, the primary action is obvious, readability is solid |
| 9.5–10.0 | Excellent: unmistakable hierarchy, the screen reads in one pass, the edge cases are covered |
**Fixes that move the score:** make one thing clearly primary and quiet the rest, move the important content up, cut a competing element, re-read the brief line by line and check each requirement against the screenshot.
---
## Brand — weight 0.2
**Judges:** token compliance, on-brand color, semantic color use, mode coverage, product voice consistency, component reuse.
**Evidence it uses**
| Tool | How |
|---|---|
| `get_variables` (`pageId`, `format`) | the variables, tokens, active `mode` and available `modes` — the reference palette |
| `lint_design` (`nodeId`, `pageId`) | `hard-coded-color` findings |
| `get_computed_styles` (`nodeIds`) / `find_nodes` (`filters`) | fills and text colors that are not following a variable |
| `get_design_spec` (`nodeId`, `target`) | which tokens the design already binds |
| `get_components` / `get_tree_summary` | components built and instanced versus copies |
| `verify_code` (`nodeId`, `target`, `code`) | `hardcoded-color`, `missing-component` in the implementation |
**Does not judge:** composition (Designer), wording line by line (Copy), whether the layout serves the brief (Critic).
**Bands**
| Band | What the Brand saw |
|---|---|
| 0.0–2.9 | Off-system: hard-coded colors where tokens belong, a foreign palette, no modes |
| 3.0–4.9 | Off-brand: technically on-token but the accent is used everywhere, or the screens read as different products |
| 5.0–6.9 | Weak: one or two hard-coded colors, the accent covers much of the screen, components copied instead of instanced |
| 7.0–7.9 | Acceptable: on-system, with one token or component inconsistency |
| 8.0–9.4 | Good: every color is a token, the accent marks the primary action only, modes defined and checked, components reused |
| 9.5–10.0 | Excellent: coherent across screens and modes, the palette carries meaning |
**Fixes that move the score:** `lint_design` with `fix: true` relinks hard-coded colors that match a variable, add the missing variable before using the color, cut accent back to the primary action, build the repeated part once and place instances, check the second mode with `set_variable_mode`.
---
## Accessibility — weight 0.2
**Judges:** WCAG contrast, the text-size floor, touch-target size, focus and hover states, semantic structure, alt text, and signalling that does not rely on color alone.
**Evidence it uses**
| Tool | How |
|---|---|
| `lint_design` (`nodeId`, `pageId`) | `contrast`, `text-size`, `touch-target` findings |
| `get_screenshot` (`nodeId`, `scale: 2`) | whether a visible focus or hover state was designed at all, and how the error state reads |
| `get_design_spec` (`nodeId`, `target`) | which text is a title, how the screen is grouped, what each control is |
| `find_nodes` (`textValue`, `filters`) | image and icon nodes, unlabeled icon buttons |
| `get_tree_summary` (`nodeId`, `depth`) | semantic structure: heading levels, groups, control order |
**Does not judge:** visual taste (Designer), palette taste (Brand), voice (Copy).
**Bands**
| Band | What Accessibility saw |
|---|---|
| 0.0–2.9 | Fails WCAG: contrast errors, text under 12px, targets under 44px, meaning carried by color alone |
| 3.0–4.9 | Poor: borderline contrast, unlabeled controls, an error state that is red text and nothing else |
| 5.0–6.9 | Weak: passes on the desktop artboard but fails on the mobile one, one image without alt text |
| 7.0–7.9 | Acceptable: compliant baseline, one gap (no visible focus state, one icon-only button) |
| 8.0–9.4 | Good: WCAG clean, targets pass, semantics and labels present, focus and hover states designed |
| 9.5–10.0 | Excellent: every state specified, sensible keyboard order, no meaning by color alone |
**Fixes that move the score:** fix the color, not the check, until `lint_design` reports no contrast error, name interactive layers `Button…` / `Tab /…` so the target rule can see them and grow them to 44px, pair every error color with an icon or a word, design the focus and hover variants as components, give every image an alt text.
PaperCraft has no focus-ring or alt-text checker: judge those from the design itself (a `Button / Focused` variant, alt text in the spec) and report what is missing as a gap, not as a tool finding.
---
## Copy — weight 0.2
**Judges:** voice and tone against the product's voice, terseness, labels and microcopy, error-message quality, empty states, placeholders versus labels, the absence of filler.
**Evidence it uses**
| Tool | How |
|---|---|
| `get_design_spec` (`nodeId`, `target`) | the authoritative copy: every text node's content, in order |
| `get_screenshot` (`nodeId`, `scale: 2`) | how the copy reads in context: line breaks, truncation, all-caps abuse |
| `find_nodes` (`textValue`) | repeated strings, leftover placeholders, "Lorem ipsum", inconsistent labels for the same action |
| `verify_code` (`nodeId`, `target`, `code`) | `missing-text` — copy that was lost between the design and the code |
**Does not judge:** typography and layout (Designer), color (Brand), whether the screen meets the brief (Critic).
**Bands**
| Band | What Copy saw |
|---|---|
| 0.0–2.9 | Wrong: placeholder text, lorem ipsum, or copy that contradicts the brief |
| 3.0–4.9 | Poor: filler adjectives, two voices on one screen, errors that blame the user |
| 5.0–6.9 | Weak: wordy, mixed formality, vague labels ("Submit" where "Save changes" is meant) |
| 7.0–7.9 | Acceptable: clear but plain; one error message says only "Error" |
| 8.0–9.4 | Good: terse, one voice, every action labeled with a verb, errors say what happened and what to do next |
| 9.5–10.0 | Excellent: reads like a product that shipped, not like a mockup |
**Fixes that move the score:** cut every word that does not inform, give each action a verb label ("Save changes", not "OK"), write errors as *what happened + what to do next*, fill empty states with an explanation and the next action, replace placeholder copy with real content, keep one formality level per screen.
PaperCraft has no spell-checker or copy linter: the copy panel reads the spec and the screenshot, and it flags what a human reviewer would flag — it does not invent grammar rules.
---
## Scoring discipline
* Half-point steps only: 7.5, 8.0, 8.5. Never 8.37.
* The score is a verdict on the screen, not an average of findings.
* A panel that finds nothing wrong and cites no evidence scores 7.0–7.9, not 10. A 10 means the screen is a reference for the next one.
* Caps bind: hard evidence (SKILL.md section 4) and degraded evidence (section 8) are applied after the verdict, never negotiated with.
* No panel may raise another panel's score. If the Critic likes the hierarchy, that stays a Designer finding.
@@ -0,0 +1,110 @@
# Reviewer checklists
Each reviewer works from its own list, alone, and cites evidence for every finding. Mark each
item pass, fail or n/a; a state or screen that was never designed is an open question, not a pass.
## vision: the person's vision
For each key element on each screen, four questions (Connor and Irizarry):
1. **Objective**: which part of the objective is this element for?
2. **Element**: which elements serve it?
3. **Effect**: do they achieve it, for this audience?
4. **Why** or why not?
Also: everything the brief, references and feedback notes asked for is there; nothing contradicts
an open or resolved note (`get_feedback`); the tone matches the references. Unknown product facts
are questions for the person, never guesses.
## ux: usability heuristics (Nielsen)
1. Visibility of system status: progress, saving, selection shown at once.
2. Match with the real world: the users' words and order, not the system's.
3. User control and freedom: a marked exit, undo, cancel.
4. Consistency and standards: one word and one look per thing, platform conventions.
5. Error prevention: risky actions confirmed, impossible choices removed.
6. Recognition rather than recall: options visible, no remembering across screens.
7. Flexibility and efficiency: shortcuts for experts that novices need not see.
8. Aesthetic and minimalist design: nothing that competes with what matters.
9. Recognize, diagnose, recover from errors: plain language, the problem, the fix.
10. Help and documentation: needed rarely, and then where the task is.
## flow: coherent journeys
Walk each top task across screens (the `flow` graph when arrows connect screens, else the screen
order and names; ask the person when the intended order is unclear). At each step, the four
walkthrough questions: will they try to do this, will they notice the control, will they connect
it to their goal, will they see progress afterwards?
* Every task has an entry point (including first run and empty state) and a clear end
(success screen or state).
* Every screen has a way forward and a way back or out; no dead ends (`deadEnds`), no screen
nothing leads to (`unreached`) unless it is an entry.
* Each action that can fail has its error state; each destructive one a confirmation and undo.
* Navigation, back and primary actions sit in the same place with the same labels on every screen.
* What the user entered or chose shows on the following screens (the cart count, the name typed).
* Steps a user must remember between screens are shown instead (recognition over recall).
* The number of steps fits the objective ("two taps" means two).
## qa: states and edge cases
Per screen and component, pass, fail or n/a:
* States: default, hover, focus, pressed, disabled, selected, loading, empty, error, success.
* Content: the longest realistic text and names, minimum content, zero, one and many items,
missing images and avatars, large numbers, special characters.
* Modes and sizes: every variable mode (screenshot each); the narrow and wide screen sizes when the
design has them.
* Layout: nothing overflows or clips (`get_bounds`, lint `overflow`), screens keep their device
height and scroll inside, fixed bars stay fixed.
* Consistency: repeated pieces are instances of the same component (lint `not-an-instance`).
## visual
* One focal point per screen; the primary action is the most prominent control.
* Scale and hierarchy: size, weight and colour follow importance.
* Balance and alignment: shared edges, a steady grid.
* Gestalt proximity: related items closer together than unrelated ones.
* Rhythm: spacing from the 4px scale, the same gaps for the same relationships.
* Type: sizes on the scale, at most three levels per screen.
* Tokens: every colour a variable, consistent radii, components reused.
## accessibility (W3C POUR, for a design)
**Perceivable**
* Text contrast 4.5:1, 3:1 for large text (18px, or 14px bold) and for control borders and icons.
* Colour is never the only signal (errors also have an icon or text; links are underlined or bold).
* Text is real text, not pictures of text; icons that act have a label or tooltip.
* The layout holds at 320px wide and with text at 200% (a narrow artboard shows it).
**Operable**
* Touch targets 44px (24px minimum with spacing).
* A visible focus state is designed for every interactive component.
* Headings, a page title and a visible current location (active nav item).
* Destructive actions confirmed or undoable; every gesture has a button alternative.
* Nothing flashes; motion can be reduced.
**Understandable**
* Fields keep a visible label (a placeholder alone disappears).
* Errors say what went wrong and how to fix it, next to the field.
* Navigation and labels are the same across screens.
* Plain language; abbreviations explained.
**Robust**
* Controls are named for their role (layer names, code links to real components), so the code
hand-off keeps them buttons and inputs, not divs.
## copy
* The users' words, not internal jargon; verbs on buttons ("Save changes", not "OK").
* No placeholder or lorem text, no "Item 1".
* Errors: what happened and what to do. Empty states: what this is and the first action.
* Neutral wording about people whose gender is unknown (their name, or they).
* Consistent terms: one word per concept across all screens.
## end-user: a walkthrough as the audience
Take the `audience` (else ask). Write as that person, in the first person, for each top task:
what I see first, what I think it does, what I try, where I hesitate, and the first point where I
would give up. One persona per run; launch another critique with a different `audience` for a
second user type.
+1 -1
View File
@@ -105,7 +105,7 @@ Run it before `finish_working_on_nodes`:
1. Direction written down; the screen has one memorable idea and one primary action.
2. Every color is a variable; both modes checked if there are two.
3. Spacing only 4, 8, 12, 16, 24, 32, 48, 64, 96; type only from the scale; radii from one family.
4. `lint_design` has zero errors and zero warnings, and the `info` items were considered.
4. A full `lint_design` (no arguments) has zero errors and zero warnings, and the `info` items were considered. Between edits, lint only what changed: see `papercraft/references/incremental-checks.md`.
5. Screenshot at scale 2 looked at: hierarchy, alignment, wrapping, clipping, empty areas, contrast by eye.
6. Interactive things at least 44px on touch and named `Button…` / `Tab /…`.
7. Repeated parts are components; states exist for every interactive component and for empty, loading and error screens.
+16 -8
View File
@@ -17,7 +17,7 @@ papercraft-cli call get_basic_info # fails with exit 1 if the app is not ru
* **Check the project is the right one.** `get_basic_info` returns `fileName` and `path`. Build only in a project that belongs to the work (a NotesCraft design file is for NotesCraft screens, not for redesigning PaperCraft). For a different product: `create_file {name}`, then `open_file {fileId}`, and say so. `open_file` swaps the project the user is looking at, so tell them. Pass `fileId` on later calls when more than one project is in play.
* Not running: ask the user to start PaperCraft and open a project (or `create_file` then `open_file`). `PAPERCRAFT_MCP_PORT` must match if the port was changed. Do not try to launch the GUI yourself unless asked.
* Read `get_basic_info` (pages, artboards, sizes, fonts), then `get_selection` (what the user is looking at) and `get_variables` and `get_components`. Reuse what exists before creating anything.
* Read `get_basic_info` (pages, artboards, sizes, fonts, and `lessons`: the person's rules from past critiques; follow every one), then `get_selection` (what the user is looking at) and `get_variables` and `get_components`. Reuse what exists before creating anything.
* `pageId` defaults to the page the user is viewing, which can change between calls: pass it explicitly. Node ids look like `3fa9c1:14`; never show them to the user.
* App closed (server, CI)? `papercraft-cli call --offline ... --project <name>` runs the same tools on the project store and saves after every editing call; `papercraft-cli shell` keeps one session for many calls and reads scripts from stdin. It is refused while the app has that project open. See `docs/agents.md`.
* With MCP tools you do not need the CLI; with a shell, `papercraft-cli list` and `papercraft-cli schema <tool>` give the schemas on demand. Pass big JSON on stdin: `... | papercraft-cli call write_html -`.
@@ -33,8 +33,10 @@ papercraft-cli call get_basic_info # fails with exit 1 if the app is not ru
3. **Build in small steps.** `create_artboard`, then one `write_html` per visual group (header, card, row) so the user sees progress. Name every layer with `layer-name`.
4. **Look.** `get_screenshot` of the artboard after each group or two. Scale 2 to read small text. Read it as a designer: hierarchy, alignment, spacing rhythm, clipping, wrapping.
5. **Lint.** `lint_design` on the artboard. Fix every error and warning; consider the `info` items. Run it again until errors and warnings are zero.
Between edits, lint only what changed: keep the `rev` each write returns and run `lint_design {changedOnly: true}` (or `{since: rev}`). `get_changes {since}` shows what an edit touched; `get_bounds` measures a whole subtree in one call instead of looping `get_node_info`.
Always finish with one full `lint_design` (no `since` or `changedOnly`: `covered.partial` is false) and a screenshot per artboard in each theme mode before reporting. Details: [incremental-checks.md](references/incremental-checks.md).
6. **Fix with the smallest edit.** `update_styles` and `set_text_content` on the existing nodes, not a rewrite. Rewrite a group with `write_html` mode `replace` only when its structure is wrong.
7. **Finish.** `finish_working_on_nodes` (saves). Tell the user what you made in a sentence or two, with artboard names, not ids.
7. **Finish.** `finish_working_on_nodes` (saves). Tell the user what you made in a sentence or two, with artboard names, not ids. When its result has `next`, offer a critique with `ask_user`; on yes run `critique_design` and follow its steps (the `papercraft-critique` skill has the full gate). Keep a finding as a lesson (`design_lessons {add}`) only when the person approved it.
Lint passes are necessary, not sufficient: contrast and grids say nothing about composition. The screenshot is the real test.
@@ -44,6 +46,10 @@ Lessons from redesigning a 3-page, 130-screen project with up to six agents at o
* **Split by section, not by page.** Give each agent named sections (frame ids) and forbid the rest. New sections go below the current lowest one; re-read positions right before creating, since another agent may have just added one.
* **Section layout**: a section frame holds a title and rows of screen slots (a route label above a fixed-size screen). Keep 640 px between screens and rows and 1600 px between sections, so notes fit beside screens. Stack sections in one column.
* **See what the others changed** before building on their work: `get_changes {since: <your last rev>, exclude: "self"}` lists layers by the client that changed them. `truncated: true` means re-read everything.
* **Name yourself and fence your area.** With the CLI pass `--as <name>` (or `PAPERCRAFT_AGENT`), so writes, conflicts and claims carry your name. `claim_nodes {ids, note}` the sections you will rewrite; others' writes there are refused until you `finish_working_on_nodes` or `release_claims`. A denial names the holder: work elsewhere, never wait in a loop.
* **Writes report conflicts.** A result with a `swarm` block lists layers another agent changed since you last looked: read them with `get_changes` before going on. Pass `ifRev: <your last rev>` to have the write refused instead (`"error": "conflict"`).
* **Undo takes back only your own steps** (`undo`, scope `mine`); it is refused with `undo_blocked` when someone changed the same layers since. Fix forward then; `scope: "page"` undoes whoever was last.
* **Recreate, then delete.** Build the new screen next to the old one, finish it, then delete the old one, and record the deleted ids and names in the report. A cleanup agent once deleted buttons and lost icons by editing in place.
* **Reuse the design system across pages**: `create_instance` / `swap_instance` / `<x-paper-instance>` take a main from any page and stay linked. Never `import_components` to use a component: that copies mains onto the page, and instances made from the copies stop following the design system. `lint_design` flags hand-made look-alikes as `not-an-instance` (a different icon is a different component); fix with `write_html` mode replace and the `<x-paper-instance>` it names.
* **QA pass after a build** (screen by screen at scale 1, one call at a time): text layers with stale fixed widths clip labels ("In prog", "New sess"): set `width: fit-content`. Sidebars and panels fixed at 900 px stop short on taller screens: make them fill the height and let the screen hug with a 900 px minimum. Tags and chips overflowing their box, cards overlapping buttons, footers not pinned, leftover `Text` / `Frame` names, gendered copy about people whose gender is unknown (use their name or neutral wording).
@@ -89,7 +95,7 @@ For a screen with dozens of parts, drive the CLI from a short Python helper (`ca
```
Artboards: mobile 390×844, tablet 768×1024, desktop 1440×900, large desktop 2560×1440 (a 1440p display; ask which the user uses and design that first). A narrow window (1280×800) is its own artboard: collapse the sidebar to an icon rail, make secondary actions icon-only with a tooltip, keep one labelled primary action.
Dot-grid canvas (no pattern fill exists): one `<svg>` with a single path of tiny round-capped dashes, absolute at 0,0 inside the canvas frame: `<svg style="position:absolute;left:0px;top:0px" width="W" height="H" viewBox="0 0 W H"><path d="M16 16h0.01M48 16h0.01..." stroke="var(--surface-2)" stroke-width="2.5" stroke-linecap="round" fill="none"/></svg>`. One vector layer, about 3,000 dots at a 32px step. Its colour is frozen at write time. Create with `height:"fit-content"` when the content decides the height. Replace margin with `gap` and `padding`.
Dot-grid canvas (no pattern fill exists): one `<svg>` with a single path of tiny round-capped dashes, absolute at 0,0 inside the canvas frame: `<svg style="position:absolute;left:0px;top:0px" width="W" height="H" viewBox="0 0 W H"><path d="M16 16h0.01M48 16h0.01..." stroke="var(--surface-2)" stroke-width="2.5" stroke-linecap="round" fill="none"/></svg>`. One vector layer, about 3,000 dots at a 32px step. Its colour is frozen at write time. A screen keeps its device's size; at a device width (390, 1440...) `height:"fit-content"` becomes the device height. Content taller than the screen scrolls by itself: the main column under a fixed sidebar and header, else the screen (write_html says which). Pass `overflow:"visible"` to let a board grow (a landing page drawn in full). Replace margin with `gap` and `padding`.
Full flows: [recipes.md](references/recipes.md).
@@ -100,6 +106,8 @@ Full flows: [recipes.md](references/recipes.md).
| Know the project, pages, artboards | `get_basic_info`, `get_tree_summary`, `get_children` |
| Know what is selected | `get_selection` |
| Inspect one node | `get_node_info`, `get_computed_styles`, `get_jsx` |
| Sizes and positions of a subtree | `get_bounds` (one call, `columns` + `rows`; `continueWith` when `truncated`) |
| What changed since a revision | `get_changes {since}` (`exclude: "self"` for other agents' edits) |
| Find nodes by text or style | `find_nodes` (text contains the phrase, any case, every page) |
| Read all copy in a subtree | `get_tree_summary {nodeId, fullText: true}` (depth counts from the node: rows under a "Screens" frame need depth 3) |
| See it | `get_screenshot` (`nodeId`, `scale` 1 or 2, `annotations: true` to include notes, `mode` to preview a theme without switching) |
@@ -115,19 +123,19 @@ Full flows: [recipes.md](references/recipes.md).
| Component properties | One component with properties instead of one per state: `set_component_props` (`text`, `bool`, `icon`, `enum` options in the overrides format; templates `text`, `active` for tab bars and navs, `status` with [{value, color}]), then `set_instance_props {nodeIds, values}` or `<x-paper-instance component="Badge" props='{"Status":"Rejeitada"}'/>`; `get_components` lists them |
| Merge per-state components | `merge_variants {componentIds, name}` turns `Tab bar / Hoje`, `Tab bar / Lojas`... into one `Tab bar` with an enum, moves every instance and deletes the emptied variants |
| Prototype | `set_prototype_links {links:[{nodeId, to}]}`: back arrows, rows and tabs go to their screens in Present mode |
| Screens | Fixed size (390x844, 1440x900...); content longer than the screen: `overflow: auto` on the screen frame, so it keeps its size and the overflow scrolls on the canvas and in Present (inspector: Scroll overflow; page: Screens scroll) |
| Screens | Fixed size (390x844, 1440x900...); content longer than the screen scrolls by itself (the main column under a fixed sidebar and header, else the screen), or set `overflow: auto` on the frame that should scroll; it keeps its size and the overflow scrolls on the canvas and in Present (inspector: Scroll overflow; page: Screens scroll) |
| Project | `rename_file {name}` (open project stays open), `move_nodes {toPageId}` keeps instances linked and notes attached |
| Shared libraries | `publish_library`, `list_libraries`, `enable_library`, `update_library`, `disable_library` |
| Icons | `search_icons`, `<x-paper-icon name="set:name">`; CLI: `papercraft-cli icons add\|list\|search` |
| Design in a library's look, hand off its code | `apply_ui_kit` (shadcn, antd, reactbits, egui), then `<x-paper-instance>` of its components; `set_code_link` for a component of your own; `get_jsx` / `get_design_spec` then write `<Button variant="outline">` instead of divs |
| Design in a library's look, hand off its code | `apply_ui_kit` (shadcn, mui, mantine, bootstrap, chakra: ~48 components and 5 screen layouts each, re-colour through their variables; antd, reactbits, egui), then `<x-paper-instance>` of its components; `set_code_link` for a component of your own; `get_jsx` / `get_design_spec` then write `<Button variant="outline">` instead of divs |
| Avatars, more icons, photos, flags, QR | `<x-plugin use="avataaars\|dicebear\|iconify\|picsum\|flags\|qr" …/>` inside `write_html` (plugins the user turned on) |
| References and art | `fetch_reference_images`, `zoom_image`, `generate_image` (when the user turned image generation on) |
| Ask the user | `ask_user` (clickable answers; end your turn after it) |
| Hand work to the helper agent | `delegate` (`role` qa, read or build, a self-contained `task`; only when Settings, Chat, Helper is set) |
| Design rules (design-playbook) | `design_rules` (`query` or `rule` id; needs the `playbook` CLI; cite ids in the report) |
| Report a PaperCraft problem | `report_issue` (a draft the user sends; synthetic repro only) |
| Check quality | `lint_design` |
| Export | `export` (PNG, SVG, PDF to files), `export_combined_pdf` |
| Check quality | `lint_design` (`changedOnly: true` or `since` between edits, a full pass at the end; `overflow` flags layers past their artboard or clipping parent) |
| Export | `export` (PNG, SVG, PDF to files), `export_combined_pdf`, `export_presentation` (a client deck: cover, contents, a slide per screen) |
| Point at things for the user | `select_nodes` (`zoom: true`) |
| Take back | `undo`, `redo` |
| Save | `finish_working_on_nodes` |
@@ -160,7 +168,7 @@ Full flows: [recipes.md](references/recipes.md).
| `papercraft-cli` exits 1, "isn't running" | The app is closed, no project is open, or the port differs. Start it and open a project; check `PAPERCRAFT_MCP_PORT`. |
| Call fails with an unknown node id | The id is from another page or was deleted. Re-read with `get_children`; pass `pageId`. |
| `write_html` reports `ignoredStyles` | You used a CSS property that has no equivalent (`margin`, `box-shadow`, `transform`...). Replace it, see [html-subset.md](references/html-subset.md). |
| Content is cut off | The artboard height is fixed. `update_styles` with `height: "fit-content"` or a larger number. |
| Content is cut off | A frame inside the screen clips it (`overflow: hidden`, or a fixed height under a hugging parent). Give the column that should scroll `overflow: auto`; for a board that should grow, `overflow: "visible"` and `height: "fit-content"`. |
| A color did not change with the theme | It was written as hex, or it is a stroke or gradient. Use `var(--name)` on fills and text; strokes need `update_styles` after a mode switch. |
| `create_instance` fails | Wrong `componentId` / `componentKey` (read `get_components`). Mains on other pages and enabled libraries work; no import needed. |
| A page is full of copied components at y=0 | Something imported mains onto the page (`import_components`, or old `write_html` builds). Swap their instances to the design-system mains (`swap_instance {componentKey}`), check a screenshot, then delete the unused copies. |
@@ -21,7 +21,7 @@ How to keep designs small, keep design and code in step, and spend few tokens do
1. Design is the source of truth for structure, tokens and copy. Code is generated or verified from it, never the other way round without updating the design.
2. `get_design_spec {nodeId}` for each artboard: one deterministic JSON (layout, sizing, tokens, icons, `instanceOf`, `componentDefinitions`). Hand that to the implementer, not screenshots.
3. Implement from the spec. `verify_code {code, nodeId, language}` after each file; fix what it reports. Re-run `get_design_spec` only for artboards that changed (`diff_frames` between the old and new version of an artboard names the changed properties).
3. Implement from the spec. `verify_code {code, nodeId, language}` after each file; fix what it reports. Re-run `get_design_spec` only for what changed: `mark_handoff {name}` when screens go to development, then `get_handoff_changes {since: name}` lists each changed screen, component and token with its kind and action, and `export_handoff {dir, since}` writes the bundle (specs, reference images, tokens, changes.md) rewriting only changed files.
4. Name code pieces after components: `Button / Primary` becomes `button::primary` or `<ButtonPrimary>`. A 1:1 name map is the cheapest way to stay synced; keep it in a table in the feature spec (`specs/<feature>/design-map.md`).
5. Screenshots only for the final visual check (one per artboard, scale 1), and for diffing code output against the design (`get_screenshot` of both, compare).
@@ -37,6 +37,6 @@ How to keep designs small, keep design and code in step, and spend few tokens do
## Sharing and several agents
* Several agents may work on one open project through one MCP server: calls run one at a time, each is one undo step, so they do not corrupt each other. Give each agent its own page or artboard prefix and say so in the brief, so they do not restyle each other's nodes.
* Several agents may work on one open project through one MCP server: calls run one at a time, each is one undo step, so they do not corrupt each other. Give each agent its own page or artboard prefix and say so in the brief, so they do not restyle each other's nodes. Each agent names itself (`papercraft-cli --as <name>`), claims what it rewrites (`claim_nodes`), reads the conflicts its writes report, and undoes only its own steps.
* Several people on a shared project: pages sync as files and are merged when both sides changed the same page (nodes by id, child lists as sets). Edits to different nodes both survive; the same property changed twice keeps the local value. Ask people to keep a page per person when restyling the same frame.
* While an agent works the app shows an animated "working" pill and a ring around the canvas; call `finish_working_on_nodes` when done so it stops.
+4 -2
View File
@@ -28,14 +28,16 @@
Supported: `display:flex` (and `inline-flex`), `flex-direction`, `flex-wrap`, `gap`, `row-gap`, `column-gap`, `padding` (shorthand, per side, `padding-inline`, `padding-block`), `align-items`, `justify-content` (including `space-between`), `align-self` (`start`, `center`, `end`, `stretch`), `flex-grow` / `flex: 1`, `width`, `height` (px, %, `fit-content`), `min-width`, `max-width`, `min-height`, `max-height`, `overflow:hidden` (clips), `position:absolute` with `left`/`top`/`right`/`bottom`, `display:none`, `visibility`.
Not supported (check `ignoredStyles` to be sure): `margin` (use `gap` and `padding`), `display:grid`, tables, `float`, `calc()`, viewport units, `transform` and rotation.
Rewritten before layers are made, each reported in `warnings`: `margin` becomes the parent's `gap` (when uniform) or spacer layers, `margin-*:auto` a growing spacer and `margin:0 auto` centring; `display:grid` becomes rows of cells (`fr` tracks grow, px tracks keep their width, `repeat(auto-fill, minmax())` counts columns from the width); inline boxes (chips, badges) become boxes in a wrapping row; `<input>` and `<textarea>` become a box showing their placeholder or value. Prefer `gap` and `padding` anyway: the result is the same and shorter.
Not supported (check `ignoredStyles` to be sure): tables, `float`, `calc()`, viewport units, `transform` and rotation.
Tips:
* Artboards are `display:flex; flex-direction:column`. Children of a column stretch to the full width unless they have a width or `align-items` / `align-self` says otherwise.
* To center something, put it in a flex parent with `align-items:center; justify-content:center`.
* To make a row fill the remaining space, give the child `flex-grow:1`.
* Use `height:"fit-content"` on artboards that should grow with content; fixed heights clip.
* A screen keeps its device's size; at a device width (390, 1440...) `height:"fit-content"` becomes the device height. Content taller than the screen scrolls by itself: the main column under a fixed sidebar and header, else the screen (write_html says which). Pass `overflow:"visible"` to let a board grow (a landing page drawn in full).
## Text
@@ -0,0 +1,50 @@
# Incremental checks
Check what you just changed between edits, and check everything once at the end. This keeps the loop fast and the context small without skipping the final full pass.
## Why
* A full `lint_design` on a big page walks every layer and returns every finding. Run after each edit, it repeats the same output and burns tokens.
* Looping `get_node_info` over nodes is slower still: one measured loop over 397 nodes took about 53 s. One `get_bounds` call returns the same geometry for a whole subtree in milliseconds, in one result.
* Reads never change the document, so they never change `rev`. Only writes do.
## The flow
1. **Note `rev`.** Every write tool result includes `rev`, the document revision after the call. `get_basic_info` reports the current one. Keep the last value.
2. **Edit.** Make the change (`write_html`, `update_styles`, `set_text_content`, ...). Note the new `rev` from the result.
3. **Lint what changed.** `lint_design {"changedOnly": true}` checks since this client's last lint. `lint_design {"since": <rev>}` checks since a revision you name. A scoped lint covers the touched layers plus their ancestors, descendants and siblings, and every layer bound to a changed variable. The result says how much it covered, for example `{"checked": 12, "total": 397, "since": 40, "partial": true}`.
4. **See what an edit really touched.** `get_changes {"since": <rev>}` returns `{rev, since, truncated, changes: [{page, ids}]}`. Add `page` to limit it to one page. If `truncated` is `true`, the log no longer reaches that far back: do a full pass instead of trusting the list.
5. **Measure in one call.** `get_bounds {"nodeIds": [...]}` (or `pageId`, with `depth`) returns `columns` `[id, parent, x, y, w, h, absX, absY, clip]` and `rows`, one array per layer, parents first. If `truncated` is `true`, call it again with `continueWith` as `nodeIds` (same `depth`). Never loop `get_node_info` to read sizes or positions.
6. **Finish with the full check.** Before you report, always:
* run `lint_design` with no arguments (a full pass, `partial: false`) and fix every error and warning, including `overflow`;
* take a `get_screenshot` of every artboard you touched in each theme mode (`mode`, scale 2).
A partial lint is a speed-up, not a verdict. Only the final full pass can say the design is clean.
## Example
```json
get_basic_info {}
// {"rev": 40, ...}
write_html {"targetNodeId": "a1:1", "mode": "insert-children", "html": "<div class='Card'>...</div>"}
// {"rev": 41, ...}
lint_design {"changedOnly": true}
// {"errors": 0, "warnings": 1, "covered": {"checked": 12, "total": 397, "since": 40, "partial": true}, ...}
update_styles {"nodeIds": ["a1:7"], "styles": {"width": "320px"}}
// {"rev": 42, ...}
get_changes {"since": 41}
// {"rev": 42, "since": 41, "truncated": false, "changes": [{"page": "p1", "ids": ["a1:7"]}]}
get_bounds {"nodeIds": ["a1:1"], "depth": 3}
// {"columns": ["id", "parent", "x", "y", "w", "h", "absX", "absY", "clip"],
// "rows": [["a1:1", null, 0, 0, 390, 844, 0, 0, true], ...]}
lint_design {}
// full pass, "partial": false, zero errors and warnings
get_screenshot {"nodeId": "a1:1", "scale": 2, "mode": "light"}
get_screenshot {"nodeId": "a1:1", "scale": 2, "mode": "dark"}
```
+1 -1
View File
@@ -57,7 +57,7 @@ For the next screens, create each artboard at 390x844, reuse the components by `
## 2. Landing page (1440 wide, height grows with content)
Create the artboard with `height:"fit-content"` so it never clips, then add one section per call.
Create the artboard with `height:"fit-content", overflow:"visible"` so it grows with its sections instead of keeping the 900px screen height, then add one section per call.
```sh
AB=$(papercraft-cli call create_artboard '{"name":"Landing","styles":{"width":"1440px","height":"fit-content","backgroundColor":"var(--bg)","display":"flex","flexDirection":"column","paddingBottom":"96px"}}' | jq -r .id)
+124 -5
View File
@@ -79,6 +79,17 @@ Details of one node: type, name, size, visibility, lock state, parent, children
| `nodeId` | string | yes | The node to inspect. |
### `get_bounds` (read-only)
Rects of a whole subtree in one read, instead of one get_node_info per layer. Returns `columns` [id, parent, x, y, w, h, absX, absY, clip] and `rows` (one array per layer, parents before children): x/y/w/h are relative to the parent, absX/absY are page coordinates, clip is true when the layer clips its content (clipping or scrolling frame), parent is null for a top-level layer. At most 2000 rows per call: then `truncated` is true and `continueWith` lists the node ids to pass as nodeIds. Use it to verify nothing leaves its artboard, and `lint_design`'s `overflow` rule to list the offenders.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `depth` | number | | Levels returned, counting each given node as 1 (default: all). |
| `nodeIds` | string[] | | Subtrees to measure; omit for all artboards on the page. |
| `pageId` | string | | Page to use (default: the active page). |
### `get_children` (read-only)
Direct children of a node (or of the page root when nodeId is "root"), with ids, names, types, child counts and positions.
@@ -233,11 +244,61 @@ Export several nodes into one PDF, one page per node, ordered top-to-bottom then
| `path` | string | | Output file (default: Downloads/<project>.pdf). |
### `export_presentation`
Export pages as a presentation PDF, the way a designer sends work to a client: a cover, contents, a divider per page, one 1920×1080 slide per screen (its name and size; narrow side panels share a slide) and a closing slide, numbered. Screens are the page's declared screens, else its top-level frames of 300×300 or more; a section holding no screen (a design-system board) gets a slide of its own. They stay vector. Returns the file path.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `pageIds` | array of string | | Pages to include, in this order (default: every page). |
| `path` | string | | Output file (default: Downloads/<title>.pdf). |
| `title` | string | | Deck title (default: the project name). |
| `subtitle` | string | | Cover subtitle (default: screen and page counts). |
| `author` | string | | Shown on the cover after the date. |
| `language` | string | | Language of the deck's own words and date: en, pt, es, fr, de, it (default: the one the screens are written in). |
### `mark_handoff`
Mark a handoff point: a named snapshot of every page, taken when screens go to development. get_handoff_changes and export_handoff `since` then report what changed against what the developers received. Marking a name again moves it to now. Saved in the project (handoffs/). Returns {name, pages, screens}.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `name` | string | yes | Name of the point, e.g. "design v1" or a release tag. |
### `list_handoffs` (read-only)
The project's handoff points (mark_handoff), newest first: [{name, saved}].
### `get_handoff_changes` (read-only)
What changed since a handoff point, sorted the way code acts on it, in few tokens: token values once (regenerate the theme), main components once with the screens using them (instances follow), then screens: added, removed, renamed, and per changed layer its kind (copy, binding, style, layout, structure, instance, note) and `field: old → new` with token names. Sizes that follow content, positions set by auto layout and instance fields that follow their main are left out. Markdown shows 8 changes per screen; pass `nodeId` (a screen or component key from it) for all of one. Layer keys work with get_design_spec {nodeId, format: compact} to fetch just that subtree.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `format` | `markdown` \| `json` | | markdown (default, an index) or json (everything). |
| `nodeId` | string | | Only this screen or main component, every change. |
| `since` | string | yes | Handoff point name (list_handoffs). |
### `export_handoff`
Write the handoff bundle a code base builds from into a folder: index.md (one line per screen with its spec file and size in tokens), inventory.json, tokens.json (DTCG with modes), tokens.css, tokens.tailwind.css, components.json, open-questions.md (`? (team)` notes and the table on a page named Handoff), and per screen a compact spec (screens/<page>/<screen>.txt) and a reference PNG at scale 1 (a scrolling screen shown whole). With `since`, also changes.md and changes.json (get_handoff_changes). manifest.json lists each file's hash and tokens. Only files whose bytes changed are written, and files a previous export wrote that no longer exist are removed; nothing else in the folder is touched. Returns {dir, files, written, removed, screens, images}.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `dir` | string | yes | Folder to write into (created if missing), e.g. docs/design. |
| `images` | boolean | | Write reference PNGs (default true). |
| `since` | string | | Handoff point to report changes against. |
## Write
### `create_artboard`
Creates an artboard (top-level frame) and returns its id; then add content with write_html({mode: "insert-children"}). `styles` are camelCase CSS; width and height are required (e.g. "1440px"). Artboards default to display:flex, flexDirection:column and a white background, and are placed in an empty spot unless left/top are given. Default sizes: desktop 1440×900, tablet 768×1024, mobile 390×844.
Creates an artboard (top-level frame) and returns its id; then add content with write_html({mode: "insert-children"}). `styles` are camelCase CSS; width and height are required (e.g. "1440px"). Artboards default to display:flex, flexDirection:column and a white background, and are placed in an empty spot unless left/top are given. Default sizes: desktop 1440×900, tablet 768×1024, mobile 390×844. At a device width, height "fit-content" becomes the device height; content taller than a screen scrolls in its main column (else the screen). overflow "visible" lets the board grow instead.
| Argument | Type | Required | Notes |
|---|---|---|---|
@@ -249,7 +310,7 @@ Creates an artboard (top-level frame) and returns its id; then add content with
Parse HTML with inline styles into layers. Write incrementally: each call should add one visual group (a header, one list row, a card) so the user sees progress.
- mode "insert-children" appends the HTML inside targetNodeId ("root" = the page); "replace" replaces targetNodeId with it.
- Inline styles only. Flexbox (display:flex, flex-direction, gap, padding, align-items, justify-content, align-self, flex-grow, flex-wrap) is the layout model; block elements stack vertically. position:absolute with left/top is supported. No margin, grid or tables.
- Inline styles only. Flexbox (display:flex, flex-direction, gap, padding, align-items, justify-content, align-self, flex-grow, flex-wrap) is the layout model; block elements stack vertically. position:absolute with left/top is supported. Margins become gaps or spacers, display:grid becomes rows of cells, text inputs show their placeholder (each reported in warnings). No tables.
- Text: font-size, font-weight (≥600 = bold), font-style, color, line-height, letter-spacing, text-align, text-decoration (including wavy and text-decoration-color); <b>/<i>/<u>/<s>/<span style> make rich text. Font family is always Inter.
- Boxes: background(-color/-image: colors, linear/radial gradients, url()), border (and border-top/right/bottom/left), border-radius, opacity, overflow:hidden, mix-blend-mode, width/height (px, %, fit-content), min-width/max-width/min-height/max-height.
- <img src> takes paper-asset:///abs/path, file:// URLs, absolute paths or data: URIs. <svg> markup is imported as vector layers.
@@ -503,9 +564,31 @@ Search installed open icon sets (Lucide, Tabler, Phosphor, Heroicons, Material).
| `set` | string | | |
### `critique_design`
Critique finished work the way a design team does (offer it with ask_user when finish_working_on_nodes says the design changed). Judges against the person's objective, through independent reviewers: vision (the person's brief and notes), ux (Nielsen's heuristics), flow (coherent journeys across screens), qa (states and edge cases), visual, accessibility (W3C POUR), copy and end-user (a walkthrough as the audience). Returns the reviewers' briefs, the finding format and 0-4 severity scale, lint, the arrows between screens (dead ends, unreached screens), the person's lessons and the steps: review each persona independently, merge, fix severity 3-4, report, then ask which findings to keep as lessons.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `nodeId` | string | | Artboard or subtree to critique; omit for the whole page. |
| `objective` | string | | What the design must achieve, for whom, and its top tasks (from the brief or the person). |
| `audience` | string | | Who the end-user reviewer plays ("first-time shopper on a phone"). |
| `personas` | array of string | | Reviewers to run (default: all): vision, ux, flow, qa, visual, accessibility, copy, end-user. |
### `design_lessons`
The person's design lessons: rules from past critiques that every design must follow (get_basic_info lists them too; read them before designing). Without arguments, lists those that apply in the open project. `add` stores one ONLY after the person approved it in this conversation (ask_user); never on your own. `remove` deletes one by id.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `add` | object | | `{rule, why, scope}`: rule is one line, an instruction; why is what went wrong; scope `all` (default) or `project`. |
| `remove` | string | | Id of a lesson to delete ("L3"). |
### `lint_design`
Check a page or subtree for common design mistakes and get a fix for each: text contrast (WCAG 4.5:1, 3:1 for large text), text under 12px, font sizes off the type scale, gap/padding off the 4px grid, buttons and tabs under 44px tall, default layer names (Frame, Rectangle), and hard-coded colors that equal a variable. Run it before finish_working_on_nodes and fix errors and warnings; `info` items are suggestions. Pass `fix: true` to automatically snap spacing/padding to 4px, relink matching color variables, snap text sizes, and enlarge small touch targets.
Check a page or subtree for common design mistakes and get a fix for each: text contrast (WCAG 4.5:1, 3:1 for large text), text under 12px, font sizes off the type scale, gap/padding off the 4px grid, buttons and tabs under 44px tall, default layer names (Frame, Rectangle), layers or text overflowing their artboard or clipping parent (rule `overflow`, never auto-fixed; scrolling frames are exempt), text too narrow for its words (text-collapsed), and hard-coded colors that equal a variable. Run it before finish_working_on_nodes and fix errors and warnings; `info` items are suggestions. Pass `fix: true` to automatically snap spacing/padding to 4px, relink matching color variables, snap text sizes, and enlarge small touch targets.
| Argument | Type | Required | Notes |
|---|---|---|---|
@@ -674,12 +757,48 @@ Move the user's view: switch to pageId (as clicking it in the page list does) an
### `undo`
Undo the last change on a page (the user's or an agent's).
Undo a change. An agent's undo (scope `mine`, its default) takes back its own newest step and leaves later steps by others in place; it is refused (`undo_blocked`, with the steps in the way) when one of them touched the same layers. Scope `page` undoes the page's last step, whoever made it.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `scope` | string | | `mine` or `page`. |
### `redo`
Redo the last undone change on a page.
Redo the last undone change on a page. With scope `mine` (an agent's default) only when that step was the caller's own.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `scope` | string | | `mine` or `page`. |
### `claim_nodes`
Several agents on one project: claim the layers you will rewrite (each with everything under it) or a shared resource, so other agents' writes there are refused while you work. All or nothing; a denial names the holder and when it expires (never wait in a loop: do other work). The claim lasts ttlSeconds after your last call and goes with finish_working_on_nodes or release_claims. The person is never blocked. Needs the running app.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `ids` | array of string | | Layer ids. |
| `resources` | array of string | | `variables`, `components`, `pages`. |
| `ttlSeconds` | integer | | Default 300 (10 to 1800); renewed by each of your calls. |
| `note` | string | | What you are doing, shown to others. |
### `release_claims`
Release your claims: one by claimId, those on ids or resources, or all of them when nothing is given.
| Argument | Type | Required | Notes |
|---|---|---|---|
| `claimId` | string | | |
| `ids` | array of string | | |
| `resources` | array of string | | |
### `list_claims` (read-only)
Who is working where: every live claim with its holder, layers, resources, note and seconds left.
### `finish_working_on_nodes`
+42
View File
@@ -0,0 +1,42 @@
# Design critique and lessons
## Problem
When an agent finishes a design it says it is done; nobody reviews the work unless the person asks,
and the `papercraft-critique` skill only reaches agents that load skills (not the in-app chat). The
same mistakes come back in the next design (a page that grows instead of scrolling, gendered copy,
clipped labels) because nothing the person corrected is remembered.
## Goal
After a design is finished the person is offered a critique; the corrections they approve are
remembered and shown to every agent before its next design, so the same mistake is not repeated.
## Non-Goals
- Scoring by a model inside the app: the agent does the judging, the tool gathers the evidence.
- Saving anything the person did not approve.
- A settings screen for lessons (the tool lists and removes them).
- Syncing lessons between machines.
## User Stories
- As a designer, I want to be offered a critique when an agent finishes, so that I don't have to remember to ask.
- As a designer, I want to choose which critique findings become lessons, so that only what I agree with sticks.
- As a designer, I want agents to follow my lessons in later designs, so that I don't correct the same thing twice.
- As a designer, I want lessons for one product to stay in that product, so that a brand rule does not leak elsewhere.
- As a designer, I want to remove a lesson, so that a rule I no longer want stops applying.
## Acceptance Criteria
- [ ] Given edits since the last critique, when an agent calls `finish_working_on_nodes`, then the result tells it to offer the person a critique (`ask_user`), and it does not after a critique with no edits since.
- [ ] Given a page or artboard, when `critique_design` runs, then it returns the objective (or that it is missing and must be asked), the chosen reviewers (vision, ux, flow, qa, visual, accessibility, copy, end-user) with their methods, the finding format and 0-4 severity scale, the lint, the flow between screens and the lessons that apply.
- [ ] Given screens joined by arrows, when `critique_design` runs, then the flow lists the links, the dead ends (reached, leading nowhere) and the screens nothing leads to or from.
- [ ] Given several reviewers, the steps have them review independently (one subagent each, or one pass each) and a coordinator merge, never debate.
- [ ] Given the person approved a finding, when `design_lessons` adds it, then it is stored in the project store and listed by `get_basic_info` and `critique_design` from then on, in every session.
- [ ] Given a lesson saved with scope `project`, when another project is open, then it is not listed.
- [ ] Given a lesson id, when `design_lessons` removes it, then it is no longer listed.
- [ ] The tool descriptions say a lesson is saved only after the person approved it.
## Constraints
- Stack: Rust, MCP tools in `src/mcp`; lessons in a JSON file at the project store root, written atomically.
- Compat: missing or unreadable lessons file means no lessons, never an error for other tools.
- Security: lessons are plain text the person approved; no secrets.
## Open Questions
- None.
+76
View File
@@ -0,0 +1,76 @@
# Design handoff and design updates
## Problem
Handing a PaperCraft design to code is a wrapper script today (`shipcraft/bin/pc-freeze.py`): one CLI call per screen (186 for Rota Fresca), the Handoff table parsed out of tree text, every file rewritten on each run, no picture of the design, and `verify_code` only against the running app. Worse, once code exists, a design edit has no handoff at all: nobody can tell which screens changed since the code was built, what kind of change it was (copy, a token, a component, the layout, a business rule), or what the code side has to do about it. Rota Fresca's `design-changes.md` shows the cost: nine design changes tracked by hand, each followed by "re-exported" of whole pages, and a stroke-colour question that took a manual check to settle. The same gap applies to any team that is not using shipcraft: there is no "what changed since you last built this" in PaperCraft.
## Goal
From any point the code was built from, PaperCraft says which screens and components changed, how, and what to do about each, in files a person or an agent can act on without opening the app.
## Non-Goals
- Generating or editing application code; PaperCraft describes, the code side implements.
- Git, issue-tracker or chat integrations; outputs are files and JSON others can feed into them.
- Merging two design branches; shared-project merge already exists.
- Replacing the presentation deck; it stays the owner-facing view.
- Pixel-diffing the running app against the design (shipcraft's `measure:route` keeps that job).
## User Stories
- As a developer, I want one command that writes the whole handoff bundle for a project (inventory, tokens, components, open questions, specs, reference images), so that I build from frozen files and never from the live app.
- As a designer, I want to mark a set of screens as handed off ("Ready for dev") at a named point, so that later edits are measured against what developers actually received.
- As a developer, I want a list of what changed since a handoff point, sorted by screen and by kind of change, each with the action it calls for, so that I update only what moved.
- As an agent building one screen, I want only the changed part of a screen's spec (the subtree and its path) plus before/after images, so that an update costs a few thousand tokens and not a whole-page rebuild.
- As a developer, I want to record which screens are implemented and from which handoff point, so that each screen's next diff starts from what was built for it, not from one global date.
- As a project owner, I want a "what changed" deck (before and after per changed screen, with the reason), so that I can approve an update without reading specs.
- As a team not using shipcraft, I want the bundle to be framework-neutral (DTCG tokens, CSS variables, Tailwind theme, SVG icons, named image assets, per-screen HTML reference), so that any stack can consume it.
## Acceptance Criteria
### Bundle
- [ ] Given a project, when the handoff export runs into a folder, then the folder holds the inventory, tokens (DTCG, CSS, Tailwind), components, open questions (including the Handoff table as structured rows), one compact spec per screen, one reference image per screen per mode, icons as SVG and images as named files, and a manifest listing every file with a content hash.
- [ ] Given a screen whose content scrolls, when it is exported, then its spec marks the scrolling frame and its full content height, and its reference image shows the whole content (as the deck does).
- [ ] Given an unchanged project, when the export runs twice, then the second run changes no file (byte-identical, same manifest).
- [ ] Given a renamed or deleted screen, when the export runs again, then the old files are removed and no stale file remains.
- [ ] Given the app is closed, when the export runs through the offline CLI on the same project, then the output is the same as with the app open.
### Handoff points
- [ ] Given selected screens or pages, when the designer marks them handed off under a name, then PaperCraft stores a baseline of those screens and the tokens and components they use, and the canvas shows each screen's status (draft, ready, changed since handoff, implemented).
- [ ] Given a screen marked ready, when anyone edits it, then its status becomes "changed since handoff" without any extra step.
- [ ] Given the code side reports a screen implemented from a named handoff point (and optionally a commit), when the next change report runs, then that screen is compared against that point.
### Change report
- [ ] Given a handoff point and later edits, when the change report runs, then it lists added, removed and renamed screens, and for each changed screen the changed nodes matched by id (not by position), each with the old and new value.
- [ ] Given a change, then it is classified as one of: copy, token value, token binding, style, layout, structure (nodes added, removed or moved), component main, instance swap, asset, annotation (behaviour or business rule), or screen added, removed or renamed.
- [ ] Given each class, then the report states the action it calls for. For example: copy → update the string key; token value → regenerate the theme, no screen work; component main → rebuild that component, and list the screens that use it with no screen work; layout or structure → rebuild that subtree; annotation → review the rule in the domain model; screen removed → remove the route.
- [ ] Given a token value or a component main changed, then the report lists every affected screen once, under that token or component, and does not repeat the change on each screen.
- [ ] Given a changed subtree, then the report includes that subtree's compact spec and its path from the screen root, and before and after images of the screen with the changed area outlined.
- [ ] Given a change report, then it is written as Markdown for people and JSON for scripts and agents, from the same data.
- [ ] Given a move or resize under 1 px, or a re-save with no content change, then the report lists nothing.
### Token cost
- [ ] Given a change report, then its first section is an index of one line per affected screen or component (name, change classes, action, file to read), and a reader reads detail files only for the items it acts on.
- [ ] Given a token or component change, then it appears once, as a single line naming the token or component, and is not repeated on each screen that uses it.
- [ ] Given a changed subtree, then its spec fragment holds only the changed nodes and the path from the screen root (names only, no styles). Unchanged siblings appear as one line each, or are left out.
- [ ] Given a change, then each value is written as `field: old → new`, using token names rather than resolved values. Values that did not change are not printed.
- [ ] Given a change that needs no screen work (token value, asset swap, annotation), then the report says so and points at no screen spec.
- [ ] Given the bundle, then every compact spec states its size in tokens in the manifest, so a brief can budget before it reads.
- [ ] Given before and after images, then they are cropped to the changed area plus a margin and kept at scale 1, so they are only fetched when needed.
- [ ] Given a one-node copy change on one screen, then the whole report for it (index line plus detail) is under 300 tokens.
### Verification and review
- [ ] Given a bundle on disk and source files, when verification runs against the bundle, then it gives the same verdict as `verify_code` against the live app, without the app running.
- [ ] Given a change report, when the "what changed" deck is exported, then it holds one slide per changed screen with before and after, the change classes, and the designer's note for the change, in the project's language.
## Constraints
- Stack: Rust (PaperCraft core, MCP tools, CLI); outputs are plain files (JSON, Markdown, PNG, SVG, CSS).
- Performance: a full export of 200 screens finishes in under a minute on the user's machine. A change report for one edited screen costs the reader under 2k tokens; the index for a 50-change update is under 3k.
- Token economy is a requirement, not polish: every output is read by agents billed per token. Fewer, smaller files read on demand beat one complete file.
- Data safety: baselines are stored in the project and migrate with it; exports write atomically; nothing is written outside the chosen folder.
- Compat: works offline (CLI) and online (app); the bundle format is versioned so a reader can refuse an unknown version.
- Tool count: each new MCP tool needs a test in `tests/mcp.rs`, and the README and ROADMAP counts updated.
## Open Questions
- Should a handoff point cover the whole project or only the screens selected? Per-screen baselines are more precise but heavier to store.
- How should "implemented" be reported back: an MCP tool the code side calls, a file in the bundle the export reads (for example `implemented.json` committed in the app repo), or both?
- Which counts as the action for a copy change in a team without a string table: edit the text in place, or always the string key?
- Should the canvas status badges ("changed since handoff") show to every viewer, or only in a "dev" view?
- Is a static handoff viewer (one HTML file in the bundle that browses screens, specs, values and changes) wanted, or are the Markdown and images enough?
- What retention applies to old baselines (keep all, keep the last N, keep the named ones)?
+17
View File
@@ -0,0 +1,17 @@
# Design handoff: tasks
Defaults taken for the spec's open questions: a handoff point covers the whole project; `since` is passed per call; old points are kept until marked again under the same name.
## Done
- [x] Compact spec marks scrolling frames: `scroll+N` (N px past the bottom).
- [x] Handoff points: `mark_handoff`, `list_handoffs` (`src/handoffs.rs`, project folder `handoffs/`).
- [x] Change report: `get_handoff_changes` (`src/mcp/handoff/changes.rs`): tokens once, mains once with the screens using them, screens by kind with the action; derived sizes, auto-layout positions and instance fields that follow their main left out; 8 lines per screen, `nodeId` for the rest.
- [x] Bundle: `export_handoff` (`src/mcp/handoff/bundle.rs`): index, inventory, DTCG/CSS/Tailwind tokens, components, open questions (with the Handoff page table), compact spec and unrolled reference PNG per screen, changes; manifest with hash and tokens; unchanged files not rewritten, stale ones removed.
## Next
- [ ] Per-screen "implemented from" record, so each screen diffs from what was built for it.
- [ ] Canvas status badges: draft, ready, changed since handoff, implemented.
- [ ] Before/after images of each changed screen, cropped to the change.
- [ ] "What changed" deck from a change report.
- [ ] `verify_code` against a bundle on disk (no app).
- [ ] shipcraft `bin/pc-freeze.py` → one `export_handoff` call.
+62
View File
@@ -0,0 +1,62 @@
# Plan: free agents
## Facts checked (2026-10-29)
* `pi-acp` 0.0.34 runs `pi --mode rpc` (or `PI_ACP_PI_COMMAND`). It honours `PI_CODING_AGENT_DIR`
and offers models through ACP `configOptions` / `availableModels` with `setSessionConfigOption`
and `setSessionModel`, so the existing ACP model code works for Pi unchanged.
* `pi-mcp-adapter` 2.11 reads `$PI_CODING_AGENT_DIR/mcp.json` (`mcpServers`, `settings`).
`settings.requestTimeoutMs` sets the call timeout. A server with `"url"` uses streamable HTTP.
`"directTools": true` registers its tools one by one instead of behind the `mcp` proxy tool.
It also reads `~/.config/mcp/mcp.json` and the project's `.mcp.json` / `.pi/mcp.json`.
* `pi --list-models` prints `provider model context max-out thinking images` for providers that
have a key. It has no price column.
* OpenCode's free models are `opencode/*-free` and `opencode/big-pickle`, and cost 0 in
`opencode models --verbose`.
## Design
* **Free models** (`src/chat/models.rs`):
* `AgentModel::is_free()`: cost 0, or an id ending in `:free` (OpenRouter).
* Pi's free-tier providers (Groq, Cerebras, NVIDIA NIM, Gemini) count as free when their key is
set. `ponytail:` a provider-level guess, because Pi lists no prices.
* `parse_pi` / `fetch_pi` read `pi --list-models`.
* `free_order(catalog, skip)` ranks by context size, then image input.
* **Rotation** (`src/chat/acp.rs`):
* `TurnConfig.fallbacks: Vec<String>` holds the next models to try, filled by the UI when the
chat's model is `FREE_AUTO`.
* A `session/prompt` error that `is_retryable` before any tool call switches the model
(`pick_model`) and resends, at most `MAX_SWITCHES`.
* `Event::ModelSwitch { from, to, reason }` becomes one line in the thread, and the UI marks
`from` as failed for 15 min.
* **Lean Pi** (`src/chat/agents.rs`):
* `pure_env("pi", home, ..)` sets `PI_CODING_AGENT_DIR=<home>/agent`.
* `write_pi_home(home, mcp_url, model)` writes `settings.json` (`packages:
["npm:pi-mcp-adapter"]`, default provider/model) and `mcp.json` atomically.
* Keys are added to the env from the keyring.
* The UI calls it right before starting the turn, because the URL carries the chat id.
* **Keys** (`src/chat/keys.rs`):
* `PROVIDERS` lists, per provider: id, name, env var and key page URL.
* `get` / `set` / `forget` go through `keyring` (service "PaperCraft", user `pi:<id>`).
* `env()` returns the env pairs for the providers that have a key.
* **Install** (`src/chat/install.rs`):
* `Method { os, label, program, args, needs, kind: Package | Script, elevated }` holds the
methods per agent, as data.
* `Host { os, distro, has(program), node_major }` is detected once.
* `methods(agent, host)` returns the methods that apply, in preference order.
* `run(method) -> Receiver<Line>` streams output and runs nothing elevated.
* **UI**:
* `chat_models.rs`: a "Free (auto)" row and a "Free only" toggle, on for opencode and pi.
* `chat_agents.rs`: Install on missing OpenCode/Pi rows. The card holds the method menu, the
command preview, Confirm, streamed output, the copy command and the docs link.
* `settings.rs`: a Pi provider key list.
* `chat.rs`: filling in the fallbacks, tracking failed models, and the switch line.
## Risks
* Retryable error text is a guess. `is_retryable` matches `429`, `rate limit`, `quota`,
`overloaded`, `unavailable`, `not found`, `insufficient`, and is tested on fixtures. An error
it doesn't recognise ends the turn, as today.
* `pi --list-models` output format may change. The parser skips lines it can't read.
* `chat.rs` and `chat_agents.rs` are already over 800 lines. New UI goes in new files
(`chat_install.rs`, `chat_keys.rs`).
+112
View File
@@ -0,0 +1,112 @@
# Free agents: OpenCode and Pi set up for free models, with an install wizard
## Why (user request, 2026-10-29)
* The user wants to run PaperCraft chats on alternative agents (OpenCode, Pi; later Codex and
Antigravity) without paying for a model.
* OpenCode ships free models (`opencode/*-free`, `opencode/big-pickle`) that need no key, but they
are "free for a limited time" and change; a chat pinned to one that disappears or is rate
limited fails.
* Pi is detected but useless in a chat: `pi-acp` accepts the MCP servers PaperCraft sends and
never passes them to Pi, so Pi has no PaperCraft tools. Pi also loads the user's whole setup
(14 packages, ~190 skills), like OpenCode did before lean mode.
* Pi supports OpenRouter (`:free` models), Groq, Gemini, NVIDIA NIM and Cerebras through
`*_API_KEY` env vars; the user has no key flow for them.
* A missing agent shows "Not found" and a docs link only. The user now wants an install wizard.
This reverses "No install instructions" in `specs/chat-agents/spec.md` for OpenCode and Pi.
## Decisions (asked 2026-10-29)
* Pi reaches PaperCraft through `pi-mcp-adapter` installed in an isolated Pi dir.
* Provider keys live in the OS secret store through the `keyring` crate, as `src/chat/endpoint.rs`
does: Keychain on macOS, Credential Manager on Windows, Secret Service on Linux. They reach Pi
only as env vars of its process.
* Pi providers: OpenRouter plus Groq, Gemini, NVIDIA NIM and Cerebras, each used when its key is
set.
* The wizard installs on a click after a confirmation, and falls back to a copyable command and
the docs link.
## Scope
1. **Free model set.** A model is free when the catalog gives it input and output cost 0
(`opencode models --verbose`; Pi: `pi --list-models` plus OpenRouter's `:free` suffix). The
model picker gets a "Free only" filter, on by default for OpenCode and Pi, and a "Free (auto)"
row that means "rotate through free models".
2. **Rotation.** With "Free (auto)", a turn starts on the first free model in a ranked order
(context size, then image input, then the last one that worked). When the turn fails with a
rate-limit, quota, overload or unknown-model error before any tool ran, PaperCraft switches the
session to the next free model (`session/set_config_option`, else `session/set_model`) and
resends the prompt once per model, at most 3 models. A model that failed is skipped for 15 min.
The thread shows one line per switch ("Switched to GLM-5.3 Flash Free: Big Pickle is rate
limited"). Errors after a tool ran are not retried (the design may have changed).
3. **Lean Pi.** `PI_CODING_AGENT_DIR=<config_dir>/agent-home/pi/agent` with a generated
`settings.json` (packages: `npm:pi-mcp-adapter` only, the chosen default provider and model)
and the adapter's MCP config pointing at PaperCraft's URL with `tools=core`, MCP timeout above
`CALL_TIMEOUT` like OpenCode's. `pi-acp` is launched with that env. Non-lean keeps the user's
own `~/.pi`.
4. **Provider keys.** Settings › Agents › Pi lists OpenRouter, Groq, Gemini, NVIDIA NIM and
Cerebras: a key field (masked, "Get a free key" link to the provider's key page), saved to the
OS secret store, removed with "Forget". Keys are passed as `OPENROUTER_API_KEY` etc. and never
written to disk or logs. The free model set for Pi is the union over providers with a key.
5. **Install wizard, per OS.** When OpenCode or Pi is not found, its row and the setup card show
"Install". The wizard detects the OS (and on Linux the distribution, from `/etc/os-release`)
and which package managers are on the resolved PATH, then offers the methods that apply, the
first one preselected and the others in a menu. The methods come from each agent's install docs
(checked 2026-10-29), as data in the agent registry:
| Agent | macOS | Linux | Windows |
|---|---|---|---|
| OpenCode | `brew install anomalyco/tap/opencode`, `npm install -g opencode-ai`, `curl -fsSL https://opencode.ai/install \| bash` | Homebrew tap, `npm install -g opencode-ai`, Arch `paru -S opencode-bin`, install script | `scoop install opencode`, `choco install opencode`, `npm install -g opencode-ai` |
| Pi | `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`, `brew install pi-coding-agent`, `curl -fsSL https://pi.dev/install.sh \| sh` | npm, install script, `nix profile add github:earendil-works/pi/stable` | npm, `powershell -c "irm https://pi.dev/install.ps1 \| iex"` |
* OpenCode's docs say plain `brew install opencode` and Arch's `pacman -S opencode` install
OpenCode 2. PaperCraft's ACP and model code is tested on 1.x, so the wizard offers the 1.x
packages until 2 is tested. A detected 2.x is still used, with a warning.
* The npm methods need Node (Pi: 22.19 or newer). When `node` is missing or too old, npm
methods are hidden and the card says so, with a link to nodejs.org. Pi's install scripts
install Node themselves.
* Script methods (`curl … | sh`, `irm … | iex`) run remote code. They are listed last and the
confirmation shows the full command and URL.
* On Windows, the commands run through PowerShell. `npx` resolves to `npx.cmd`. The agent home
goes under `%APPDATA%` through `config_dir()`.
* The click shows exactly what will run, and runs it only after "Install" is confirmed. Output
streams into the card, then the agent is detected again.
* Nothing runs elevated. When a method needs `sudo` or an admin shell, the card shows the
command to copy instead of running it.
* On failure, the card keeps the output, the copyable command and the docs link.
* After install, Pi asks for at least one provider key. OpenCode needs nothing.
* `pi-acp` and `pi-mcp-adapter` are fetched on first use.
6. **Usage and price.** Free models show "Free" in the chip; context use comes from
`usage_update` (Pi sends it each turn) or the catalog's context size.
## Not in scope
* Codex and Antigravity (separate spec; Codex lean mode, Antigravity after checking its CLI).
* Paid-model rotation, provider sign-up flows, `pi-freerouter`.
* Installing Node or Homebrew themselves (the wizard says what is missing and links to them).
## Risks
* The free lists and their limits change without notice; rotation reads the live catalog at the
start of each chat, never a hard-coded list.
* OpenRouter `:free` allows 50 requests a day without credits, and one design turn makes many.
The picker says so next to OpenRouter.
* `pi-mcp-adapter` and `pi-acp` are third-party npm code fetched on first use; enabling Pi
already requires a confirmation, and the wizard repeats it.
* The error text OpenCode and Pi send for rate limits is not documented; classification is
tested against recorded fixtures and falls back to "not retried".
## Acceptance
* A new OpenCode chat with "Free (auto)" builds an artboard on a free model; with the first model
forced to fail (fixture), the turn switches once and completes, and the thread shows the switch.
* A lean Pi chat with an OpenRouter key lists only free models, calls PaperCraft tools through
`pi-mcp-adapter`, and loads none of the user's `~/.pi` packages or skills.
* No key appears in any file under the config dir, the agent home or the logs.
* With OpenCode missing from PATH (test PATH), the card offers Install. The install command is
shown before it runs. A failure keeps the command and docs link.
* The offered methods match a fake OS, distribution and PATH: macOS with brew, macOS without
Node, Ubuntu, Arch, and Windows with scoop.
* Keys round-trip through `keyring` on macOS here. Windows is covered by the CI run.
* Tests: free filter and ranking, error classification (recorded fixtures), rotation with a fake
ACP agent, Pi lean env and generated settings, key env passing (fake keyring), wizard state, method selection per OS.
+15
View File
@@ -0,0 +1,15 @@
# Tasks: free agents
1. [x] Free models: `is_free`, `parse_pi`/`fetch_pi`, `free_order`. Unit tests in `models.rs`.
2. [x] Rotation: `fallbacks`, `is_retryable`, `Event::ModelSwitch`, retry loop. Fake-agent fixture
test (first model rate limited, second completes; error after a tool is not retried).
3. [x] Provider keys: `chat/keys.rs` (keyring, env). Test env building with an injected getter.
4. [x] Lean Pi: `pure_env("pi")`, `write_pi_home`, keys in env, Pi catalog fetch. Tests for env and
generated files.
5. [x] UI models: "Free (auto)" row, "Free only" toggle, fallbacks filled, failed cache, switch line.
UI test: clicking Free (auto) sets `FREE_AUTO`.
6. [x] Install data and runner: `chat/install.rs` methods per OS, `Host` detection. Tests per fake
host (macOS brew, macOS no Node, Ubuntu, Arch, Windows scoop).
7. [x] Install UI card + Pi key settings UI. UI tests: Install shows command before running; failure
keeps command and docs link.
8. [x] README/ROADMAP notes, clippy, targeted tests.
+20
View File
@@ -0,0 +1,20 @@
# Presentation export v2: plan
All in `src/io/deck.rs` unless noted; the PDF writer and tools stay as they are.
## Tasks (each with a test in `deck.rs`)
1. **Notes per screen.** `notes_of(doc, screen)`: attached notes whose target is the screen or inside it, in reading order of their targets. Category colour from the project's categories, else the built-ins.
2. **Annotated screen slide.** `Slide::Screen` with notes: the screen fitted in the left 64% of the stage, numbered accent markers at each noted layer's top-left, the note column on the right (number, title bold, first body line muted, wrapped). `NOTES_PER_SLIDE` = 6; more continue on a repeat slide titled `… (notes 2/2)`.
3. **States to an appendix.** Main flow: the first state, its caption `+ N states`; the rest collected per page into Appendix slides after the last page (a divider `Appendix`, rows of two titled `Page · Screen`).
4. **Map slide.** After each divider: up to 12 key screens (one per state group, boards excluded) as a grid of thumbnails with names; more pages of the map when needed.
5. **Open questions.** Notes containing `?`, listed with their screen's name, before the end slide; split at 8 per slide.
6. **Counts.** Contents and dividers say `N screens · M boards`.
## Risks
- Notes on tiny layers: the marker sits on the layer's top-left, clamped inside the screen.
- Long note bodies: one line in the column, cut with an ellipsis (text wrap at fixed width, max rows 2).
- Projects without notes: nothing changes for their slides.
## Data (needs the owner's go-ahead, not code)
- Interview: about 40 screens are named without ` / ` (`Challenges List No Match`), so they don't group as states; rename to `Screen / Challenges / No match`.
- Interview: 76 detached notes (their targets were deleted in the v1 cleanup).
+44
View File
@@ -0,0 +1,44 @@
# Presentation export
## Problem
Exporting a project as PDF gives one bare page per frame: no cover, no titles, no order beyond the canvas, and boards whose content sits on top of them as sibling layers came out empty. Sending designs to a client or team means rebuilding the deck by hand in another tool.
## Goal
One export produces a client-ready PDF deck of a project's screens, the way a freelance designer presents work.
## Non-Goals
- Authored narrative (problem statements, research, rationale paragraphs): the deck uses what the project knows (names, pages, sizes).
- Editable slide documents (Keynote, PowerPoint) or slide editing in the app.
- Theming the deck from the project's variables.
## User Stories
- As a designer, I want to export a page or the whole project as a presentation, so that I can send it to a client without rebuilding slides.
- As an agent, I want a tool and a CLI flag for the same export, so that I can deliver designs as a deck.
- As a reviewer, I want each screen on its own slide with its name, so that I can refer to it in feedback.
## Acceptance Criteria
- [ ] Given the Export section, when the format is Presentation and the scope is All pages, then one PDF is written with a cover, a contents slide, a divider per page that has screens, one slide per screen, and a closing slide.
- [ ] Given a page with declared screens, then the deck shows those screens; otherwise its top-level frames of at least 300 × 300.
- [ ] Given narrow, tall screens (side panels), then up to five share a slide, each with its name.
- [ ] Given a board frame with layers laid over it as siblings, then its slide shows those layers (as the canvas does).
- [ ] Every slide but the cover has the deck title and a page number; screen slides show the page name, the screen name and its size.
- [ ] Screens stay vector in the PDF (scaled, not rasterised).
- [ ] `papercraft --export deck.pdf --format presentation --scope all <project>` and the MCP tool `export_presentation {pageIds?, path?, title?, subtitle?, author?}` produce the same deck.
## v2: presentable like a designer's deck
Research (client-presentation guides, the pptx skill's slide rules): show the big picture before details, annotate key decisions, keep filler (states, look-alike screens) out of the main flow, close on open questions, keep one visual system.
- [x] Given a page, after its divider, then a map slide shows its key screens as a captioned thumbnail grid in reading order.
- [x] Given a screen with notes on it (or on its layers), then its slide shows the screen with numbered markers on the noted layers and a column of the numbered notes (title, first line of the body, the category's colour); more notes than fit continue on a second slide of the same screen.
- [x] Given states of one screen (`Sessions / List`, `Sessions / Empty`), then the main flow shows the first, captioned with how many states it has, and the others are in an Appendix section at the end, two per slide.
- [x] Given notes that ask a question (a `?`), then an Open questions slide before the end lists them with their screen.
- [x] Given a page with boards, then the contents and its divider count screens and boards apart.
- [x] Detached notes (their layer was deleted) are left out.
## Constraints
- Stack: Rust, the existing PDF writer (`io/pdf.rs`); no new dependencies, no browser.
- Performance: a 120-screen project exports in seconds.
- Compat: PDF 1.7, readable in Preview, Acrobat and browsers.
## Open Questions
None: defaults chosen (dark slides, 1920 × 1080, deck title from the file name in the app and CLI).
+85
View File
@@ -0,0 +1,85 @@
# Plan
Read [spec.md](spec.md) first. Phase 0 is the change log and `rev` that another change is adding; nothing here starts before it merges (the harness skeleton and identity can start against its interface).
## Architecture in one paragraph
A new module tree `src/mcp/swarm/` holds the target-agnostic logic (compiles for wasm): `mod.rs` (the `Swarm` struct: claims, `seen` map, settings, and `Swarm::check(...) -> Gate` / `Swarm::finish(...)` / `swarm::attach(client, result)`), `targets.rs` (tool -> targets, `reach`, resources), `conflicts.rs` (the rule over the change log), `claims.rs` (state machine, TTL, overlap), `gate.rs` (the ordered checks, so claims and conflicts are separate files). `App::run_mcp_calls` and `cli::Offline::call` wrap their existing `Tracker::call` with `Swarm::check` before and `swarm::attach` after; nothing else in `exec.rs` changes, so the tools stay oblivious. Per-client undo lives in `history.rs`/`editor` with a thin change in `exec::undo_redo`. Offline and save-time work is in `cli.rs`, `session.rs`, `project/`, `merge.rs`.
## Phases
Size: S under 150 changed lines, M 150-500, L over 500, tests included. "Needs" lists real dependencies; phases with no overlap in files can run in parallel (wave column).
| # | Phase | Needs | Wave | Size | Files touched |
|---|---|---|---|---|---|
| 0 | Change log, `rev`, `get_changes`, scoped lint (other agent, external) | | - | | `src/mcp/changes*`, `exec.rs`, `tools.rs` |
| 1a | Identity (protocol) | 0 | 1 | M | `src/mcp/mod.rs` (`Client.parent`), `src/mcp/server.rs` (`agent_of`), `src/bin/papercraft-cli.rs` (`--as`, `--parent`, env, URL query), `src/cli.rs` (`Offline::new(.., client)`), `src/mcp/delegate.rs` (env), `src/runs.rs` (label for named sessions, run id in log entries) |
| 1b | Harness skeleton + gate skeleton | 0 | 1 | M | `tests/common/swarm.rs`, `tests/swarm.rs`, `src/mcp/swarm/{mod,gate}.rs` (empty `Gate` chain, `attach`), call sites in `src/app.rs` and `src/cli.rs` |
| 2 | Conflicts: `ifRev`, rule, warn/strict, settings | 1a, 1b | 2 | L | `src/mcp/swarm/{conflicts,targets}.rs`, `src/mcp/tools.rs` (`ifRev`/`onConflict` on write tools, `reach` test), `src/ui/settings.rs` + `src/settings`-side struct, `src/ui/chat_msgs.rs` (warning chip) |
| 3 | Claims: tools, state machine, auto-release, delegate scope | 1a, 1b | 2 | L | `src/mcp/swarm/claims.rs`, `src/mcp/tools.rs` (3 tools, `delegate.scope`), `src/mcp/exec.rs` (3 tool arms call `Swarm`), `src/app.rs` (claim before delegate spawn, turn end, project switch), `src/mcp/delegate.rs` (release on exit) |
| 4 | UI: agent colours, presence pin, claim outlines, Agent view, Break | 1a, 3 (claims part) | 3 | L | `src/theme.rs` (`agent_1..8`), `src/ui/mod.rs` (`mark_agent`, `AgentMark`), `src/ui/panels.rs` (Agent view), canvas painter, `src/ui/palette.rs` (Break all claims) |
| 5 | Per-client undo and run revert under concurrency | 0, 1a | 2 | M | `src/history.rs` (`author`, `undo_by`, root set-diff), `src/editor/mod.rs`, `src/mcp/exec.rs::undo_redo`, `src/mcp/tools.rs` (`scope`), `src/runs.rs` (`blocker`, `revert`, `foreign_changed`), `src/ui/panels.rs` (Undo this step, kept-layers list) |
| 6 | Offline: per-call lease, page refresh, app takes the lock, holder info, `Tracker` in `Offline`, `activity.json`, offline claims file | 0, 1a | 2 | L | `src/cli.rs`, `src/session.rs` (`open`), `src/project/mod.rs` (stamp), `src/bin/papercraft-cli.rs`, changes persistence file |
| 7 | Save-time stamp check, three-way merge, merge report | none (6 helps) | 1 | M | `src/session.rs::save`, `src/merge.rs` (`Merged`/notes), `src/project/packed.rs` (keep bytes), `src/editor/pages.rs` (`restore_snapshot` reuse) |
| 8 | Skill, docs, tool counts | 2, 3 | 4 | S | `skills/papercraft/SKILL.md`, `docs/agents.md`, `README.md`, `ROADMAP.md`, `src/mcp/tools.rs::INSTRUCTIONS`, chat system prompt (`src/ui/chat.rs`) |
| 9 | Swarm scenarios and coverage gate | per phase | with each | M | `tests/swarm.rs` grows with each phase |
**Order and parallelism.**
* Wave 1: 1a, 1b, 7 in parallel (disjoint files: 7 touches only session/merge/packed).
* Wave 2 (after 1a and 1b merge): 2, 3, 5, 6 in parallel. They share only `src/mcp/tools.rs` (different tool entries: add each in its own `fn` group to avoid conflicts) and `src/mcp/exec.rs` (3 and 5 add arms in different places). 2 and 3 plug into the `Gate` chain from 1b as separate files, so they do not edit each other's code. 5 and 6 are independent of 2 and 3.
* Wave 3: 4 (UI), once 3 exposes the claims API; the colour/pin half of 4 only needs 1a and can start in wave 2 if split (`4a` colours and pin, `4b` claims UI).
* Wave 4: 8.
* Merge conflict hot spots to coordinate: `tools.rs` (tool list and the `edits_doc` classification: new tools `claim_nodes`/`release_claims` edit nothing; `list_claims` read-only), `app.rs::run_mcp_calls` (1b owns the call-site edit; 3 adds the delegate claim in its own function), `panels.rs` (4 and 5 add different sections).
## Test plan
**Harness (Phase 1b, grows per phase).** `tests/common/swarm.rs`:
* `Sim { host: SessionHost, tracker: Tracker, swarm: Swarm, clock: FakeClock }` over a temp store (`temp_store`, as `tests/cli_offline.rs`), headless (no GPU unless a step needs a screenshot), single-threaded: determinism comes from scripted order, not threads.
* `SimClient { client: Client }`; `Step { at_ms, client, tool, args, expect }`; `Sim::run(script) -> Vec<Outcome>`. Every step goes through the **same entry the app uses** (`swarm::call(host, tracker, swarm, client, name, args, now)`, the function `App::run_mcp_calls` and `Offline::call` both call), so the harness cannot drift from production.
* `Sim::human(edit)` applies a canvas edit through `Editor::edit` with the human author, to test `You`.
* Scenario builders: `disjoint(n)` (N clients, own artboards), `overlap(n)` (shared frame), `shared_resources()`, `chain()` (delegate parent/child), `churn(seed)` (random ops from `fastrand::Rng::with_seed`).
* **Oracle.** A deliberately naive reference (`Oracle`) re-implements the section 2 table over the list of executed ops (per-node last-writer map, ancestor walk, per-tool `reach`) in O(n^2) and is compared with the product's `conflicts` and with the final document: every accepted write's value is present unless a later accepted write to the same property exists (no lost update). `churn` runs 200 seeds in CI, 5000 under `--ignored`.
* Offline: `OfflineSim` runs 3 `Offline` instances on threads against one folder with real locks (different `File` handles conflict on every platform), each doing N edits to its own artboard plus M to a shared one; asserts 3N + M edits in a fresh `Project::load_all`, no torn file, no panic, and that a held idle lock (shell between lines) does not block.
**Per-phase unit tests**
* 1a: `agent_of` parsing and sanitizing, reserved names, `Client` equality with `parent`, env -> flags precedence, `delegate::run` passes env (existing unix test extended with `env | grep`), stable session for `--as`, run label for named sessions.
* 2: each relation row positive and negative (self, ancestor own-fields vs `children`, descendant only for `subtree`, `children` reach not conflicting on sibling append, variable set vs bind, component, page); implicit reference per `(client, artboard)`; `ifRev` > current -> `history_reset`; strict leaves `rev`, doc, history, runs untouched (assert equality of all four); mode precedence table; human edit reported; conflict cap 20; every tool classified.
* 3: grant, deny with each `relation`, atomic denial (nothing claimed), own-claim merge, TTL renewal by reads, expiry with fake clock, each auto-release row, limits, `Block` vs `Warn`, parent-chain exemption, human exempt, resource names and `Claim required`, delegate scope required for `build`, claim exists before spawn and is gone after helper exit (stub command).
* 4: `agent_color` stable and in range; screenshot tests at scale 2 in both themes (`tests/agent_view.rs` style) for outlines, claims tags, Agent view, long names; Break removes the claim and the holder gets the notice.
* 5: `undo_by` independence matrix (disjoint ok; same node blocked; same parent children blocked; root set-diff ok; design/variables/page_modes/annotations; main component blocked); redo mine; default scope; human Ctrl+Z unchanged; run revert partial with a foreign edit, all-foreign, "Revert anyway".
* 6: lease around each call; interleaved shells; page refresh keeps other pages' history; app `Session::open` waits and reports the holder; holder info in the lock file; `activity.json` roundtrip, bounded, absent file; offline run/version created; `claims.json` roundtrip and expiry.
* 7: unchanged stamp writes; changed stamp merges and reports notes; undecodable or newer-format file refuses; merged result is one undo step; no layer dropped (property test over `merge::merge`: node count of merged >= union of kept ids).
**Coverage.** `cargo llvm-cov` (or `cargo tarpaulin` where the maintainer already uses it) on `src/mcp/swarm/`, `history.rs` changes and `cli.rs`; gate at 80% lines for the new modules. UI painting is covered by screenshots, not counted.
## Risks
| Risk | Mitigation |
|---|---|
| Conflict noise: agents ignore `conflicts` that fire on every call | `children` is a separate field so sibling appends do not fire; the implicit reference is per artboard; `reach` limits `descendant` to subtree tools; conflicts cap at 20; measure on the harness `churn` scenario (target: no conflict on pure disjoint work, by construction) |
| Under-reporting from the implicit reference (coarse, artboard-level) | `ifRev` is exact; the skill tells swarm agents to use it |
| Default `undo` scope change breaks single-agent habits | `scope: "page"` keeps the old behaviour; the tool description says so; only differs when someone else edited in between |
| Claims fence off the canvas (a stalled agent) | TTL with renewal only by the holder's calls, per-client and per-project limits, human Break, parent exemption |
| MCP session close not observable with rmcp's `LocalSessionManager` | TTL fallback; Phase 3 checks whether the manager can notify, else adds a `Drop`-guard on the per-session service handle |
| Per-call offline lease and page refresh cost on large projects | refresh is by stamp, only changed pages; `verify_large.rs`/`perf.rs` get a case |
| `PageBase` memory (compressed bytes of every saved page) | bytes already exist at save time; keep only for pages saved in this session; evict when the page is unloaded by `lazy_load` |
| Advisory locks on network folders | unsupported, documented; holder info and stamp check (Phase 7) still catch lost updates after the fact |
| Merge hides a semantic clash (both changed the same scalar, local wins) | the merge report surfaces each such scalar; the human decides |
| Change log assumptions differ from what Phase 0 ships | all dependence is in `conflicts.rs` and the entry struct; reconcile before wave 2 |
| `tools.rs` / `app.rs` merge conflicts between parallel agents | file ownership table above; each phase adds code in new files and one-line call sites |
## Open questions for the maintainer
1. **Default for claims:** `Block` (proposed) or `Warn`? Block makes claims meaningful but can stop an agent in a way the user sees as "stuck"; the denial message names the holder and time.
2. **`undo` default scope `mine`:** accept the behaviour change for single-agent use, or keep `page` as the default and make agents opt in through the skill? (Proposed: `mine`.)
3. **Session close hook:** is it acceptable to patch or wrap rmcp's session manager to learn of a closed session, or is TTL expiry enough?
4. **Human `locked` flag vs agents:** should agent writes honour `Node.locked` (reject with a clear error)? It is a one-line check in `swarm::targets` and would make "lock this for me" work with agents; it also changes today's behaviour where agents edit locked layers. Out of scope here unless you say otherwise.
5. **`delegate` `scope` required for `build`:** is a hard error acceptable, or should it default to the caller's current claims?
6. **Offline runs:** is it right that offline edits now create runs and auto-versions (disk cost per CLI invocation), or should they be opt-in (`--run`)?
7. **Merge on save (Phase 7):** worth its memory and complexity now, or defer until a sync-less second-writer case actually occurs? It is independent and can be dropped without affecting the rest.
8. **Notice/conflict placement:** trailing `swarm` content block (proposed) vs adding keys to the tool's JSON when it is an object. The block is uniform for text-only and image results; keys are easier for some clients to parse.
9. **Naming collision:** `rev` (log) vs `Editor::revision` (redraw counter). Rename the editor field (touches many files) or keep both and document?
10. **Where does the human's mid-edit text field count?** Proposed: nowhere (committed on blur). Confirm.
+354
View File
@@ -0,0 +1,354 @@
# Swarm safety: several agents on one project
## Why
One project can now have many writers at once: the in-app Chat agent, one or more external MCP clients (Claude Code, Codex), `papercraft-cli` calls online and offline, `delegate`d helpers, the person at the canvas, and (through the relay) other machines. Today the *transport* is safe: every online call is serialized on the UI thread and is one undo step, so nothing tears. What is missing is the *semantics*: an agent that read a frame, thinks for 40 s and then overwrites it does not learn that another agent rebuilt it meanwhile; two agents can both edit `variables`; `undo` undoes whoever was last; an offline CLI and a second process can race on the folder. This spec makes those cases visible, mostly non-blocking, and recoverable.
Design stance: **cooperative and fail-fast**. No tool call ever waits on another agent (no deadlock is possible). Conflicts are reported by default and rejected only on request. The human always wins and is never blocked.
## Builds on (do not redesign)
A change log with a document revision is being added by another change. This spec assumes exactly this interface and names it `rev`:
* `rev: u64`, bumped once per committed write. Every write result returns `rev`. It is **not** `Editor::revision` (`src/editor/mod.rs:253`), which is a redraw counter that `App::run_mcp_calls` bumps after every call.
* A bounded in-memory log of entries `{rev, client, tool, page, nodes[], fields[], variables?, at}`; `client` is the label of the caller; the human is `You`.
* `get_changes {since, exclude:"self"}` and `lint_design {since | changedOnly}`.
Two small additions are needed from that log and are tracked as Phase 0 follow-ups below: entries must say **which fields** of a node changed and keep `children` as its own field name (so "another agent added a child" is distinguishable from "another agent restyled the frame"), and the log must survive restart (see 6.4). If the other change lands differently, only `src/mcp/swarm/conflicts.rs` adapts.
## What exists today (checked 2026-10-28)
* **One chokepoint, online.** `server.rs::call_tool` builds a `Call {name, args, client, reply}`, `Dispatch` sends it down an mpsc channel and wakes the loop with `UserEvent::Mcp`; `App::run_mcp_calls` (`src/app.rs:1562`) runs each call in order via `Tracker::call` (`src/runs.rs:522`), then `UiState::mark_agent`, `log_agent`, and `steer::attach`. The chat's API backend uses the same channel (`App::tool_dispatch`), and its CLI backends reach the same HTTP server with `?chat=<id>` (`server.rs::client_of`, `chat_of`). `refs`, `imagegen` and `delegate` are the exception: they run on a spawned thread (`app.rs:1573`), because the helper calls back into the app through `papercraft-cli`.
* **Identity.** `Client {name, session}` (`src/mcp/mod.rs`). `name` is the MCP `clientInfo` title or name, or `CHAT_CLIENT`; `session` is the `mcp-session-id` header or the chat id. `Tracker` keeps one open run per `Client` (`Tracker.open`, `open_of`) and labels the second session of a name "Claude Code · 2" (`Tracker::label`). `papercraft-cli` connects with `().serve(...)` (`bin/papercraft-cli.rs:309`): default client info, a **new MCP session per process**, so each `papercraft-cli call` is a different `Client` and opens its own run. A delegated helper is just another such CLI process; nothing links it to its parent.
* **Touched layers.** `Editor.touch_log` is filled by `log_touched` on every commit while `Tracker::call` has it open; `take_touched` hands (page id, node) pairs to `UiState::mark_agent`, which keeps the topmost ones as `AgentMark {page_id, node, verb, client, at}` (cap `AGENT_MARKS_MAX`, fade `AGENT_MARK_SECS`). `RunPage.nodes` persists the node set per run and page; `runs::blocker` / `keep_own` / `revert` already use it to refuse or narrow a revert when a *later run* touched the same nodes.
* **Layer `lock`** is a human flag (`Node.locked`, `is_effectively_locked`): it stops canvas hit-testing and canvas editing. No tool in `src/mcp/exec.rs` checks it, so agents write through locked layers today. This spec does not change that (open question 4).
* **Undo** is per page (`ed.with_page(page, ..)`, `History.undo/redo` stacks of `Change`), global across authors. The `undo` / `redo` tools (`exec.rs::undo_redo`) pop the top `Change` of the page whoever made it. A `Change` has no author. A design-system edit puts the same `design` before/after in a step on **every** page (`history.rs`, `Change.design`).
* **Offline.** `cli::Offline` (`src/cli.rs`) wraps `SessionHost` and calls `exec::call` directly: no `Tracker`, no runs, no versions, identity-less. It already has two locks: `APP_LOCK` (`.papercraft-app.lock` in the projects root, held by the app for its whole life from `app.rs:1714`) and `PROJECT_LOCK` (`.papercraft-cli.lock` in the project folder, taken by `lock_for_write` before the first editing call, with a 5 s wait, then a **reload** of the project from disk). `refuse_if_open` refuses `--offline` on a project the app reports as `open` in `list_resources`. All are OS advisory locks (`File::try_lock`), so a crash releases them. Gaps are listed in section 6.
* **Saving.** `Session::save` (`src/session.rs:217`) writes every dirty page, `design.json` and the manifest atomically (`io::atomic::write`, temp + rename) but **never looks at what is on disk**: it is last-writer-wins per file. Only shared projects have a three-way page merge (`sync.rs` + `merge::merge`, base copy in `.sync-base/`).
* **Skills.** `skills/papercraft/SKILL.md` teaches single-agent use; nothing about sharing a project.
## Scope
### 1. Identity
Every call is attributed to an `AgentId`:
```rust
pub struct Client { // src/mcp/mod.rs, extended; stays Eq + Hash (Tracker key)
pub name: String, // "Claude Code", "Codex", "Chat", "You", "Actions", or --as value
pub session: String, // MCP session id, chat id, or stable agent session (below)
pub parent: Option<String>,// session of the agent that delegated this one
}
```
`run` is not a field of `Client`: the run is derived (`Tracker.open_of(client)`), and the change-log entry stores `run_id` when one is open so Review can group them.
**Sources of identity**
| Caller | name | session | parent |
|---|---|---|---|
| MCP client | `clientInfo` title or name (as today) | `mcp-session-id` | none |
| Chat turn (API or CLI backend) | `Chat` | chat id | none |
| `papercraft-cli` online | `--as <name>` > `$PAPERCRAFT_AGENT` > `cli` | `agent:<name>` (stable across invocations) | `--parent` / `$PAPERCRAFT_PARENT` |
| `papercraft-cli` offline / `shell` | same as online | same | same |
| `delegate` helper | `<parent label> / <role>` e.g. `Chat / build` | `d<n>-<chat id>` | the caller's session |
| Actions menu | `Actions` | `""` | none |
| The person at the canvas | `You` (reserved, cannot be claimed by `--as`) | `""` | none |
* **Why a query string, not `clientInfo`.** `papercraft-cli` has no per-call client info and a fresh MCP session per invocation. The chat already proves the pattern: `?chat=<id>`. The CLI appends `?agent=<name>&parent=<session>` to the MCP URL; `server.rs::client_of` reads it (`agent_of(query)` next to `chat_of`) and builds the stable session `agent:<name>`. Names are sanitized (`[A-Za-z0-9 ._/-]{1,40}`); `You`, `Chat` and `Actions` are rejected for `--as`. An unnamed CLI is `cli` and prints one stderr hint: "set --as <name> so other agents can tell you apart".
* **Delegation.** `delegate::run` sets `PAPERCRAFT_AGENT` and `PAPERCRAFT_PARENT` on the helper process (it already sets `PAPERCRAFT_PROMPT` and `PATH`), and the preamble tells the helper to pass nothing else: `papercraft-cli` reads the env. Grandchildren inherit the env, so chains work (`parent` is the immediate delegator).
* **Offline.** `Offline::new(store, project, client)` takes the same `Client`; the CLI binary builds it from the flags and env above. Offline gets a `Tracker` (Phase 6) so offline work also produces runs, versions and attributed log entries, not an anonymous blob.
* **Run labels.** `Tracker::label` keeps its numbering for MCP clients with no stable name. A named CLI agent is not numbered (its session is the name).
**Where it shows**
* *Canvas.* `mark_agent` already carries `client` (the label). The outline and its tag are drawn in the agent's colour: `agent_color(label) -> theme slot`, a stable hash of the label into 8 theme tokens `agent_1..agent_8` (added to `src/theme.rs` next to the other palette entries; both themes; no hex in UI code). The tag reads `Codex . Styling` (label, then verb); a delegate reads `Chat / build`. A *presence pin* (a small coloured dot plus the label, no text editing cursor exists for agents) sits on the top-left corner of the last touched layer for `AGENT_MARK_SECS`. The human's own edits get no mark.
* *Agent view.* One group per `Client` with its colour dot, label, state (working per `AGENT_WORKING_SECS`, idle, finished), runs, and its claims (section 3). Delegates are nested under their parent. Rows are one line, truncate with an ellipsis, and have 44 px targets for actions.
* *Change log and `get_changes`.* Entries carry `{client, session, parent, run}`; `exclude:"self"` matches on `(name, session)`.
### 2. Optimistic concurrency
**Reference rev.** The point in history the caller's picture of a layer is from.
* Explicit: any write tool accepts `ifRev` (integer, the `rev` the caller last synced to).
* Implicit (default, no `ifRev`): the server remembers `seen[(client, page, artboard)] = rev at the end of the client's last call that read or wrote anything under that artboard` (any tool whose resolved node ids sit under it; `get_screenshot`, `get_tree_summary`, `get_jsx`, writes, ...). A client with no history on an artboard has reference = the rev when its session first called. Tradeoff: coarse (artboard, not node) so a read of the header does not hide a stale body, in the direction of *over*-reporting; it costs one small map per client, dropped when the client has been silent for an hour.
**The rule.** A write call has a target set `T` (resolved before the call from `nodeId`, `nodeIds`, `targetNodeId`, parent, page and variable arguments by `swarm::targets::of(name, args, ed)`, the same resolution `runs::target_pages` already does for pages). It conflicts when the log has an entry with `rev > ref` by a **different client** (including `You`) whose node set matches one of:
| relation | an entry conflicts when it ... | applies to |
|---|---|---|
| `self` | changed a node in `T` (any field) | all writes |
| `ancestor` | changed the **own fields** (not `children`) of an ancestor of a node in `T`, or deleted or moved one | all writes (size, layout, clip, visibility of a parent change what a child edit means) |
| `descendant` | changed any node under a node in `T` | writes with `reach: subtree` (see below) |
| `variable` | changed (value, rename, delete) a variable the call **sets**, or deleted/renamed one the call **binds** with `var(--x)` or `bind_variable` | variable tools; node writes that bind variables |
| `component` | changed the main component of an instance in `T`, or an instance's main when `T` is a main | writes to instances and mains |
| `page` | created, deleted, renamed or reordered pages | page tools |
Per-tool `reach` (table in `src/mcp/swarm/targets.rs`, one test asserts every tool in `tools::definitions()` is classified, like the `edits_doc` test):
* `node`: `update_styles`, `set_text_content`, `rename_nodes`, `set_code_link`, `bind_variable`, ... (own fields only; descendants are not affected).
* `subtree`: `write_html` in replace mode, `delete_nodes`, `move_nodes` (also its source and destination parents' `children`), `detach_instance`, `apply_ui_kit`, anything that rebuilds children.
* `children`: `write_html` `insert-children`, `create_shape` under a parent, `duplicate_nodes`: adds below the target; conflicts only through `self` / `ancestor` (target deleted or moved), so two agents appending to the same frame do not conflict.
* `none`: `create_artboard`, `create_page` (no existing target; page relation only).
**Reading the result.** Conflicts are computed *before* the call runs, against the log, on the UI thread, so there is no check-then-act gap.
```json
// warn (default): the call is applied; trailing content block of the result
{"swarm": {"rev": 58, "refRev": 51, "applied": true,
"conflicts": [
{"node": "1:12", "name": "Header", "relation": "self",
"by": {"client": "Codex", "session": "agent:Codex", "label": "Codex"},
"rev": 55, "tool": "update_styles", "at": "2026-10-28T10:02:11Z",
"changed": ["fill", "paddingTop"]}
],
"hint": "Codex changed 1 layer you just wrote. get_changes {since: 51, exclude: \"self\"}, re-read those layers, adjust."}}
```
```json
// strict: nothing applied; isError result, text is this JSON
{"error": "conflict", "applied": false, "rev": 57, "refRev": 51,
"conflicts": [ ... same objects ... ],
"hint": "Re-read the layers above (get_changes {since: 51, exclude: \"self\"}), then retry with ifRev 57."}
```
The result stays a `ToolResult = Result<Vec<Out>, String>`: strict errors are the JSON string above (stable `error` codes: `conflict`, `claimed`, `needs_claim`, `undo_blocked`); warnings ride in a trailing `Out::Text` block, exactly how `steer::attach` appends its note, so tools' own JSON is untouched and image results keep working. `conflicts` is capped at 20 with `"more": n`.
**Modes**
| Setting | How set | Behaviour |
|---|---|---|
| `warn` (default) | nothing | apply; report conflicts against the implicit or explicit reference |
| `strict` per call | `ifRev` present (and no `onConflict: "warn"`) | reject if any conflict against `ifRev`; nothing applied |
| `strict` global | Settings, Agents, "Reject conflicting writes"; env `PAPERCRAFT_CONFLICTS=strict` | like strict per call, using the implicit reference when `ifRev` is absent |
| `warn` per call | `onConflict: "warn"` | override the above for this call |
Precedence: `onConflict` > presence of `ifRev` > env > setting > default.
`ifRev` newer than the current `rev` (the log was reset, for example the app restarted without a persisted log) is reported as one conflict `{"relation": "history_reset"}`: reported in warn, rejected in strict.
**Recovery protocol** (what the tool hint and the skill say): on `conflict` or a non-empty `conflicts`, call `get_changes {since: <refRev>, exclude: "self"}`, `get_tree_summary` / `get_screenshot` on only the listed nodes, decide whether the other change is compatible, redo your edit if not, and continue with `ifRev` = the `rev` you got back. Never retry the same call blindly.
**The human.** Canvas edits are recorded in the log as `You` through the editor commit path (a `HUMAN` author when no tool call is running), never checked, never blocked, and reported to agents by the same `conflicts` structure (`by.client == "You"`). An agent write is not blocked by a selection or an open text edit; the in-progress text edit is committed on Esc/blur as a normal human write and conflicts back in the other direction.
### 3. Soft claims
A claim is a short lease that says "I am working here". It is advisory by default and enforced for other agents (not the human) when the setting says so.
```json
// claim_nodes
{"name": "claim_nodes", "inputSchema": {"type": "object", "properties": {
"ids": {"type": "array", "items": {"type": "string"}, "description": "Layer ids (\"<page>:<n>\"). Each claims the layer and everything under it."},
"resources": {"type": "array", "items": {"enum": ["variables", "components", "pages", "settings"]}, "description": "Shared resources that cannot be split by layer."},
"ttlSeconds": {"type": "integer", "minimum": 10, "maximum": 1800, "default": 300},
"note": {"type": "string", "maxLength": 120, "description": "Shown to the person and to other agents."}},
"anyOf": [{"required": ["ids"]}, {"required": ["resources"]}]}}
// -> {"claimId": "c7", "claimed": ["1:12"], "resources": [], "expiresAt": "...", "ttlSeconds": 300, "rev": 58}
// release_claims {"claimId"?: "c7", "ids"?: [...], "resources"?: [...]} (nothing = all of mine)
// -> {"released": ["c7"]}
// list_claims {} (read-only) -> {"claims": [{claimId, holder, ids, resources, note, expiresInSeconds}]}
```
Resource names are the "named shared resource" form of a claim: `variables` (collections, variables, modes, tokens, the design system), `components` (creating or editing main components), `pages` (create, delete, rename, reorder, group), `settings` (project-level settings, libraries).
**Semantics**
* **Subtree.** A claim on a layer covers it and all descendants. It does not cover ancestors' own fields.
* **Overlap.** Another agent's claim `X` overlaps a request `Y` when `X` is the same layer, an ancestor, or a descendant of `Y`. A request overlapping *another client's* live claim is denied. Overlap with the caller's own claims merges (the existing claim is extended and renewed).
* **Atomic.** `claim_nodes` takes all of `ids` and `resources` or none. A denial is a normal result, not a thrown error:
```json
{"claimed": [], "denied": [
{"id": "1:12", "relation": "ancestor", "heldBy": "Codex", "claimId": "c3", "ids": ["1:3"],
"note": "rebuilding Settings screen", "expiresInSeconds": 212, "retryAfterSeconds": 212}]}
```
* **Limits.** At most 16 live claims per client and 64 per project (`MAX_CLAIMS_PER_CLIENT`, `MAX_CLAIMS`), so a runaway agent cannot fence off the canvas.
* **Lease, not lock.** The expiry is `now + ttl` and is renewed by any call from the holder (read or write) while the claim lives, so an active agent never loses a claim and a stalled one loses it `ttl` after its last call. Expiry is checked lazily on every claim check and by `Tracker::tick`; there is no timer thread.
* **What a claim does for others** (Settings, Agents, "Claimed layers": `Block` (default) or `Warn`; per call `onClaim` is not offered, the holder decides by claiming):
* `Block`: a write by another agent whose resolved targets (with `reach`) overlap a claim is rejected before it runs: `{"error": "claimed", "applied": false, "claims": [{claimId, heldBy, ids, note, expiresInSeconds}], "hint": "Work elsewhere or retry after expiresInSeconds; ask the holder through your orchestrator."}`.
* `Warn`: applied, with `claimWarnings` in the trailing `swarm` block.
* Reads and screenshots are never blocked. The parent chain of a delegate (delegator, its delegator, ...) is never blocked by the delegate's claim, only warned, so an orchestrator can always step in.
* The human is never blocked. A human edit inside a claim is logged as `You`, so the holder sees it as a conflict on its next call, and the canvas shows the claim as "edited".
* **Resources.** Writes that touch a shared resource map to a resource name by `swarm::targets::resources_of(name, args)`: `set_variable*`, `create_variable*`, `set_variable_mode`, token tools -> `variables`; component tools and writes whose target is a main component or inside one -> `components`; `create_page`, `delete_page`, `rename_page`, reorder and group tools -> `pages`; project settings and library tools -> `settings`. A resource claim held by someone else blocks (or warns) like a layer claim. Setting "Shared resources" (Settings, Agents): `Open` (default: no claim needed) or `Claim required` (a write to a shared resource without holding its claim is rejected with `needs_claim`; this is how an orchestrator reserves them for itself: it claims and holds them, and helpers cannot).
* **Auto-release**
| Event | Effect |
|---|---|
| `release_claims` | released |
| `finish_working_on_nodes {nodeIds}` | the caller's claims on those layers (or all of its claims when no ids) are released, then the run ends as today |
| Chat turn ends (`Tracker::finish`, `app.rs:772`) | all claims of that chat |
| `delegate` helper process ends, times out or is stopped | all claims of the helper |
| Run ends by idle (`RUN_IDLE_SECS` = 30) | **kept**: an agent thinking for 45 s is not finished; the TTL covers a dead one |
| MCP session closes (transport DELETE) | all claims of that session, if the session manager reports it (open question 3); else TTL |
| TTL passes with no call from the holder | expired |
| Project switch (`Tracker::sync_project` sees another dir) | all claims |
| App restart | gone (claims are memory-only online; MCP session ids do not survive a restart) |
| Human "Break claim" | removed; the holder's next result carries `notices: [{"type": "claim_broken", "by": "You", "claimId": "c7"}]` |
* **State machine of a claim**
| State | On | Next |
|---|---|---|
| (none) | `claim_nodes`, no overlap with others | Active |
| (none) | `claim_nodes`, overlap with another client | denied, no state created |
| Active | holder calls any tool | Active (expiry renewed) |
| Active | holder `claim_nodes` overlapping its own | Active (merged, renewed, one id) |
| Active | `release_claims`, `finish_working_on_nodes`, turn/helper end, project switch | Released |
| Active | no call from holder for `ttl` | Expired |
| Active | human Break | Broken |
| Expired / Released / Broken | any | removed at once; the change log keeps `claim_*` entries |
* **Deadlock freedom by construction.** No tool waits. A claim attempt returns immediately (granted or denied with holder and expiry). A claim is all-or-nothing, so no agent holds a partial set while asking for more; claims always expire, so no chain of holders can be unbounded. The remaining failure is *starvation*, not deadlock; the denial tells the caller `retryAfterSeconds` and the protocol (section 4) tells it to do other work first.
* **Delegation.** The `delegate` tool gains `scope` (`{"ids": [...], "resources": [...]}`), required for role `build`, ignored for `qa` and `read` (they do not edit). `run_mcp_calls` takes the claim **on the UI thread before spawning the helper** (the spawn happens at `app.rs:1573`), with holder = the helper's `Client` (name `<parent> / build`, `parent` = caller session) and a TTL of 15 min (the helper's timeout is `TIMEOUT` = 900 s), released when the process ends. If the scope is denied, the delegate call returns the `denied` list and no process starts. The parent can read and write inside the child's claim (warned, not blocked).
**Seeing and breaking claims (human)**
* *Canvas:* a claimed layer gets a dashed outline in the holder's colour and a small tag `Codex . 4:12 left` (a painted lock-and-clock icon, truncated note in the tooltip). Right-click on a claimed layer: "Claimed by Codex (4:12 left, rebuilding Settings)", "Break claim".
* *Agent view:* a `Claims` section per agent: target names, note, remaining time, a "Break" button (44 px). Resources show as chips (`variables`).
* *Editing under a claim:* allowed; the first human edit inside a claim shows a one-line status ("Codex has claimed this; it will be told") and no modal.
### 4. Swarm partitioning guidance
For the orchestrator (a person's prompt, or a lead agent). Prefer to split by things that do not share state, in this order:
| Split by | Why it is safe | Notes |
|---|---|---|
| **Page** | pages have their own `Document`, history and file; the only shared state is the design system and component sources | best default for large work |
| **Artboard** | one artboard = one subtree; claims and conflicts are cheap | the usual unit inside a page |
| **Component** | a main component and its instances | claim `components` unless every agent owns a different main |
| **Variables** | one agent owns the design system for the swarm | do this *first*, then fan out |
| **Annotations** | stored per page | partition by page like layers |
Shared resources that cannot be partitioned (each of these is a single value in the project: `design.json`, the manifest page list, component sources shared across pages via `flush_cross_pages`, project settings):
| Resource | Rule |
|---|---|
| Variables, modes, tokens | Orchestrator defines them up front. Later changes: `claim_nodes {resources:["variables"]}`, change, release, in a short window. Never switch the document mode (`set_variable_mode`) while others take screenshots: it changes what every agent sees. Do it last or have the orchestrator do it |
| Components | One owner per main component. Anyone may place instances; only the owner edits the main. Use `components` claim for new components |
| Page list and order | Orchestrator creates pages first (`pages` claim for later changes) |
| Project settings, libraries | Orchestrator only (`settings` claim held for the swarm, setting "Claim required") |
**Recommended agent protocol** (the block for `skills/papercraft/SKILL.md`, about 20 lines):
```
Sharing a project with other agents
1. Identify yourself: papercraft-cli --as <short name> (or set PAPERCRAFT_AGENT). MCP clients are named by the client.
2. Read before you write: note `rev` (get_basic_info). Work only in the layers you were assigned.
3. Claim what you will rewrite: claim_nodes {ids:[<your artboard>], ttlSeconds:600, note:"<what you do>"}.
If denied, do other work or report back; never wait in a loop.
4. Edit with ifRev = the rev your last result returned.
5. If a result has `conflicts` or error `conflict`: get_changes {since: <refRev>, exclude:"self"}, re-read only those layers, redo what is no longer right. Do not blindly retry.
6. After a batch: lint_design {changedOnly:true}, fix findings in your layers only.
7. Shared things (variables, components, pages, settings): claim the resource, change, release in the same minute.
8. Finish: finish_working_on_nodes {nodeIds:[...]} (releases your claims) and report which layers you changed, which conflicts you saw and how you resolved them.
9. Never undo with scope "page"; use undo {scope:"mine"}.
Orchestrators: give each helper a disjoint `scope` in `delegate`; create pages and variables before fanning out.
```
### 5. Undo and revert under concurrency
**Per-client undo.** `undo` and `redo` get `scope`:
```json
{"name": "undo", "inputSchema": {"type": "object", "properties": {
"pageId": {"type": "string"},
"scope": {"enum": ["mine", "page"], "default": "mine",
"description": "mine: undo only your latest step, if no later step by someone else touched the same layers. page: undo the page's latest step whoever made it."}}}}
// -> {"done": true, "what": "write_html", "step": "s41", "rev": 61}
// -> refused: {"done": false, "reason": "undo_blocked", "step": "s41", "blockedBy": [{"client": "Codex", "rev": 59, "tool": "update_styles", "nodes": ["1:12"]}]}
```
* **Authorship.** `History` stores per `Change` an `author: Arc<str>` (the client label, `You` for canvas edits), its `rev` and a step id. Coalesced canvas steps (`coalesce_key`) keep the human author.
* **Algorithm** (`History::undo_by(doc, author) -> Result<Option<Undone>, Blocked>`): find the newest `Change` `m` by the caller on the page. Let `later` be the changes above it. `m` is *independent* when, for every `l` in `later` by anyone: entry ids of `l` and `m` are disjoint, `m.design`/`m.variables`/`m.page_modes`/`m.annotations` are `None` or the same field is `None` in `l`, and `m` touched no main component (a `touched_mains` step may rewrite instances on other pages). If independent, apply `m` backwards, splice it out of the undo stack, and push it to the redo stack. If not, return `Blocked` with the offending `l`s. Conservative on purpose: if both changed `children` of the same parent they both have an entry for the parent, so it is refused. The root list is handled by set difference (remove ids `m` added, re-insert ids `m` removed after their old predecessor), so two agents each creating an artboard do not block each other's undo.
* **Redo** `scope: "mine"` re-applies the caller's last undone step if the same independence holds in reverse; as always, any new commit on the page clears the redo stack, so an agent cannot redo across someone else's later edit (documented, not worked around).
* **Default.** `scope` defaults to `mine` for every client except `You`, because "undo" from an agent should never remove a person's or another agent's work. The old behaviour is `scope: "page"`. This is a behaviour change for single-agent use when the human edits between agent steps; it is deliberate (open question 2).
* **The human's Ctrl+Z / Ctrl+Shift+Z** is unchanged: it undoes the newest step on the page whatever its author, because that is what the canvas shows and what the person expects. The status line says whose step it was ("Undid Codex: write_html"). The Agent view run rows get "Undo this step" using the same independence check, with the refusal explained in a toast.
* **Cross-page steps.** A design-system edit adds a step on every page; its independence check is against later `design` changes only, so undoing one's variable edit works while others edit layers.
**Run revert** (`runs::revert`, `revert_change`, "Restore to here") under concurrency:
* The existing `blocker(runs, run)` refuses when a *later run* touched the same nodes. Extend it with the change log: a node of `RunPage.nodes` that has a log entry by another client (including `You` and clients with no run, like offline CLI before Phase 6) with `rev` after the run's first call is **foreign-changed**.
* Outcomes of "Revert run":
1. *No foreign-changed nodes:* as today (full page restore when the run is the only writer, node-level when `shared`).
2. *Some:* revert only the clean nodes (the existing node-level path used for `shared` pages, now chosen whenever *any* foreign entry exists on the page since the run started, not only when another run exists), skip the foreign-changed ones, and say so: "Reverted 14 layers. Kept 3 that Codex or you changed afterwards." with a list and a per-row "Revert anyway" (restores that node to the snapshot, overwriting the later change; one undo step, shows what will be lost).
3. *Everything is foreign-changed:* nothing is reverted; the state stays `Review`.
* An agent-driven revert (a future tool) is never forced; only the person can use "Revert anyway".
* The auto-version `Before agent run N` is a whole-page snapshot taken when *that client's* run starts, so it contains other agents' in-flight work. `RunPage.nodes` / `keep_own` already restrict review and revert to the run's own nodes; the change log makes that precise for clients that never had a run.
### 6. Offline CLI and multi-process
**6.1 What races today**
| Race | Today | Verdict |
|---|---|---|
| Offline A vs offline B, same project | `PROJECT_LOCK` taken at first edit, held until the process exits; B waits 5 s then fails; A reloads at lock time | Safe but unfair: a long `shell` starves everyone (G1) |
| Offline vs running app, project open in the app | `--offline` refused via `list_resources.open` for `open_file` / `--project` | Safe |
| Offline vs running app, project **not** open in the app, app opens it later | the app's `Session::open` never looks at `PROJECT_LOCK`; it loads mid-edit state, then saves over the CLI's later edits | Race (G2) |
| Save over a changed file (Dropbox, a second machine's copy, a manual copy) | blind overwrite | Last writer wins (G3) |
| Offline writes carry no identity, runs, versions or log entries | `Offline::call` bypasses `Tracker` | Gap (G4) |
**6.2 Per-call lease (G1).** `Offline::call` takes the project lock **around each editing call**, not for the process lifetime: `lock -> refresh -> exec -> save -> unlock`. Waits stay `PROJECT_LOCK_WAIT` (5 s), but now a held lock lasts one call (milliseconds to a second), so shells and scripts interleave. `refresh` compares the on-disk stamp (`manifest.modified` plus `len + mtime` of each page file and `design.json`) with the stamp recorded at the last load/save; for each page whose stamp changed it reloads **that page only** (replacing its `Document` and resetting only its history); unchanged pages keep their history, so `:undo` in a shell works across interleaving as long as that page was not changed meanwhile. Because every offline editing call saves before unlocking, the process has no dirty pages at refresh time, so the refresh never needs a merge.
**6.3 The app takes the lock too (G2).** `Session::open` (native) takes `PROJECT_LOCK` with a 2 s wait before loading and keeps it while the project is open (released on close or switch, and by the OS on crash). An offline process that finds it held by the app reports "PaperCraft has this project open" (same text as `refuse_if_open`) instead of "another papercraft-cli is writing". The lock file's content records the holder (`{"pid", "client", "since"}`) so errors can say "held by papercraft-cli --as Codex (pid 4120, 12 s)". The windows between app open and offline lease are one call long, thanks to 6.2.
**6.4 Identity and the log offline (G4).** `Offline` gets a `Client` and a `Tracker`; the run closes when the process ends or after `RUN_IDLE_SECS`, and the auto-version rules apply, so Review/Revert cover offline work. The change log (Phase 0) is persisted as `activity.json` in the project folder (bounded: `ACTIVITY_KEEP` = 500 entries, plus `epoch` and `rev`), written atomically by the process holding the lock after each editing call, and loaded by the app on open and by offline processes at lease time. This is what makes `ifRev` and `get_changes` meaningful across offline processes and across an app restart. A project without the file starts at `rev = 0` with a new epoch (`history_reset` for older `ifRev`). Format: additive, optional, ignored by older builds.
**6.5 Claims offline.** With no app running, claims live in `claims.json` in the project folder, read and written under the lease (expired ones are dropped on load); the holder is the stable `agent:<name>` session, so a claim survives across that agent's CLI invocations. With the app running, offline is only used on projects the app does not hold, and the app discards `claims.json` when it opens the project (agents using the app are on MCP sessions that the file cannot represent). Every offline process reads the file at lease time, so claims are enforced between offline processes too.
**6.6 Save-time check, merge or refuse (G3).** `Session::save` keeps per page the packed bytes it last read or wrote (`PageBase`, zstd, about the size of the file) and the file stamp. Before writing a dirty page it compares the stamp on disk. Unchanged (the normal case): write. Changed: three-way merge with `merge::merge(base, local, disk)` (decoded JSON), write the result atomically, and install it in the editor as one undo step "Merged changes from disk" (via `Editor::restore_snapshot`, which already exists for versions). `merge` is extended to return a report (`Merged { value, notes }`, notes for each scalar where both sides changed and local won, and each renumbered id) because RULES.md says a merge that cannot keep something must say so; the notes go to the status line and the Agent view. Refuse (save skipped, status "Disk changed and cannot be merged: ...") when either side fails to decode or the page file has a newer format version. `design.json` and the manifest are small objects; they use the same merge with `base` = last written. The shared-project sync engine keeps its own `.sync-base/` merge; this check runs first and does not replace it.
**6.7 App running, offline requested.** Unchanged: plain `call` goes through the app; `--offline` on a project the app has open is refused; `--offline` on another project works under the lease. A CLI that finds `APP_LOCK` held but no server yet keeps waiting (`app_starting`).
### 7. Chat vs MCP
Both reach `App::run_mcp_calls`, so identity, conflicts, claims, rev, runs and the log are identical. Differences, all unchanged by this spec:
| Aspect | Chat | External MCP / CLI |
|---|---|---|
| Identity | `Chat` + chat id, from `?chat=` or the API backend's dispatch | client info / `--as` |
| Steering | `steer::attach` appends the user's mid-turn messages to the next tool result | none |
| Run end | `Tracker::finish` when the turn ends; also releases claims | idle 30 s or `finish_working_on_nodes` |
| Auto mode | answers `ask_user` with the first option; unaffected | not applicable |
| Sub-agents | `delegate` (off the UI thread) | an MCP client's own sub-agents are not visible; they appear as the same or new sessions |
The swarm block must surface in chat the same way: `swarm::attach(client, r)` runs for every client right before `steer::attach`, so the chat model sees `conflicts`, `claimWarnings` and `notices` in its tool results. In the chat UI, `chat_msgs` renders a result with `swarm.conflicts` or a `claimed` / `conflict` error as a warning chip on the tool card ("Codex changed Header at rev 55") with a "Show" action that selects the node; the chat system prompt gets the protocol block of section 4 (the chat agent is a swarm member, and its `delegate` calls carry `scope`).
### 8. Relay and other machines
Out of scope: real-time cross-machine claims, and cross-machine `rev` (each machine has its own counter). In scope by reference only:
* A relay sync is **page granularity** (`sync.rs`): when both sides changed a page it merges it with `merge::merge` against `.sync-base/` and the folder wins ties; the open project reloads (`Session::sync_poll`) unless it has unsaved edits (those win and go up on the next save).
* A synced merge lands in the editor as a reload, so it is recorded in the log as one entry by `client: "Sync"`, `nodes` = the pages' changed nodes if cheap to compute, else `page: <id>, whole: true`. Agents then see it as a conflict (`by: Sync`) on their next write to that page. `Tracker` already flags "Includes changes synced from others" in Review; this reuses that signal.
* Claims are local to the machine that holds the app; a remote editor is like the human: never blocked, always reported (as `Sync`).
* Remote agents on the relay (`mcp/relay.rs`) arrive through the same MCP path on the host machine and are ordinary clients there.
## Not in scope
* Real-time collaborative cursors for humans.
* Automatic semantic merge of conflicting edits on the same property (the agent decides).
* Enforcing the human `Node.locked` flag against agents (open question 4).
* Blocking a read while another agent is writing (reads see the committed state).
* Per-property claims; layer granularity only.
* Cross-machine claims or `rev`.
* Cross-page atomic undo.
* Locking on network filesystems where advisory locks are unreliable: documented as unsupported, not detected.
## Acceptance
* Two simulated clients editing disjoint artboards produce no `conflicts`; overlapping edits produce exactly the conflicts the brute-force oracle computes (section 2 table), in `warn` and `strict`, for every relation.
* A strict rejection leaves the document, the log (`rev`), the undo stack and runs unchanged.
* `claim_nodes` on a layer makes another client's `update_styles` on it or a descendant fail with `claimed` (`Block`) or succeed with `claimWarnings` (`Warn`); the holder is unaffected; the human is never blocked. A claim expires after `ttl` of holder silence (fake clock), is released by `finish_working_on_nodes`, by turn end, by helper end, by project switch, and by Break; overlapping and ancestor/descendant requests are denied atomically.
* `delegate` of role `build` without `scope` is an error; with `scope` the helper's claim exists before the process starts and is gone after it ends.
* `undo {scope:"mine"}` undoes the caller's newest step when later steps by others touch other layers and returns `undo_blocked` with `blockedBy` when they touch the same ones; Ctrl+Z still undoes the newest step.
* Run revert with a later foreign edit to one of its nodes reverts the others and reports the kept one; revert never changes a layer the run did not touch.
* Two offline `Offline` instances on one folder (threads, real locks) each doing N edits end with 2N edits on disk and in a fresh load; the shell with an idle prompt does not block the other.
* `Session::open` on a project whose `PROJECT_LOCK` is held waits, then reports the holder. Saving a page whose file changed on disk merges and reports notes, or refuses; a layer is never silently dropped.
* A project without `activity.json`, `claims.json` or the new run fields loads unchanged; an older build ignores them.
* Tool schemas and descriptions exist for `claim_nodes`, `release_claims`, `list_claims`, the new `ifRev` / `onConflict` / `scope` arguments, each tested in `tests/mcp.rs`; README and ROADMAP tool counts are updated.
* Screenshot inspection at scale 2 in both themes of: agent colours on outlines, claim outline and tag, Agent view with two agents and a delegate, Claims section, a long agent name and a long note (no overflow, 44 px targets).
* `cargo test --no-fail-fast`, `cargo check --lib --target wasm32-unknown-unknown` (swarm logic is target-agnostic; file locks are native only) and the Windows check pass. 80% line coverage on the new `src/mcp/swarm/` modules and the changed lines elsewhere.
## Open questions for the maintainer
See `plan.md`.
+44
View File
@@ -0,0 +1,44 @@
# Tasks
Each task is independently testable. Tests first. Stop on failure. Tasks in the same wave touch different files and can run in parallel; a wave starts when the previous one passes `cargo test`. Phase 0 (change log, `rev`, `get_changes`, scoped lint) must be merged first.
## Wave 1: foundations (parallel)
- [x] 1. **Client identity** (`src/mcp/mod.rs`, `src/mcp/server.rs`). `Client.parent: Option<String>`; `agent_of(query) -> Option<AgentQuery{name,parent}>` next to `chat_of`; `client_of` builds `Client{name, session:"agent:<name>", parent}`; sanitize names, reject `You`/`Chat`/`Actions`. Test: parsing, sanitizing, reserved names, equality, `chat=` still wins.
- [ ] 2. **CLI identity** (`src/bin/papercraft-cli.rs`, `src/cli.rs`, `src/mcp/delegate.rs`). `--as`, `--parent`, `PAPERCRAFT_AGENT`, `PAPERCRAFT_PARENT` (flag > env > `cli`); online appends the query to the MCP URL; `Offline::new(store, project, client)`; `delegate::run` sets both env vars on the helper; one-time stderr hint for unnamed. Test: precedence, URL, offline carries the client, helper env visible (unix test), shell keeps one identity across lines. Depends on 1. *Partly done: `--as`/`--parent`, env and helper env; offline client and stderr hint open.*
- [x] 3. **Gate skeleton** (new `src/mcp/swarm/{mod,gate}.rs`, `src/lib.rs` or `src/mcp/mod.rs` registration; call sites in `src/app.rs::run_mcp_calls` and `cli::Offline::call`). `Swarm`, `Gate::{Allow, Reject(String)}`, `swarm::call(host, tracker, swarm, client, name, args, now)`, `swarm::attach(client, r)` (before `steer::attach`). Empty check chain; behaviour unchanged. Test: all existing `tests/mcp.rs` and `tests/cli_offline.rs` pass; a stub check can reject and annotate.
- [ ] 4. **Harness skeleton** (`tests/common/swarm.rs`, `tests/swarm.rs`). `Sim`, `SimClient`, `Step`, `FakeClock`, `Oracle` stub, `disjoint(n)` scenario: N clients write own artboards, assert every write present and ordered `rev`s. Depends on 3. *Partly done: `Sim` in `tests/swarm.rs` with a fake clock; oracle and seeds open.*
- [ ] 5. **Save-time stamp check and merge** (`src/session.rs::save`, `src/merge.rs`, `src/project/packed.rs`, `src/editor/pages.rs`). `PageBase`, stamp per page file, `merge::merge_report -> Merged{value, notes}` (keep `merge` as a wrapper), changed file -> merge -> write -> `restore_snapshot` as "Merged changes from disk"; undecodable or newer format -> refuse with a message. Test: unchanged writes; changed merges and reports; refusal; one undo step; property test: no kept id lost.
## Wave 2: behaviour (after wave 1; 6, 8, 10, 11 parallel)
- [ ] 6. **Targets and reach** (`src/mcp/swarm/targets.rs`). `of(name, args, ed) -> Targets{nodes, pages, variables, resources, reach}`, `Reach::{None,Node,Children,Subtree}`, `resources_of`. Test: every tool in `tools::definitions()` classified (fails on a new unclassified tool); resolution of `nodeId`, `nodeIds`, `targetNodeId`, parent, page, `var(--x)` in html/styles. *Partly done: `swarm::reach` and `exec::named_layers`; variable and page targets open.*
- [ ] 7. **Conflict rule** (`src/mcp/swarm/conflicts.rs`, `tools.rs` schemas, settings). `ifRev`, `onConflict`, `seen[(client,page,artboard)]`, relations table, warn trailing block, strict `conflict` error before execution, `history_reset`, cap 20, Settings entry + `PAPERCRAFT_CONFLICTS`. Test: each relation +/-, mode precedence, strict changes nothing (doc, rev, history, runs), human reported, oracle comparison in `tests/swarm.rs` (`overlap`, `churn` 200 seeds). Depends on 6. *Partly done: `ifRev`, `onConflict`, `PAPERCRAFT_CONFLICTS`, warn block, strict error, cap 20; settings entry open.*
- [x] 8. **Claims core** (`src/mcp/swarm/claims.rs`). State machine, overlap (same/ancestor/descendant), atomic all-or-nothing, own-claim merge, sliding TTL, limits, lazy expiry plus `tick`, parent-chain exemption, `Block`/`Warn`, resources, `Claim required`. Pure logic over ids and a clock, no UI. Test: the full state table and each auto-release row except those needing the app (project switch is a `Swarm::reset`). Depends on 3.
- [x] 9. **Claim tools and delegate scope** (`src/mcp/tools.rs`, `src/mcp/exec.rs`, `src/app.rs`, `src/mcp/delegate.rs`). `claim_nodes`, `release_claims`, `list_claims`; `finish_working_on_nodes` releases; turn end (`app.rs:772` neighbourhood) releases chat claims; delegate `scope` required for `build`, claim taken before spawn on the UI thread, released when the helper ends; `claimed` / `needs_claim` errors. Update README and ROADMAP tool counts. Test in `tests/mcp.rs` per tool; stub-helper test for claim lifetime. Depends on 8.
- [ ] 10. **Per-client undo** (`src/history.rs`, `src/editor/mod.rs`, `src/mcp/exec.rs::undo_redo`, `tools.rs`). `Change.author/rev/step`, `History::undo_by/redo_by`, independence check, root set-difference, `scope` argument, default `mine` for agents, `undo_blocked` result, author in the status text for Ctrl+Z. Test: independence matrix, redo, defaults, Ctrl+Z unchanged, cross-page design steps. *Partly done: `undo_by`, `scope`, `undo_blocked`, redo of own step; author in Ctrl+Z status open.*
- [ ] 11. **Offline lease and app lock** (`src/cli.rs`, `src/session.rs::open`, `src/project/mod.rs`, `src/bin/papercraft-cli.rs`). Lock around each editing call; stamp-based per-page refresh; lock file records holder; `Session::open` takes the project lock with a 2 s wait and keeps it; error text distinguishes app from CLI. Test: 3-thread `OfflineSim` (3N + M edits), idle shell does not block, app open waits then reports the holder, other pages keep history.
- [ ] 12. **Offline runs, log and claims file** (`src/cli.rs`, change-log persistence, `src/runs.rs`). `Tracker` in `Offline`, run closed at exit; `activity.json` (bounded, epoch) written under the lease and loaded by app and CLI; `claims.json` offline claims; app discards the file on open. Test: offline run and version exist and revert; roundtrip; bound; absent file. Depends on 2, 8, 11.
## Wave 3: runs and UI (after wave 2)
- [ ] 13. **Run revert under concurrency** (`src/runs.rs`, `src/ui/panels.rs`). `foreign_changed` from the log, outcomes 1 to 3, "Revert anyway" row action, kept-layers list, "Undo this step" in run rows. Test: partial revert, all-foreign, offline-client edits count as foreign, other layers untouched. Depends on 10.
- [ ] 14. **Agent colours and presence pin** (`src/theme.rs`, `src/ui/mod.rs`, canvas painter). Theme tokens `agent_1..8` in both themes, `agent_color(label)`, tinted outlines and tags, pin, `Chat / build` label. Screenshot at scale 2 in each theme (`tests/agent_view.rs` style), long label truncates. Depends on 2.
- [ ] 15. **Claims UI** (`src/ui/panels.rs`, canvas painter, `src/ui/palette.rs`). Dashed claim outline and tag, right-click "Break claim", Agent view `Claims` section and delegate nesting, resource chips, notice to the holder on Break, "Break all claims" palette entry. Screenshots both themes, 1440p and 1280x800, long note and name, 44 px targets. Depends on 9, 14.
- [ ] 16. **Chat surface** (`src/ui/chat_msgs.rs`, `src/ui/chat.rs`). Warning chip for `swarm.conflicts` / `claimed` / `conflict` on tool cards with Show; protocol block added to the chat system prompt. Test: parse of the `swarm` block, chip text, prompt contains the protocol. Depends on 7, 9.
## Wave 4: finish
- [ ] 17. **Skill and docs**. `skills/papercraft/SKILL.md` gets the section 4 protocol and the partitioning table (kept short; run it with two real agents against a test project on a private port, per AGENTS.md "Running the app safely"); `docs/agents.md` (identity, `--as`, conflicts, claims, undo scope, offline lease); `src/mcp/tools.rs::INSTRUCTIONS`; README and ROADMAP tool counts; `ROADMAP.md` row.
- [ ] 18. **Swarm scenarios complete** (`tests/swarm.rs`). Adds `shared_resources`, `chain` (delegate), claim expiry, per-client undo, offline sim, revert-with-foreign scenarios; `churn` 200 seeds default, 5000 `--ignored`. Coverage gate 80% on `src/mcp/swarm/` and changed lines.
- [ ] 19. **Verify**. Full `cargo test --no-fail-fast` (known `tests/update.rs` failure on Windows), `cargo check --lib --target wasm32-unknown-unknown`, Windows check, `cargo clippy --all-targets`, `cargo fmt --all`. Manual: two MCP clients and the chat on one project on a private `PAPERCRAFT_HOME` and `PAPERCRAFT_MCP_PORT`, never the person's running app.
## Independence summary
* Fully independent: 5 (save merge), 10 (undo), 11 (offline lease).
* Share only the gate skeleton: 7 and 8/9.
* UI tasks 14 to 16 touch `panels.rs` in separate sections; land 14 first.
## Model per task (subagents)
Claude Sonnet: 1, 2, 3, 4, 7, 8, 9, 10, 12, 13. Claude Haiku: 6 (table), 17. Codex coding model: 5, 11, 14, 15, 16, and a read-only review after each wave. Only one editing agent per file at a time (see the hot spots in `plan.md`).
+96 -6
View File
@@ -60,6 +60,9 @@ const AGENT_FRAME: Duration = Duration::from_millis(50);
pub struct App {
gfx: Option<Gfx>,
/// The undecorated window edge under the pointer (Linux), which a press resizes.
#[cfg(all(unix, not(target_os = "macos")))]
resize_edge: Option<winit::window::ResizeDirection>,
pub ed: Editor,
session: Session,
st: UiState,
@@ -86,6 +89,9 @@ pub struct App {
)>,
/// Groups the agent's editing calls into reviewable runs.
runs: crate::runs::Tracker,
/// Claims and what each agent last saw; shared with delegate threads, which release their
/// helper's claims when it ends.
swarm: std::sync::Arc<std::sync::Mutex<crate::mcp::swarm::Swarm>>,
}
/// Events delivered to the winit loop from other sources.
@@ -119,6 +125,8 @@ impl App {
let library = crate::library::Library::load(&crate::library::Library::path_in(&store.root));
let mut app = App {
gfx: None,
#[cfg(all(unix, not(target_os = "macos")))]
resize_edge: None,
ed: Editor::default(),
session: Session::new(store),
st: UiState::default(),
@@ -135,9 +143,11 @@ impl App {
menu: None,
mcp: None,
runs: Default::default(),
swarm: Default::default(),
};
app.st.library.library = library;
app.st.perf.prefs = crate::ui::perf::PerfPrefs::load();
app.st.menu_bar_hidden = crate::ui::menu_toggle::load_hidden();
app.ed.clipboard_io = crate::io::clipboard::System::new()
.map(|c| Box::new(c) as Box<dyn crate::io::clipboard::Provider>);
match start {
@@ -477,7 +487,8 @@ impl App {
}
let ext = spec.format.ext();
let out = if spec.single_file(items.len()) {
let base = if items.len() == 1 {
// A presentation is named after the project: the name is its title.
let base = if items.len() == 1 && spec.format != export::Format::Presentation {
items[0].name.clone()
} else {
self.st.project_name.clone()
@@ -694,8 +705,15 @@ impl App {
}
}
AppRequest::ExportFormat(f) => {
// From the menu, a presentation is of the whole project.
let scope = if f == crate::io::export::Format::Presentation {
crate::io::export::Scope::AllPages
} else {
self.st.export.scope
};
let spec = crate::io::export::Spec {
format: f,
scope,
..self.st.export
};
self.export(spec);
@@ -764,6 +782,7 @@ impl App {
if self.st.chat.take_finish_run() {
// A chat turn that edited is over: close its run now, not after the 30 s idle timeout.
self.runs.finish(crate::project::format::now_ms(), &self.ed);
self.swarm.lock().unwrap().release_chats();
}
self.st.sync_runs(&self.ctx, &mut self.runs, &self.ed);
self.st.chat.tools = self.tool_dispatch().map(crate::chat::events::ToolDispatch);
@@ -1038,8 +1057,12 @@ impl ApplicationHandler<UserEvent> for App {
.with_corner_preference(CornerPreference::Round)
.with_taskbar_icon(icon)
};
// Linux: no native frame either; the toolbar carries the window buttons and the window
// edges resize (`edge_resize`).
#[cfg(all(unix, not(target_os = "macos")))]
let attrs = attrs.with_decorations(false);
let window = Arc::new(event_loop.create_window(attrs).expect("create window"));
self.st.custom_titlebar = cfg!(windows);
self.st.custom_titlebar = cfg!(any(windows, all(unix, not(target_os = "macos"))));
window.set_ime_allowed(true);
#[cfg(target_os = "macos")]
{
@@ -1119,6 +1142,10 @@ impl ApplicationHandler<UserEvent> for App {
log::trace!("event {event:?} -> egui repaint {}", resp.repaint);
}
let scale = g.window.scale_factor();
#[cfg(all(unix, not(target_os = "macos")))]
if self.st.custom_titlebar && edge_resize(&g.window, &event, &mut self.resize_edge) {
return;
}
let mut redraw = resp.repaint;
let now = self.now();
match event {
@@ -1155,6 +1182,14 @@ impl ApplicationHandler<UserEvent> for App {
// egui-winit reports `repaint: true` for RedrawRequested itself; honouring it
// re-requested a redraw every frame (a 100% CPU busy loop). Whether another
// frame is needed is decided inside redraw() from egui's repaint delay.
// The frame-rate cap (Settings > Performance) holds a frame that comes too soon
// until its turn; every redraw request ends up here, so one check covers them all.
let since_last = self.last_redraw.map_or(Duration::MAX, |t| t.elapsed());
if let Some(wait) = ui::perf::cap_wait(self.st.perf.prefs.frame_interval(), since_last) {
let due = Instant::now() + wait;
self.next_repaint = Some(self.next_repaint.map_or(due, |r| r.min(due)));
return;
}
self.redraw();
return;
}
@@ -1553,9 +1588,27 @@ impl App {
let chat = (c.client.name == crate::mcp::CHAT_CLIENT).then(|| c.client.session.clone());
let provider = self.st.settings.chat.image_provider();
let helper = self.st.settings.chat.helper_command.clone();
// A helper is its own agent: named after its caller, with its scope claimed before
// it starts and released when it ends.
let agent = if c.name == crate::mcp::delegate::TOOL {
let role = c.args["role"].as_str().unwrap_or_default();
let claimed = self.swarm.lock().unwrap().claim_for_helper(&mut self.runs, &mut self.ed, &c.client, role, &c.args["scope"], crate::project::format::now_ms());
match claimed {
Ok(a) => Some(a),
Err(e) => {
let _ = c.reply.send(Err(e));
continue;
}
}
} else {
None
};
let swarm = self.swarm.clone();
std::thread::spawn(move || {
let r = if c.name == crate::mcp::delegate::TOOL {
crate::mcp::delegate::run(&helper, chat.as_deref(), &c.args)
let r = if let Some(a) = &agent {
let r = crate::mcp::delegate::run(&helper, chat.as_deref(), (&a.name, a.parent.as_deref().unwrap_or_default()), &c.args);
swarm.lock().unwrap().release_client(a);
r
} else if c.name == crate::mcp::refs::TOOL {
crate::mcp::refs::fetch(dir.as_deref(), chat.as_deref(), &c.args)
} else {
@@ -1566,14 +1619,15 @@ impl App {
continue;
}
let mut runs = std::mem::take(&mut self.runs);
let r = runs.call(self, &c.client, &c.name, &c.args, crate::project::format::now_ms());
let swarm = self.swarm.clone();
let r = swarm.lock().unwrap().call(&mut runs, self, &c.client, &c.name, &c.args, crate::project::format::now_ms());
let touched = runs.take_touched();
if r.is_ok() {
let who = runs.label(&c.client);
self.st.mark_agent(&self.ed, who, &c.name, &c.args, &touched);
}
self.runs = runs;
self.st.log_agent(&c.name, r.as_ref().err().cloned());
self.st.log_agent(&c.name, &c.args, r.as_ref().err().cloned());
if let Err(e) = &r {
log::info!("mcp {}: {e}", c.name);
}
@@ -1743,3 +1797,39 @@ mod tests {
));
}
}
/// An undecorated window has no resize border (Linux): the pointer within a few pixels of an
/// edge shows a resize cursor and a press resizes. True when the event was consumed.
#[cfg(all(unix, not(target_os = "macos")))]
fn edge_resize(window: &Window, event: &WindowEvent, edge: &mut Option<winit::window::ResizeDirection>) -> bool {
use winit::window::{CursorIcon, ResizeDirection as D};
const BORDER: f64 = 6.0;
match event {
WindowEvent::CursorMoved { position, .. } => {
let size = window.inner_size();
let b = BORDER * window.scale_factor();
let (l, r) = (position.x < b, position.x > f64::from(size.width) - b);
let (t, bo) = (position.y < b, position.y > f64::from(size.height) - b);
let next = match (l, r, t, bo) {
(true, _, true, _) => Some(D::NorthWest),
(_, true, true, _) => Some(D::NorthEast),
(true, _, _, true) => Some(D::SouthWest),
(_, true, _, true) => Some(D::SouthEast),
(true, ..) => Some(D::West),
(_, true, ..) => Some(D::East),
(_, _, true, _) => Some(D::North),
(.., true) => Some(D::South),
_ => None,
};
if next != *edge {
window.set_cursor(next.map_or(CursorIcon::Default, CursorIcon::from));
*edge = next;
}
false
}
WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => {
edge.is_some_and(|d| window.drag_resize_window(d).is_ok())
}
_ => false,
}
}
+14 -7
View File
@@ -1,7 +1,8 @@
//! Image assets, registered process-wide by content hash.
//!
//! Image fills reference an asset id (a hash of the encoded bytes). The registry keeps the
//! decoded pixels for rendering and the original bytes for saving and export. Projects store
//! original bytes and the size; pixels are decoded only when an image is uploaded to the GPU or
//! exported, since decoded images are several times their file size and are never dropped. Projects store
//! their assets as `assets/<id>.<ext>`; copy/paste between projects carries only the id, and
//! the destination project writes the file on its next save.
@@ -13,7 +14,6 @@ pub struct ImageAsset {
pub id: String,
pub width: u32,
pub height: u32,
pub rgba: image::RgbaImage,
/// The original encoded file.
pub bytes: Vec<u8>,
/// "png", "jpg", ...
@@ -21,6 +21,11 @@ pub struct ImageAsset {
}
impl ImageAsset {
/// The decoded pixels. Decodes every call: the callers keep the result as long as they need.
pub fn rgba(&self) -> Option<image::RgbaImage> {
image::load_from_memory(&self.bytes).ok().map(|i| i.to_rgba8())
}
pub fn mime(&self) -> &'static str {
match self.ext {
"jpg" => "image/jpeg",
@@ -61,14 +66,15 @@ pub fn register(bytes: &[u8]) -> Result<String, String> {
if registry().lock().unwrap().contains_key(&id) {
return Ok(id);
}
let img = image::load_from_memory(bytes)
let (width, height) = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|e| format!("unsupported image: {e}"))?
.to_rgba8();
.into_dimensions()
.map_err(|e| format!("unsupported image: {e}"))?;
let a = ImageAsset {
id: id.clone(),
width: img.width(),
height: img.height(),
rgba: img,
width,
height,
bytes: bytes.to_vec(),
ext: ext_of(bytes),
};
@@ -208,5 +214,6 @@ mod tests {
let asset = get(&a).unwrap();
assert_eq!((asset.width, asset.height), (3, 2));
assert!(register(b"not an image").is_err());
assert_eq!(asset.rgba().map(|p| p.get_pixel(2, 1).0), Some([255, 0, 0, 255]), "decoded on demand");
}
}
+23 -1
View File
@@ -306,8 +306,26 @@ fn runtime() -> Result<tokio::runtime::Runtime, String> {
.map_err(|e| e.to_string())
}
/// Who this CLI is to other agents (`--as`, `--parent`, else `$PAPERCRAFT_AGENT`,
/// `$PAPERCRAFT_PARENT`): a named agent keeps one session across its calls and claims.
static AGENT: std::sync::OnceLock<(Option<String>, Option<String>)> = std::sync::OnceLock::new();
/// Percent-encoding for a query value.
fn encode(s: &str) -> String {
s.bytes()
.map(|b| if b.is_ascii_alphanumeric() || b"._-".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") })
.collect()
}
fn connect(rt: &tokio::runtime::Runtime) -> Result<Client, String> {
let url = mcp::url(mcp::port());
let mut url = mcp::url(mcp::port());
let (name, parent) = AGENT.get().cloned().unwrap_or_default();
if let Some(name) = name {
url = format!("{url}?agent={}", encode(&name));
if let Some(p) = parent {
url = format!("{url}&parent={}", encode(&p));
}
}
rt.block_on(async { ().serve(StreamableHttpClientTransport::from_uri(url.clone())).await })
.map_err(|e| format!("cannot reach papercraft at {url}: {e}. Is the app running?"))
}
@@ -742,6 +760,10 @@ fn main() -> ExitCode {
let mut args: Vec<String> = std::env::args().skip(1).collect();
let out = take_flag(&mut args, "--out", Some("-o"));
let project = take_flag(&mut args, "--project", None);
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
let agent = take_flag(&mut args, "--as", None).or_else(|| env("PAPERCRAFT_AGENT"));
let parent = take_flag(&mut args, "--parent", None).or_else(|| env("PAPERCRAFT_PARENT"));
AGENT.get_or_init(|| (agent, parent));
let offline = args.iter().any(|a| a == "--offline");
ONLINE_ONLY.store(args.iter().any(|a| a == "--online"), Ordering::Relaxed);
args.retain(|a| a != "--offline" && a != "--online");
+250 -28
View File
@@ -106,13 +106,14 @@ impl Turn for AcpTurn {
/// Starts `program args…` and runs one prompt. Events arrive on `tx`; the last is `TurnEnd` or
/// `Error`.
pub fn start(cfg: &TurnConfig, program: &Path, args: &[String], prompt: &str, tx: Sender<Event>) -> Result<AcpTurn, String> {
spawn(cfg, program, args, prompt, tx, None)
/// `env` is added to the agent's environment (a lean turn's `agents::pure_env`).
pub fn start(cfg: &TurnConfig, program: &Path, args: &[String], env: &[(String, String)], prompt: &str, tx: Sender<Event>) -> Result<AcpTurn, String> {
spawn(cfg, program, args, env, prompt, tx, None)
}
fn spawn(cfg: &TurnConfig, program: &Path, args: &[String], prompt: &str, tx: Sender<Event>, bridge: Option<PathBuf>) -> Result<AcpTurn, String> {
fn spawn(cfg: &TurnConfig, program: &Path, args: &[String], env: &[(String, String)], prompt: &str, tx: Sender<Event>, bridge: Option<PathBuf>) -> Result<AcpTurn, String> {
let mut cmd = Command::new(program);
cmd.args(args).current_dir(&cfg.project_dir).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
cmd.args(args).envs(env.iter().cloned()).current_dir(&cfg.project_dir).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
for k in CREDENTIAL_ENV {
cmd.env_remove(k);
}
@@ -213,6 +214,14 @@ fn spawn(cfg: &TurnConfig, program: &Path, args: &[String], prompt: &str, tx: Se
Ok(turn)
}
/// An error that says the model, not the request, is the problem: rate limited, out of quota,
/// overloaded or gone. ponytail: agents do not document these, so it matches their wording.
fn is_retryable(e: &str) -> bool {
const SIGNS: [&str; 10] = ["429", "rate limit", "rate_limit", "too many requests", "quota", "overloaded", "unavailable", "model not found", "no longer available", "insufficient"];
let e = e.to_lowercase();
SIGNS.iter().any(|s| e.contains(s))
}
fn tail(s: &str) -> &str {
const KEEP: usize = 600;
let mut from = s.len().saturating_sub(KEEP);
@@ -253,6 +262,20 @@ impl Client {
let _ = self.tx.send(e);
}
/// Switches the session to the chat's model when the agent offers it. A refusal keeps the
/// agent's model, which is what the chat then shows.
fn pick_model(&mut self, sid: &str, m: &mut Models, want: Option<&str>) -> Option<Value> {
let want = want.filter(|w| *w != m.current && m.options.iter().any(|(id, _)| id == w))?;
let r = match &m.config_id {
Some(config) => self.call("session/set_config_option", json!({"sessionId": sid, "configId": config, "value": want}), Some(HANDSHAKE_TIMEOUT)),
None => self.call("session/set_model", json!({"sessionId": sid, "modelId": want}), Some(HANDSHAKE_TIMEOUT)),
};
match r {
Ok(r) => { want.clone_into(&mut m.current); Some(r) },
Err(e) => { log::warn!("acp: could not switch the model to {want}: {e}"); None },
}
}
fn run(&mut self, cfg: &TurnConfig, prompt: &str, bridge: Option<PathBuf>, slot: &Mutex<Option<String>>) -> Result<String, String> {
let init = self.call(
"initialize",
@@ -268,7 +291,7 @@ impl Client {
let image = caps["promptCapabilities"]["image"] == true;
let bridge = if http { None } else { bridge.or_else(find_bridge) };
let session_params = |extra: Value| -> Result<Value, String> {
let mut p = json!({"cwd": cfg.project_dir, "mcpServers": mcp_servers(&cfg.mcp_url, http, bridge.as_deref())?});
let mut p = json!({"cwd": cfg.project_dir, "mcpServers": mcp_servers(&session_url(cfg), http, bridge.as_deref())?});
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
@@ -281,21 +304,46 @@ impl Client {
let r = self.call("session/load", session_params(json!({"sessionId": id}))?, Some(HANDSHAKE_TIMEOUT));
self.replay = false;
match r {
Ok(_) => loaded = Some(id.clone()),
Ok(r) => loaded = Some((id.clone(), r)),
Err(e) => log::warn!("acp: session/load failed ({e}); starting a new session"),
}
}
let first = loaded.is_none();
let sid = match loaded {
Some(id) => id,
let (sid, initial) = match loaded {
Some((id, r)) => (id, r),
None => {
let r = self.call("session/new", session_params(json!({}))?, Some(HANDSHAKE_TIMEOUT))?;
r["sessionId"].as_str().ok_or("session/new returned no sessionId")?.to_string()
(r["sessionId"].as_str().ok_or("session/new returned no sessionId")?.to_string(), r)
}
};
let mut models = session_models(&initial);
self.sid = Some(sid.clone());
*slot.lock().unwrap() = Some(sid.clone());
self.emit(Event::Session(sid.clone()));
if let Some(m) = models.as_mut() {
let updated = self.pick_model(&sid, m, cfg.model.as_deref());
self.emit(Event::Models { current: m.current.clone(), options: m.options.clone() });
if cfg.effort.is_some() && cfg.model.as_deref().is_some_and(|want| want != m.current) {
return Err("Could not select the model for the requested effort".into());
}
let configs = updated.as_ref().unwrap_or(&initial);
if let Some(option) = effort_option(configs) {
self.emit(Event::ModelEfforts { model: m.current.clone(), options: option.options.clone() });
if let Some(want) = cfg.effort.as_deref() {
if !option.options.iter().any(|(id, _)| id == want) {
return Err(format!("The selected model does not offer effort {want}"));
}
if want != option.current {
self.call("session/set_config_option", json!({"sessionId": sid, "configId": option.id, "value": want}), Some(HANDSHAKE_TIMEOUT))
.map_err(|e| format!("Could not set effort to {want}: {e}"))?;
}
}
} else if cfg.effort.is_some() {
return Err("This agent did not offer an effort setting for the selected model".into());
}
} else if cfg.effort.is_some() {
return Err("This agent did not offer an effort setting for the selected model".into());
}
// ACP has no system prompt: the PaperCraft text leads the first prompt of a session.
let mut blocks = vec![];
@@ -306,7 +354,24 @@ impl Client {
if image {
blocks.extend(cfg.images.iter().map(|i| json!({"type": "image", "mimeType": i.mime, "data": STANDARD.encode(&i.data)})));
}
let r = self.call("session/prompt", json!({"sessionId": sid, "prompt": blocks}), None)?;
let mut fallbacks = cfg.fallbacks.iter();
let r = loop {
let e = match self.call("session/prompt", json!({"sessionId": sid, "prompt": blocks}), None) {
Ok(r) => break r,
Err(e) => e,
};
// A failure after a tool ran is not retried: the design may already have changed.
let retry = is_retryable(&e) && self.tools.is_empty() && !self.stopped.load(Ordering::SeqCst);
let Some(m) = models.as_mut().filter(|_| retry) else { return Err(e) };
let Some(next) = fallbacks.find(|f| m.options.iter().any(|(id, _)| id == *f)) else { return Err(e) };
let from = m.current.clone();
self.pick_model(&sid, m, Some(next));
if m.current != *next {
return Err(e);
}
self.emit(Event::ModelSwitch { from, to: next.clone(), reason: e });
self.emit(Event::Models { current: m.current.clone(), options: m.options.clone() });
};
self.usage = usage_of(&r["usage"]).map(|mut u| {
u.cost_usd = self.cost;
u
@@ -530,6 +595,45 @@ fn content_text(v: &Value) -> String {
.unwrap_or_default()
}
/// The models of a session: its current one and the ones it offers.
struct Models {
current: String,
options: Vec<(String, String)>,
/// The `model` config option's id; None when the agent only has the older `models` field.
config_id: Option<String>,
}
struct EffortOption {
id: String,
current: String,
options: Vec<(String, String)>,
}
fn effort_option(r: &Value) -> Option<EffortOption> {
let o = r["configOptions"].as_array()?.iter().find(|o| o["category"] == "thought_level" || ["effort", "reasoning_effort"].contains(&o["id"].as_str().unwrap_or_default()))?;
let options = o["options"].as_array()?.iter().filter_map(|v| {
let id = v["value"].as_str()?;
Some((id.to_owned(), v["name"].as_str().unwrap_or(id).to_owned()))
}).collect();
Some(EffortOption { id: o["id"].as_str()?.to_owned(), current: o["currentValue"].as_str()?.to_owned(), options })
}
/// The models in a `session/new` or `session/load` result: the `model` config option, else the
/// older (unstable) `models` field.
fn session_models(r: &Value) -> Option<Models> {
let pairs = |list: &Value, id: &str| -> Vec<(String, String)> {
let list = list.as_array().into_iter().flatten();
list.filter_map(|o| Some((o[id].as_str()?.to_owned(), o["name"].as_str().or(o[id].as_str())?.to_owned()))).collect()
};
let opts = r["configOptions"].as_array().into_iter().flatten();
if let Some(o) = opts.into_iter().find(|o| o["category"] == "model" || o["id"] == "model") {
let current = o["currentValue"].as_str()?.to_owned();
return Some(Models { current, options: pairs(&o["options"], "value"), config_id: o["id"].as_str().map(String::from) });
}
let m = &r["models"];
Some(Models { current: m["currentModelId"].as_str()?.to_owned(), options: pairs(&m["availableModels"], "modelId"), config_id: None })
}
/// `{inputTokens, outputTokens, cachedReadTokens, cachedWriteTokens}` of a prompt response.
fn usage_of(u: &Value) -> Option<Usage> {
if !u.is_object() {
@@ -539,6 +643,16 @@ fn usage_of(u: &Value) -> Option<Usage> {
Some(Usage { input: get("inputTokens"), output: get("outputTokens"), cache_read: get("cachedReadTokens"), cache_write: get("cachedWriteTokens"), cost_usd: None })
}
/// The MCP URL for the session. ACP agents load every tool schema up front, so a lean turn asks
/// for the core list (`mcp::core_tools`); the rest stay reachable through `call_tool`.
pub fn session_url(cfg: &TurnConfig) -> String {
if !cfg.lean {
return cfg.mcp_url.clone();
}
let join = if cfg.mcp_url.contains('?') { '&' } else { '?' };
format!("{}{join}tools=core", cfg.mcp_url)
}
/// PaperCraft's MCP server as an ACP `mcpServers` list: HTTP when the agent supports it, else
/// the stdio `papercraft-mcp` bridge aimed at the same port.
fn mcp_servers(url: &str, http: bool, bridge: Option<&Path>) -> Result<Value, String> {
@@ -563,6 +677,10 @@ mod tests {
const AGENT: &str = include_str!("../../tests/fixtures/chat/acp_fake_agent.sh");
const HTTP: &str = include_str!("../../tests/fixtures/chat/acp_http.jsonl");
const MODEL: &str = include_str!("../../tests/fixtures/chat/acp_model.jsonl");
const EFFORT: &str = include_str!("../../tests/fixtures/chat/acp_effort.jsonl");
const ROTATE: &str = include_str!("../../tests/fixtures/chat/acp_rotate.jsonl");
const ROTATE_LATE: &str = include_str!("../../tests/fixtures/chat/acp_rotate_late.jsonl");
const STDIO: &str = include_str!("../../tests/fixtures/chat/acp_stdio.jsonl");
const PERMISSION: &str = include_str!("../../tests/fixtures/chat/acp_permission.jsonl");
const CANCEL: &str = include_str!("../../tests/fixtures/chat/acp_cancel.jsonl");
@@ -584,7 +702,7 @@ mod tests {
std::fs::write(&fx, fixture).unwrap();
let args: Vec<String> = [&script, &fx, &log].iter().map(|p| p.display().to_string()).collect();
let (tx, rx) = channel();
let mut turn = spawn(&cfg, Path::new("/bin/sh"), &args, "hello", tx, bridge).unwrap();
let mut turn = spawn(&cfg, Path::new("/bin/sh"), &args, &[], "hello", tx, bridge).unwrap();
let mut events = vec![];
loop {
let e = rx.recv_timeout(Duration::from_secs(15)).expect("turn timed out");
@@ -630,19 +748,122 @@ mod tests {
assert_eq!(sent.iter().find(|v| v["id"] == 50).unwrap()["error"]["code"], METHOD_NOT_FOUND);
assert_eq!(ev[0], Event::Session("sess-1".into()));
assert_eq!(ev[1], Event::Thinking("hmm".into()));
assert_eq!(ev[2], Event::Text("Hel".into()));
assert_eq!(ev[3], Event::Text("lo".into()));
assert_eq!(ev[4], Event::ToolStart { id: "t1".into(), name: "get_basic_info".into(), args: json!({}) });
assert_eq!(ev[5], Event::ToolEnd { id: "t1".into(), result: Some(json!("{\"ok\":true}")), error: None });
assert_eq!(ev[6], Event::ToolStart { id: "t2".into(), name: "ls".into(), args: json!({"path": "."}) });
assert_eq!(ev[7], Event::ToolEnd { id: "t2".into(), result: None, error: Some("denied".into()) });
assert_eq!(ev[8], Event::ToolStart { id: "acp-plan-1".into(), name: "TodoWrite".into(), args: json!({"todos": [{"content": "A", "status": "completed"}, {"content": "B", "status": "pending"}]}) });
assert_eq!(ev[9], Event::ToolEnd { id: "acp-plan-1".into(), result: Some(json!("ok")), error: None });
assert_eq!(ev[10], Event::Context(5000));
let Event::TurnEnd { usage: Some(u), session: Some(s), stop_reason: Some(r) } = &ev[11] else { panic!("{:?}", ev[11]) };
assert_eq!(ev[1], Event::Models { current: "opencode/big-pickle".into(), options: vec![] }, "the model option, not the mode");
assert_eq!(ev[2], Event::Thinking("hmm".into()));
assert_eq!(ev[3], Event::Text("Hel".into()));
assert_eq!(ev[4], Event::Text("lo".into()));
assert_eq!(ev[5], Event::ToolStart { id: "t1".into(), name: "get_basic_info".into(), args: json!({}) });
assert_eq!(ev[6], Event::ToolEnd { id: "t1".into(), result: Some(json!("{\"ok\":true}")), error: None });
assert_eq!(ev[7], Event::ToolStart { id: "t2".into(), name: "ls".into(), args: json!({"path": "."}) });
assert_eq!(ev[8], Event::ToolEnd { id: "t2".into(), result: None, error: Some("denied".into()) });
assert_eq!(ev[9], Event::ToolStart { id: "acp-plan-1".into(), name: "TodoWrite".into(), args: json!({"todos": [{"content": "A", "status": "completed"}, {"content": "B", "status": "pending"}]}) });
assert_eq!(ev[10], Event::ToolEnd { id: "acp-plan-1".into(), result: Some(json!("ok")), error: None });
assert_eq!(ev[11], Event::Context(5000));
let Event::TurnEnd { usage: Some(u), session: Some(s), stop_reason: Some(r) } = &ev[12] else { panic!("{:?}", ev[12]) };
assert_eq!((u.input, u.output, u.cost_usd, s.as_str(), r.as_str()), (7, 3, Some(0.5), "sess-1", "end_turn"));
assert_eq!(ev.len(), 12);
assert_eq!(ev.len(), 13);
}
#[test]
fn switches_to_the_chats_model_when_offered() {
let mut c = cfg();
c.model = Some("paid/b".into());
let (ev, sent) = run(MODEL, c, None, |_, _| {});
assert_eq!(method(&sent, "session/set_config_option")["params"], json!({"sessionId": "sess-1", "configId": "model", "value": "paid/b"}));
let options = vec![("free/a".into(), "A".into()), ("paid/b".into(), "B".into())];
assert_eq!(ev[1], Event::Models { current: "paid/b".into(), options });
}
#[test]
fn selects_effort_after_switching_model() {
let mut c = cfg();
c.model = Some("paid/b".into());
c.effort = Some("high".into());
let (ev, sent) = run(EFFORT, c, None, |_, _| {});
let settings: Vec<_> = sent.iter().filter(|v| v["method"] == "session/set_config_option").collect();
assert_eq!(settings[0]["params"]["value"], "paid/b");
assert_eq!(settings[1]["params"], json!({"sessionId": "sess-1", "configId": "effort", "value": "high"}));
assert!(ev.iter().any(|e| matches!(e, Event::ModelEfforts { model, options } if model == "paid/b" && options.iter().any(|(id, _)| id == "high"))));
assert!(matches!(ev.last(), Some(Event::TurnEnd { .. })));
}
#[test]
fn model_switch_without_refreshed_options_never_uses_old_efforts() {
let fixture = r#"> "method":"initialize"
< {"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{}}}
> "method":"session/new"
< {"jsonrpc":"2.0","id":1,"result":{"sessionId":"sess-1","configOptions":[{"id":"model","category":"model","currentValue":"free/a","options":[{"value":"free/a"},{"value":"paid/b"}]},{"id":"effort","category":"thought_level","currentValue":"low","options":[{"value":"low"},{"value":"high"}]}]}}
> "method":"session/set_config_option"
< {"jsonrpc":"2.0","id":2,"result":{}}
"#;
let mut c = cfg();
c.model = Some("paid/b".into());
c.effort = Some("high".into());
let (ev, sent) = run(fixture, c, None, |_, _| {});
assert!(matches!(ev.last(), Some(Event::Error(e)) if e.contains("effort setting")), "{ev:?}");
assert_eq!(sent.iter().filter(|v| v["method"] == "session/set_config_option").count(), 1);
assert!(sent.iter().all(|v| v["method"] != "session/prompt"));
let rejected = fixture.replace(r#"{"jsonrpc":"2.0","id":2,"result":{}}"#, r#"{"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"invalid model"}}"#);
let mut c = cfg();
c.model = Some("paid/b".into());
c.effort = Some("high".into());
let (ev, sent) = run(&rejected, c, None, |_, _| {});
assert!(matches!(ev.last(), Some(Event::Error(e)) if e.contains("select the model")), "{ev:?}");
assert_eq!(sent.iter().filter(|v| v["method"] == "session/set_config_option").count(), 1);
}
#[test]
fn effort_without_session_model_is_not_silently_ignored() {
let fixture = r#"> "method":"initialize"
< {"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{}}}
> "method":"session/new"
< {"jsonrpc":"2.0","id":1,"result":{"sessionId":"sess-1"}}
"#;
let mut c = cfg();
c.effort = Some("high".into());
let (ev, sent) = run(fixture, c, None, |_, _| {});
assert!(matches!(ev.last(), Some(Event::Error(e)) if e.contains("effort setting")), "{ev:?}");
assert!(sent.iter().all(|v| v["method"] != "session/prompt"));
}
#[test]
fn a_rate_limited_model_hands_the_turn_to_the_next_free_one() {
let mut c = cfg();
c.fallbacks = vec!["gone/x".into(), "paid/b".into()];
let (ev, sent) = run(ROTATE, c, None, |_, _| {});
assert_eq!(sent.iter().filter(|v| v["method"] == "session/prompt").count(), 2);
assert_eq!(method(&sent, "session/set_config_option")["params"]["value"], "paid/b");
assert!(ev.iter().any(|e| matches!(e, Event::ModelSwitch { from, to, reason } if from == "free/a" && to == "paid/b" && reason.contains("Rate limit"))), "{ev:?}");
assert!(matches!(ev.last(), Some(Event::TurnEnd { .. })), "{ev:?}");
}
#[test]
fn a_failure_after_a_tool_ran_is_not_retried() {
let mut c = cfg();
c.fallbacks = vec!["paid/b".into()];
let (ev, sent) = run(ROTATE_LATE, c, None, |_, _| {});
assert_eq!(sent.iter().filter(|v| v["method"] == "session/prompt").count(), 1);
assert!(matches!(ev.last(), Some(Event::Error(e)) if e.contains("Rate limit")), "{ev:?}");
assert!(!is_retryable("invalid params") && is_retryable("HTTP 429 Too Many Requests"));
}
#[test]
fn a_model_the_agent_does_not_offer_is_not_sent() {
let mut c = cfg();
c.model = Some("gone/x".into());
let (ev, sent) = run(HTTP, c, None, |_, _| {});
assert!(sent.iter().all(|v| v["method"] != "session/set_config_option" && v["method"] != "session/set_model"));
assert!(matches!(ev.last(), Some(Event::TurnEnd { .. })), "{ev:?}");
}
#[test]
fn a_lean_turn_asks_for_the_core_tools() {
let mut c = cfg();
assert_eq!(session_url(&c), c.mcp_url);
c.lean = true;
c.mcp_url = "http://127.0.0.1:1/mcp?chat=c1".into();
assert_eq!(session_url(&c), "http://127.0.0.1:1/mcp?chat=c1&tools=core");
}
#[test]
@@ -693,7 +914,7 @@ mod tests {
fn stop_kills_an_agent_that_ignores_cancel() {
let (tx, rx) = channel();
let args = ["-c".to_string(), "trap '' INT TERM; while :; do sleep 1; done".to_string()];
let mut turn = spawn(&cfg(), Path::new("/bin/sh"), &args, "x", tx, None).unwrap();
let mut turn = spawn(&cfg(), Path::new("/bin/sh"), &args, &[], "x", tx, None).unwrap();
thread::sleep(Duration::from_millis(100));
let t = Instant::now();
turn.stop();
@@ -717,8 +938,9 @@ mod tests {
assert!(sent.iter().all(|v| v["method"] != "session/new"));
assert_eq!(method(&sent, "session/prompt")["params"]["prompt"], json!([{"type": "text", "text": "hello"}]));
assert_eq!(ev[0], Event::Session("old".into()));
assert_eq!(ev[1], Event::Text("fresh".into()), "replayed history must not surface: {ev:?}");
assert!(matches!(&ev[2], Event::TurnEnd { session: Some(s), .. } if s == "old"));
assert_eq!(ev[1], Event::Models { current: "gemini-3-pro".into(), options: vec![] });
assert_eq!(ev[2], Event::Text("fresh".into()), "replayed history must not surface: {ev:?}");
assert!(matches!(&ev[3], Event::TurnEnd { session: Some(s), .. } if s == "old"));
}
#[test]
@@ -739,7 +961,7 @@ mod tests {
#[test]
fn missing_program_is_an_error() {
let (tx, _rx) = channel();
assert!(spawn(&cfg(), Path::new("/nonexistent/agent"), &[], "x", tx, None).is_err());
assert!(spawn(&cfg(), Path::new("/nonexistent/agent"), &[], &[], "x", tx, None).is_err());
}
#[test]
@@ -782,7 +1004,7 @@ mod tests {
let (tx, rx) = channel();
// never reads stdin; a big write fills the pipe and blocks
let args = ["-c".to_string(), "trap '' INT TERM; while :; do sleep 1; done".to_string()];
let mut turn = spawn(&cfg(), Path::new("/bin/sh"), &args, "x", tx, None).unwrap();
let mut turn = spawn(&cfg(), Path::new("/bin/sh"), &args, &[], "x", tx, None).unwrap();
*turn.session.lock().unwrap() = Some("s".repeat(1 << 20));
thread::sleep(Duration::from_millis(100));
turn.stop();
+113 -10
View File
@@ -2,13 +2,14 @@
//! on the resolved PATH and the command that launches one over ACP.
//!
//! Launch args were checked against the agents installed on the dev machine (2026-10-21):
//! * Gemini CLI 0.44.1: `gemini --acp` (`--help` lists `--acp`; `--experimental-acp` is deprecated).
//! * OpenCode 1.18.30: `opencode acp` ("start ACP (Agent Client Protocol) server").
//! * Cursor Agent 2026.03.20: the binary is `cursor-agent` (its help says `agent`); `cursor-agent acp`
//! ("Start the Cursor Agent as an ACP server").
//! * Pi 0.80.3 has no ACP mode of its own; the `pi-acp` adapter is run with `npx`.
//! * Goose: `/opt/homebrew/bin/goose` here is pressly/goose, the SQL migration tool. Block's agent
//! has an `acp` subcommand; the migration tool's `--help` never says `acp`, so that is the identity.
//!
//! Gemini CLI is left out: Google retired it for the Antigravity CLI (June 2026).
//! The rest keep their documented command and fail with the agent's own error.
#[cfg(not(target_arch = "wasm32"))]
@@ -52,7 +53,6 @@ const fn npx(id: &'static str, name: &'static str, package: &'static str, launch
pub const AGENTS: &[AgentDef] = &[
AgentDef { id: "claude-code", name: "Claude Code", binary: "claude", launch: &[], kind: AgentKind::Direct, docs_url: super::CLAUDE_DOCS, identity: Some("claude code") },
AgentDef { id: "codex", name: "Codex", binary: "codex", launch: &[], kind: AgentKind::Direct, docs_url: super::CODEX_DOCS, identity: Some("codex") },
native("gemini", "Gemini CLI", "gemini", &["--acp"], "https://github.com/google-gemini/gemini-cli", Some("gemini cli")),
native("cursor", "Cursor", "cursor-agent", &["acp"], "https://cursor.com/cli", Some("cursor agent")),
native("opencode", "OpenCode", "opencode", &["acp"], "https://opencode.ai/docs", Some("opencode")),
native("goose", "Goose", "goose", &["acp"], "https://block.github.io/goose", Some("acp")),
@@ -264,6 +264,75 @@ fn probe(bin: &std::path::Path, arg: &str, path: &std::ffi::OsStr, timeout: std:
done.then_some(out)
}
/// Environment agent `id` always runs with. opencode waits 60 s for an MCP reply (the SDK's
/// default), less than PaperCraft lets a call run (`CALL_TIMEOUT`): a slow `generate_image` would
/// finish with nobody left to read it.
#[cfg(not(target_arch = "wasm32"))]
pub fn base_env(id: &str) -> Vec<(String, String)> {
const MARGIN_MS: u128 = 30_000;
match id {
"opencode" => {
let ms = crate::mcp::server::CALL_TIMEOUT.as_millis() + MARGIN_MS;
vec![("OPENCODE_CONFIG_CONTENT".into(), serde_json::json!({"experimental": {"mcp_timeout": ms}}).to_string())]
}
_ => vec![],
}
}
/// Environment that starts agent `id` without the user's own setup (config, plugins, rules,
/// skills), so a lean turn carries only PaperCraft's instructions. `home` is an empty folder
/// PaperCraft owns. Empty for agents whose sign-in would not survive it, and where `real_home` is
/// unknown (Windows).
pub fn pure_env(id: &str, home: &std::path::Path, real_home: Option<&std::path::Path>) -> Vec<(String, String)> {
let Some(real) = real_home else { return vec![] };
let xdg = |k: &str, under: &str| (k.to_owned(), std::env::var(k).unwrap_or_else(|_| real.join(under).display().to_string()));
match id {
// Skills are found under HOME (~/.agents, ~/.claude) and config under XDG_CONFIG_HOME;
// sign-ins and sessions (so `session/load` still works) stay in the real data folder.
"opencode" => vec![
("HOME".into(), home.display().to_string()),
("XDG_CONFIG_HOME".into(), home.join("config").display().to_string()),
xdg("XDG_DATA_HOME", ".local/share"),
xdg("XDG_CACHE_HOME", ".cache"),
xdg("XDG_STATE_HOME", ".local/state"),
("OPENCODE_PURE".into(), "1".into()),
("OPENCODE_DISABLE_PROJECT_CONFIG".into(), "1".into()),
],
// Pi finds skills under HOME (~/.agents/skills) and its config, packages and sessions in
// PI_CODING_AGENT_DIR; npm (npx pi-acp, Pi's package installs) keeps the user's cache.
"pi" => vec![
("HOME".into(), home.display().to_string()),
("PI_CODING_AGENT_DIR".into(), home.join(PI_AGENT_DIR).display().to_string()),
("npm_config_cache".into(), std::env::var("npm_config_cache").unwrap_or_else(|_| real.join(".npm").display().to_string())),
],
_ => vec![],
}
}
/// Pi's folder inside its lean home (`PI_CODING_AGENT_DIR`).
pub const PI_AGENT_DIR: &str = "agent";
/// Writes the lean Pi folder under `home`: only `pi-mcp-adapter` as a package, connected to
/// PaperCraft at `mcp_url` with its tools listed one by one (not behind the adapter's `mcp`
/// proxy) and a call timeout above PaperCraft's own.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_pi_home(home: &std::path::Path, mcp_url: &str) -> Result<(), String> {
const MARGIN_MS: u128 = 30_000;
let dir = home.join(PI_AGENT_DIR);
crate::vfs::create_dir_all(&dir).map_err(|e| format!("Could not make {}: {e}", dir.display()))?;
let settings = serde_json::json!({"packages": ["npm:pi-mcp-adapter"], "quietStartup": true});
let mcp = serde_json::json!({
"mcpServers": {"papercraft": {"url": mcp_url, "directTools": true}},
"settings": {"requestTimeoutMs": crate::mcp::server::CALL_TIMEOUT.as_millis() + MARGIN_MS},
});
for (name, v) in [("settings.json", settings), ("mcp.json", mcp)] {
let path = dir.join(name);
let text = serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?;
crate::io::atomic::write(&path, text.as_bytes()).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
}
Ok(())
}
/// What the ACP backend runs for this agent: program and args. None for an unknown id, a
/// `Direct` agent, an `npx` agent that is not enabled, or a program that is not on PATH.
#[cfg(not(target_arch = "wasm32"))]
@@ -331,7 +400,7 @@ mod tests {
#[test]
fn detects_ready_wrong_missing_and_npx_states() {
let (dir, path) = fake_dir(&[
("gemini", r#"if [ "$1" = --version ]; then echo 0.1.0; else echo "Gemini CLI help"; fi"#),
("cursor-agent", r#"if [ "$1" = --version ]; then echo 0.1.0; else echo "Cursor Agent help"; fi"#),
// The migration tool: version string and help with no "acp".
("goose", r#"if [ "$1" = --version ]; then echo "goose version: v3.27.1"; else echo "Usage: goose DRIVER DBSTRING"; fi"#),
("opencode", r#"echo "opencode 1.0""#),
@@ -341,10 +410,10 @@ mod tests {
let all = detect_all_in(&prefs, &path);
assert_eq!(all.len(), AGENTS.len());
let shown = |n: &str| dir.join(n).display().to_string();
assert_eq!(state(&all, "gemini"), AgentState::Ready { path: shown("gemini"), version: "0.1.0".into() });
assert_eq!(state(&all, "cursor"), AgentState::Ready { path: shown("cursor-agent"), version: "0.1.0".into() });
assert_eq!(state(&all, "opencode"), AgentState::Ready { path: shown("opencode"), version: "opencode 1.0".into() });
assert_eq!(state(&all, "goose"), AgentState::WrongProgram { path: shown("goose") });
assert_eq!(state(&all, "cursor"), AgentState::NotFound);
assert_eq!(state(&all, "kimi"), AgentState::NotFound);
assert_eq!(state(&all, "pi"), AgentState::NeedsEnable);
prefs.agents.insert("pi".into(), AgentPrefs { enabled: true, ..Default::default() });
assert_eq!(state(&detect_all_in(&prefs, &path), "pi"), AgentState::Ready { path: shown("npx"), version: String::new() });
@@ -367,22 +436,56 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn opencode_waits_longer_for_a_tool_than_papercraft_lets_it_run() {
let env = base_env("opencode");
let config: serde_json::Value = serde_json::from_str(&env[0].1).unwrap();
let ms = config["experimental"]["mcp_timeout"].as_u64().unwrap();
assert!(u128::from(ms) > crate::mcp::server::CALL_TIMEOUT.as_millis());
assert!(base_env("cursor").is_empty());
}
#[test]
fn pure_opencode_hides_the_users_home_but_keeps_its_sign_ins() {
let env = pure_env("opencode", std::path::Path::new("/pc/home"), Some(std::path::Path::new("/Users/me")));
let get = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
assert_eq!((get("HOME"), get("XDG_CONFIG_HOME"), get("OPENCODE_PURE")), (Some("/pc/home"), Some("/pc/home/config"), Some("1")));
let data = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| "/Users/me/.local/share".into());
assert_eq!(get("XDG_DATA_HOME"), Some(data.as_str()), "auth.json and sessions live there");
assert!(pure_env("cursor", std::path::Path::new("/pc/home"), Some(std::path::Path::new("/Users/me"))).is_empty(), "its sign-in is under HOME");
assert!(pure_env("opencode", std::path::Path::new("/pc/home"), None).is_empty());
let pi = pure_env("pi", std::path::Path::new("/pc/home"), Some(std::path::Path::new("/Users/me")));
assert!(pi.contains(&("HOME".into(), "/pc/home".into())) && pi.contains(&("PI_CODING_AGENT_DIR".into(), "/pc/home/agent".into())), "{pi:?}");
}
#[test]
fn the_lean_pi_folder_has_only_the_mcp_adapter_pointed_at_papercraft() {
let home = std::env::temp_dir().join(format!("pc-pi-home-{}", std::process::id()));
write_pi_home(&home, "http://127.0.0.1:1/mcp?chat=c1&tools=core").unwrap();
let read = |f: &str| serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(home.join("agent").join(f)).unwrap()).unwrap();
assert_eq!(read("settings.json")["packages"], serde_json::json!(["npm:pi-mcp-adapter"]));
let mcp = read("mcp.json");
assert_eq!(mcp["mcpServers"]["papercraft"]["url"], "http://127.0.0.1:1/mcp?chat=c1&tools=core");
assert!(mcp["settings"]["requestTimeoutMs"].as_u64().unwrap() > crate::mcp::server::CALL_TIMEOUT.as_millis() as u64);
std::fs::remove_dir_all(&home).unwrap();
}
#[test]
fn launch_commands_for_native_npx_custom_and_direct() {
let (dir, path) = fake_dir(&[("gemini", ""), ("npx", ""), ("my-agent", "")]);
let (dir, path) = fake_dir(&[("cursor-agent", ""), ("npx", ""), ("my-agent", "")]);
let mut prefs = ChatPrefs::default();
prefs.custom_agents.push(CustomAgent { id: "mine".into(), name: "Mine".into(), command: "my-agent".into(), args: "serve --stdio".into() });
let at = |n: &str| dir.join(n);
assert_eq!(launch_command_in("gemini", &prefs, &path), Some((at("gemini"), vec!["--acp".into()])));
assert_eq!(launch_command_in("cursor", &prefs, &path), Some((at("cursor-agent"), vec!["acp".into()])));
assert_eq!(launch_command_in("mine", &prefs, &path), Some((at("my-agent"), vec!["serve".into(), "--stdio".into()])));
assert_eq!(launch_command_in("pi", &prefs, &path), None);
prefs.agents.insert("pi".into(), AgentPrefs { enabled: true, ..Default::default() });
assert_eq!(launch_command_in("pi", &prefs, &path), Some((at("npx"), vec!["-y".into(), "pi-acp".into()])));
prefs.agents.insert("gemini".into(), AgentPrefs { args: Some("--acp --debug".into()), ..Default::default() });
assert_eq!(launch_command_in("gemini", &prefs, &path).unwrap().1, ["--acp", "--debug"]);
prefs.agents.insert("cursor".into(), AgentPrefs { args: Some("acp --debug".into()), ..Default::default() });
assert_eq!(launch_command_in("cursor", &prefs, &path).unwrap().1, ["acp", "--debug"]);
assert_eq!(launch_command_in("claude-code", &prefs, &path), None);
assert_eq!(launch_command_in("nope", &prefs, &path), None);
assert_eq!(launch_command_in("cursor", &prefs, &path), None);
assert_eq!(launch_command_in("kimi", &prefs, &path), None);
std::fs::remove_dir_all(&dir).unwrap();
}
}
+11 -1
View File
@@ -24,6 +24,13 @@ pub enum Event {
/// Tokens in the context at the backend's latest model call (input and cache), not summed
/// over the turn: the header meter.
Context(u64),
/// The model the agent's session runs on and the ones it offers, as `(id, name)`.
Models { current: String, options: Vec<(String, String)> },
/// The selected ACP model's available reasoning levels.
ModelEfforts { model: String, options: Vec<(String, String)> },
/// The turn moved from model `from` to `to` because `from` failed with `reason` before doing
/// anything ("Free (auto)").
ModelSwitch { from: String, to: String, reason: String },
}
/// Sends a tool call to the UI thread (the app's MCP dispatch), so runs, undo and the agent log
@@ -73,7 +80,10 @@ pub struct TurnConfig {
pub ds_digest: String,
/// Model id; None = the backend's default (API: the endpoint's model).
pub model: Option<String>,
/// `low` | `medium` | `high`; None = the backend's default.
/// ACP: models to move to, in order, when `model` fails before any tool ran (rate limit,
/// quota, gone). Filled for "Free (auto)".
pub fallbacks: Vec<String>,
/// Reasoning level; None = the backend's default.
pub effort: Option<String>,
/// Resume this backend session.
pub session: Option<String>,
+278
View File
@@ -0,0 +1,278 @@
//! Installing an agent PaperCraft can run on free models (OpenCode, Pi): the methods each agent's
//! install docs give per OS (checked 2026-10-29), the ones that apply to this machine, and a
//! runner that streams their output. Nothing runs elevated; methods that need `sudo` or an admin
//! shell are offered as a command to copy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Mac,
Linux,
Windows,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
/// A package manager installs it.
Package,
/// A script downloaded from the agent's site runs: listed last, its URL shown in full.
Script,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Method {
pub label: &'static str,
pub os: &'static [Os],
/// Linux only: the distributions (os-release `ID` or `ID_LIKE`) it is for; empty = any.
pub distros: &'static [&'static str],
/// The program that must be on PATH (`brew`, `npm`, `curl`, ...).
pub needs: &'static str,
/// Lowest Node version (major, minor) an npm method needs.
pub node: Option<(u32, u32)>,
pub command: &'static str,
pub kind: Kind,
/// Asks for a password or an admin shell: shown to copy, never run.
pub elevated: bool,
}
const UNIX: &[Os] = &[Os::Mac, Os::Linux];
const ALL: &[Os] = &[Os::Mac, Os::Linux, Os::Windows];
const WINDOWS: &[Os] = &[Os::Windows];
const fn method(label: &'static str, os: &'static [Os], needs: &'static str, command: &'static str, kind: Kind) -> Method {
Method { label, os, distros: &[], needs, node: None, command, kind, elevated: false }
}
/// OpenCode 1.x: plain `brew install opencode` and Arch's `pacman -S opencode` install OpenCode 2,
/// which PaperCraft's ACP and model code has not been tested on.
const OPENCODE: &[Method] = &[
method("Homebrew", UNIX, "brew", "brew install anomalyco/tap/opencode", Kind::Package),
method("Scoop", WINDOWS, "scoop", "scoop install opencode", Kind::Package),
method("npm", ALL, "npm", "npm install -g opencode-ai", Kind::Package),
Method { distros: &["arch"], elevated: true, ..method("AUR (paru)", &[Os::Linux], "paru", "paru -S opencode-bin", Kind::Package) },
Method { elevated: true, ..method("Chocolatey", WINDOWS, "choco", "choco install opencode", Kind::Package) },
method("Install script", UNIX, "curl", "curl -fsSL https://opencode.ai/install | bash", Kind::Script),
];
const PI: &[Method] = &[
Method { node: Some((22, 19)), ..method("npm", ALL, "npm", "npm install -g --ignore-scripts @earendil-works/pi-coding-agent", Kind::Package) },
method("Homebrew", UNIX, "brew", "brew install pi-coding-agent", Kind::Package),
method("Nix", UNIX, "nix", "nix profile add github:earendil-works/pi/stable", Kind::Package),
method("Install script", UNIX, "curl", "curl -fsSL https://pi.dev/install.sh | sh", Kind::Script),
method("Install script", WINDOWS, "powershell", "powershell -c \"irm https://pi.dev/install.ps1 | iex\"", Kind::Script),
];
/// The agents the wizard installs.
pub const AGENTS: [&str; 2] = ["opencode", "pi"];
/// What the wizard knows about this machine.
pub struct Host {
pub os: Os,
/// os-release `ID` and `ID_LIKE` words (Linux).
pub distro: Vec<String>,
/// Programs found on PATH, from those methods need.
pub has: Vec<&'static str>,
pub node: Option<(u32, u32)>,
}
/// Why a method this OS has is not offered: shown so the user knows what to add.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Missing {
pub label: &'static str,
pub reason: String,
}
/// The methods for `agent` that can run here, best first, and the ones this OS has that cannot.
pub fn methods(agent: &str, host: &Host) -> (Vec<Method>, Vec<Missing>) {
let all = match agent {
"opencode" => OPENCODE,
"pi" => PI,
_ => &[],
};
let mut ok = vec![];
let mut missing = vec![];
for m in all.iter().filter(|m| m.os.contains(&host.os) && (m.distros.is_empty() || m.distros.iter().any(|d| host.distro.iter().any(|h| h == d)))) {
let reason = if !host.has.contains(&m.needs) {
Some(format!("needs {}", m.needs))
} else {
m.node.filter(|min| host.node.is_none_or(|v| v < *min)).map(|(a, b)| format!("needs Node {a}.{b} or newer"))
};
match reason {
Some(reason) => missing.push(Missing { label: m.label, reason }),
None => ok.push(*m),
}
}
ok.sort_by_key(|m| m.kind == Kind::Script);
(ok, missing)
}
/// One line of a running install, or its end.
#[derive(Debug, Clone, PartialEq)]
pub enum Line {
Out(String),
Done(Result<(), String>),
}
#[cfg(not(target_arch = "wasm32"))]
pub use native::{detect, run};
#[cfg(not(target_arch = "wasm32"))]
mod native {
use super::*;
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::sync::mpsc::{Receiver, Sender, channel};
/// `v22.19.0` as (22, 19).
pub(super) fn parse_node(v: &str) -> Option<(u32, u32)> {
let mut parts = v.trim().trim_start_matches('v').split('.');
Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
}
/// os-release `ID` and `ID_LIKE` words.
pub(super) fn parse_os_release(text: &str) -> Vec<String> {
text.lines()
.filter_map(|l| l.strip_prefix("ID=").or_else(|| l.strip_prefix("ID_LIKE=")))
.flat_map(|v| v.trim_matches('"').split_whitespace().map(str::to_owned).collect::<Vec<_>>())
.collect()
}
/// The OS, distribution, the programs methods need and the Node version. Runs `node
/// --version`, so call it off the UI thread.
pub fn detect() -> Host {
let os = if cfg!(windows) {
Os::Windows
} else if cfg!(target_os = "macos") {
Os::Mac
} else {
Os::Linux
};
let distro = std::fs::read_to_string("/etc/os-release").map(|t| parse_os_release(&t)).unwrap_or_default();
let mut needs: Vec<&'static str> = OPENCODE.iter().chain(PI).map(|m| m.needs).collect();
needs.dedup();
let has = needs.into_iter().filter(|n| crate::chat::path::which(n).is_some()).collect();
let node = crate::chat::path::which("node").and_then(|n| {
let mut cmd = Command::new(n);
crate::chat::path::apply(cmd.arg("--version").stdin(Stdio::null()));
cmd.output().ok().and_then(|o| parse_node(&String::from_utf8_lossy(&o.stdout)))
});
Host { os, distro, has, node }
}
/// Runs `m` through the shell (pipes and quoting as the docs write them) with the merged
/// PATH, streaming stdout and stderr lines. An elevated method is refused.
pub fn run(m: &Method) -> Receiver<Line> {
let (tx, rx) = channel();
if m.elevated {
let _ = tx.send(Line::Done(Err(format!("{} needs an admin shell or a password: run it yourself", m.label))));
return rx;
}
let mut cmd = if cfg!(windows) {
let mut c = Command::new("powershell");
c.args(["-NoProfile", "-Command", m.command]);
c
} else {
let mut c = Command::new("sh");
c.args(["-c", m.command]);
c
};
crate::chat::path::apply(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let command = m.command;
std::thread::spawn(move || {
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
let _ = tx.send(Line::Done(Err(format!("Could not start `{command}`: {e}"))));
return;
}
};
let pipe = |r: Box<dyn std::io::Read + Send>, tx: Sender<Line>| {
std::thread::spawn(move || {
for l in BufReader::new(r).lines().map_while(Result::ok) {
if tx.send(Line::Out(l)).is_err() {
break;
}
}
})
};
let readers = [child.stdout.take().map(|o| pipe(Box::new(o), tx.clone())), child.stderr.take().map(|e| pipe(Box::new(e), tx.clone()))];
let status = child.wait();
for r in readers.into_iter().flatten() {
let _ = r.join();
}
let end = match status {
Ok(s) if s.success() => Ok(()),
Ok(s) => Err(format!("`{command}` failed ({s})")),
Err(e) => Err(format!("`{command}`: {e}")),
};
let _ = tx.send(Line::Done(end));
});
rx
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::native::{parse_node, parse_os_release};
fn host(os: Os, distro: &[&str], has: &[&'static str], node: Option<(u32, u32)>) -> Host {
Host { os, distro: distro.iter().map(|d| (*d).to_owned()).collect(), has: has.to_vec(), node }
}
fn labels(agent: &str, h: &Host) -> Vec<&'static str> {
methods(agent, h).0.iter().map(|m| m.label).collect()
}
#[test]
fn mac_with_homebrew_and_node() {
let h = host(Os::Mac, &[], &["brew", "npm", "curl"], Some((24, 13)));
assert_eq!(labels("opencode", &h), ["Homebrew", "npm", "Install script"]);
assert_eq!(labels("pi", &h), ["npm", "Homebrew", "Install script"]);
}
#[test]
fn mac_without_node_hides_npm_and_says_why() {
let h = host(Os::Mac, &[], &["curl"], None);
let (ok, missing) = methods("pi", &h);
assert_eq!(ok.iter().map(|m| m.label).collect::<Vec<_>>(), ["Install script"]);
assert!(missing.contains(&Missing { label: "npm", reason: "needs npm".into() }));
let old = host(Os::Mac, &[], &["npm"], Some((22, 3)));
assert!(methods("pi", &old).1.iter().any(|m| m.reason == "needs Node 22.19 or newer"));
}
#[test]
fn ubuntu_and_arch() {
let ubuntu = host(Os::Linux, &parse_os_release("ID=ubuntu\nID_LIKE=debian\n").iter().map(String::as_str).collect::<Vec<_>>(), &["curl", "npm", "paru"], Some((22, 20)));
assert_eq!(labels("opencode", &ubuntu), ["npm", "Install script"], "paru is for Arch only");
let arch = host(Os::Linux, &["arch"], &["curl", "paru"], None);
let (ok, _) = methods("opencode", &arch);
assert!(ok.iter().any(|m| m.label == "AUR (paru)" && m.elevated), "offered to copy, never run");
}
#[test]
fn windows_with_scoop() {
let h = host(Os::Windows, &[], &["scoop", "powershell"], None);
assert_eq!(labels("opencode", &h), ["Scoop"]);
assert_eq!(labels("pi", &h), ["Install script"]);
assert!(methods("pi", &h).0[0].command.contains("install.ps1"));
}
#[test]
fn versions_and_distros_parse() {
assert_eq!(parse_node("v22.19.0\n"), Some((22, 19)));
assert_eq!(parse_os_release("NAME=\"Arch Linux\"\nID=arch\n"), ["arch"]);
}
#[cfg(unix)]
#[test]
fn a_run_streams_lines_and_reports_failure() {
let ok = run(&method("echo", UNIX, "sh", "echo one; echo two >&2", Kind::Package));
let lines: Vec<Line> = ok.iter().collect();
assert!(lines.contains(&Line::Out("one".into())) && lines.contains(&Line::Out("two".into())));
assert_eq!(lines.last(), Some(&Line::Done(Ok(()))));
let bad: Vec<Line> = run(&method("false", UNIX, "sh", "exit 3", Kind::Package)).iter().collect();
assert!(matches!(bad.last(), Some(Line::Done(Err(_)))));
let sudo: Vec<Line> = run(&Method { elevated: true, ..method("x", UNIX, "sh", "echo never", Kind::Package) }).iter().collect();
assert_eq!(sudo.len(), 1, "an elevated method never runs");
}
}
+67
View File
@@ -0,0 +1,67 @@
//! API keys for the model providers Pi runs on, kept in the OS secret store (Keychain, Credential
//! Manager, Secret Service) and handed to Pi only as environment variables of its process.
/// A provider Pi reads a key for from the environment.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Provider {
pub id: &'static str,
pub name: &'static str,
pub env: &'static str,
/// Where the user gets a free key.
pub key_url: &'static str,
/// Shown next to the key: what the free tier allows.
pub note: &'static str,
}
pub const PROVIDERS: [Provider; 5] = [
Provider { id: "openrouter", name: "OpenRouter", env: "OPENROUTER_API_KEY", key_url: "https://openrouter.ai/keys", note: ":free models, 50 requests a day (1000 after buying 10 credits)" },
Provider { id: "groq", name: "Groq", env: "GROQ_API_KEY", key_url: "https://console.groq.com/keys", note: "Free tier with per-minute limits" },
Provider { id: "gemini", name: "Gemini", env: "GEMINI_API_KEY", key_url: "https://aistudio.google.com/apikey", note: "Free tier on Flash models" },
Provider { id: "nvidia", name: "NVIDIA NIM", env: "NVIDIA_API_KEY", key_url: "https://build.nvidia.com/settings/api-keys", note: "Free tier with per-minute limits" },
Provider { id: "cerebras", name: "Cerebras", env: "CEREBRAS_API_KEY", key_url: "https://cloud.cerebras.ai", note: "Free tier with daily limits" },
];
/// `(env var, key)` for each provider `get` has a key for. Never log the result.
pub fn env(get: impl Fn(&Provider) -> Option<String>) -> Vec<(String, String)> {
PROVIDERS.iter().filter_map(|p| get(p).map(|k| (p.env.to_owned(), k))).collect()
}
#[cfg(not(target_arch = "wasm32"))]
pub use store::{forget, get, set};
#[cfg(not(target_arch = "wasm32"))]
mod store {
use super::Provider;
const SERVICE: &str = "PaperCraft";
fn entry(p: &Provider) -> Result<keyring::Entry, String> {
keyring::Entry::new(SERVICE, &format!("pi:{}", p.id)).map_err(|e| e.to_string())
}
pub fn get(p: &Provider) -> Option<String> {
entry(p).ok()?.get_password().ok().map(|k| k.trim().to_owned()).filter(|k| !k.is_empty())
}
pub fn set(p: &Provider, key: &str) -> Result<(), String> {
entry(p)?.set_password(key.trim()).map_err(|e| e.to_string())
}
pub fn forget(p: &Provider) -> Result<(), String> {
match entry(p)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_providers_with_a_key_reach_the_environment() {
let env = env(|p| (p.id == "openrouter").then(|| "sk-or-test".to_owned()));
assert_eq!(env, [("OPENROUTER_API_KEY".to_owned(), "sk-or-test".to_owned())]);
}
}
+37 -4
View File
@@ -10,6 +10,9 @@ pub mod codex;
pub mod ds_digest;
pub mod endpoint;
pub mod events;
pub mod install;
pub mod keys;
pub mod models;
#[cfg(not(target_arch = "wasm32"))]
pub mod openai;
#[cfg(not(target_arch = "wasm32"))]
@@ -32,10 +35,13 @@ const IMAGE_MAX_EDGE: f64 = ZOOM_MAX_EDGE as f64;
const IMAGE_MAX_PIXELS: f64 = 1_150_000.0;
/// Only used when a JPEG had to be scaled down: high enough that re-encoding is invisible.
const IMAGE_JPEG_QUALITY: u8 = 95;
/// An opaque PNG (a screenshot, a photo) is also tried as a JPEG this good; text stays legible.
const IMAGE_LOSSY_QUALITY: u8 = 82;
/// Scales an image down to the send cap, then re-encodes it: PNG at the best lossless
/// compression, JPEG stays JPEG (a PNG of a photo is often bigger than the original). Keeps the
/// original bytes when they are already smaller. The third value is the original when scaled.
/// compression, JPEG stays JPEG (a PNG of a photo is often bigger than the original), and an
/// opaque PNG becomes a JPEG when that is smaller. Keeps the original bytes when they are
/// already smaller. The third value is the original when scaled.
pub fn shrink_image(name: String, img: events::ImageAttachment) -> (String, events::ImageAttachment, Option<Vec<u8>>) {
use image::codecs::{jpeg::JpegEncoder, png};
let Ok(decoded) = image::load_from_memory(&img.data) else { return (name, img, None) };
@@ -45,13 +51,20 @@ pub fn shrink_image(name: String, img: events::ImageAttachment) -> (String, even
return (name, img, None); // re-encoding a JPEG loses detail for little gain
}
let decoded = if k < 1.0 { decoded.resize((w * k) as u32, (h * k) as u32, image::imageops::FilterType::Lanczos3) } else { decoded };
let jpeg = img.mime == "image/jpeg";
let mut jpeg = img.mime == "image/jpeg";
let mut out = Vec::new();
let encoded = if jpeg {
let mut encoded = if jpeg {
decoded.to_rgb8().write_with_encoder(JpegEncoder::new_with_quality(&mut out, IMAGE_JPEG_QUALITY))
} else {
decoded.write_with_encoder(png::PngEncoder::new_with_quality(&mut out, png::CompressionType::Best, png::FilterType::Adaptive))
};
let opaque = || !decoded.color().has_alpha() || decoded.to_rgba8().pixels().all(|px| px[3] == u8::MAX);
if !jpeg && opaque() {
let mut lossy = Vec::new();
if decoded.to_rgb8().write_with_encoder(JpegEncoder::new_with_quality(&mut lossy, IMAGE_LOSSY_QUALITY)).is_ok() && (encoded.is_err() || lossy.len() < out.len()) {
(out, encoded, jpeg) = (lossy, Ok(()), true);
}
}
if encoded.is_err() || (k >= 1.0 && out.len() >= img.data.len()) {
return (name, img, None);
}
@@ -191,6 +204,26 @@ pub struct Chat {
pub issues: std::collections::BTreeMap<String, IssueOutcome>,
}
/// A chat as the history list shows it, without its messages: a long chat's screenshots run to
/// hundreds of MB, and the list must not hold a copy of every chat.
#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
pub struct ChatSummary {
#[serde(default)]
pub id: String,
#[serde(default)]
pub title: String,
#[serde(default)]
pub updated: u64,
#[serde(default)]
pub backend: Backend,
}
impl ChatSummary {
pub fn of(c: &Chat) -> Self {
Self { id: c.id.clone(), title: c.title.clone(), updated: c.updated, backend: c.backend.clone() }
}
}
/// A drafted issue the user sent or dropped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "lowercase")]
+222
View File
@@ -0,0 +1,222 @@
//! The models an agent can run: read from the agent's own CLI where it has one (`opencode models
//! --verbose` gives names, prices, context sizes and image input without starting a session), else
//! from the model option of its ACP sessions.
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// One model an agent offers. Prices are US dollars per million tokens.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentModel {
/// What the agent takes to select it, e.g. `opencode/big-pickle`.
pub id: String,
pub name: String,
pub provider: String,
pub cost_in: Option<f64>,
pub cost_out: Option<f64>,
pub context: Option<u64>,
pub image: Option<bool>,
/// Model-specific reasoning variants offered by the agent.
pub variants: Vec<String>,
}
impl AgentModel {
/// "Free", "$0.30 / $1.20", or "" when the price is unknown.
pub fn price(&self) -> String {
match (self.cost_in, self.cost_out) {
(Some(i), Some(o)) if i == 0.0 && o == 0.0 => "Free".into(),
(Some(i), Some(o)) => format!("${i:.2} / ${o:.2}"),
_ => String::new(),
}
}
/// Costs nothing to run: priced at 0, an OpenRouter `:free` variant, or served by a provider
/// whose API keys come with a free tier.
pub fn is_free(&self) -> bool {
matches!((self.cost_in, self.cost_out), (Some(i), Some(o)) if i == 0.0 && o == 0.0)
|| self.id.ends_with(":free")
|| FREE_TIER_PROVIDERS.contains(&self.provider.as_str())
}
}
/// The chat's model when it runs on whichever free model works ("Free (auto)").
pub const FREE_AUTO: &str = "free-auto";
/// Models a "Free (auto)" turn may move to after its first one fails.
pub const MAX_FALLBACKS: usize = 2;
/// Pi providers whose keys have a free tier. ponytail: per provider, because `pi --list-models`
/// gives no prices; a paid model there runs on the free tier's limits.
const FREE_TIER_PROVIDERS: [&str; 4] = ["groq", "cerebras", "nvidia", "google"];
/// The free models of `catalog` minus `skip`, the most capable first: larger context, then image
/// input. The order "Free (auto)" tries them in.
pub fn free_order(catalog: &[AgentModel], skip: &[String]) -> Vec<String> {
let mut free: Vec<&AgentModel> = catalog.iter().filter(|m| m.is_free() && !skip.contains(&m.id)).collect();
free.sort_by_key(|m| (std::cmp::Reverse(m.context.unwrap_or(0)), m.image != Some(true)));
free.into_iter().map(|m| m.id.clone()).collect()
}
/// ACP config option values `(id, name)`; a name like "Ollama Cloud/GLM-5.3" carries its provider.
pub fn from_options(options: &[(String, String)]) -> Vec<AgentModel> {
options
.iter()
.map(|(id, name)| {
let (provider, name) = name.split_once('/').unwrap_or_else(|| (id.split_once('/').map_or("", |(p, _)| p), name));
AgentModel { id: id.clone(), name: name.to_owned(), provider: provider.to_owned(), ..Default::default() }
})
.collect()
}
/// `fresh` becomes the list; what it does not say (price, context, a provider name) is kept from
/// the old entry with the same id. True when anything changed.
pub fn merge(list: &mut Vec<AgentModel>, fresh: Vec<AgentModel>) -> bool {
let merged: Vec<AgentModel> = fresh
.into_iter()
.map(|mut m| {
if let Some(old) = list.iter().find(|o| o.id == m.id) {
if m.provider.is_empty() {
m.provider.clone_from(&old.provider);
}
m.cost_in = m.cost_in.or(old.cost_in);
m.cost_out = m.cost_out.or(old.cost_out);
m.context = m.context.or(old.context);
m.image = m.image.or(old.image);
if m.variants.is_empty() {
m.variants.clone_from(&old.variants);
}
}
m
})
.collect();
let changed = *list != merged;
*list = merged;
changed
}
/// `opencode models --verbose`: a `provider/model` line, then the model as pretty JSON, per model.
pub fn parse_opencode(out: &str) -> Vec<AgentModel> {
let mut models = vec![];
let mut lines = out.lines();
while let Some(head) = lines.next() {
let Some((provider, _)) = head.trim().split_once('/').filter(|_| !head.starts_with([' ', '{', '}'])) else { continue };
let mut body = String::new();
for l in lines.by_ref() {
body.push_str(l);
if l == "}" {
break;
}
}
let Ok(v) = serde_json::from_str::<Value>(&body) else { continue };
let num = |p: &str| v.pointer(p).and_then(Value::as_f64);
models.push(AgentModel {
id: head.trim().to_owned(),
name: v["name"].as_str().unwrap_or(head.trim()).to_owned(),
provider: provider.to_owned(),
cost_in: num("/cost/input"),
cost_out: num("/cost/output"),
context: v.pointer("/limit/context").and_then(Value::as_u64),
image: v.pointer("/capabilities/input/image").and_then(Value::as_bool),
variants: v["variants"].as_object().map(|v| v.iter().filter(|(_, value)| value["disabled"] != true).map(|(name, _)| name.clone()).collect()).unwrap_or_default(),
});
}
models
}
/// `pi --list-models`: a header, then `provider model context max-out thinking images` columns,
/// sizes written like `131.1K` or `1M`.
pub fn parse_pi(out: &str) -> Vec<AgentModel> {
let size = |s: &str| -> Option<u64> {
let (n, mul) = match s.as_bytes().last()? {
b'K' => (&s[..s.len() - 1], 1e3),
b'M' => (&s[..s.len() - 1], 1e6),
_ => (s, 1.0),
};
n.parse::<f64>().ok().map(|v| (v * mul).round() as u64)
};
out.lines()
.filter_map(|l| {
let c: Vec<&str> = l.split_whitespace().collect();
let [provider, model, context, _, _, images] = c[..] else { return None };
if provider == "provider" {
return None;
}
Some(AgentModel {
id: format!("{provider}/{model}"),
name: model.to_owned(),
provider: provider.to_owned(),
context: size(context),
image: Some(images == "yes"),
..Default::default()
})
})
.collect()
}
/// Runs `pi --list-models --offline` with `env` (the lean Pi folder and the provider keys).
#[cfg(not(target_arch = "wasm32"))]
pub fn fetch_pi(program: &std::path::Path, env: &[(String, String)]) -> Option<Vec<AgentModel>> {
let mut cmd = std::process::Command::new(program);
cmd.args(["--list-models", "--offline"]).envs(env.iter().cloned()).stdin(std::process::Stdio::null());
super::path::apply(&mut cmd);
let out = cmd.output().map_err(|e| log::warn!("models: could not run {}: {e}", program.display())).ok()?;
let models = parse_pi(&String::from_utf8_lossy(&out.stdout));
(!models.is_empty()).then_some(models)
}
/// Runs `program models --verbose` with `env` (the lean environment, so the list matches what a
/// lean session offers). None when it fails or lists nothing.
#[cfg(not(target_arch = "wasm32"))]
pub fn fetch_opencode(program: &std::path::Path, env: &[(String, String)]) -> Option<Vec<AgentModel>> {
let mut cmd = std::process::Command::new(program);
cmd.args(["models", "--verbose"]).envs(env.iter().cloned()).stdin(std::process::Stdio::null());
super::path::apply(&mut cmd);
let out = cmd.output().map_err(|e| log::warn!("models: could not run {}: {e}", program.display())).ok()?;
let models = parse_opencode(&String::from_utf8_lossy(&out.stdout));
(!models.is_empty()).then_some(models)
}
#[cfg(test)]
mod tests {
use super::*;
const OUT: &str = "opencode/big-pickle\n{\n \"id\": \"big-pickle\",\n \"name\": \"Big Pickle\",\n \"cost\": {\n \"input\": 0,\n \"output\": 0\n },\n \"limit\": {\n \"context\": 200000\n },\n \"capabilities\": {\n \"input\": {\n \"image\": false\n }\n }\n}\nminimax/MiniMax-M3\n{\n \"name\": \"MiniMax-M3\",\n \"cost\": {\n \"input\": 0.3,\n \"output\": 1.2\n }\n}\n";
#[test]
fn opencode_listing_gives_names_prices_and_limits() {
let m = parse_opencode(OUT);
assert_eq!(m.iter().map(|m| (m.id.as_str(), m.provider.as_str(), m.price())).collect::<Vec<_>>(), [("opencode/big-pickle", "opencode", "Free".to_owned()), ("minimax/MiniMax-M3", "minimax", "$0.30 / $1.20".to_owned())]);
assert_eq!((m[0].context, m[0].image, m[1].context), (Some(200_000), Some(false), None));
}
#[test]
fn opencode_listing_keeps_model_variants() {
let models = parse_opencode("provider/model\n{\n\"name\":\"Model\",\n\"variants\":{\"high\":{},\"low\":{}}\n}\n");
assert_eq!(models[0].variants, ["high", "low"]);
}
#[test]
fn pi_listing_gives_ids_context_and_images() {
let out = "provider model context max-out thinking images\nopenrouter qwen/qwen3-coder:free 262.1K 32.8K no no\ngroq llama-4-scout 1M 8.2K yes yes\nbroken line\n";
let m = parse_pi(out);
assert_eq!(m.iter().map(|m| (m.id.as_str(), m.context, m.image)).collect::<Vec<_>>(), [("openrouter/qwen/qwen3-coder:free", Some(262_100), Some(false)), ("groq/llama-4-scout", Some(1_000_000), Some(true))]);
}
#[test]
fn free_models_go_first_by_context_and_skip_the_failed() {
let mut list = parse_opencode(OUT);
list.extend(parse_pi("openrouter a:free 1M 1K no no\nopenrouter b 1M 1K no no\ngroq c 100K 1K no yes\n"));
assert_eq!(free_order(&list, &[]), ["openrouter/a:free", "opencode/big-pickle", "groq/c"]);
assert_eq!(free_order(&list, &["openrouter/a:free".into()]), ["opencode/big-pickle", "groq/c"]);
}
#[test]
fn session_options_keep_what_the_listing_knew() {
let mut list = parse_opencode(OUT);
let fresh = from_options(&[("opencode/big-pickle".into(), "OpenCode Zen/Big Pickle".into()), ("x/y".into(), "Y".into())]);
assert!(merge(&mut list, fresh));
assert_eq!((list[0].provider.as_str(), list[0].name.as_str(), list[0].price(), list[0].context), ("OpenCode Zen", "Big Pickle", "Free".to_owned(), Some(200_000)));
assert_eq!((list[1].provider.as_str(), list.len()), ("x", 2), "a model the session no longer offers is dropped");
assert!(!merge(&mut list.clone(), list.clone()));
}
}
+139 -6
View File
@@ -1,7 +1,9 @@
//! Chat files in the project folder: `chats/<id>.json`, plus `chats/<id>.api.json` for the raw
//! Anthropic API messages (exact replay, thinking blocks included).
use super::{valid_id, Chat, TMP_DIR};
use super::{valid_id, Chat, ChatSummary, TMP_DIR};
use base64::{engine::general_purpose::STANDARD, Engine};
use serde_json::Value;
use crate::vfs;
use std::path::{Path, PathBuf};
@@ -27,23 +29,114 @@ pub fn save(project: &Path, chat: &Chat) -> std::io::Result<()> {
vfs::write(file_of(project, &chat.id), bytes)
}
/// Reads chat `id`. Screenshots still inline (older chats) move to files, and the slimmer chat
/// is written back at once, so the move happens only once.
pub fn load(project: &Path, id: &str) -> Option<Chat> {
if !valid_id(id) {
return None;
}
serde_json::from_slice(&vfs::read(file_of(project, id)).ok()?).ok()
let mut chat: Chat = serde_json::from_slice(&vfs::read(file_of(project, id)).ok()?).ok()?;
let mut moved = false;
for t in chat.messages.iter_mut().flat_map(|m| &mut m.tools) {
if let Some(r) = &mut t.result {
moved |= offload_images(project, id, &t.id, r);
}
}
if moved && let Err(e) = save(project, &chat) {
log::warn!("could not save chat {id}: {e}");
}
Some(chat)
}
/// Every readable chat, newest updated first. Unreadable files are skipped.
pub fn list(project: &Path) -> Vec<Chat> {
/// How long agents' screenshots are kept; an older one shows no thumbnail in its chat.
pub const RESULT_IMAGES_KEEP: std::time::Duration = std::time::Duration::from_secs(14 * 24 * 60 * 60);
const RESULT_PREFIX: &str = "result-";
/// Deletes the agents' screenshots (not the person's own images) older than `keep` from every
/// chat's image folder of `project`, so long chats do not pile up on disk.
pub fn prune_result_images(project: &Path, keep: std::time::Duration) {
let Ok(chats) = vfs::read_dir(project.join(TMP_DIR)) else { return };
for folder in chats.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) {
let Ok(files) = vfs::read_dir(folder.path()) else { continue };
for f in files.flatten() {
let old = f.metadata().and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|age| age > keep));
if old && f.file_name().to_string_lossy().starts_with(RESULT_PREFIX) && let Err(e) = vfs::remove_file(f.path()) {
log::warn!("could not remove {}: {e}", f.path().display());
}
}
}
}
/// Inline images shorter than this stay in the chat.
const OFFLOAD_MIN: usize = 4096;
/// An image block of a tool result: its mime type and base64 data (inline), or its file.
pub fn image_data(block: &Value) -> Option<(&str, ImageSrc<'_>)> {
if block["type"] != "image" {
return None;
}
let mime = block["source"]["media_type"].as_str().or_else(|| block["mimeType"].as_str()).unwrap_or("image/png");
if let Some(path) = block["path"].as_str() {
return Some((mime, ImageSrc::File(path)));
}
let data = block["source"]["data"].as_str().or_else(|| block["data"].as_str())?;
Some((mime, ImageSrc::Base64(data)))
}
pub enum ImageSrc<'a> {
Base64(&'a str),
File(&'a str),
}
impl ImageSrc<'_> {
pub fn bytes(&self) -> Option<Vec<u8>> {
match self {
ImageSrc::Base64(d) => STANDARD.decode(d.as_bytes()).ok(),
ImageSrc::File(p) => vfs::read(p).ok(),
}
}
}
/// Moves the inline images of a tool result into the chat's image folder, leaving their path:
/// a long chat's screenshots would otherwise stay in memory and be rewritten with every save.
/// An image that cannot be written stays inline. True when any image moved.
pub fn offload_images(project: &Path, chat_id: &str, tool_id: &str, result: &mut Value) -> bool {
let (Some(blocks), Some(folder)) = (result.as_array_mut(), tmp_of(project, chat_id)) else { return false };
let mut moved = false;
let name: String = tool_id.chars().filter(|c| c.is_ascii_alphanumeric() || ['-', '_'].contains(c)).collect();
for (n, b) in blocks.iter_mut().enumerate() {
let Some((mime, ImageSrc::Base64(data))) = image_data(b) else { continue };
if data.len() < OFFLOAD_MIN {
continue;
}
let Ok(bytes) = STANDARD.decode(data.as_bytes()) else { continue };
let ext = mime.strip_prefix("image/").filter(|e| ["png", "jpeg", "webp", "gif"].contains(e)).unwrap_or("png");
let path = folder.join(format!("{RESULT_PREFIX}{name}-{n}.{ext}"));
let mime = mime.to_owned();
// Named by tool id and position, so a file already there is this image.
if !vfs::exists(&path)
&& let Err(e) = vfs::create_dir_all(&folder).and_then(|()| vfs::write(&path, &bytes))
{
log::warn!("could not save a chat image: {e}");
continue;
}
*b = serde_json::json!({"type": "image", "mimeType": mime, "path": path.to_string_lossy()});
moved = true;
}
moved
}
/// Every readable chat, newest updated first, without messages (`load` reads one whole).
/// Unreadable files are skipped.
pub fn list(project: &Path) -> Vec<ChatSummary> {
let Ok(entries) = vfs::read_dir(dir(project)) else {
return Vec::new();
};
let mut out: Vec<Chat> = entries
let mut out: Vec<ChatSummary> = entries
.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "json"))
.filter(|e| !e.path().to_string_lossy().ends_with(API_SUFFIX))
.filter_map(|e| serde_json::from_slice::<Chat>(&vfs::read(e.path()).ok()?).ok())
.filter_map(|e| serde_json::from_slice::<ChatSummary>(&vfs::read(e.path()).ok()?).ok())
.filter(|c| valid_id(&c.id))
.collect();
out.sort_by_key(|c| std::cmp::Reverse(c.updated));
@@ -124,6 +217,45 @@ mod tests {
}
}
#[test]
fn screenshots_move_out_of_the_chat_into_files() {
let dir = temp_project();
let png = vec![7u8; OFFLOAD_MIN];
let mut c = chat("shots", 1);
c.messages[0].tools[0].result = Some(serde_json::json!([{"type": "image", "mimeType": "image/png", "data": STANDARD.encode(&png)}, {"type": "text", "text": "ok"}]));
save(&dir, &c).unwrap();
let loaded = load(&dir, "shots").unwrap();
let r = loaded.messages[0].tools[0].result.as_ref().unwrap();
let Some((mime, ImageSrc::File(path))) = image_data(&r[0]) else { panic!("still inline: {r}") };
let on_disk = std::fs::read_to_string(file_of(&dir, "shots")).unwrap();
let saved: Value = serde_json::from_str(&on_disk).unwrap();
assert_eq!(saved["messages"][0]["tools"][0]["result"][0]["path"], path, "the slimmer chat was written back");
assert!(!on_disk.contains(&STANDARD.encode(&png)));
assert_eq!((mime, ImageSrc::File(path).bytes()), ("image/png", Some(png)));
assert_eq!(r[1]["text"], "ok");
remove_tmp(&dir, "shots");
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn old_agent_screenshots_are_pruned_and_the_persons_images_kept() {
let dir = temp_project();
let folder = dir.join(TMP_DIR).join("c1");
std::fs::create_dir_all(&folder).unwrap();
let month_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(30 * 24 * 60 * 60);
for name in ["result-t1-0.png", "result-t2-0.png", "1792910692197-crop.png"] {
std::fs::write(folder.join(name), b"x").unwrap();
}
for name in ["result-t1-0.png", "1792910692197-crop.png"] {
std::fs::File::options().write(true).open(folder.join(name)).unwrap().set_modified(month_ago).unwrap();
}
prune_result_images(&dir, RESULT_IMAGES_KEEP);
let mut left: Vec<String> = std::fs::read_dir(&folder).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
left.sort();
assert_eq!(left, ["1792910692197-crop.png", "result-t2-0.png"]);
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn chat_round_trips() {
let dir = temp_project();
@@ -202,3 +334,4 @@ mod tests {
std::fs::remove_dir_all(dir).ok();
}
}
+356
View File
@@ -0,0 +1,356 @@
//! A bounded log of which layers changed at which revision, so an agent can ask "what changed
//! since I last looked" (`get_changes`) and lint only that (`lint_design {since}`).
//!
//! The revision here is the log's own counter, not `Editor::revision`: that one also moves when
//! the camera does and once per batch of MCP calls, so a read would bump it. This one moves only
//! when a committed edit, undo or redo changes layers.
use super::Editor;
use crate::model::{Document, NodeId};
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
/// Entries kept; a caller older than the oldest one gets `truncated` and does a full pass.
pub const MAX_ENTRIES: usize = 10_000;
/// The MCP client behind a change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Who {
/// Name and session: two agents with the same client name stay apart.
pub key: String,
/// What the canvas tag shows ("Claude Code", "Claude Code \u{b7} 2").
pub label: String,
}
/// One layer changed at one revision.
#[derive(Debug, Clone, PartialEq)]
struct Entry {
rev: u64,
page: String,
id: NodeId,
/// None for the person using the app (and for calls made without a client).
by: Option<Arc<Who>>,
}
/// Which changes `since` returns.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Filter<'a> {
All,
/// Everything but this client key's own changes.
Exclude(&'a str),
/// Only this client's changes, by label or key.
Only(&'a str),
}
/// Layers one client changed on one page since the asked revision.
#[derive(Debug, Clone, PartialEq)]
pub struct Group {
pub page: String,
pub by: Option<String>,
/// The latest revision in the group.
pub rev: u64,
/// Each layer once, in first-change order.
pub ids: Vec<NodeId>,
}
/// The answer to "what changed since revision N".
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Since {
/// The log no longer reaches back to the asked revision (or it is from the future): the
/// caller cannot trust `changes` and should look at everything.
pub truncated: bool,
pub changes: Vec<Group>,
}
#[derive(Debug, Clone)]
pub struct ChangeLog {
rev: u64,
entries: VecDeque<Entry>,
/// Highest revision of an entry dropped for space: asking since less than this is incomplete.
floor: u64,
max: usize,
/// The MCP client whose call is running, set by the run tracker around each call.
pub client: Option<Arc<Who>>,
/// Revision of the last whole-page lint per (client key, page id), for `changedOnly`.
linted: HashMap<(String, String), u64>,
}
impl Default for ChangeLog {
fn default() -> Self {
ChangeLog::with_capacity(MAX_ENTRIES)
}
}
impl ChangeLog {
pub fn with_capacity(max: usize) -> ChangeLog {
ChangeLog { rev: 0, entries: VecDeque::new(), floor: 0, max, client: None, linted: HashMap::new() }
}
/// The revision after the latest change.
pub fn rev(&self) -> u64 {
self.rev
}
/// Logs `ids` of `page` as changed in a new revision by the running client. Nothing
/// changed, no new revision.
pub fn record(&mut self, page: &str, ids: impl IntoIterator<Item = NodeId>) {
let mut ids = ids.into_iter().peekable();
if ids.peek().is_none() {
return;
}
self.rev += 1;
for id in ids {
self.entries.push_back(Entry { rev: self.rev, page: page.to_string(), id, by: self.client.clone() });
}
while self.entries.len() > self.max {
if let Some(dropped) = self.entries.pop_front() {
self.floor = self.floor.max(dropped.rev);
}
}
}
/// Forgets everything (another project was opened): every caller must start over.
pub fn reset(&mut self) {
self.rev += 1;
self.floor = self.rev;
self.entries.clear();
self.linted.clear();
}
/// Layers changed after revision `since`, optionally only on `page`, grouped by page and
/// client in first-change order.
pub fn since(&self, since: u64, page: Option<&str>, filter: Filter) -> Since {
if since > self.rev || since < self.floor {
return Since { truncated: true, changes: Vec::new() };
}
let keep = |e: &Entry| match filter {
Filter::All => true,
Filter::Exclude(k) => e.by.as_ref().is_none_or(|w| w.key != k),
Filter::Only(k) => e.by.as_ref().is_some_and(|w| w.key == k || w.label == k),
};
let mut changes: Vec<Group> = Vec::new();
for e in self.entries.iter().filter(|e| e.rev > since && page.is_none_or(|p| p == e.page) && keep(e)) {
let by = e.by.as_ref().map(|w| w.label.clone());
let at = changes.iter().position(|g| g.page == e.page && g.by == by);
let i = at.unwrap_or_else(|| {
changes.push(Group { page: e.page.clone(), by, rev: e.rev, ids: Vec::new() });
changes.len() - 1
});
let g = &mut changes[i];
g.rev = g.rev.max(e.rev);
if !g.ids.contains(&e.id) {
g.ids.push(e.id);
}
}
Since { truncated: false, changes }
}
/// Notes that the running client linted all of `page` as of the current revision.
pub fn note_lint(&mut self, page: &str) {
if let Some(c) = &self.client {
self.linted.insert((c.key.clone(), page.to_string()), self.rev);
}
}
/// Revision of the running client's last whole-page lint of `page`.
pub fn last_lint(&self, page: &str) -> Option<u64> {
let key = self.client.as_ref()?.key.clone();
self.linted.get(&(key, page.to_string())).copied()
}
}
/// Layers of `doc` bound to a variable in `names` (CSS names), or to any variable when `names`
/// is None: through a fill that follows it or a field binding. Sorted by id.
pub fn bound_layers(doc: &Document, names: Option<&BTreeSet<String>>) -> Vec<NodeId> {
let hit = |v: &str| names.is_none_or(|n| n.contains(v));
let mut out: Vec<NodeId> = doc
.nodes
.values()
.filter(|n| n.style.fills.iter().filter_map(|p| p.var()).any(hit) || n.bindings.values().any(|v| hit(v)))
.map(|n| n.id)
.collect();
out.sort();
out
}
impl Editor {
/// Logs the layers bound to the variables `names` (all variables when None) on every page:
/// an edit to a variable changes how they look or lay out even when no layer was written.
pub fn log_variable_users(&mut self, names: Option<&BTreeSet<String>>) {
self.finish_loading();
for i in 0..self.pages.len() {
let ids = bound_layers(self.page_doc(i), names);
let page = self.pages[i].id.clone();
self.changes.record(&page, ids);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geom::Rect;
use crate::model::{Color, Node, NodeKind, Paint};
#[test]
fn bound_layers_follow_fills_and_field_bindings() {
let mut doc = Document::default();
let mut add = |f: &dyn Fn(&mut Node)| {
let id = doc.alloc_id();
let mut n = Node::new(id, NodeKind::Frame { clip: false }, Rect::new(0.0, 0.0, 10.0, 10.0));
f(&mut n);
doc.nodes.insert(id, n);
id
};
let fill = add(&|n| n.style.fills = vec![Paint::solid_var(Color::rgb(1, 2, 3), "brand")]);
let gap = add(&|n| {
n.bindings.insert("gap".into(), "space-4".into());
});
let _plain = add(&|n| n.style.fills = vec![Paint::solid(Color::rgb(1, 2, 3))]);
let some = |s: &str| Some(BTreeSet::from([s.to_string()]));
assert_eq!(bound_layers(&doc, some("brand").as_ref()), vec![fill]);
assert_eq!(bound_layers(&doc, some("space-4").as_ref()), vec![gap]);
assert!(bound_layers(&doc, some("other").as_ref()).is_empty());
assert_eq!(bound_layers(&doc, None), vec![fill, gap]);
}
fn ids(v: &[u64]) -> Vec<NodeId> {
v.iter().map(|n| NodeId(*n)).collect()
}
fn who(key: &str, label: &str) -> Option<Arc<Who>> {
Some(Arc::new(Who { key: key.into(), label: label.into() }))
}
fn all(log: &ChangeLog, since: u64) -> Since {
log.since(since, None, Filter::All)
}
#[test]
fn each_recorded_edit_is_a_revision() {
let mut log = ChangeLog::default();
assert_eq!(log.rev(), 0);
log.record("p1", ids(&[1, 2]));
log.record("p1", ids(&[3]));
assert_eq!(log.rev(), 2);
let g = &all(&log, 0).changes;
assert_eq!((g.len(), g[0].ids.clone(), g[0].rev), (1, ids(&[1, 2, 3]), 2));
assert_eq!(all(&log, 1).changes[0].ids, ids(&[3]));
assert!(all(&log, 2).changes.is_empty());
}
#[test]
fn an_empty_edit_keeps_the_revision() {
let mut log = ChangeLog::default();
log.record("p1", []);
assert_eq!(log.rev(), 0);
}
#[test]
fn a_layer_changed_twice_is_listed_once() {
let mut log = ChangeLog::default();
log.record("p1", ids(&[1]));
log.record("p1", ids(&[1, 2]));
assert_eq!(all(&log, 0).changes[0].ids, ids(&[1, 2]));
}
#[test]
fn changes_can_be_limited_to_a_page() {
let mut log = ChangeLog::default();
log.record("p1", ids(&[1]));
log.record("p2", ids(&[1]));
let s = log.since(0, Some("p2"), Filter::All);
assert_eq!((s.changes.len(), s.changes[0].page.as_str()), (1, "p2"));
assert_eq!(all(&log, 0).changes.len(), 2);
}
#[test]
fn asking_older_than_the_oldest_entry_is_truncated() {
let mut log = ChangeLog::with_capacity(3);
log.record("p", ids(&[1])); // rev 1
log.record("p", ids(&[2, 3])); // rev 2
assert!(!all(&log, 0).truncated);
log.record("p", ids(&[4])); // rev 3 drops the rev 1 entry
assert!(all(&log, 0).truncated);
// Everything after the dropped revision is still complete.
let s = all(&log, 1);
assert!(!s.truncated);
assert_eq!(s.changes[0].ids, ids(&[2, 3, 4]));
}
#[test]
fn the_log_stays_bounded() {
let mut log = ChangeLog::with_capacity(5);
for n in 0..20 {
log.record("p", ids(&[n]));
}
assert_eq!(log.entries.len(), 5);
assert_eq!(all(&log, 15).changes[0].ids, ids(&[15, 16, 17, 18, 19]));
assert!(all(&log, 14).truncated);
}
#[test]
fn a_future_revision_is_truncated() {
let mut log = ChangeLog::default();
log.record("p", ids(&[1]));
assert!(all(&log, 9).truncated);
}
#[test]
fn reset_forces_a_full_pass() {
let mut log = ChangeLog::default();
log.record("p", ids(&[1]));
let old = log.rev();
log.reset();
assert!(all(&log, old).truncated);
assert!(!all(&log, log.rev()).truncated);
}
#[test]
fn lint_revisions_are_per_client_session_and_page() {
let mut log = ChangeLog::default();
log.record("p", ids(&[1]));
assert_eq!(log.last_lint("p"), None, "no client, nothing remembered");
log.client = who("rmcp#1", "rmcp");
log.note_lint("p");
assert_eq!(log.last_lint("p"), Some(1));
assert_eq!(log.last_lint("q"), None);
// Same client name, another session.
log.client = who("rmcp#2", "rmcp \u{b7} 2");
assert_eq!(log.last_lint("p"), None);
}
#[test]
fn two_clients_changes_are_attributed_separately() {
let mut log = ChangeLog::default();
log.client = who("rmcp#1", "rmcp");
log.record("p", ids(&[1, 2]));
log.client = who("rmcp#2", "rmcp \u{b7} 2");
log.record("p", ids(&[2, 3]));
log.client = None;
log.record("p", ids(&[4]));
let g = all(&log, 0).changes;
assert_eq!(g.len(), 3);
assert_eq!((g[0].by.as_deref(), g[0].ids.clone(), g[0].rev), (Some("rmcp"), ids(&[1, 2]), 1));
assert_eq!((g[1].by.as_deref(), g[1].ids.clone(), g[1].rev), (Some("rmcp \u{b7} 2"), ids(&[2, 3]), 2));
assert_eq!((g[2].by.clone(), g[2].ids.clone()), (None, ids(&[4])));
}
#[test]
fn filters_pick_one_client_or_everyone_else() {
let mut log = ChangeLog::default();
log.client = who("a#1", "A");
log.record("p", ids(&[1]));
log.client = who("b#1", "B");
log.record("p", ids(&[2]));
log.client = None;
log.record("p", ids(&[3]));
let others = log.since(0, None, Filter::Exclude("a#1"));
let labels: Vec<_> = others.changes.iter().map(|g| g.by.as_deref()).collect();
assert_eq!(labels, vec![Some("B"), None], "the person's edits are someone else's too");
let only = log.since(0, None, Filter::Only("B"));
assert_eq!(only.changes.len(), 1);
assert_eq!(only.changes[0].ids, ids(&[2]));
assert_eq!(log.since(0, None, Filter::Only("b#1")).changes, only.changes);
}
}
+1
View File
@@ -12,6 +12,7 @@ pub enum UiEvent {
TogglePalette,
Rename(NodeId),
ToggleUi,
TogglePanels,
ToggleChat,
ToggleHelp,
ToggleGrid,
+1 -1
View File
@@ -168,7 +168,7 @@ impl Editor {
}
match self.take_rec() {
Some((rec, key)) if keep => {
if self.log_touched(&rec) && self.history.commit(&self.doc, rec, key) {
if self.log_touched(&rec) && self.history.commit_by(&self.doc, rec, key, self.changes.client.as_ref().map(|w| w.key.clone())) {
self.revision += 1;
}
}
+62 -23
View File
@@ -3,6 +3,7 @@
//! It consumes platform-agnostic [`InputEvent`]s, so every interaction can be scripted in tests.
pub mod annotations;
pub mod changes;
pub mod commands;
pub mod design;
pub mod hit;
@@ -17,7 +18,7 @@ pub mod vector_ops;
pub mod whiteboard;
use crate::geom::{Camera, Rect, V2, next_zoom_step, v2};
use crate::history::{History, Recording, Tx};
use crate::history::{History, Recording, Tx, Undone};
use crate::ink::{self, InkBuilder};
use crate::model::{Color, Document, Node, NodeId, NodeKind, StrokePoint, TextAlign};
use crate::text;
@@ -269,6 +270,8 @@ pub struct Editor {
pub active_page: usize,
/// Page groups (folders): group name -> page ids, in page order.
pub page_groups: BTreeMap<String, Vec<String>>,
/// Page id -> icon (`set:name`), saved in the manifest.
pub page_icons: BTreeMap<String, String>,
/// Page list or names changed (not tracked by undo history).
pub meta_dirty: bool,
/// The open project's design system (`design.json`).
@@ -317,6 +320,8 @@ pub struct Editor {
/// While set, every committed change appends the (page id, node) pairs it changed: the agent
/// run tracker attributes nodes to the run that made the call.
pub touch_log: Option<Vec<(String, NodeId)>>,
/// Which layers changed at which revision (`get_changes`, incremental lint).
pub changes: changes::ChangeLog,
}
impl Default for Editor {
@@ -370,6 +375,7 @@ impl Editor {
pages: vec![PageSlot::new(&name)],
active_page: 0,
page_groups: BTreeMap::new(),
page_icons: BTreeMap::new(),
meta_dirty: false,
design: Default::default(),
library_docs: BTreeMap::new(),
@@ -393,6 +399,7 @@ impl Editor {
clipboard_style: None,
cam_moved: None,
touch_log: None,
changes: changes::ChangeLog::default(),
clipboard_io: None,
clipboard_written: None,
}
@@ -426,7 +433,7 @@ impl Editor {
let mains = std::mem::take(&mut self.touched_mains);
if let Some((rec, key)) = self.take_rec()
&& self.log_touched(&rec)
&& self.history.commit(&self.doc, rec, key)
&& self.history.commit_by(&self.doc, rec, key, self.changes.client.as_ref().map(|w| w.key.clone()))
{
self.revision += 1;
if !mains.is_empty() {
@@ -436,24 +443,40 @@ impl Editor {
self.flush_cross_pages();
}
/// Appends the nodes `rec` changed to `touch_log`. Always true, so it chains before a commit.
/// Appends the nodes `rec` changed to `touch_log` and the change log. Always true, so it
/// chains before a commit.
pub(crate) fn log_touched(&mut self, rec: &Recording) -> bool {
let Some(page) = self.touch_log.as_ref().and_then(|_| self.pages.get(self.edit_page_index())) else {
let Some(page) = self.pages.get(self.edit_page_index()).map(|p| p.id.clone()) else {
return true;
};
let page = page.id.clone();
let changed: Vec<_> = rec
let changed: Vec<NodeId> = rec
.touched()
.iter()
.filter(|id| rec.before(**id).map(Option::as_ref) != Some(self.doc.nodes.get(id)))
.map(|id| (page.clone(), *id))
.copied()
.collect();
self.changes.record(&page, changed.iter().copied());
if let Some(log) = &mut self.touch_log {
log.extend(changed);
log.extend(changed.into_iter().map(|id| (page.clone(), id)));
}
true
}
/// A restored design system moves variables under their layers, which the step's own
/// layers do not list.
fn log_history_design(&mut self, design_restored: bool) {
if design_restored {
self.log_variable_users(None);
}
}
/// Logs the layers an undo or redo restored.
fn log_history(&mut self, nodes: &[NodeId]) {
if let Some(page) = self.pages.get(self.edit_page_index()).map(|p| p.id.clone()) {
self.changes.record(&page, nodes.iter().copied());
}
}
/// Run one edit as a complete transaction.
pub fn edit<R>(&mut self, label: &str, f: impl FnOnce(&mut Tx) -> R) -> R {
self.begin(label);
@@ -468,7 +491,7 @@ impl Editor {
let result = f(&mut self.tx());
if let Some((rec, key)) = self.take_rec()
&& self.log_touched(&rec)
&& self.history.commit(&self.doc, rec, key)
&& self.history.commit_by(&self.doc, rec, key, self.changes.client.as_ref().map(|w| w.key.clone()))
{
self.revision += 1;
}
@@ -488,29 +511,38 @@ impl Editor {
}
pub fn undo(&mut self) {
self.cancel_gesture();
self.end_text_edit();
self.commit();
let mut changed = Changed::Nodes(Arc::new([]));
if let Some(mut u) = self.history.undo(&mut self.doc) {
self.status = format!("Undo {}", u.label);
changed = Changed::Nodes(std::mem::take(&mut u.nodes).into());
self.restore_project_state(u);
}
self.after_history(changed);
let Ok(()) = self.step_history("Undo", |h, doc| Ok::<_, std::convert::Infallible>(h.undo(doc)));
}
pub fn redo(&mut self) {
let Ok(()) = self.step_history("Redo", |h, doc| Ok::<_, std::convert::Infallible>(h.redo(doc)));
}
/// Undoes `author`'s newest step under later steps by others (see [`History::undo_by`]).
/// Err: the labels of the later steps that touched the same things.
pub fn undo_by(&mut self, author: &str) -> Result<(), Vec<String>> {
self.step_history("Undo", |h, doc| h.undo_by(doc, author))
}
fn step_history<E>(
&mut self,
verb: &str,
step: impl FnOnce(&mut History, &mut Document) -> Result<Option<Undone>, E>,
) -> Result<(), E> {
self.cancel_gesture();
self.end_text_edit();
self.commit();
let mut changed = Changed::Nodes(Arc::new([]));
if let Some(mut u) = self.history.redo(&mut self.doc) {
self.status = format!("Redo {}", u.label);
if let Some(mut u) = step(&mut self.history, &mut self.doc)? {
self.status = format!("{verb} {}", u.label);
self.log_history(&u.nodes);
let design = u.design.is_some();
changed = Changed::Nodes(std::mem::take(&mut u.nodes).into());
self.restore_project_state(u);
self.log_history_design(design);
}
self.after_history(changed);
Ok(())
}
fn after_history(&mut self, changed: Changed) {
@@ -558,8 +590,11 @@ impl Editor {
sticky_color: self.sticky_color,
clipboard_io: self.clipboard_io.take(),
clipboard_written: self.clipboard_written.take(),
changes: std::mem::take(&mut self.changes),
..Editor::new(doc)
};
// A fresh log would restart rev at 0 and agents' old `since` values would look current.
self.changes.reset();
self.file_path = path;
match camera {
Some(c) => self.camera = c,
@@ -733,8 +768,8 @@ impl Editor {
/// zoomed-out page shows a few clean names instead of a pile.
pub fn frame_labels(&self) -> Vec<(NodeId, Rect)> {
let screen = Rect::new(0.0, 0.0, self.viewport.x, self.viewport.y);
// Top-level frames, then declared screens nested in sections.
let nested = screens::declared(&self.doc).into_iter().filter(|id| self.doc.get(*id).is_some_and(|n| n.parent.is_some()));
// Top-level frames, then declared screens and sections nested in sections.
let nested = self.doc.paint_order().into_iter().filter(|id| self.doc.get(*id).is_some_and(|n| n.parent.is_some() && (n.screen || n.section)));
let bodies: Vec<(usize, NodeId, Rect)> = self
.doc
.root
@@ -2155,6 +2190,9 @@ impl Editor {
A::ExportPdf => self
.requests
.push(AppRequest::ExportFormat(crate::io::export::Format::Pdf)),
A::ExportPresentation => self
.requests
.push(AppRequest::ExportFormat(crate::io::export::Format::Presentation)),
A::CopyAsPng => self.requests.push(AppRequest::CopyAsPng),
A::CopyAsSvg => self.copy_as_svg(),
A::ToggleSnapping => {
@@ -2186,6 +2224,7 @@ impl Editor {
}
}
A::ToggleUi => self.ui_events.push(commands::UiEvent::ToggleUi),
A::TogglePanels => self.ui_events.push(commands::UiEvent::TogglePanels),
A::ToggleChat => self.ui_events.push(commands::UiEvent::ToggleChat),
A::ToggleHelp => self.ui_events.push(commands::UiEvent::ToggleHelp),
A::ToggleGrid => self.ui_events.push(commands::UiEvent::ToggleGrid),
+16
View File
@@ -98,6 +98,7 @@ impl Editor {
self.meta_dirty = false;
// The groups of the previous project are gone; the session sets the new ones.
self.page_groups.clear();
self.page_icons.clear();
}
pub fn active_page_id(&self) -> &str {
@@ -323,6 +324,7 @@ impl Editor {
{
members.retain(|id| id != &removed.id);
}
self.page_icons.remove(&removed.id);
if self.active_page > i {
self.active_page -= 1;
}
@@ -656,6 +658,20 @@ impl Editor {
/// Page groups (folders). Groups are single level: a page belongs to at most one group,
/// and a group keeps its pages in the order of the page list.
impl Editor {
/// A page's icon (`set:name`), or none to show the default page icon.
pub fn set_page_icon(&mut self, page_id: &str, icon: Option<&str>) -> bool {
if !self.pages.iter().any(|p| p.id == page_id) || self.page_icons.get(page_id).map(String::as_str) == icon {
return false;
}
match icon {
Some(i) => self.page_icons.insert(page_id.to_string(), i.to_string()),
None => self.page_icons.remove(page_id),
};
self.meta_dirty = true;
self.revision += 1;
true
}
/// Create an empty group. Fails on an empty or already used name.
pub fn create_page_group(&mut self, name: &str) -> bool {
let name = name.trim();
+51 -1
View File
@@ -25,6 +25,7 @@ const OPAQUE: f64 = 0.95;
pub enum Role {
Screen,
Overlay,
Section,
None,
}
@@ -58,9 +59,29 @@ pub fn refusal(doc: &Document, id: NodeId, role: Role) -> Option<&'static str> {
Role::Screen => None,
Role::Overlay if screen_of(doc, id).is_none() => Some("an overlay (drawer, modal, sheet) must be inside a screen"),
Role::Overlay => None,
Role::Section if !n.is_frame() => Some("only a frame can be a section"),
Role::Section if in_component() => Some("a component main, an instance or a layer inside a main can't be a section"),
Role::Section if screen_of(doc, id).is_some() => Some("it is inside a screen"),
Role::Section => None,
}
}
/// Frames that look like sections: top-level frames named `Section / ...` or holding declared
/// screens, not declared yet.
pub fn section_candidates(doc: &Document) -> Vec<NodeId> {
doc.root
.iter()
.copied()
.filter(|id| {
doc.get(*id).is_some_and(|n| {
!n.section
&& !n.screen
&& (n.name.starts_with("Section /") || doc.subtree(*id).iter().skip(1).any(|d| doc.get(*d).is_some_and(|c| c.screen)))
}) && refusal(doc, *id, Role::Section).is_none()
})
.collect()
}
/// Frames that look like screens: named `Screen / ...`, the frame shown in a `Slot / ...`
/// frame, or a top-level frame at exactly a device size (a tall section at a device width
/// is not one). The outermost of nested candidates wins,
@@ -191,11 +212,17 @@ impl Editor {
pub fn set_role(&mut self, ids: &[NodeId], role: Role) -> Result<(), String> {
if let Some((id, why)) = ids.iter().find_map(|id| refusal(&self.doc, *id, role).map(|w| (*id, w))) {
let name = self.doc.get(id).map_or("?", |n| n.name.as_str());
return Err(format!("`{name}` can't be a {}: {why}", if role == Role::Overlay { "overlay" } else { "screen" }));
let what = match role {
Role::Overlay => "overlay",
Role::Section => "section",
_ => "screen",
};
return Err(format!("`{name}` can't be a {what}: {why}"));
}
let label = match role {
Role::Screen => "Declare screens",
Role::Overlay => "Mark overlays",
Role::Section => "Declare sections",
Role::None => "Clear screen roles",
};
self.edit(label, |tx| {
@@ -203,6 +230,11 @@ impl Editor {
if let Some(n) = tx.node_mut(*id) {
n.screen = role == Role::Screen;
n.overlay = role == Role::Overlay;
// A section is drawn by the canvas (outline and name), not by its own fill.
if role == Role::Section && !n.section {
n.style.fills.clear();
}
n.section = role == Role::Section;
}
}
});
@@ -275,4 +307,22 @@ mod tests {
let b = Rect::new(5.0, 5.0, 10.0, 10.0);
assert!((union_area(&[a, b]) - 175.0).abs() < 1e-9);
}
#[test]
fn sections_lose_their_fill_and_stay_out_of_screens() {
let mut ed = Editor::default();
let white = Some(Color { r: 255, g: 255, b: 255, a: 255 });
let section = frame(&mut ed, None, Rect::new(0.0, 0.0, 3000.0, 3000.0), white);
let screen = frame(&mut ed, Some(section), Rect::new(0.0, 0.0, 1440.0, 900.0), None);
let inner = frame(&mut ed, Some(screen), Rect::new(0.0, 0.0, 100.0, 100.0), None);
ed.set_role(&[screen], Role::Screen).unwrap();
assert_eq!(section_candidates(&ed.doc), vec![section], "holds a screen");
ed.set_role(&[section], Role::Section).unwrap();
let n = ed.doc.get(section).unwrap();
assert!(n.section && n.style.fills.is_empty());
assert!(section_candidates(&ed.doc).is_empty());
assert!(ed.set_role(&[inner], Role::Section).is_err(), "inside a screen");
ed.undo();
assert_eq!(ed.doc.get(section).unwrap().style.fills.len(), 1, "one undo step");
}
}
+8 -1
View File
@@ -59,6 +59,7 @@ pub enum Action {
Ask,
Rename,
ToggleUi,
TogglePanels,
ToggleChat,
ToggleHelp,
ToggleGrid,
@@ -75,6 +76,7 @@ pub enum Action {
PasteProps,
Home,
ExportPdf,
ExportPresentation,
CopyAsPng,
CopyAsSvg,
}
@@ -168,6 +170,7 @@ fn bindings() -> Vec<(Key, Chord, Action, &'static str)> {
(Char('/'), CMD_SHIFT, A::CommandPalette, "Command palette"),
(Char('r'), CMD, A::Rename, "Rename layer"),
(Char('\\'), CMD, A::ToggleUi, "Show / hide UI"),
(Char('/'), PLAIN, A::TogglePanels, "Show / hide the side panels"),
(Char('/'), CMD, A::ToggleHelp, "Keyboard shortcuts"),
(Char('?'), SHIFT, A::ToggleHelp, "Keyboard shortcuts"),
(Char('\''), CMD_SHIFT, A::ToggleGrid, "Show / hide dot grid"),
@@ -404,6 +407,7 @@ pub fn category(a: Action) -> &'static str {
| A::SaveAs
| A::ExportPng
| A::ExportSvg
| A::ExportPresentation
| A::PlaceImage
| A::Home => "File",
A::Undo
@@ -434,6 +438,7 @@ pub fn category(a: Action) -> &'static str {
| A::ToggleAnnotations
| A::OpenVariables
| A::ToggleUi
| A::TogglePanels
| A::ToggleChat
| A::ToggleHelp
| A::NextPage
@@ -511,6 +516,7 @@ pub fn menus() -> Vec<(&'static str, Vec<MenuEntry>)> {
I("Export PNG…", A::ExportPng),
I("Export SVG…", A::ExportSvg),
I("Export PDF…", A::ExportPdf),
I("Export Presentation…", A::ExportPresentation),
],
),
(
@@ -618,6 +624,7 @@ pub fn menus() -> Vec<(&'static str, Vec<MenuEntry>)> {
I("Dot Grid", A::ToggleGrid),
I("Annotations", A::ToggleAnnotations),
I("Show/Hide UI", A::ToggleUi),
I("Show/Hide Panels", A::TogglePanels),
I("Design / Chat Mode", A::ToggleChat),
I("Keyboard Shortcuts", A::ToggleHelp),
],
@@ -671,7 +678,7 @@ mod tests {
// Delete is bound to the Delete key; everything should be reachable.
assert!(
super::chord_of(*a).is_some()
|| matches!(a, super::Action::ExportSvg),
|| matches!(a, super::Action::ExportSvg | super::Action::ExportPresentation),
"{label} has no shortcut"
);
}
+89
View File
@@ -0,0 +1,89 @@
//! Handoff points: a named snapshot of every page, taken when screens go to development, so a
//! later design edit can be reported against what the developers received. Kept in the project
//! folder under `handoffs/`, one file per name (marking a name again moves it).
use crate::model::Document;
use crate::project::packed;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
const DIR: &str = "handoffs";
#[derive(Serialize, Deserialize)]
pub struct Page {
pub id: String,
pub name: String,
pub doc: Document,
}
#[derive(Serialize, Deserialize)]
pub struct Handoff {
pub name: String,
/// Unix milliseconds.
pub saved: u64,
pub pages: Vec<Page>,
}
/// A handoff file without its pages: listing must not build every document.
#[derive(Deserialize)]
pub struct Header {
pub name: String,
pub saved: u64,
}
fn dir(project: &Path) -> PathBuf {
project.join(DIR)
}
/// The file stem of a name: letters and digits, the rest as `-`.
fn stem(name: &str) -> String {
let s: String = name.trim().chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
let s = s.split('-').filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-");
if s.is_empty() { "handoff".into() } else { s }
}
pub fn save(project: &Path, h: &Handoff) -> std::io::Result<()> {
crate::vfs::create_dir_all(dir(project))?;
let json = serde_json::to_string(h).map_err(std::io::Error::other)?;
packed::write(&packed::path(&dir(project), &stem(&h.name)), &json)
}
/// Every handoff point, newest first.
pub fn list(project: &Path) -> Vec<Header> {
let Ok(entries) = crate::vfs::read_dir(dir(project)) else { return Vec::new() };
let mut out: Vec<Header> = entries
.flatten()
.filter_map(|e| {
let id = packed::stem(e.file_name().to_str()?)?.to_owned();
serde_json::from_str(&packed::read(&packed::path(&dir(project), &id)).ok()?).ok()
})
.collect();
out.sort_by_key(|h| std::cmp::Reverse(h.saved));
out
}
pub fn load(project: &Path, name: &str) -> Result<Handoff, String> {
let json = packed::read(&packed::path(&dir(project), &stem(name))).map_err(|_| {
let known: Vec<String> = list(project).into_iter().map(|h| h.name).collect();
format!("no handoff point named `{name}` (known: {})", if known.is_empty() { "none, mark one with mark_handoff".into() } else { known.join(", ") })
})?;
serde_json::from_str(&json).map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_name_marked_again_moves_and_lists_once() {
let dir = std::env::temp_dir().join(format!("papercraft-handoffs-{:016x}", fastrand::u64(..)));
let h = |saved| Handoff { name: "Design v1".into(), saved, pages: vec![Page { id: "p".into(), name: "P".into(), doc: Document::default() }] };
save(&dir, &h(1)).unwrap();
save(&dir, &h(2)).unwrap();
let all = list(&dir);
assert_eq!((all.len(), all[0].saved), (1, 2));
assert_eq!(load(&dir, "design v1").unwrap().pages.len(), 1, "names match by their stem");
assert!(load(&dir, "v2").err().is_some_and(|e| e.contains("Design v1")));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+47
View File
@@ -33,6 +33,8 @@ pub struct Change {
annotations: Option<(Vec<Annotation>, Vec<Annotation>)>,
next_id: (u64, u64),
coalesce_key: Option<String>,
/// The agent that made it (its client key); None for the person.
author: Option<String>,
}
/// Project-level state a step carries besides the page document; the editor puts it back.
@@ -538,6 +540,11 @@ pub struct History {
impl History {
/// Finalize a recording into a change. Returns false when nothing changed.
pub fn commit(&mut self, doc: &Document, rec: Recording, coalesce_key: Option<String>) -> bool {
self.commit_by(doc, rec, coalesce_key, None)
}
/// [`History::commit`] for a change made by `author` (an agent's client key).
pub fn commit_by(&mut self, doc: &Document, rec: Recording, coalesce_key: Option<String>, author: Option<String>) -> bool {
let entries: Vec<Entry> = rec
.order
.iter()
@@ -584,11 +591,13 @@ impl History {
annotations,
next_id: (rec.next_id_before, doc.next_id),
coalesce_key,
author,
};
self.generation += 1;
if let (Some(key), Some(top)) = (&change.coalesce_key, self.undo.last_mut())
&& self.redo.is_empty()
&& top.coalesce_key.as_ref() == Some(key)
&& top.author == change.author
{
merge(top, change);
return true;
@@ -619,6 +628,34 @@ impl History {
Some(u)
}
/// Undoes `author`'s newest step only, leaving later steps by others in place, when none
/// of them touched what it touched (the same layers, the top-level order, variables, the
/// design system, modes or notes). Blocked: the labels of the later steps in the way.
pub fn undo_by(&mut self, doc: &mut Document, author: &str) -> Result<Option<Undone>, Vec<String>> {
let Some(i) = self.undo.iter().rposition(|c| c.author.as_deref() == Some(author)) else {
return Ok(None);
};
let mine = &self.undo[i];
let blocked: Vec<String> = self.undo[i + 1..].iter().filter(|l| overlaps(mine, l)).map(|l| l.label.clone()).collect();
if !blocked.is_empty() {
return Err(blocked);
}
let c = self.undo.remove(i);
// Later steps may have made layers since: new ids keep counting up from there.
let next = doc.next_id;
c.apply(doc, false);
doc.next_id = doc.next_id.max(next);
self.generation += 1;
let u = c.undone(false);
self.redo.push(c);
Ok(Some(u))
}
/// Who made the step `redo` would bring back (None: the person, or nothing to redo).
pub fn redo_author(&self) -> Option<&str> {
self.redo.last().and_then(|c| c.author.as_deref())
}
pub fn generation(&self) -> u64 {
self.generation
}
@@ -666,6 +703,16 @@ impl History {
}
}
/// Two steps touched something in common, so one cannot be undone under the other.
fn overlaps(a: &Change, b: &Change) -> bool {
a.entries.iter().any(|e| b.entries.iter().any(|x| x.id == e.id))
|| (a.root.is_some() && b.root.is_some())
|| (a.variables.is_some() && b.variables.is_some())
|| (a.design.is_some() && b.design.is_some())
|| (a.page_modes.is_some() && b.page_modes.is_some())
|| (a.annotations.is_some() && b.annotations.is_some())
}
/// Fold `newer` into `older`, keeping the oldest before-state of each node.
fn merge(older: &mut Change, newer: Change) {
for e in newer.entries {
+784
View File
@@ -0,0 +1,784 @@
//! Presentation export: a PDF deck of a project's screens, the way a designer sends work to a
//! client. A cover, contents, a divider per page, one slide per screen (narrow side panels share
//! one), a closing slide; every slide numbered. Slides are drawn from a generated document
//! (text and cards); the screens are drawn into them scaled, so they stay vector.
//! Spec: `specs/presentation-export/spec.md`.
use super::pdf::{Insert, PdfPage};
use crate::editor::Editor;
use crate::geom::{Rect, V2, v2};
use crate::model::{Color, Document, Node, NodeId, NodeKind, TextAlign};
pub use words::Lang;
use words::{Noun, Words, fill};
pub(crate) mod unroll;
mod words;
/// A page of the project in the deck.
pub struct Section<'a> {
pub name: String,
pub doc: &'a Document,
pub screens: Vec<NodeId>,
}
/// What the cover says.
pub struct Meta {
pub title: String,
pub subtitle: Option<String>,
pub author: Option<String>,
/// Unix milliseconds, for the date on the cover.
pub now_ms: u64,
/// The deck's own words; None: the language the screens are written in.
pub language: Option<Lang>,
}
const W: f64 = 1920.0;
const H: f64 = 1080.0;
const MARGIN: f64 = 96.0;
/// Slides are laid out in the generated document one under the other with this gap.
const SLIDE_GAP: f64 = 200.0;
/// Frames smaller than this on either side are parts (components), not screens.
const MIN_SCREEN: f64 = 300.0;
/// Screens narrower than this share of their height are side panels, shown side by side.
const NARROW: f64 = 0.45;
const PANELS_PER_SLIDE: usize = 5;
const PANEL_GAP: f64 = 48.0;
/// A board fitted smaller than this scale is split top to bottom over several slides, each
/// part at the stage's width (at most 1:1). Narrower boards are panels and stay whole.
const READABLE: f64 = 0.5;
const MIN_SPLIT_W: f64 = 600.0;
/// Where a screen goes on its slide (under the title, above the footer).
const STAGE: Rect = Rect { x: MARGIN, y: 196.0, w: W - 2.0 * MARGIN, h: H - 196.0 - 110.0 };
const CAPTION_H: f64 = 44.0;
const BG: Color = Color { r: 22, g: 22, b: 30, a: 255 };
/// A screen's frame: light enough to edge a dark screen on the dark slide.
const CARD_EDGE: Color = Color { r: 84, g: 84, b: 104, a: 255 };
const CARD_EDGE_W: f64 = 2.0;
const INK: Color = Color { r: 232, g: 232, b: 242, a: 255 };
const MUTED: Color = Color { r: 150, g: 150, b: 170, a: 255 };
const ACCENT: Color = Color { r: 180, g: 160, b: 250, a: 255 };
/// The screens of a page in reading order (top to bottom, then left to right): its declared
/// screens, else its visible top-level frames (not component mains) of at least [`MIN_SCREEN`]
/// on both sides. A
/// section holding no screen (a design-system board) is shown whole.
pub fn screens_of(doc: &Document) -> Vec<NodeId> {
let declared = crate::editor::screens::declared(doc);
let mut ids: Vec<NodeId> = if declared.is_empty() {
doc.root
.iter()
.copied()
.filter(|id| doc.get(*id).is_some_and(|n| n.is_frame() && n.visible && !n.section && !n.component && n.rect.w >= MIN_SCREEN && n.rect.h >= MIN_SCREEN))
.collect()
} else {
declared.iter().copied().filter(|id| doc.get(*id).is_some_and(|n| n.visible)).collect()
};
let holds_screen = |id: NodeId| declared.iter().any(|s| doc.ancestors(*s).contains(&id));
ids.extend(doc.root.iter().copied().filter(|id| doc.get(*id).is_some_and(|n| n.section && n.visible) && !holds_screen(*id)));
let at = |id: &NodeId| doc.world_rect(*id).map_or((0.0, 0.0), |r| (r.y, r.x));
ids.sort_by(|a, b| at(a).partial_cmp(&at(b)).unwrap_or(std::cmp::Ordering::Equal));
ids
}
enum Slide {
Cover,
Contents,
Divider(usize),
/// One screen, whole, with its notes (numbered from 1 across its slides), which of its note
/// slides this is (`k` of `n`), and how many more states of it the appendix shows.
Screen { i: usize, id: NodeId, notes: Vec<(usize, Note)>, part: Option<(usize, usize)>, states: usize },
/// The appendix's divider: the states of screens, after the last page.
Appendix,
/// A page's key screens as captioned thumbnails, after its divider.
Map(usize, Vec<NodeId>),
/// A page's notes that ask a question, with their screen's name.
Questions(usize, Vec<(String, String)>),
/// What is left to do: the open questions, the review, the appendix.
NextSteps,
/// Screens side by side with captions, `n` to a slide: side panels, or the other states
/// of a screen.
Row(usize, String, Vec<NodeId>, usize),
/// An area of a layer: a board's cards, or a part of a tall screen. Title, source rect.
Crop(usize, NodeId, String, Rect),
End,
}
/// Layer-name prefixes that say what a layer is, not what it shows; left out of titles.
const KIND_PREFIXES: [&str; 4] = ["Section", "Screen", "Group", "Slot"];
/// States in the appendix (a reference): a 3 × 2 grid to a slide.
const APPENDIX_PER_SLIDE: usize = 6;
const APPENDIX_COLS: usize = 3;
/// Characters kept of an appendix slide's title (the groups on it).
const APPENDIX_TITLE_CHARS: usize = 70;
/// Cards pack onto a slide down to this share of their part scale.
const PACK_MIN_SCALE: f64 = 0.8;
/// A part of a tall card shrinks down to this share of its scale to keep blocks (a row of
/// cells) whole rather than cut through them.
const CUT_MIN_SCALE: f64 = 0.7;
/// Room around a board's cards on their slide.
const CARD_PAD: f64 = 24.0;
/// Notes shown beside a screen per slide; more continue on a repeat of the slide.
const NOTES_PER_SLIDE: usize = 8;
/// The share of the stage an annotated screen takes; its notes fill the rest.
const NOTED_SCREEN: f64 = 0.62;
const MARKER: f64 = 28.0;
/// Characters kept of a note's title and of its first body line.
const NOTE_TITLE_CHARS: usize = 80;
const NOTE_BODY_CHARS: usize = 120;
/// About how many title characters fit on one line of the note column.
const NOTE_TITLE_LINE_CHARS: usize = 50;
/// Thumbnails on a map slide (four across, three down).
const MAP_COLS: usize = 4;
const MAP_ROWS: usize = 3;
/// A map for fewer key screens than this adds nothing: the slides follow right after it.
const MAP_MIN: usize = 3;
const QUESTIONS_PER_SLIDE: usize = 8;
/// "12 screens · 6 boards": a page's screens and boards (sections shown by their cards).
fn tally(w: &Words, s: &Section) -> String {
let boards = s.screens.iter().filter(|id| s.doc.get(**id).is_some_and(|n| n.section)).count();
let screens = w.count(s.screens.len() - boards, Noun::Screen);
if boards == 0 { screens } else { format!("{screens} \u{b7} {}", w.count(boards, Noun::Board)) }
}
/// A design note shown on a slide.
#[derive(Clone)]
struct Note {
target: NodeId,
title: String,
body: String,
/// The line of the note that asks something (`?`), if any.
question: Option<String>,
color: Color,
}
/// The notes on screen `id`: attached notes whose layer is the screen, inside it or laid over
/// it, in reading order of their layers. Detached notes (their layer is gone) are left out.
fn notes_of(doc: &Document, id: NodeId) -> Vec<Note> {
let roots = super::export::with_layers_on_top(doc, &[id]);
let cats = crate::model::annotation::default_categories();
let mut notes: Vec<(Rect, Note)> = doc
.annotations
.iter()
.filter(|a| !a.detached)
.filter_map(|a| {
let target = a.target?;
if !(roots.contains(&target) || doc.ancestors(target).iter().any(|p| roots.contains(p))) {
return None;
}
let color = crate::model::annotation::category_by_key(&cats, &a.category).map_or(ACCENT, |c| c.color);
let body = a.body.lines().next().unwrap_or("").to_owned();
let question = std::iter::once(a.label.as_str()).chain(a.body.lines()).find(|l| l.contains('?')).map(str::to_owned);
Some((doc.world_rect(target)?, Note { target, title: a.label.clone(), body, question, color }))
})
.collect();
notes.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal));
notes.into_iter().map(|(_, n)| n).collect()
}
/// The slides of one screen: one, or one per [`NOTES_PER_SLIDE`] of its notes.
fn screen_slides(i: usize, doc: &Document, id: NodeId, states: usize) -> Vec<Slide> {
let notes: Vec<(usize, Note)> = notes_of(doc, id).into_iter().enumerate().map(|(k, n)| (k + 1, n)).collect();
if notes.is_empty() {
return vec![Slide::Screen { i, id, notes, part: None, states }];
}
let chunks: Vec<&[(usize, Note)]> = notes.chunks(NOTES_PER_SLIDE).collect();
let n = chunks.len();
chunks
.into_iter()
.enumerate()
.map(|(k, c)| Slide::Screen { i, id, notes: c.to_vec(), part: (n > 1).then_some((k + 1, n)), states })
.collect()
}
/// `s` cut to `n` characters, with an ellipsis when cut.
fn clip(s: &str, n: usize) -> String {
if s.chars().count() <= n {
return s.to_owned();
}
format!("{}\u{2026}", s.chars().take(n - 1).collect::<String>().trim_end())
}
/// A layer name's parts without its kind prefix: `Screen / Sessions / Empty` is
/// `[Sessions, Empty]`.
fn name_parts(name: &str) -> Vec<&str> {
let mut parts: Vec<&str> = name.split(" / ").collect();
if parts.len() > 1 && KIND_PREFIXES.contains(&parts[0]) {
parts.remove(0);
}
parts
}
/// A layer name as a slide title: `Screen / Sessions / Empty` reads `Sessions · Empty`.
fn clean(name: &str) -> String {
name_parts(name).join(" \u{b7} ")
}
fn name_of(doc: &Document, id: NodeId) -> &str {
doc.get(id).map_or("", |n| n.name.as_str())
}
/// The slides of one page in reading order, and its slides for the appendix. A screen whose
/// name has states (`Sessions / List`, `Sessions / Empty`) is shown once, its other states in
/// the appendix; narrow panels share rows; boards are shown by their cards; tall screens in parts.
fn section_slides(i: usize, s: &Section) -> (Vec<Slide>, Vec<Slide>) {
enum Item {
Done(Slide),
States(usize),
}
let doc = s.doc;
let mut items = Vec::new();
let mut groups: Vec<(String, Vec<NodeId>)> = Vec::new();
let mut panels = Vec::new();
let flush = |panels: &mut Vec<NodeId>, items: &mut Vec<Item>| {
if panels.is_empty() {
return;
}
let mut heads: Vec<&str> = Vec::new();
for id in panels.iter() {
let head = name_parts(name_of(doc, *id))[0];
if !heads.contains(&head) {
heads.push(head);
}
}
items.push(Item::Done(Slide::Row(i, heads.join(" \u{b7} "), std::mem::take(panels), PANELS_PER_SLIDE)));
};
for id in &s.screens {
let Some(n) = doc.get(*id) else { continue };
if n.section {
flush(&mut panels, &mut items);
items.extend(board_slides(i, doc, *id).into_iter().map(Item::Done));
continue;
}
if let Some(parts) = tall_parts(doc, *id) {
flush(&mut panels, &mut items);
let k = parts.len();
let title = clean(&n.name);
items.extend(parts.into_iter().enumerate().map(|(j, from)| Item::Done(Slide::Crop(i, *id, format!("{title} ({}/{k})", j + 1), from))));
continue;
}
if n.rect.w < n.rect.h * NARROW {
panels.push(*id);
if panels.len() == PANELS_PER_SLIDE {
flush(&mut panels, &mut items);
}
continue;
}
flush(&mut panels, &mut items);
let parts = name_parts(&n.name);
// `Sessions / Empty` is a state of `Sessions`; a name without parts
// (`Challenges List Archived`) is grouped by its first two words.
let words: Vec<&str> = parts[0].split_whitespace().collect();
let base = if parts.len() > 1 {
parts[..parts.len() - 1].join(" \u{b7} ")
} else if words.len() > 1 {
words[..2].join(" ")
} else {
items.extend(screen_slides(i, doc, *id, 0).into_iter().map(Item::Done));
continue;
};
match groups.iter().position(|(b, _)| *b == base) {
Some(g) => groups[g].1.push(*id),
None => {
items.push(Item::States(groups.len()));
groups.push((base, vec![*id]));
}
}
}
flush(&mut panels, &mut items);
let mut slides = Vec::new();
let mut states: Vec<(&str, NodeId)> = Vec::new();
for item in items {
match item {
Item::Done(slide) => slides.push(slide),
Item::States(g) => {
let (base, ids) = &groups[g];
slides.extend(screen_slides(i, doc, ids[0], ids.len() - 1));
states.extend(ids[1..].iter().map(|id| (base.as_str(), *id)));
}
}
}
// The page's other states fill the appendix's grids in order, groups sharing slides.
let appendix = states
.chunks(APPENDIX_PER_SLIDE)
.map(|c| {
let mut bases: Vec<&str> = Vec::new();
for (b, _) in c {
if !bases.contains(b) {
bases.push(b);
}
}
let title = if bases.len() == 1 { bases[0].to_owned() } else { clip(&bases.join(", "), APPENDIX_TITLE_CHARS) };
Slide::Row(i, title, c.iter().map(|(_, id)| *id).collect(), APPENDIX_PER_SLIDE)
})
.collect();
(slides, appendix)
}
/// A board (a section without screens) on slides. One that fits at 1:1 is shown whole;
/// otherwise its cards (the children of its widest card container) are packed in order onto
/// slides at 1:1, titled by their names. A card too tall for a slide is cut at gaps.
fn board_slides(i: usize, doc: &Document, id: NodeId) -> Vec<Slide> {
let Some(b) = crate::io::svg::export_bounds(doc, &[id]) else { return Vec::new() };
if fits(b) {
return screen_slides(i, doc, id, 0);
}
let board = clean(name_of(doc, id));
let parts_of = |title: &str, r: Rect| {
let parts = cut(doc, id, r);
let k = parts.len();
parts.into_iter().enumerate().map(move |(j, from)| Slide::Crop(i, id, format!("{title} ({}/{k})", j + 1), from)).collect::<Vec<_>>()
};
let Some(cards) = cards_of(doc, id) else { return parts_of(&board, b) };
let mut slides = Vec::new();
let mut pack: Option<(Rect, Vec<String>)> = None;
for c in cards {
let Some(r) = doc.world_rect(c) else { continue };
let r = Rect::new(r.x - CARD_PAD, r.y - CARD_PAD, r.w + 2.0 * CARD_PAD, r.h + 2.0 * CARD_PAD);
let title = clean(name_of(doc, c));
let label = title.strip_prefix(&format!("{board} \u{b7} ")).map_or(title.clone(), str::to_owned);
if let Some((u, mut names)) = pack.take() {
if fits(u.union(&r)) {
names.push(label);
pack = Some((u.union(&r), names));
continue;
}
slides.push(Slide::Crop(i, id, names.join(" \u{b7} "), u));
}
if fits(r) {
pack = Some((r, vec![label]));
} else if (STAGE.w / r.w).min(STAGE.h / r.h) >= READABLE {
slides.push(Slide::Crop(i, id, label, r));
} else {
slides.extend(parts_of(&label, r));
}
}
if let Some((u, names)) = pack {
slides.push(Slide::Crop(i, id, names.join(" \u{b7} "), u));
}
slides
}
/// Whether `r` fits on a slide at the scale parts are shown at.
fn fits(r: Rect) -> bool {
r.h * part_scale(r) * PACK_MIN_SCALE <= STAGE.h
}
/// A board's cards: the children of whichever of the board and its child frames holds the
/// most frames (at least two). Text and single wrappers (a title, an intro) are not cards.
fn cards_of(doc: &Document, board: NodeId) -> Option<Vec<NodeId>> {
let frames = |id: NodeId| -> Vec<NodeId> {
doc.get(id).map_or_else(Vec::new, |n| n.children.iter().copied().filter(|c| doc.get(*c).is_some_and(|c| c.visible && c.is_frame())).collect())
};
std::iter::once(board).chain(frames(board)).map(frames).filter(|f| f.len() >= 2).max_by_key(Vec::len)
}
/// The deck as PDF bytes. Sections without screens are left out.
pub fn build(meta: &Meta, sections: &[Section]) -> Vec<u8> {
let unrolled: Vec<Option<Document>> = sections.iter().map(|s| unroll::unrolled(s.doc, &s.screens)).collect();
let sections: Vec<Section> = sections
.iter()
.zip(&unrolled)
.filter(|(s, _)| !s.screens.is_empty())
.map(|(s, u)| Section { name: s.name.clone(), doc: u.as_ref().unwrap_or(s.doc), screens: s.screens.clone() })
.collect();
let sections: Vec<&Section> = sections.iter().collect();
let mut slides = vec![Slide::Cover, Slide::Contents];
let mut starts = Vec::new();
let mut appendix = Vec::new();
let mut questions = Vec::new();
for (i, s) in sections.iter().enumerate() {
starts.push(slides.len() + 1);
slides.push(Slide::Divider(i));
let (main, extra) = section_slides(i, s);
// The big picture first: the page's screens (one per state group) at a glance.
let mut key: Vec<NodeId> = Vec::new();
for slide in &main {
if let Slide::Screen { id, .. } = slide
&& !key.contains(id)
&& s.doc.get(*id).is_some_and(|n| !n.section)
{
key.push(*id);
}
}
if key.len() >= MAP_MIN {
// Even maps: 17 screens are 9 and 8, not 12 and 5.
let per = key.len().div_ceil(key.len().div_ceil(MAP_COLS * MAP_ROWS));
slides.extend(key.chunks(per).map(|c| Slide::Map(i, c.to_vec())));
}
let mut asked = Vec::new();
for id in s.screens.iter().filter(|id| s.doc.get(**id).is_some_and(|n| !n.section)) {
for n in notes_of(s.doc, *id) {
if let Some(line) = n.question {
let q = if line == n.title { ask(&line) } else { format!("{}: {}", n.title, ask(&line)) };
asked.push((clean(name_of(s.doc, *id)), q));
}
}
}
questions.extend(asked.chunks(QUESTIONS_PER_SLIDE).map(|c| Slide::Questions(i, c.to_vec())));
slides.extend(main);
appendix.extend(extra);
}
let questions_start = (!questions.is_empty()).then(|| slides.len() + 1);
let asked: usize = questions.iter().map(|q| if let Slide::Questions(_, qs) = q { qs.len() } else { 0 }).sum();
slides.extend(questions);
slides.push(Slide::NextSteps);
let appendix_start = (!appendix.is_empty()).then(|| slides.len() + 1);
if appendix_start.is_some() {
slides.push(Slide::Appendix);
slides.extend(appendix);
}
slides.push(Slide::End);
let total = slides.len();
let screens: usize = sections.iter().map(|s| s.screens.iter().filter(|id| s.doc.get(**id).is_some_and(|n| !n.section)).count()).sum();
let w = meta.language.unwrap_or_else(|| Lang::detect(sections.iter().map(|s| s.doc))).words();
let mut ed = Editor::default();
// Each slide, and its overlay (drawn above the screens: note markers).
let mut pages: Vec<(Rect, NodeId, Option<NodeId>, Vec<Insert>)> = Vec::new();
for (k, slide) in slides.iter().enumerate() {
let r = Rect::new(0.0, k as f64 * (H + SLIDE_GAP), W, H);
let mut frame = Node::new(NodeId(0), NodeKind::Frame { clip: true }, r);
frame.style.set_fill(Some(BG));
let f = ed.add_node(frame, None);
let mut inserts = Vec::new();
let mut overlay = None;
match slide {
Slide::Cover => {
t(&mut ed, f, w.presentation, 22.0, true, ACCENT, v2(MARGIN, 330.0));
text(&mut ed, f, &meta.title, 88.0, true, INK, v2(MARGIN, 372.0), Some((800.0, TextAlign::Left)));
let sub = meta.subtitle.clone().unwrap_or_else(|| format!("{} \u{b7} {}", w.count(screens, Noun::Screen), w.count(sections.len(), Noun::Page)));
text(&mut ed, f, &sub, 30.0, false, MUTED, v2(MARGIN, 520.0), Some((800.0, TextAlign::Left)));
let by = match &meta.author {
Some(a) => format!("{} \u{b7} {a}", w.date(meta.now_ms)),
None => w.date(meta.now_ms),
};
text(&mut ed, f, &by, 22.0, false, MUTED, v2(MARGIN, H - MARGIN - 30.0), None);
// The hero: the largest regular screen of the deck (the first of equals).
let hero = sections
.iter()
.flat_map(|s| s.screens.iter().filter_map(|id| Some((s.doc, *id, s.doc.world_rect(*id)?))))
.filter(|(doc, id, b)| b.w >= b.h * NARROW && doc.get(*id).is_some_and(|n| !n.section))
.fold(None::<(&Document, NodeId, Rect)>, |best, c| match best {
Some(b) if b.2.w * b.2.h >= c.2.w * c.2.h => Some(b),
_ => Some(c),
})
.map(|(doc, id, _)| (doc, id));
if let Some((doc, id)) = hero {
inserts.extend(place(&mut ed, f, doc, id, None, Rect::new(960.0, 140.0, W - 960.0 - MARGIN + 40.0, H - 280.0), r));
}
}
Slide::Contents => {
t(&mut ed, f, w.contents, 56.0, true, INK, v2(MARGIN, MARGIN));
for (i, s) in sections.iter().enumerate() {
let y = 230.0 + i as f64 * 64.0;
t(&mut ed, f, &format!("{:02}", i + 1), 28.0, true, ACCENT, v2(MARGIN, y));
t(&mut ed, f, &s.name, 28.0, false, INK, v2(MARGIN + 84.0, y));
t(&mut ed, f, &tally(w, s), 22.0, false, MUTED, v2(1200.0, y + 4.0));
text(&mut ed, f, &starts[i].to_string(), 22.0, false, MUTED, v2(W - MARGIN - 200.0, y + 4.0), Some((200.0, TextAlign::Right)));
}
let extras = [("?", w.open_questions, questions_start), ("A", w.appendix_states, appendix_start)];
for (j, (mark, name, start)) in extras.iter().filter_map(|(m, n, s)| Some((*m, *n, (*s)?))).enumerate() {
let y = 230.0 + (sections.len() + j) as f64 * 64.0;
t(&mut ed, f, mark, 28.0, true, ACCENT, v2(MARGIN, y));
t(&mut ed, f, name, 28.0, false, INK, v2(MARGIN + 84.0, y));
text(&mut ed, f, &start.to_string(), 22.0, false, MUTED, v2(W - MARGIN - 200.0, y + 4.0), Some((200.0, TextAlign::Right)));
}
}
Slide::Map(i, ids) => {
let s = sections[*i];
t(&mut ed, f, &s.name.to_uppercase(), 20.0, true, ACCENT, v2(MARGIN, 64.0));
t(&mut ed, f, w.at_a_glance, 44.0, true, INK, v2(MARGIN, 96.0));
const GAP: f64 = 32.0;
let cw = (STAGE.w - GAP * (MAP_COLS - 1) as f64) / MAP_COLS as f64;
let ch = (STAGE.h - GAP * (MAP_ROWS - 1) as f64) / MAP_ROWS as f64;
for (j, id) in ids.iter().enumerate() {
let (cx, cy) = ((j % MAP_COLS) as f64, (j / MAP_COLS) as f64);
let cell = Rect::new(STAGE.x + cx * (cw + GAP), STAGE.y + cy * (ch + GAP), cw, ch - CAPTION_H + 12.0);
let placed = place(&mut ed, f, s.doc, *id, None, cell, r);
let under = placed.as_ref().map_or(cell.bottom(), |p| p.to.bottom() - r.y);
text(&mut ed, f, &clip(&clean(name_of(s.doc, *id)), 48), 16.0, false, MUTED, v2(cell.x, under + 8.0), Some((cw, TextAlign::Center)));
inserts.extend(placed);
}
}
Slide::Questions(i, qs) => {
t(&mut ed, f, &sections[*i].name.to_uppercase(), 20.0, true, ACCENT, v2(MARGIN, 64.0));
t(&mut ed, f, w.open_questions, 44.0, true, INK, v2(MARGIN, 96.0));
let slot = STAGE.h / QUESTIONS_PER_SLIDE as f64;
for (j, (screen, q)) in qs.iter().enumerate() {
let y = STAGE.y + j as f64 * slot;
t(&mut ed, f, "?", 28.0, true, ACCENT, v2(MARGIN, y));
text(&mut ed, f, &clip(q, 150), 22.0, false, INK, v2(MARGIN + 56.0, y), Some((STAGE.w - 56.0, TextAlign::Left)));
t(&mut ed, f, screen, 16.0, false, MUTED, v2(MARGIN + 56.0, y + 40.0));
}
}
Slide::NextSteps => {
t(&mut ed, f, w.next_steps, 56.0, true, INK, v2(MARGIN, MARGIN));
let boards: usize = sections.iter().map(|s| s.screens.len()).sum::<usize>() - screens;
let mut steps = Vec::new();
if let Some(q) = questions_start {
steps.push((fill(w.answer, &[&w.count(asked, Noun::OpenQuestion)]), fill(w.answer_detail, &[&q.to_string()])));
}
let reviewed = if boards == 0 {
w.count(screens, Noun::Screen)
} else {
fill(w.and, &[&w.count(screens, Noun::Screen), &w.count(boards, Noun::Board)])
};
steps.push((fill(w.review, &[&reviewed]), w.review_detail.to_owned()));
if let Some(a) = appendix_start {
steps.push((w.check_states.to_owned(), fill(w.check_states_detail, &[&a.to_string()])));
}
if let Some(a) = &meta.author {
steps.push((w.send_feedback.to_owned(), fill(w.to, &[a])));
}
for (j, (step, detail)) in steps.iter().enumerate() {
let y = 260.0 + j as f64 * 130.0;
t(&mut ed, f, &format!("{:02}", j + 1), 32.0, true, ACCENT, v2(MARGIN, y));
t(&mut ed, f, step, 32.0, true, INK, v2(MARGIN + 96.0, y));
t(&mut ed, f, detail, 22.0, false, MUTED, v2(MARGIN + 96.0, y + 50.0));
}
}
Slide::Appendix => {
t(&mut ed, f, "A", 160.0, true, ACCENT, v2(MARGIN, 300.0));
t(&mut ed, f, w.appendix, 80.0, true, INK, v2(MARGIN, 500.0));
t(&mut ed, f, w.other_states, 28.0, false, MUTED, v2(MARGIN, 620.0));
}
Slide::Divider(i) => {
let s = sections[*i];
t(&mut ed, f, &format!("{:02}", i + 1), 160.0, true, ACCENT, v2(MARGIN, 300.0));
text(&mut ed, f, &s.name, 80.0, true, INK, v2(MARGIN, 500.0), Some((W - 2.0 * MARGIN, TextAlign::Left)));
t(&mut ed, f, &tally(w, s), 28.0, false, MUTED, v2(MARGIN, 620.0));
}
Slide::Screen { i, id, notes, part, states } => {
let s = sections[*i];
kicker(&mut ed, f, s, *id);
let mut title = clean(name_of(s.doc, *id));
if let Some((k, n)) = part {
title = format!("{title} ({})", fill(w.notes, &[&k.to_string(), &n.to_string()]));
}
t(&mut ed, f, &title, 44.0, true, INK, v2(MARGIN, 96.0));
let mut aside = Vec::new();
if *states > 0 {
aside.push(fill(w.in_appendix, &[&w.count(*states, Noun::State)]));
}
if let Some(b) = s.doc.world_rect(*id) {
aside.push(format!("{} \u{d7} {}", b.w.round(), b.h.round()));
}
text(&mut ed, f, &aside.join(" \u{b7} "), 22.0, false, MUTED, v2(W - MARGIN - 700.0, 116.0), Some((700.0, TextAlign::Right)));
if notes.is_empty() {
inserts.extend(place(&mut ed, f, s.doc, *id, None, STAGE, r));
} else {
let area = Rect::new(STAGE.x, STAGE.y, STAGE.w * NOTED_SCREEN, STAGE.h);
let placed = place(&mut ed, f, s.doc, *id, None, area, r);
let mut ov = Node::new(NodeId(0), NodeKind::Frame { clip: false }, r);
ov.style.set_fill(None);
let ov = ed.add_node(ov, None);
if let Some(p) = &placed {
let sc = p.to.w / p.from.w;
let to = p.to.translate(v2(0.0, -r.y));
for (num, note) in notes {
let Some(tr) = s.doc.world_rect(note.target) else { continue };
// Centred on the layer's top-left corner, so it points without hiding it.
let x = (to.x + (tr.x - p.from.x) * sc - MARKER / 2.0).clamp(to.x - MARKER / 2.0, to.right() - MARKER / 2.0);
let y = (to.y + (tr.y - p.from.y) * sc - MARKER / 2.0).clamp(to.y - MARKER / 2.0, to.bottom() - MARKER / 2.0);
marker(&mut ed, ov, *num, note.color, v2(x, y));
}
}
inserts.extend(placed);
overlay = Some(ov);
let col_x = area.right() + 56.0;
let col_w = W - MARGIN - col_x;
let slot = STAGE.h / NOTES_PER_SLIDE as f64;
for (j, (num, note)) in notes.iter().enumerate() {
let y = STAGE.y + j as f64 * slot;
marker(&mut ed, f, *num, note.color, v2(col_x, y));
let tx = col_x + MARKER + 14.0;
let title = clip(&note.title, NOTE_TITLE_CHARS);
// The body sits under the title's one or two lines.
let title_lines = if title.chars().count() > NOTE_TITLE_LINE_CHARS { 2.0 } else { 1.0 };
text(&mut ed, f, &title, 20.0, true, INK, v2(tx, y + 2.0), Some((col_w - MARKER - 14.0, TextAlign::Left)));
text(&mut ed, f, &clip(&note.body, NOTE_BODY_CHARS), 16.0, false, MUTED, v2(tx, y + 10.0 + title_lines * 26.0), Some((col_w - MARKER - 14.0, TextAlign::Left)));
}
}
}
Slide::Row(i, title, ids, per) => {
let s = sections[*i];
kicker(&mut ed, f, s, ids[0]);
t(&mut ed, f, title, 44.0, true, INK, v2(MARGIN, 96.0));
// An appendix grid sized by what is on it: a last slide of two is not a grid of six.
let (cols, rows) = if *per == APPENDIX_PER_SLIDE {
let cols = ids.len().min(APPENDIX_COLS);
(cols, ids.len().div_ceil(cols))
} else {
(*per, 1)
};
let cw = (STAGE.w - PANEL_GAP * (cols - 1) as f64) / cols as f64;
let ch = (STAGE.h - PANEL_GAP * (rows - 1) as f64) / rows as f64;
let across = ids.len().min(cols);
let used = cw * across as f64 + PANEL_GAP * (across - 1) as f64;
let x0 = STAGE.x + (STAGE.w - used) / 2.0;
for (j, id) in ids.iter().enumerate() {
let (cx, cy) = ((j % cols) as f64, (j / cols) as f64);
let col = Rect::new(x0 + cx * (cw + PANEL_GAP), STAGE.y + cy * (ch + PANEL_GAP), cw, ch - CAPTION_H);
let placed = place(&mut ed, f, s.doc, *id, None, col, r);
let under = placed.as_ref().map_or(col.bottom(), |p| p.to.bottom() - r.y);
// A state reads by what differs: `Empty` under a `Sessions` title.
let name = clean(name_of(s.doc, *id));
let caption = name.strip_prefix(&format!("{title} \u{b7} ")).or_else(|| name.strip_prefix(&format!("{title} "))).unwrap_or(&name);
text(&mut ed, f, caption, 18.0, false, MUTED, v2(col.x, under + 14.0), Some((cw, TextAlign::Center)));
inserts.extend(placed);
}
}
Slide::Crop(i, id, title, from) => {
let s = sections[*i];
kicker(&mut ed, f, s, *id);
t(&mut ed, f, title, 44.0, true, INK, v2(MARGIN, 96.0));
// Top-aligned at the scale of the other parts, however short this one is.
let area = Rect::new(STAGE.x, STAGE.y, STAGE.w, (from.h * part_scale(*from)).min(STAGE.h));
inserts.extend(place(&mut ed, f, s.doc, *id, Some(*from), area, r));
}
Slide::End => {
t(&mut ed, f, w.thank_you, 96.0, true, INK, v2(MARGIN, 380.0));
t(&mut ed, f, &meta.title, 30.0, false, MUTED, v2(MARGIN, 520.0));
t(&mut ed, f, &format!("{} \u{b7} {}", w.count(screens, Noun::Screen), w.date(meta.now_ms)), 22.0, false, MUTED, v2(MARGIN, 570.0));
}
}
if k > 0 {
text(&mut ed, f, &meta.title, 18.0, false, MUTED, v2(MARGIN, H - 64.0), None);
text(&mut ed, f, &format!("{} / {total}", k + 1), 18.0, false, MUTED, v2(W - MARGIN - 200.0, H - 64.0), Some((200.0, TextAlign::Right)));
}
pages.push((r, f, overlay, inserts));
}
let doc = &ed.doc;
let pdf_pages: Vec<PdfPage> = pages
.into_iter()
.map(|(r, f, overlay, mut inserts)| {
inserts.extend(overlay.map(|ov| Insert { doc, roots: vec![ov], from: r, to: r }));
PdfPage { doc, roots: vec![f], bounds: r, background: Some(BG), inserts }
})
.collect();
super::pdf::export(&pdf_pages)
}
/// [`text`] that sizes to its content.
fn t(ed: &mut Editor, f: NodeId, s: &str, size: f64, bold: bool, color: Color, at: V2) -> NodeId {
text(ed, f, s, size, bold, color, at, None)
}
/// A text layer on slide `f` at `at` (slide units). `width` fixes the box (wrapping, aligned).
#[allow(clippy::too_many_arguments)]
fn text(ed: &mut Editor, f: NodeId, s: &str, size: f64, bold: bool, color: Color, at: V2, width: Option<(f64, TextAlign)>) -> NodeId {
let (w, align) = width.unwrap_or((1.0, TextAlign::Left));
let mut n = Node::new(NodeId(0), NodeKind::Text { text: s.into(), font_size: size, auto_width: width.is_none(), align }, Rect::new(at.x, at.y, w, 1.0));
n.style.set_fill(Some(color));
n.text_style.bold = bold;
ed.add_node(n, Some(f))
}
/// The source rects of a screen too tall to read fitted on one slide, top to bottom; None for
/// one that fits.
fn tall_parts(doc: &Document, id: NodeId) -> Option<Vec<Rect>> {
let b = crate::io::svg::export_bounds(doc, &[id])?;
if b.w < MIN_SPLIT_W || (STAGE.w / b.w).min(STAGE.h / b.h) >= READABLE {
return None;
}
Some(cut(doc, id, b))
}
/// `b` (an area of layer `id`) cut top to bottom into parts of about a slide each. Each part
/// ends at the lowest line within a slide's reach that crosses no block small enough to fit
/// on a slide (a card, a row), so blocks are not split between slides.
fn cut(doc: &Document, id: NodeId, b: Rect) -> Vec<Rect> {
/// A part is at least this share of a slide, else it is cut through a block.
const MIN_PART: f64 = 0.4;
let rects: Vec<Rect> = super::export::with_layers_on_top(doc, &[id])
.iter()
.flat_map(|r| doc.subtree(*r))
.filter_map(|d| doc.world_rect(d))
.filter(|r| r.h > 0.0 && r.intersects(&b) && r.h < b.h)
.collect();
let step = STAGE.h / part_scale(b);
// How far a part may run, shown smaller (down to CUT_MIN_SCALE), to end in a gap.
let reach = step / CUT_MIN_SCALE;
let blocks: Vec<(f64, f64)> = rects.iter().filter(|r| r.h <= reach).map(|r| (r.y, r.bottom())).collect();
let crosses = |y: f64| blocks.iter().any(|(top, bottom)| *top < y && y < *bottom);
let mut parts = Vec::new();
let mut top = b.y;
// What is left fits on one last slide, shown a little smaller.
while b.bottom() - top > reach {
let gaps: Vec<f64> = blocks.iter().map(|(_, bottom)| *bottom).filter(|y| *y > top + step * MIN_PART && !crosses(*y)).collect();
// The lowest gap within a slide; else the nearest one within reach; else cut at a slide.
let y = gaps
.iter()
.copied()
.filter(|y| *y <= top + step)
.reduce(f64::max)
.or_else(|| gaps.iter().copied().filter(|y| *y <= top + reach).reduce(f64::min))
.unwrap_or(top + step);
parts.push(Rect::new(b.x, top, b.w, y - top));
top = y;
}
parts.push(Rect::new(b.x, top, b.w, b.bottom() - top));
parts
}
/// A numbered note marker on `f` with its top-left at `at` (slide units).
fn marker(ed: &mut Editor, f: NodeId, num: usize, color: Color, at: V2) {
let mut dot = Node::new(NodeId(0), NodeKind::Ellipse, Rect::new(at.x, at.y, MARKER, MARKER));
dot.style.set_fill(Some(color));
ed.add_node(dot, Some(f));
text(ed, f, &num.to_string(), 15.0, true, Color { r: 255, g: 255, b: 255, a: 255 }, v2(at.x, at.y + 5.0), Some((MARKER, TextAlign::Center)));
}
/// The page name over a slide's title, and the board's for a board's cards.
fn kicker(ed: &mut Editor, f: NodeId, s: &Section, id: NodeId) {
let mut k = s.name.to_uppercase();
if s.doc.get(id).is_some_and(|n| n.section) {
k = format!("{k} \u{b7} {}", clean(name_of(s.doc, id)).to_uppercase());
}
t(ed, f, &k, 20.0, true, ACCENT, v2(MARGIN, 64.0));
}
/// The scale every part of a tall board is shown at: the stage's width, at most 1:1.
fn part_scale(board: Rect) -> f64 {
(STAGE.w / board.w).min(1.0)
}
/// Screen `id` (or the `crop` of it) fitted into `area` (slide units) on a hairline card;
/// `slide` is the slide's rect in the generated document. None when the screen has no area.
fn place<'d>(ed: &mut Editor, f: NodeId, doc: &'d Document, id: NodeId, crop: Option<Rect>, area: Rect, slide: Rect) -> Option<Insert<'d>> {
let from = crop.or_else(|| crate::io::svg::export_bounds(doc, &[id]))?;
let s = (area.w / from.w).min(area.h / from.h);
let (w, h) = (from.w * s, from.h * s);
let to = Rect::new(area.x + (area.w - w) / 2.0, area.y + (area.h - h) / 2.0, w, h);
let mut card = Node::new(NodeId(0), NodeKind::Rect, Rect::new(to.x - CARD_EDGE_W, to.y - CARD_EDGE_W, w + 2.0 * CARD_EDGE_W, h + 2.0 * CARD_EDGE_W));
card.style.set_fill(Some(CARD_EDGE));
ed.add_node(card, Some(f));
Some(Insert {
doc,
roots: super::export::with_layers_on_top(doc, &[id]),
from,
to: to.translate(v2(slide.x, slide.y)),
})
}
/// A question line without the team markers the notes use: `Days ? (team)` is `Days?`, and
/// `(? team: limit)` is `(limit?)`.
fn ask(line: &str) -> String {
const ASK: &str = "(? team: ";
let mut s = line.to_owned();
while let Some(a) = s.find(ASK) {
let Some(b) = s[a..].find(')') else { break };
let topic = s[a + ASK.len()..a + b].to_owned();
s.replace_range(a..=a + b, &format!("({topic}?)"));
}
let s = s.replace("(? team)", "").replace("? (team)", "?").replace(": ?", "?").replace(" ?", "?").replace("??", "?");
let s = s.trim();
if s.contains('?') { s.to_owned() } else { format!("{s}?") }
}
#[cfg(test)]
mod tests;
+182
View File
@@ -0,0 +1,182 @@
use super::*;
use crate::editor::screens::Role;
fn named(ed: &mut Editor, name: &str, r: Rect, parent: Option<NodeId>) -> NodeId {
let mut n = Node::new(NodeId(0), NodeKind::Frame { clip: true }, r);
n.name = name.into();
ed.add_node(n, parent)
}
#[test]
fn titles_drop_the_kind_and_states_follow_their_screen() {
assert_eq!(clean("Screen / Sessions / Empty"), "Sessions \u{b7} Empty");
assert_eq!(clean("Section"), "Section");
let mut ed = Editor::default();
let list = named(&mut ed, "Screen / Sessions / List", Rect::new(0.0, 0.0, 1440.0, 900.0), None);
let home = named(&mut ed, "Screen / Home", Rect::new(2000.0, 0.0, 1440.0, 900.0), None);
let states: Vec<NodeId> = ["Empty", "Loading", "Error", "Offline"]
.iter()
.enumerate()
.map(|(k, st)| named(&mut ed, &format!("Screen / Sessions / {st}"), Rect::new(k as f64 * 2000.0, 1200.0, 1440.0, 900.0), None))
.collect();
let s = Section { name: "Admin".into(), doc: &ed.doc, screens: screens_of(&ed.doc) };
let (slides, appendix) = section_slides(0, &s);
let shape = |slides: &[Slide]| -> Vec<String> {
slides
.iter()
.map(|sl| match sl {
Slide::Screen { id, states, .. } => format!("screen {} +{states}", name_of(&ed.doc, *id)),
Slide::Row(_, title, ids, _) => format!("row {title} {}", ids.len()),
_ => "other".into(),
})
.collect()
};
assert_eq!(shape(&slides), ["screen Screen / Sessions / List +4", "screen Screen / Home +0"]);
assert_eq!(shape(&appendix), ["row Sessions 4"], "the other states wait in the appendix");
assert!(matches!(&appendix[0], Slide::Row(_, _, ids, _) if ids[0] == states[0]) && list != home);
}
#[test]
fn notes_on_a_screen_number_its_layers_and_continue_on_a_second_slide() {
use crate::model::annotation::Annotation;
let mut ed = Editor::default();
let screen = named(&mut ed, "Screen / Sessions", Rect::new(0.0, 0.0, 1440.0, 900.0), None);
let rows: Vec<NodeId> = (0..10).map(|k| named(&mut ed, "Row", Rect::new(0.0, 820.0 - k as f64 * 90.0, 1440.0, 80.0), Some(screen))).collect();
let other = named(&mut ed, "Screen / Elsewhere", Rect::new(2000.0, 0.0, 1440.0, 900.0), None);
for (k, row) in rows.iter().enumerate() {
ed.doc.annotations.push(Annotation::new(Some(*row), &format!("Rule {k}"), "data"));
}
ed.doc.annotations.push(Annotation::new(Some(other), "Not here", "rule"));
let mut gone = Annotation::new(Some(rows[0]), "Detached", "rule");
gone.detached = true;
ed.doc.annotations.push(gone);
let notes = notes_of(&ed.doc, screen);
assert_eq!(notes.len(), 10, "this screen's attached notes only");
assert_eq!(notes[0].title, "Rule 9", "top to bottom");
let slides = screen_slides(0, &ed.doc, screen, 0);
assert_eq!(slides.len(), 2);
assert!(matches!(&slides[1], Slide::Screen { notes, part: Some((2, 2)), .. } if notes[0].0 == 9));
let pdf = build(&Meta { title: "T".into(), subtitle: None, author: None, now_ms: 0, language: None }, &[Section { name: "P".into(), doc: &ed.doc, screens: vec![screen] }]);
assert!(String::from_utf8_lossy(&pdf).contains("/Count 7"), "cover, contents, divider, 2 note slides, next steps, end");
}
#[test]
fn a_page_opens_with_a_map_and_the_deck_closes_on_its_questions() {
use crate::model::annotation::Annotation;
let mut ed = Editor::default();
let a = named(&mut ed, "Screen / Home", Rect::new(0.0, 0.0, 1440.0, 900.0), None);
let b = named(&mut ed, "Screen / Settings", Rect::new(2000.0, 0.0, 1440.0, 900.0), None);
ed.doc.annotations.push(Annotation::new(Some(b), "Who can change the plan?", "rule"));
let pdf = build(&Meta { title: "T".into(), subtitle: None, author: None, now_ms: 0, language: None }, &[Section { name: "P".into(), doc: &ed.doc, screens: vec![a, b] }]);
// Cover, contents, divider, map, Home, Settings (noted), open questions, end.
assert!(String::from_utf8_lossy(&pdf).contains("/Count 8"));
}
#[test]
fn a_tall_card_is_cut_between_its_cells_not_through_them() {
let mut ed = Editor::default();
let card = named(&mut ed, "Group / App shell", Rect::new(0.0, 0.0, 1376.0, 2900.0), None);
for row in 0..3 {
for col in 0..5 {
named(&mut ed, "Cell", Rect::new(col as f64 * 270.0, 20.0 + row as f64 * 960.0, 248.0, 924.0), Some(card));
}
}
let parts = cut(&ed.doc, card, ed.doc.world_rect(card).unwrap());
assert_eq!(parts.len(), 3, "a row of cells to a slide, shown a little smaller");
assert!(parts.iter().all(|p| (0..3).any(|row| (p.bottom() - (944.0 + row as f64 * 960.0)).abs() < 40.0 || p.bottom() == 2900.0)), "{parts:?}");
}
#[test]
fn a_tall_board_is_shown_by_its_cards() {
let mut ed = Editor::default();
let board = named(&mut ed, "Section / Colors", Rect::new(0.0, 0.0, 1440.0, 2000.0), None);
named(&mut ed, "Section Intro", Rect::new(32.0, 32.0, 1376.0, 40.0), Some(board));
let groups = named(&mut ed, "Groups", Rect::new(32.0, 100.0, 1376.0, 1880.0), Some(board));
for (k, h) in [300.0, 300.0, 1700.0].iter().enumerate() {
named(&mut ed, &format!("Colors / Card {k}"), Rect::new(0.0, k as f64 * 340.0, 1376.0, *h), Some(groups));
}
ed.set_role(&[board], Role::Section).unwrap();
let titles: Vec<String> = board_slides(0, &ed.doc, board)
.iter()
.map(|sl| match sl {
Slide::Crop(_, _, title, _) => title.clone(),
_ => "other".into(),
})
.collect();
assert_eq!(titles[0], "Card 0 \u{b7} Card 1", "small cards share a slide, named without the board");
assert!(titles[1..].iter().all(|t| t.starts_with("Card 2 (")), "{titles:?}");
}
#[test]
fn questions_drop_the_team_markers() {
assert_eq!(ask("Days ? (team)"), "Days?");
assert_eq!(ask("Other roles (Interviewer): ? (team)"), "Other roles (Interviewer)?");
assert_eq!(ask("Editable? ? (team)"), "Editable?");
assert_eq!(ask("Lock after 5 (? team: limit)"), "Lock after 5 (limit?)");
assert_eq!(ask("Hiring panel only (? team)"), "Hiring panel only?");
}
#[test]
fn dates_read_as_days() {
assert_eq!(Lang::En.words().date(0), "1 January 1970");
assert_eq!(Lang::En.words().date(1_793_145_600_000), "28 October 2026");
assert_eq!(Lang::Pt.words().date(1_793_145_600_000), "28 de outubro de 2026");
}
#[test]
fn the_deck_speaks_the_language_its_screens_are_written_in() {
let mut ed = Editor::default();
let screen = ed.add_node(Node::new(NodeId(0), NodeKind::Frame { clip: true }, Rect::new(0.0, 0.0, 390.0, 844.0)), None);
let text = |t: &str| Node::new(NodeId(0), NodeKind::Text { text: t.into(), font_size: 16.0, auto_width: true, align: Default::default() }, Rect::new(0.0, 0.0, 200.0, 20.0));
ed.add_node(text("Distribuição de alimentos para a sua comunidade"), Some(screen));
assert_eq!(Lang::detect([&ed.doc]), Lang::Pt);
assert_eq!(Lang::detect([&Editor::default().doc]), Lang::En, "nothing to go by");
// The deck's words are real text: the font's ToUnicode map lists what it drew.
let drawn = |language| {
let pdf = build(&Meta { title: "T".into(), subtitle: None, author: None, now_ms: 0, language }, &[Section { name: "P".into(), doc: &ed.doc, screens: vec![screen] }]);
pdf.windows(7)
.enumerate()
.filter(|(_, w)| *w == b"stream\n")
.filter_map(|(at, _)| miniz_oxide::inflate::decompress_to_vec_zlib(&pdf[at + 7..]).ok())
.map(|s| String::from_utf8_lossy(&s).into_owned())
.collect::<String>()
};
// Capitals the screen does not use: the cover's "APRESENTAÇÃO" and "PRÄSENTATION".
assert!(drawn(None).contains("<00C7>"), "the detected Portuguese");
assert!(!drawn(Some(Lang::En)).contains("<00C7>"), "English when asked for");
assert!(drawn(Some(Lang::De)).contains("<00C4>"), "German when asked for");
}
#[test]
fn deck_has_cover_contents_divider_screens_panels_and_end() {
let mut ed = Editor::default();
let mut frame = |r: Rect| ed.add_node(Node::new(NodeId(0), NodeKind::Frame { clip: true }, r), None);
let wide = frame(Rect::new(0.0, 0.0, 1440.0, 900.0));
let panels: Vec<NodeId> = (0..6).map(|i| frame(Rect::new(2000.0 + i as f64 * 400.0, 0.0, 344.0, 1440.0))).collect();
frame(Rect::new(0.0, 2000.0, 80.0, 40.0)); // a component part, not a screen
let main = frame(Rect::new(0.0, 2500.0, 400.0, 400.0));
let board = frame(Rect::new(0.0, 3000.0, 1440.0, 200.0));
ed.doc.nodes.get_mut(&main).unwrap().component = true; // a component main, not a screen
let screens = screens_of(&ed.doc);
assert_eq!(screens.len(), 7);
assert_eq!(screens[0], wide);
ed.set_role(&[board], Role::Section).unwrap();
assert_eq!(screens_of(&ed.doc).last(), Some(&board), "a section is shown whole, whatever its size");
let long = ed.add_node(Node::new(NodeId(0), NodeKind::Frame { clip: true }, Rect::new(0.0, 4000.0, 1440.0, 3000.0)), None);
for k in 0..4 {
let card = Node::new(NodeId(0), NodeKind::Frame { clip: true }, Rect::new(0.0, k as f64 * 720.0, 1440.0, 700.0));
ed.add_node(card, Some(long));
}
let parts = tall_parts(&ed.doc, long).unwrap();
let cuts: Vec<f64> = parts.iter().map(|p| p.bottom()).collect();
assert_eq!(cuts, vec![4700.0, 5420.0, 6140.0, 7000.0], "cut in the gaps between cards, not through them");
assert!(tall_parts(&ed.doc, wide).is_none() && tall_parts(&ed.doc, panels[0]).is_none());
ed.set_role(&[wide], Role::Screen).unwrap();
assert_eq!(screens_of(&ed.doc), vec![wide, board], "a section without screens is shown beside declared screens");
ed.set_role(&[wide, board], Role::None).unwrap();
let meta = Meta { title: "Deck".into(), subtitle: None, author: None, now_ms: 0, language: None };
let pdf = build(&meta, &[Section { name: "Page".into(), doc: &ed.doc, screens }]);
// Cover, contents, divider (no map for one key screen), the wide screen, 5 + 1 panels,
// next steps, end.
assert!(String::from_utf8_lossy(&pdf).contains("/Count 8"), "{} panels", panels.len());
}
+109
View File
@@ -0,0 +1,109 @@
//! Scrolling screens unrolled for print: paper cannot scroll, so each frame whose content
//! scrolls grows to show all of it and its screen grows with it, like a full-page capture.
//! Parts pinned to the bottom (a tab bar) follow the new bottom; what sits below a grown
//! screen on the canvas moves down so it stays clear of it.
use crate::editor::{Editor, scroll_range};
use crate::layout::resize_children;
use crate::model::{Constraint, Document, NodeId};
/// How close to the bottom edge a pinned bar sits.
const FLUSH: f64 = 1.0;
/// `doc` with the `screens` unrolled; None when none of them scrolls.
pub(crate) fn unrolled(doc: &Document, screens: &[NodeId]) -> Option<Document> {
let scrolls = |doc: &Document, s: NodeId| -> Vec<NodeId> {
let mut ids = doc.subtree(s);
// Innermost first: unrolling one grows its ancestors, not what is inside it.
ids.reverse();
ids.retain(|id| doc.get(*id).is_some_and(|n| n.scroll && n.visible) && scroll_range(doc, *id) > 0.0);
ids
};
if screens.iter().all(|s| scrolls(doc, *s).is_empty()) {
return None;
}
let mut ed = Editor::default();
ed.doc = doc.clone();
let mut order = screens.to_vec();
order.sort_by(|a, b| doc.get(*a).map(|n| n.rect.y).partial_cmp(&doc.get(*b).map(|n| n.rect.y)).unwrap_or(std::cmp::Ordering::Equal));
ed.edit("Unroll scrolling screens", |tx| {
for s in order {
let Some(before) = tx.doc().world_rect(s) else { continue };
for f in scrolls(tx.doc(), s) {
let grow = scroll_range(tx.doc(), f);
let Some(n) = tx.node_mut(f) else { continue };
n.scroll = false;
n.scroll_y = 0.0;
let mut cur = Some(f);
while let Some(id) = cur {
// A bar flush with the bottom edge is meant to stay there, however it is
// positioned (`top: 756px` on an 844 px screen).
let h = tx.doc().get(id).map_or(0.0, |n| n.rect.h);
let pinned: Vec<NodeId> = tx
.doc()
.get(id)
.map(|n| n.children.clone())
.unwrap_or_default()
.into_iter()
.filter(|k| tx.doc().get(*k).is_some_and(|c| c.layout_child.absolute && (c.rect.bottom() - h).abs() < FLUSH))
.collect();
for k in pinned {
if let Some(c) = tx.node_mut(k) {
c.layout_child.constraints.v = Constraint::Max;
}
}
let Some(n) = tx.node_mut(id) else { break };
let old = n.rect;
n.rect.h += grow;
let (new, parent) = (n.rect, n.parent);
resize_children(tx, id, old, new);
cur = parent.filter(|_| id != s);
}
}
let Some(after) = tx.doc().world_rect(s) else { continue };
let grew = after.h - before.h;
let below: Vec<NodeId> = tx
.doc()
.root
.iter()
.copied()
.filter(|id| *id != s && tx.doc().get(*id).is_some_and(|n| n.rect.y >= before.bottom() && n.rect.x < before.right() && n.rect.right() > before.x))
.collect();
for id in below {
if let Some(n) = tx.node_mut(id) {
n.rect.y += grew;
}
}
}
});
Some(ed.doc)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geom::Rect;
use crate::model::{Node, NodeKind};
#[test]
fn a_scrolling_screen_shows_all_its_content_with_its_tab_bar_at_the_bottom() {
let mut ed = Editor::default();
let frame = |r: Rect| Node::new(NodeId(0), NodeKind::Frame { clip: true }, r);
let screen = ed.add_node(frame(Rect::new(0.0, 0.0, 390.0, 844.0)), None);
ed.doc.nodes.get_mut(&screen).unwrap().scroll = true;
ed.add_node(frame(Rect::new(0.0, 0.0, 390.0, 1500.0)), Some(screen));
let mut bar = frame(Rect::new(0.0, 764.0, 390.0, 80.0));
bar.layout_child.absolute = true;
let bar = ed.add_node(bar, Some(screen));
let below = ed.add_node(frame(Rect::new(0.0, 1484.0, 390.0, 844.0)), None);
let beside = ed.add_node(frame(Rect::new(1000.0, 1484.0, 390.0, 844.0)), None);
assert!(unrolled(&ed.doc, &[below]).is_none(), "nothing scrolls");
let doc = unrolled(&ed.doc, &[screen, below]).unwrap();
let rect = |id| doc.get(id).unwrap().rect;
assert_eq!(rect(screen).h, 1500.0);
assert!(!doc.get(screen).unwrap().scroll);
assert_eq!(rect(bar).bottom(), 1500.0, "pinned to the new bottom");
assert_eq!(rect(below).y, 1484.0 + 656.0, "moved clear of the grown screen");
assert_eq!(rect(beside).y, 1484.0, "not under it");
}
}
+304
View File
@@ -0,0 +1,304 @@
//! The deck's own words in the language the project is written in: detected from its text, or
//! named by the caller. Templates take their values for `{}` in order.
use crate::model::{Document, NodeKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Lang {
#[default]
En,
Pt,
Es,
Fr,
De,
It,
}
/// Things the deck counts.
#[derive(Clone, Copy)]
pub enum Noun {
Screen,
Board,
Page,
State,
OpenQuestion,
}
pub struct Words {
pub presentation: &'static str,
pub contents: &'static str,
pub at_a_glance: &'static str,
pub open_questions: &'static str,
pub next_steps: &'static str,
pub appendix: &'static str,
pub appendix_states: &'static str,
pub other_states: &'static str,
pub thank_you: &'static str,
pub answer: &'static str,
pub answer_detail: &'static str,
pub review: &'static str,
pub and: &'static str,
pub review_detail: &'static str,
pub check_states: &'static str,
pub check_states_detail: &'static str,
pub send_feedback: &'static str,
pub to: &'static str,
pub notes: &'static str,
pub in_appendix: &'static str,
/// Singular and plural of each [`Noun`], in its order.
nouns: [(&'static str, &'static str); 5],
months: [&'static str; 12],
/// Day, month name, year.
date: &'static str,
}
/// `template` with each `{}` replaced by the next of `values`.
pub fn fill(template: &str, values: &[&str]) -> String {
let mut out = String::new();
let mut rest = template;
for v in values {
let Some((head, tail)) = rest.split_once("{}") else { break };
out.push_str(head);
out.push_str(v);
rest = tail;
}
out.push_str(rest);
out
}
impl Words {
pub fn count(&self, n: usize, what: Noun) -> String {
let (one, many) = self.nouns[what as usize];
format!("{n} {}", if n == 1 { one } else { many })
}
/// The date of Unix milliseconds (UTC; civil-from-days), as the language writes it.
pub fn date(&self, ms: u64) -> String {
let z = (ms / 86_400_000) as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
fill(self.date, &[&d.to_string(), self.months[(m - 1) as usize], &y.to_string()])
}
}
impl Lang {
/// `en`, `pt`, `pt-BR`, `es`, `fr`, `de` or `it`.
pub fn parse(code: &str) -> Option<Lang> {
let base = code.split(['-', '_']).next()?.to_ascii_lowercase();
Some(match base.as_str() {
"en" => Lang::En,
"pt" => Lang::Pt,
"es" => Lang::Es,
"fr" => Lang::Fr,
"de" => Lang::De,
"it" => Lang::It,
_ => return None,
})
}
/// The language most of the documents' text is written in; English when nothing stands out.
pub fn detect<'a>(docs: impl IntoIterator<Item = &'a Document>) -> Lang {
// Common words, and letters only some of the languages use.
const CUES: [(Lang, &[&str], &str); 6] = [
(Lang::En, &["the", "and", "of", "to", "is", "with", "for", "your", "you", "this", "on"], ""),
(Lang::Pt, &["de", "da", "do", "que", "para", "com", "não", "uma", "os", "das", "dos", "em", "você", "seu", "sua"], "ãõç"),
(Lang::Es, &["de", "la", "el", "que", "en", "los", "para", "con", "una", "del", "las", "tu", "su"], "ñ¿¡"),
(Lang::Fr, &["le", "la", "les", "de", "des", "et", "pour", "avec", "une", "du", "vous", "est", "votre"], "èêëœ"),
(Lang::De, &["der", "die", "und", "das", "mit", "für", "ist", "ein", "eine", "nicht", "zu", "den", "ihre"], "äöüß"),
(Lang::It, &["il", "di", "che", "per", "con", "una", "gli", "della", "del", "non", "le", "sono"], "ìòù"),
];
const LETTER_WEIGHT: usize = 3;
let mut score = [0usize; 6];
for doc in docs {
for n in doc.nodes.values() {
let (NodeKind::Text { text, .. } | NodeKind::Sticky { text, .. }) = &n.kind else { continue };
let lower = text.to_lowercase();
for word in lower.split(|c: char| !c.is_alphabetic()).filter(|w| !w.is_empty()) {
for (i, (_, words, _)) in CUES.iter().enumerate() {
score[i] += usize::from(words.contains(&word));
}
}
for c in lower.chars() {
for (i, (_, _, letters)) in CUES.iter().enumerate() {
score[i] += LETTER_WEIGHT * usize::from(letters.contains(c));
}
}
}
}
let best = (0..CUES.len()).max_by_key(|i| (score[*i], std::cmp::Reverse(*i))).unwrap_or(0);
if score[best] == 0 { Lang::En } else { CUES[best].0 }
}
pub fn words(self) -> &'static Words {
match self {
Lang::En => &EN,
Lang::Pt => &PT,
Lang::Es => &ES,
Lang::Fr => &FR,
Lang::De => &DE,
Lang::It => &IT,
}
}
}
static EN: Words = Words {
presentation: "DESIGN PRESENTATION",
contents: "Contents",
at_a_glance: "At a glance",
open_questions: "Open questions",
next_steps: "Next steps",
appendix: "Appendix",
appendix_states: "Appendix \u{b7} states",
other_states: "Other states of the screens",
thank_you: "Thank you",
answer: "Answer {}",
answer_detail: "From the notes on the screens; slide {} on",
review: "Review the {}",
and: "{} and {}",
review_detail: "Feedback on a screen by its name, as titled on its slide",
check_states: "Check the other states",
check_states_detail: "The states kept out of the main flow; appendix, slide {} on",
send_feedback: "Send feedback",
to: "To {}",
notes: "notes {}/{}",
in_appendix: "+ {} in the appendix",
nouns: [("screen", "screens"), ("board", "boards"), ("page", "pages"), ("state", "states"), ("open question", "open questions")],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
date: "{} {} {}",
};
static PT: Words = Words {
presentation: "APRESENTA\u{c7}\u{c3}O DE DESIGN",
contents: "Sum\u{e1}rio",
at_a_glance: "Vis\u{e3}o geral",
open_questions: "Perguntas em aberto",
next_steps: "Pr\u{f3}ximos passos",
appendix: "Ap\u{ea}ndice",
appendix_states: "Ap\u{ea}ndice \u{b7} estados",
other_states: "Outros estados das telas",
thank_you: "Obrigado",
answer: "Responder {}",
answer_detail: "Das notas nas telas; a partir do slide {}",
review: "Revisar {}",
and: "{} e {}",
review_detail: "Coment\u{e1}rios sobre uma tela pelo nome, como no t\u{ed}tulo do slide",
check_states: "Ver os outros estados",
check_states_detail: "Os estados fora do fluxo principal; ap\u{ea}ndice, a partir do slide {}",
send_feedback: "Enviar coment\u{e1}rios",
to: "Para {}",
notes: "notas {}/{}",
in_appendix: "+ {} no ap\u{ea}ndice",
nouns: [("tela", "telas"), ("quadro", "quadros"), ("p\u{e1}gina", "p\u{e1}ginas"), ("estado", "estados"), ("pergunta em aberto", "perguntas em aberto")],
months: ["janeiro", "fevereiro", "mar\u{e7}o", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
date: "{} de {} de {}",
};
static ES: Words = Words {
presentation: "PRESENTACI\u{d3}N DE DISE\u{d1}O",
contents: "\u{cd}ndice",
at_a_glance: "De un vistazo",
open_questions: "Preguntas abiertas",
next_steps: "Pr\u{f3}ximos pasos",
appendix: "Ap\u{e9}ndice",
appendix_states: "Ap\u{e9}ndice \u{b7} estados",
other_states: "Otros estados de las pantallas",
thank_you: "Gracias",
answer: "Responder {}",
answer_detail: "De las notas en las pantallas; desde la diapositiva {}",
review: "Revisar {}",
and: "{} y {}",
review_detail: "Comentarios sobre una pantalla por su nombre, como se titula en su diapositiva",
check_states: "Revisar los otros estados",
check_states_detail: "Los estados fuera del flujo principal; ap\u{e9}ndice, desde la diapositiva {}",
send_feedback: "Enviar comentarios",
to: "Para {}",
notes: "notas {}/{}",
in_appendix: "+ {} en el ap\u{e9}ndice",
nouns: [("pantalla", "pantallas"), ("tablero", "tableros"), ("p\u{e1}gina", "p\u{e1}ginas"), ("estado", "estados"), ("pregunta abierta", "preguntas abiertas")],
months: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
date: "{} de {} de {}",
};
static FR: Words = Words {
presentation: "PR\u{c9}SENTATION DESIGN",
contents: "Sommaire",
at_a_glance: "En bref",
open_questions: "Questions ouvertes",
next_steps: "Prochaines \u{e9}tapes",
appendix: "Annexe",
appendix_states: "Annexe \u{b7} \u{e9}tats",
other_states: "Autres \u{e9}tats des \u{e9}crans",
thank_you: "Merci",
answer: "R\u{e9}pondre \u{e0} {}",
answer_detail: "D\u{2019}apr\u{e8}s les notes des \u{e9}crans ; \u{e0} partir de la diapositive {}",
review: "Relire {}",
and: "{} et {}",
review_detail: "Vos retours sur un \u{e9}cran par son nom, tel qu\u{2019}il est titr\u{e9} sur sa diapositive",
check_states: "Voir les autres \u{e9}tats",
check_states_detail: "Les \u{e9}tats hors du parcours principal ; annexe, \u{e0} partir de la diapositive {}",
send_feedback: "Envoyer vos retours",
to: "\u{c0} {}",
notes: "notes {}/{}",
in_appendix: "+ {} en annexe",
nouns: [("\u{e9}cran", "\u{e9}crans"), ("tableau", "tableaux"), ("page", "pages"), ("\u{e9}tat", "\u{e9}tats"), ("question ouverte", "questions ouvertes")],
months: ["janvier", "f\u{e9}vrier", "mars", "avril", "mai", "juin", "juillet", "ao\u{fb}t", "septembre", "octobre", "novembre", "d\u{e9}cembre"],
date: "{} {} {}",
};
static DE: Words = Words {
presentation: "DESIGN-PR\u{c4}SENTATION",
contents: "Inhalt",
at_a_glance: "Auf einen Blick",
open_questions: "Offene Fragen",
next_steps: "N\u{e4}chste Schritte",
appendix: "Anhang",
appendix_states: "Anhang \u{b7} Zust\u{e4}nde",
other_states: "Weitere Zust\u{e4}nde der Screens",
thank_you: "Vielen Dank",
answer: "{} beantworten",
answer_detail: "Aus den Notizen auf den Screens; ab Folie {}",
review: "{} pr\u{fc}fen",
and: "{} und {}",
review_detail: "Feedback zu einem Screen mit seinem Namen, wie auf seiner Folie betitelt",
check_states: "Die weiteren Zust\u{e4}nde ansehen",
check_states_detail: "Die Zust\u{e4}nde au\u{df}erhalb des Hauptablaufs; Anhang, ab Folie {}",
send_feedback: "Feedback senden",
to: "An {}",
notes: "Notizen {}/{}",
in_appendix: "+ {} im Anhang",
nouns: [("Screen", "Screens"), ("Board", "Boards"), ("Seite", "Seiten"), ("Zustand", "Zust\u{e4}nde"), ("offene Frage", "offene Fragen")],
months: ["Januar", "Februar", "M\u{e4}rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
date: "{}. {} {}",
};
static IT: Words = Words {
presentation: "PRESENTAZIONE DI DESIGN",
contents: "Indice",
at_a_glance: "In sintesi",
open_questions: "Domande aperte",
next_steps: "Prossimi passi",
appendix: "Appendice",
appendix_states: "Appendice \u{b7} stati",
other_states: "Altri stati delle schermate",
thank_you: "Grazie",
answer: "Rispondere a {}",
answer_detail: "Dalle note sulle schermate; dalla slide {}",
review: "Rivedere {}",
and: "{} e {}",
review_detail: "Feedback su una schermata con il suo nome, come nel titolo della slide",
check_states: "Controllare gli altri stati",
check_states_detail: "Gli stati fuori dal flusso principale; appendice, dalla slide {}",
send_feedback: "Inviare feedback",
to: "A {}",
notes: "note {}/{}",
in_appendix: "+ {} in appendice",
nouns: [("schermata", "schermate"), ("board", "board"), ("pagina", "pagine"), ("stato", "stati"), ("domanda aperta", "domande aperte")],
months: ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"],
date: "{} {} {}",
};
+66 -10
View File
@@ -11,6 +11,8 @@ pub enum Format {
Png,
Svg,
Pdf,
/// A PDF deck: cover, contents, a slide per screen (`io::deck`).
Presentation,
}
impl Format {
@@ -18,10 +20,10 @@ impl Format {
match self {
Format::Png => "png",
Format::Svg => "svg",
Format::Pdf => "pdf",
Format::Pdf | Format::Presentation => "pdf",
}
}
pub const ALL: [Format; 3] = [Format::Png, Format::Svg, Format::Pdf];
pub const ALL: [Format; 4] = [Format::Png, Format::Svg, Format::Pdf, Format::Presentation];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -77,7 +79,7 @@ impl Default for Spec {
impl Spec {
/// One output file, or a folder of files?
pub fn single_file(&self, items: usize) -> bool {
self.format == Format::Pdf || items <= 1
[Format::Pdf, Format::Presentation].contains(&self.format) || items <= 1
}
}
@@ -97,6 +99,11 @@ pub fn items<'a>(
selection: &[NodeId],
) -> Vec<Item<'a>> {
let (pname, doc) = pages[active];
// A presentation takes whole pages: each frame is already a slide of it.
let scope = match spec.scope {
Scope::Frames if spec.format == Format::Presentation => Scope::Page,
s => s,
};
let frames_of = |doc: &'a Document, among: &[NodeId]| -> Vec<Item<'a>> {
among
.iter()
@@ -108,7 +115,7 @@ pub fn items<'a>(
})
.collect()
};
match spec.scope {
match scope {
Scope::Selection if !selection.is_empty() => vec![Item {
name: if selection.len() == 1 {
doc.get(selection[0])
@@ -143,6 +150,45 @@ pub fn items<'a>(
}
}
/// `roots` plus, for each top-level frame among them, the top-level layers painted after it
/// that lie inside it: what the canvas shows on the frame (component mains laid out over a
/// board frame are its siblings, not its children).
pub fn with_layers_on_top(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
let mut out = roots.to_vec();
for root in roots {
let Some(at) = doc.root.iter().position(|id| id == root) else { continue };
let Some(frame) = doc.get(*root).filter(|n| n.is_frame()).and_then(|_| doc.world_rect(*root)) else { continue };
for id in &doc.root[at + 1..] {
let on_top = doc.get(*id).is_some_and(|n| n.visible) && doc.world_rect(*id).is_some_and(|r| frame.contains_rect(&r));
if on_top && !out.contains(id) {
out.push(*id);
}
}
}
out
}
/// The items as a presentation deck titled `title`: a page's own roots mean its screens, a
/// selection is shown as it is.
pub fn presentation(items: &[Item], title: &str) -> Vec<u8> {
let sections: Vec<crate::io::deck::Section> = items
.iter()
.map(|it| crate::io::deck::Section {
name: it.name.clone(),
doc: it.doc,
screens: if it.roots == it.doc.root { crate::io::deck::screens_of(it.doc) } else { it.roots.clone() },
})
.collect();
let meta = crate::io::deck::Meta {
title: title.to_string(),
subtitle: None,
author: None,
now_ms: crate::project::format::now_ms(),
language: None,
};
crate::io::deck::build(&meta, &sections)
}
fn safe(name: &str) -> String {
let s = crate::project::folder_name(name);
if s.is_empty() { "export".into() } else { s }
@@ -160,6 +206,11 @@ pub fn write(
if items.is_empty() {
return Err("nothing to export".into());
}
if spec.format == Format::Presentation {
let title = out.file_stem().map_or("Presentation".into(), |s| s.to_string_lossy().into_owned());
crate::io::atomic::write(out, &presentation(items, &title)).map_err(|e| e.to_string())?;
return Ok(vec![out.to_path_buf()]);
}
if spec.format == Format::Pdf {
let mut pages = Vec::new();
for it in items {
@@ -195,9 +246,10 @@ pub fn write(
crate::vfs::create_dir_all(out).map_err(|e| e.to_string())?;
out.join(format!("{name}.{}", spec.format.ext()))
};
let roots = with_layers_on_top(it.doc, &it.roots);
match spec.format {
Format::Svg => {
let s = crate::io::svg::export(it.doc, Some(&it.roots), bg)
let s = crate::io::svg::export(it.doc, Some(&roots), bg)
.ok_or("nothing to export")?;
crate::io::atomic::write(&path, s.as_bytes()).map_err(|e| e.to_string())?;
}
@@ -210,13 +262,13 @@ pub fn write(
&owned
}
};
let img = crate::io::png::render(g, it.doc, Some(&it.roots), spec.scale, bg)?;
let img = crate::io::png::render(g, it.doc, Some(&roots), spec.scale, bg)?;
let mut buf = std::io::Cursor::new(Vec::new());
img.write_to(&mut buf, image::ImageFormat::Png)
.map_err(|e| e.to_string())?;
crate::io::atomic::write(&path, &buf.into_inner()).map_err(|e| e.to_string())?;
}
Format::Pdf => unreachable!(),
Format::Pdf | Format::Presentation => unreachable!(),
}
written.push(path);
}
@@ -245,6 +297,9 @@ pub async fn render_files(
}
let bg = (!spec.transparent).then_some(Color::WHITE);
let ext = spec.format.ext();
if spec.format == Format::Presentation {
return Ok(vec![(format!("{}.{ext}", safe(base)), presentation(items, base))]);
}
if spec.format == Format::Pdf {
let frames = spec.scope == Scope::Frames;
let pages: Vec<_> = items
@@ -268,14 +323,15 @@ pub async fn render_files(
} else {
crate::io::zip::unique_name(&format!("{}.{ext}", safe(&it.name)), &mut used)
};
let roots = with_layers_on_top(it.doc, &it.roots);
let bytes = match spec.format {
Format::Svg => crate::io::svg::export(it.doc, Some(&it.roots), bg)
Format::Svg => crate::io::svg::export(it.doc, Some(&roots), bg)
.ok_or("nothing to export")?
.into_bytes(),
Format::Png => encode_png(
&crate::io::png::render_async(gpu, it.doc, Some(&it.roots), spec.scale, bg).await?,
&crate::io::png::render_async(gpu, it.doc, Some(&roots), spec.scale, bg).await?,
)?,
Format::Pdf => unreachable!(),
Format::Pdf | Format::Presentation => unreachable!(),
};
files.push((name, bytes));
}
+1
View File
@@ -6,6 +6,7 @@ pub mod export;
pub mod fig;
pub mod file;
pub mod import;
pub mod deck;
pub mod pdf;
pub mod png;
pub mod svg;
+153 -17
View File
@@ -3,23 +3,36 @@
//! One PDF page per exported area (a selection, each frame, or a whole page). Shapes, strokes
//! and glyph outlines are vector paths; gradients are axial/radial shadings; images are
//! deflated RGB XObjects with an alpha soft mask; opacity and all 16 blend modes go through
//! ExtGState; clipping frames clip. Text is outlined (not selectable), as in the SVG export.
//! ExtGState; clipping frames clip. Text is real text in the embedded Inter faces (`font`), so
//! it can be selected, searched and edited.
use crate::assets;
use crate::geom::{Rect, V2};
use crate::model::{BlendMode, Cap, Color, Document, Join, NodeId, NodeKind, Stop};
use crate::render::draw::{self, DrawOp, PaintSpec};
use crate::text;
use crate::vector::{Seg, VPath};
use std::collections::HashMap;
use std::fmt::Write;
mod font;
/// One page of output: what to draw and the area it covers.
pub struct PdfPage<'a> {
pub doc: &'a Document,
pub roots: Vec<NodeId>,
pub bounds: Rect,
pub background: Option<Color>,
/// Drawn after `roots`, each scaled into its own area (a presentation's screens).
pub inserts: Vec<Insert<'a>>,
}
/// Layers of another document drawn scaled: `from` (world units of `doc`) maps onto `to`
/// (the page's units), uniformly by width, clipped to `to`. Stays vector.
pub struct Insert<'a> {
pub doc: &'a Document,
pub roots: Vec<NodeId>,
pub from: Rect,
pub to: Rect,
}
fn num(x: f64) -> String {
@@ -90,12 +103,16 @@ struct Res {
gstate_objs: Vec<(String, usize)>,
shadings: Vec<(String, usize)>,
images: HashMap<String, (String, usize)>,
fonts: std::collections::BTreeMap<String, usize>,
}
struct PageWriter<'a> {
objs: &'a mut Objects,
fonts: &'a mut font::Fonts,
res: Res,
out: String,
/// While drawing an insert: its source area. Layers outside it are left out of the file.
cull: Option<Rect>,
}
impl PageWriter<'_> {
@@ -243,11 +260,11 @@ impl PageWriter<'_> {
if let Some((n, _)) = self.res.images.get(asset) {
return Some(n.clone());
}
let a = assets::get(asset)?;
let (w, h) = (a.width, a.height);
let rgba = assets::get(asset)?.rgba()?;
let (w, h) = (rgba.width(), rgba.height());
let mut rgb = Vec::with_capacity((w * h * 3) as usize);
let mut alpha = Vec::with_capacity((w * h) as usize);
for p in a.rgba.pixels() {
for p in rgba.pixels() {
rgb.extend_from_slice(&p.0[..3]);
alpha.push(p.0[3]);
}
@@ -407,13 +424,35 @@ impl PageWriter<'_> {
color,
glyphs,
} => {
let mut p = VPath::new();
for (gid, o) in glyphs {
p.append(&text::glyph_path(*face, *gid, *o, *size));
}
let path = self.emit_path(&p);
let (name, id) = self.fonts.name(self.objs, *face, glyphs.iter().map(|g| g.0));
self.res.fonts.insert(name.clone(), id);
let gs = self.gstate(color[3], 1.0, blend);
let _ = writeln!(self.out, "q /{gs} gs {} rg {path}f\nQ", Self::rgb(*color));
let _ = write!(self.out, "q /{gs} gs {} rg BT /{name} {} Tf", Self::rgb(*color), num(*size));
// One text matrix per baseline (it flips y back upright), then each glyph
// nudged from where the font's advance would put it to where layout did.
let mut pen: Option<V2> = None;
for (gid, o) in glyphs {
match pen {
Some(p) if (p.y - o.y).abs() < 0.01 => {
let adj = (p.x - o.x) * 1000.0 / size;
if adj.abs() > 0.05 {
let _ = write!(self.out, " {}", num(adj));
}
}
_ => {
if pen.is_some() {
self.out.push_str("] TJ");
}
let _ = write!(self.out, " 1 0 0 -1 {} {} Tm [", num(o.x), num(o.y));
}
}
let _ = write!(self.out, "<{gid:04X}>");
pen = Some(V2 { x: o.x + font::advance(*face, *gid, *size), y: o.y });
}
if pen.is_some() {
self.out.push_str("] TJ");
}
self.out.push_str(" ET Q\n");
}
}
}
@@ -426,12 +465,19 @@ impl PageWriter<'_> {
}
let wr = doc.world_rect(id).unwrap();
let op = opacity * n.style.opacity;
let d = draw::node_draw(n, wr, op);
self.ops(&d.ops, d.blend);
let clip = matches!(n.kind, NodeKind::Frame { clip: true });
// Outside the insert's area: nothing of it shows, unless an unclipped child pokes in.
let outside = self.cull.is_some_and(|c| !wr.intersects(&c));
if outside && (clip || n.children.is_empty()) {
return;
}
if !outside {
let d = draw::node_draw(n, wr, op);
self.ops(&d.ops, d.blend);
}
if n.children.is_empty() {
return;
}
let clip = matches!(n.kind, NodeKind::Frame { clip: true });
if clip {
let p = self.emit_path(&draw::shape_path(n, wr).unwrap_or_default());
let _ = writeln!(self.out, "q {p}W n");
@@ -451,12 +497,15 @@ pub fn export(pages: &[PdfPage]) -> Vec<u8> {
let catalog = objs.reserve();
let pages_id = objs.reserve();
let mut kids = Vec::new();
let mut fonts = font::Fonts::default();
for pg in pages {
let b = pg.bounds;
let mut w = PageWriter {
objs: &mut objs,
fonts: &mut fonts,
res: Res::default(),
out: String::new(),
cull: None,
};
// y-down user space with the page's top-left at the area's top-left.
let _ = writeln!(w.out, "1 0 0 -1 {} {} cm", num(-b.x), num(b.y + b.h));
@@ -476,6 +525,31 @@ pub fn export(pages: &[PdfPage]) -> Vec<u8> {
let op = draw::inherited_opacity(pg.doc, *r);
w.node(pg.doc, *r, op);
}
for ins in &pg.inserts {
let s = ins.to.w / ins.from.w.max(f64::EPSILON);
let (t, f) = (ins.to, ins.from);
// Full precision: the scale multiplies world coordinates in the tens of thousands, so
// rounding it to num()'s 3 decimals shifts the screen inside its window.
let _ = writeln!(
w.out,
"q {} {} {} {} re W n {s:.9} 0 0 {s:.9} {:.4} {:.4} cm",
num(t.x),
num(t.y),
num(t.w),
num(t.h),
t.x - f.x * s,
t.y - f.y * s
);
// A margin for strokes drawn outside their layer.
const CULL_MARGIN: f64 = 16.0;
w.cull = Some(Rect::new(f.x - CULL_MARGIN, f.y - CULL_MARGIN, f.w + 2.0 * CULL_MARGIN, f.h + 2.0 * CULL_MARGIN));
for r in &ins.roots {
let op = draw::inherited_opacity(ins.doc, *r);
w.node(ins.doc, *r, op);
}
w.cull = None;
w.out.push_str("Q\n");
}
let content = std::mem::take(&mut w.out);
let res = std::mem::take(&mut w.res);
let content_id = objs.stream("", content.as_bytes());
@@ -487,19 +561,22 @@ pub fn export(pages: &[PdfPage]) -> Vec<u8> {
.join(" ")
};
let images: Vec<(String, usize)> = res.images.values().cloned().collect();
let fonts_of_page: Vec<(String, usize)> = res.fonts.into_iter().collect();
let page = objs.add(
format!(
"<< /Type /Page /Parent {pages_id} 0 R /MediaBox [0 0 {} {}] /Contents {content_id} 0 R /Resources << /ExtGState << {} >> /Shading << {} >> /XObject << {} >> >> >>",
"<< /Type /Page /Parent {pages_id} 0 R /MediaBox [0 0 {} {}] /Contents {content_id} 0 R /Resources << /ExtGState << {} >> /Shading << {} >> /XObject << {} >> /Font << {} >> >> >>",
num(b.w),
num(b.h),
dict(&res.gstate_objs),
dict(&res.shadings),
dict(&images)
dict(&images),
dict(&fonts_of_page)
)
.into_bytes(),
);
kids.push(page);
}
fonts.finish(&mut objs);
objs.set(
catalog,
format!("<< /Type /Catalog /Pages {pages_id} 0 R >>").into_bytes(),
@@ -561,19 +638,22 @@ pub fn pages_for<'a>(
Some(PdfPage {
doc,
bounds: crate::io::svg::export_bounds(doc, &[f])?,
roots: vec![f],
roots: crate::io::export::with_layers_on_top(doc, &[f]),
background,
inserts: Vec::new(),
})
})
.collect();
}
}
let roots = crate::io::export::with_layers_on_top(doc, &roots);
match crate::io::svg::export_bounds(doc, &roots) {
Some(b) => vec![PdfPage {
doc,
roots,
bounds: b,
background,
inserts: Vec::new(),
}],
None => vec![],
}
@@ -610,4 +690,60 @@ mod tests {
let first_off: usize = table.lines().nth(3).unwrap()[..10].parse().unwrap();
assert!(pdf[first_off..].starts_with(b"1 0 obj"));
}
#[test]
fn text_is_written_as_text_in_an_embedded_font() {
use crate::model::{Node, NodeKind};
let mut ed = crate::editor::Editor::default();
let t = ed.add_node(Node::new(NodeId(0), NodeKind::Text { text: "Olá".into(), font_size: 16.0, auto_width: true, align: Default::default() }, Rect::new(0.0, 0.0, 200.0, 40.0)), None);
let pdf = export(&pages_for(&ed.doc, Some(&[t]), false, None));
let s = String::from_utf8_lossy(&pdf);
assert!(s.contains("/Subtype /Type0") && s.contains("/ToUnicode") && s.contains("/FontFile2"), "embedded font");
assert_eq!(s.matches("/Subtype /Type0").count(), 1, "one font object per face");
}
#[test]
fn an_insert_far_from_the_origin_lands_where_it_is_placed() {
use crate::geom::Rect;
use crate::model::{Node, NodeKind};
let mut ed = crate::editor::Editor::default();
let from = Rect::new(4192.0, 25412.0, 1440.0, 900.0);
let screen = ed.edit("Add", |tx| {
let id = tx.alloc_id();
tx.insert(Node::new(id, NodeKind::Frame { clip: true }, from), None, None);
id
});
let to = Rect::new(100.0, 100.0, 1440.0 * 0.3361, 900.0 * 0.3361);
let page = PdfPage { doc: &ed.doc, roots: Vec::new(), bounds: Rect::new(0.0, 0.0, 1920.0, 1080.0), background: None, inserts: vec![Insert { doc: &ed.doc, roots: vec![screen], from, to }] };
let pdf = export(&[page]);
let content = pdf
.windows(7)
.position(|w| w == b"stream\n")
.and_then(|at| miniz_oxide::inflate::decompress_to_vec_zlib(&pdf[at + 7..]).ok())
.expect("a page content stream");
let line = String::from_utf8_lossy(&content).lines().find(|l| l.ends_with(" cm") && l.contains("re W n")).unwrap().to_owned();
let n: Vec<f64> = line.split_whitespace().filter_map(|t| t.parse().ok()).collect();
let (s, ty) = (n[4], n[9]);
assert!((from.y * s + ty - to.y).abs() < 0.01, "the screen's top maps onto the window's top: {line}");
}
#[test]
fn a_frame_page_includes_layers_laid_over_it() {
use crate::geom::Rect;
use crate::model::{Node, NodeKind};
let mut ed = crate::editor::Editor::default();
let mut add = |r: Rect| {
ed.edit("Add", |tx| {
let id = tx.alloc_id();
tx.insert(Node::new(id, NodeKind::Frame { clip: true }, r), None, None);
id
})
};
let board = add(Rect::new(0.0, 0.0, 400.0, 300.0));
let main = add(Rect::new(20.0, 20.0, 100.0, 40.0));
let outside = add(Rect::new(500.0, 0.0, 100.0, 40.0));
let pages = pages_for(&ed.doc, Some(&[board]), true, None);
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].roots, vec![board, main], "the main on the board, not the one beside it ({outside:?})");
}
}
+130
View File
@@ -0,0 +1,130 @@
//! Text as real PDF text: each Inter face a text uses is embedded once per file (a Type0 font
//! over a CIDFontType2, glyph ids as character codes) with a ToUnicode map, so a reader can
//! select, search, copy and edit it in any language the font covers.
use super::{Objects, num};
use crate::text::{self, FaceId};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
/// The faces a file uses: the object id reserved for each and the glyphs drawn with it.
#[derive(Default)]
pub(super) struct Fonts {
used: BTreeMap<FaceId, (usize, BTreeSet<u16>)>,
}
/// PDF glyph space: 1000 units to the em.
const EM: f64 = 1000.0;
impl Fonts {
/// The resource name of `face` (`/F<face>`), its object reserved on first use.
pub(super) fn name(&mut self, objs: &mut Objects, face: FaceId, gids: impl IntoIterator<Item = u16>) -> (String, usize) {
let (id, set) = self.used.entry(face).or_insert_with(|| (objs.reserve(), BTreeSet::new()));
set.extend(gids);
(format!("F{face}"), *id)
}
/// Writes every font used, once all pages are drawn.
pub(super) fn finish(self, objs: &mut Objects) {
for (face, (id, gids)) in self.used {
let f = text::face_of(face);
let bytes = text::face_bytes(face);
let k = EM / f64::from(f.units_per_em());
let name = f
.names()
.into_iter()
.find(|n| n.name_id == ttf_parser::name_id::POST_SCRIPT_NAME)
.and_then(|n| n.to_string())
.unwrap_or_else(|| "Inter".into());
let file = objs.stream(&format!("/Length1 {}", bytes.len()), bytes);
let b = f.global_bounding_box();
let descriptor = objs.add(
format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags {} /FontBBox [{} {} {} {}] /ItalicAngle {} /Ascent {} /Descent {} /CapHeight {} /StemV 80 /FontFile2 {file} 0 R >>",
if f.is_italic() { 32 | 64 } else { 32 },
num(f64::from(b.x_min) * k),
num(f64::from(b.y_min) * k),
num(f64::from(b.x_max) * k),
num(f64::from(b.y_max) * k),
num(f.italic_angle().into()),
num(f64::from(f.ascender()) * k),
num(f64::from(f.descender()) * k),
num(f64::from(f.capital_height().unwrap_or(f.ascender())) * k),
)
.into_bytes(),
);
let widths: String = gids
.iter()
.map(|g| format!("{g} [{}]", num(f64::from(f.glyph_hor_advance(ttf_parser::GlyphId(*g)).unwrap_or(0)) * k)))
.collect::<Vec<_>>()
.join(" ");
let cid = objs.add(
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /CIDToGIDMap /Identity /W [{widths}] >>"
)
.into_bytes(),
);
let to_unicode = objs.stream("", to_unicode(f, &gids).as_bytes());
objs.set(
id,
format!("<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{cid} 0 R] /ToUnicode {to_unicode} 0 R >>")
.into_bytes(),
);
}
}
}
/// Glyph advance in points at `size`.
pub(super) fn advance(face: FaceId, gid: u16, size: f64) -> f64 {
let f = text::face_of(face);
f64::from(f.glyph_hor_advance(ttf_parser::GlyphId(gid)).unwrap_or(0)) * size / f64::from(f.units_per_em())
}
/// The character each glyph stands for, read back from the font's own character map (the
/// lowest code point when several share a glyph).
fn chars_of(f: &ttf_parser::Face, gids: &BTreeSet<u16>) -> BTreeMap<u16, char> {
let mut out = BTreeMap::new();
for t in f.tables().cmap.into_iter().flat_map(|c| c.subtables).filter(|t| t.is_unicode()) {
t.codepoints(|cp| {
let (Some(g), Some(c)) = (t.glyph_index(cp), char::from_u32(cp)) else { return };
if gids.contains(&g.0) && out.get(&g.0).is_none_or(|old: &char| c < *old) {
out.insert(g.0, c);
}
});
}
out
}
fn to_unicode(f: &ttf_parser::Face, gids: &BTreeSet<u16>) -> String {
let map = chars_of(f, gids);
let mut s = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
// A bfchar block holds at most 100 entries.
let entries: Vec<(u16, char)> = map.into_iter().collect();
for chunk in entries.chunks(100) {
let _ = writeln!(s, "{} beginbfchar", chunk.len());
for (g, c) in chunk {
let utf16: String = c.encode_utf16(&mut [0; 2]).iter().map(|u| format!("{u:04X}")).collect();
let _ = writeln!(s, "<{g:04X}> <{utf16}>");
}
s.push_str("endbfchar\n");
}
s.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
s
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_in_any_language_the_font_covers_maps_back_to_its_characters() {
let f = text::face_of(0);
let s = "Ação, saída! Привет Ωμέγα";
let gids: BTreeSet<u16> = s.chars().filter_map(|c| f.glyph_index(c)).map(|g| g.0).collect();
let back: BTreeSet<char> = chars_of(f, &gids).into_values().collect();
assert!(s.chars().all(|c| back.contains(&c)), "{back:?}");
assert!(to_unicode(f, &gids).contains(&format!("<{:04X}>", 'ç' as u32)));
}
}
+36 -2
View File
@@ -53,7 +53,7 @@ pub fn flow_children(doc: &Document, id: NodeId) -> Vec<NodeId> {
}
/// Intrinsic (hug) size of a node along an axis, without changing anything.
fn hug_size(doc: &Document, id: NodeId, axis: usize) -> f64 {
pub(crate) fn hug_size(doc: &Document, id: NodeId, axis: usize) -> f64 {
let n = doc.get(id).unwrap();
let (_, cur) = get(&n.rect, axis);
let Some(l) = n.layout else {
@@ -74,7 +74,7 @@ fn hug_size(doc: &Document, id: NodeId, axis: usize) -> f64 {
// A growing child still brings its content (CSS flex-basis auto); its current
// size is what it grew to, so it is not used.
Sizing::Fill if kn.layout.is_some() => clamp_size(&kn.layout_child, axis, hug_size(doc, *k, axis)),
Sizing::Fill => clamp_size(&kn.layout_child, axis, 0.0),
Sizing::Fill => clamp_size(&kn.layout_child, axis, text_content(kn, axis)),
Sizing::Fixed => clamp_size(&kn.layout_child, axis, get(&kn.rect, axis).1),
}
})
@@ -112,6 +112,19 @@ fn hug_size(doc: &Document, id: NodeId, axis: usize) -> f64 {
clamp_size(&n.layout_child, axis, result)
}
/// What a growing text brings to a parent that hugs it: its one-line width and its height, as
/// a browser sizes a fit-content box by its content. Without it, a text that fills a hugging
/// row gets no width and wraps a letter per line. Other leaves bring nothing.
fn text_content(n: &crate::model::Node, axis: usize) -> f64 {
let NodeKind::Text { text, font_size, align, .. } = &n.kind else {
return 0.0;
};
if axis == 1 {
return n.rect.h;
}
crate::text::layout_rich(text, *font_size, crate::model::Color::INK, &n.text_style, None, *align).width
}
fn wrap_lines(
doc: &Document,
_id: NodeId,
@@ -710,6 +723,27 @@ mod tests {
const FX: [Sizing; 2] = [Sizing::Fixed, Sizing::Fixed];
#[test]
fn a_growing_text_in_a_hugging_row_keeps_its_width() {
let mut doc = Document::default();
let mut rec = Recording::new("t", &doc);
let mut tx = Tx::new(&mut doc, &mut rec);
let row = tx.alloc_id();
let mut f = Node::new(row, NodeKind::Frame { clip: true }, Rect::new(0.0, 0.0, 10.0, 10.0));
f.layout = Some(AutoLayout::default());
f.layout_child.sizing = [Sizing::Hug; 2];
tx.insert(f, None, None);
let id = tx.alloc_id();
let kind = NodeKind::Text { text: "Two Sum".into(), font_size: 14.0, auto_width: false, align: crate::model::TextAlign::Left };
let mut t = Node::new(id, kind, Rect::new(0.0, 0.0, 0.0, 17.0));
t.layout_child.sizing = [Sizing::Fill, Sizing::Hug];
tx.insert(t, Some(row), None);
layout_frame(&mut tx, row);
let w = doc.get(id).unwrap().rect.w;
assert!(w > 40.0, "one line wide, not 0: {w}");
assert!(doc.get(id).unwrap().rect.h < 20.0, "one line tall");
}
#[test]
fn horizontal_hug_with_gap_and_padding() {
let l = AutoLayout {
+1
View File
@@ -11,6 +11,7 @@ pub mod demo;
pub mod design_system;
pub mod editor;
pub mod geom;
pub mod handoffs;
pub mod history;
pub mod icons;
#[cfg(not(target_arch = "wasm32"))]
+2 -1
View File
@@ -23,7 +23,7 @@ USAGE:
papercraft --export-png OUT.png PROJECT|FILE [--page N] [--scale S] [--transparent]
papercraft --export-svg OUT.svg PROJECT|FILE [--page N]
papercraft --export-pdf OUT.pdf PROJECT|FILE [--page N] [--frames | --all-pages]
papercraft --export OUT PROJECT|FILE --format png|svg|pdf [--scope page|frames|all]
papercraft --export OUT PROJECT|FILE --format png|svg|pdf|presentation [--scope page|frames|all]
[--page N] [--scale S] [--transparent]
(frames/all with PNG/SVG write a folder)
papercraft --import FILE create a project from .excalidraw, .svg or
@@ -240,6 +240,7 @@ fn run(args: Vec<String>) -> Result<(), String> {
"png" => export::Format::Png,
"svg" => export::Format::Svg,
"pdf" => export::Format::Pdf,
"presentation" => export::Format::Presentation,
f => return Err(format!("unknown --format {f}")),
};
let scope = match value("--scope").as_deref().unwrap_or("page") {
+127
View File
@@ -0,0 +1,127 @@
//! `get_bounds`: the rects of a whole subtree in one read, so an agent can check layout (overflow,
//! alignment, overlap) without one `get_node_info` call per layer.
use crate::model::{Document, NodeId, NodeKind};
use serde_json::{Value, json};
/// Rows returned per call; the rest is reported as `truncated` with where to continue.
pub const MAX_ROWS: usize = 2000;
/// Column names of a row, in order.
pub const COLUMNS: [&str; 9] = ["id", "parent", "x", "y", "w", "h", "absX", "absY", "clip"];
/// Rows for the subtrees under `roots`, depth first (parents before children).
pub struct Collected {
pub rows: Vec<Value>,
/// Layers not reached because of the row cap, in the order they would have come.
pub pending: Vec<NodeId>,
}
/// One decimal is far finer than a pixel and keeps rows short.
fn tenth(v: f64) -> f64 {
(v * 10.0).round() / 10.0
}
/// Whether the layer clips what is drawn outside it (a clipping frame, or a scrolling one).
fn clips(doc: &Document, id: NodeId) -> bool {
doc.get(id)
.is_some_and(|n| n.scroll || matches!(n.kind, NodeKind::Frame { clip: true }))
}
/// Walk `roots` and emit at most `cap` rows. `depth` counts the roots as level 1 (`None` = all
/// levels). `key` turns a node id into the id string tools accept.
pub fn collect(doc: &Document, roots: &[NodeId], depth: Option<usize>, cap: usize, key: &dyn Fn(NodeId) -> String) -> Collected {
let mut stack: Vec<(NodeId, usize)> = roots.iter().rev().map(|r| (*r, 1)).collect();
let mut rows = Vec::new();
while let Some((id, level)) = stack.pop() {
let (Some(n), Some(w)) = (doc.get(id), doc.world_rect(id)) else { continue };
if rows.len() >= cap {
stack.push((id, level));
break;
}
let parent = n.parent.map_or(Value::Null, |p| json!(key(p)));
rows.push(json!([
key(id),
parent,
tenth(n.rect.x),
tenth(n.rect.y),
tenth(n.rect.w),
tenth(n.rect.h),
tenth(w.x),
tenth(w.y),
clips(doc, id)
]));
if depth.is_none_or(|d| level < d) {
stack.extend(n.children.iter().rev().map(|c| (*c, level + 1)));
}
}
Collected { rows, pending: stack.into_iter().rev().map(|(id, _)| id).collect() }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geom::Rect;
use crate::model::Node;
fn add(doc: &mut Document, parent: Option<NodeId>, kind: NodeKind, r: Rect) -> NodeId {
let id = doc.alloc_id();
let mut n = Node::new(id, kind, r);
n.parent = parent;
doc.nodes.insert(id, n);
match parent {
Some(p) => doc.nodes.get_mut(&p).unwrap().children.push(id),
None => doc.root.push(id),
}
id
}
fn tree() -> (Document, NodeId, NodeId, NodeId) {
let mut d = Document::default();
let board = add(&mut d, None, NodeKind::Frame { clip: true }, Rect::new(100.0, 50.0, 300.0, 200.0));
let card = add(&mut d, Some(board), NodeKind::Frame { clip: false }, Rect::new(10.0, 20.0, 100.0, 80.0));
let dot = add(&mut d, Some(card), NodeKind::Rect, Rect::new(5.04, 6.0, 8.0, 8.0));
(d, board, card, dot)
}
fn key(id: NodeId) -> String {
format!("p:{}", id.0)
}
#[test]
fn rows_carry_local_and_world_positions_in_paint_order() {
let (d, board, card, dot) = tree();
let c = collect(&d, &[board], None, MAX_ROWS, &key);
assert_eq!(c.rows.len(), 3);
assert!(c.pending.is_empty());
assert_eq!(c.rows[0], json!([key(board), null, 100.0, 50.0, 300.0, 200.0, 100.0, 50.0, true]));
assert_eq!(c.rows[1], json!([key(card), key(board), 10.0, 20.0, 100.0, 80.0, 110.0, 70.0, false]));
assert_eq!(c.rows[2][0], json!(key(dot)));
assert_eq!(c.rows[2][2], json!(5.0), "rounded to a tenth");
assert_eq!(c.rows[2][6], json!(115.0));
}
#[test]
fn depth_counts_the_roots_as_level_one() {
let (d, board, ..) = tree();
assert_eq!(collect(&d, &[board], Some(1), MAX_ROWS, &key).rows.len(), 1);
assert_eq!(collect(&d, &[board], Some(2), MAX_ROWS, &key).rows.len(), 2);
}
#[test]
fn the_cap_stops_the_walk_and_names_what_is_left() {
let (d, board, card, dot) = tree();
let c = collect(&d, &[board], None, 1, &key);
assert_eq!(c.rows.len(), 1);
assert_eq!(c.pending, vec![card]);
let rest = collect(&d, &c.pending, None, 1, &key);
assert_eq!(rest.pending, vec![dot]);
}
#[test]
fn a_scrolling_frame_counts_as_clipping() {
let (mut d, _, card, _) = tree();
d.nodes.get_mut(&card).unwrap().scroll = true;
assert!(clips(&d, card));
}
}
+8 -1
View File
@@ -1676,6 +1676,10 @@ fn build_spec_tree(
if let NodeKind::Frame { clip } = n.kind {
m.insert("clip".into(), json!(clip));
}
if n.scroll {
// How far the content reaches past the frame: code needs it for `overflow: auto`.
m.insert("scroll".into(), json!(crate::editor::scroll_range(doc, n.id).round()));
}
if let Some(sh) = n.style.shadow {
m.insert(
"shadow".into(),
@@ -2036,7 +2040,7 @@ fn format_compact(spec: &Value) -> String {
out.push('\n');
}
}
out.push_str("## Tree\nFormat: Kind \"layer\" WxH layout style. hug/fill = sizing. Tokens as --name. Text: \"content\" size/lineHeight weight color.\n\n");
out.push_str("## Tree\nFormat: Kind \"layer\" WxH layout style. hug/fill = sizing. Tokens as --name. scroll+N = content scrolls, N px past the bottom. Text: \"content\" size/lineHeight weight color.\n\n");
compact_node(&spec["layoutTree"], 0, &mut out);
out
}
@@ -2137,6 +2141,9 @@ fn compact_style(st: &Value) -> Vec<String> {
if st["clip"] == true {
parts.push("clip".into());
}
if let Some(more) = st["scroll"].as_f64() {
parts.push(format!("scroll+{}", px_num(more)));
}
parts
}
+123
View File
@@ -0,0 +1,123 @@
//! The lean tool list (`?tools=core` on the MCP URL) for agents that load every tool schema up
//! front: the tools a design turn nearly always uses in full, every other tool by name only, and
//! two tools that reach the rest (`search_tools` to read one, `call_tool` to run it).
use serde_json::{Value, json};
/// Listed in full. Picked from the calls in saved chats: together they make nearly all of them.
pub const CORE: [&str; 33] = [
"get_basic_info", "get_selection", "get_tree_summary", "get_children", "find_nodes", "get_node_info",
"get_computed_styles", "get_screenshot", "create_page", "create_artboard", "write_html", "update_styles",
"set_text_content", "rename_nodes", "duplicate_nodes", "move_nodes", "delete_nodes", "create_component",
"create_instance", "swap_instance", "get_components", "get_variables", "set_variables", "bind_variable",
"set_variable_mode", "search_icons", "lint_design", "finish_working_on_nodes", "ask_user", "generate_image",
"fetch_reference_images", "get_guide", "report_issue",
];
pub const SEARCH: &str = "search_tools";
pub const CALL: &str = "call_tool";
/// Most tools `search_tools` returns at once.
const MAX_HITS: usize = 8;
/// `all` (the full catalogue) cut to the core tools, plus `search_tools` and `call_tool`, whose
/// description names every tool left out.
pub fn definitions(all: Vec<Value>) -> Vec<Value> {
let (mut core, rest): (Vec<Value>, Vec<Value>) = all.into_iter().partition(|t| CORE.contains(&name(t)));
let others: Vec<&str> = rest.iter().map(name).collect();
core.push(json!({
"name": SEARCH,
"description": "Find a PaperCraft tool this session does not list (call_tool's description names them all) and read how to use it. Then run it with call_tool.",
"inputSchema": {"type": "object", "properties": {
"query": {"type": "string", "description": "An exact tool name, or words its name or description contains."},
"detail": {"type": "string", "enum": ["name", "description", "schema"], "description": "How much to return per tool (default schema: description and input schema)."}},
"required": ["query"]},
"annotations": {"readOnlyHint": true},
}));
core.push(json!({
"name": CALL,
"description": format!("Run a PaperCraft tool that is not listed here, with the arguments its schema takes (read it with search_tools first). The other tools: {}.", others.join(", ")),
"inputSchema": {"type": "object", "properties": {
"name": {"type": "string"},
"arguments": {"type": "object"}},
"required": ["name"]},
"annotations": {"readOnlyHint": false},
}));
core
}
/// The tools in `all` that `query` names exactly, else those whose name or description holds
/// every word of it; at most `MAX_HITS`, cut to `detail`.
pub fn search(all: &[Value], query: &str, detail: &str) -> Value {
let q = query.trim().to_lowercase();
let exact: Vec<&Value> = all.iter().filter(|t| name(t) == q).collect();
let hits = if exact.is_empty() {
let words: Vec<&str> = q.split_whitespace().collect();
let text = |t: &Value| format!("{} {}", name(t), t["description"].as_str().unwrap_or_default()).to_lowercase();
all.iter().filter(|t| !words.is_empty() && words.iter().all(|w| text(t).contains(w))).collect()
} else {
exact
};
let more = hits.len().saturating_sub(MAX_HITS);
let tools: Vec<Value> = hits
.into_iter()
.take(MAX_HITS)
.map(|t| match detail {
"name" => json!(name(t)),
"description" => json!({"name": name(t), "description": t["description"]}),
_ => json!({"name": name(t), "description": t["description"], "inputSchema": t["inputSchema"]}),
})
.collect();
if tools.is_empty() {
return json!({"tools": [], "hint": "No tool matches; call_tool's description lists every name."});
}
json!({"tools": tools, "more": more})
}
/// `call_tool`'s target: the tool name and its arguments (an empty object when left out).
pub fn target(args: &Value) -> Result<(String, Value), String> {
let name = args["name"].as_str().filter(|n| !n.is_empty()).ok_or("call_tool needs the name of a tool")?;
if [SEARCH, CALL].contains(&name) {
return Err(format!("{name} cannot be run through call_tool"));
}
Ok((name.to_owned(), args.get("arguments").filter(|a| !a.is_null()).cloned().unwrap_or_else(|| json!({}))))
}
fn name(t: &Value) -> &str {
t["name"].as_str().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_core_tool_exists_and_the_rest_are_named() {
let all = crate::mcp::tools::definitions();
let names: Vec<&str> = all.iter().map(name).collect();
assert!(CORE.iter().all(|c| names.contains(c)), "a core tool was renamed or removed");
let lean = definitions(all.clone());
assert_eq!(lean.len(), CORE.len() + 2);
let call = lean.iter().find(|t| name(t) == CALL).unwrap()["description"].as_str().unwrap().to_owned();
assert!(names.iter().filter(|n| !CORE.contains(n)).all(|n| call.contains(n)), "call_tool names every other tool");
let size = |v: &[Value]| serde_json::to_string(v).unwrap().len();
assert!(size(&lean) * 2 < size(&all), "the lean list is less than half the full one");
}
#[test]
fn search_finds_by_name_or_words_and_cuts_to_the_detail() {
let all = crate::mcp::tools::definitions();
let one = search(&all, "update_annotation", "schema");
assert_eq!(one["tools"].as_array().unwrap().len(), 1);
assert!(one["tools"][0]["inputSchema"]["properties"].is_object());
let words = search(&all, "Annotation TEMPLATE", "name");
assert!(words["tools"].as_array().unwrap().iter().all(|n| n.as_str().unwrap().contains("annotation_template")), "{words}");
assert!(search(&all, "zzzz", "name")["tools"].as_array().unwrap().is_empty());
}
#[test]
fn call_tool_unwraps_its_target_but_never_itself() {
assert_eq!(target(&json!({"name": "undo"})).unwrap(), ("undo".into(), json!({})));
assert_eq!(target(&json!({"name": "export", "arguments": {"format": "png"}})).unwrap().1, json!({"format": "png"}));
assert!(target(&json!({"name": "call_tool"})).is_err() && target(&json!({})).is_err());
}
}
+224
View File
@@ -0,0 +1,224 @@
//! A critique offered when a design is finished, and the lessons the person keeps from it
//! (`specs/design-critique/spec.md`). `critique_design` gathers the evidence the agent judges
//! by; `design_lessons` stores what the person approved, in the project store, so every later
//! session sees it in `get_basic_info` and in the next critique.
use crate::io::atomic;
use crate::project::Store;
use crate::model::{Document, NodeId, NodeKind};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::path::PathBuf;
const FILE: &str = ".design-lessons.json";
/// Lessons are rules read before every design: short enough to scan.
const MAX_RULE: usize = 160;
/// Lint issues listed in a critique; the counts cover the rest.
pub const MAX_ISSUES: usize = 20;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lesson {
pub id: String,
pub rule: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub why: String,
/// The project (file id) it belongs to; none for every project.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project: Option<String>,
}
fn path(store: &Store) -> PathBuf {
store.root.join(FILE)
}
/// Every stored lesson; none when the file is missing or unreadable.
pub fn load(store: &Store) -> Vec<Lesson> {
crate::vfs::read(path(store)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
/// The lessons that apply in `project` (its own and the global ones).
pub fn applying(store: &Store, project: Option<&str>) -> Vec<Lesson> {
load(store).into_iter().filter(|l| l.project.is_none() || l.project.as_deref() == project).collect()
}
fn save(store: &Store, lessons: &[Lesson]) -> Result<(), String> {
let json = serde_json::to_vec_pretty(lessons).map_err(|e| e.to_string())?;
atomic::write(&path(store), &json).map_err(|e| format!("could not save lessons: {e}"))
}
/// Store a lesson the person approved and return it.
pub fn add(store: &Store, rule: &str, why: &str, project: Option<String>) -> Result<Lesson, String> {
let rule = rule.trim();
if rule.is_empty() {
return Err("a lesson needs a rule".into());
}
if rule.chars().count() > MAX_RULE {
return Err(format!("keep the rule under {MAX_RULE} characters; put the reason in `why`"));
}
let mut all = load(store);
if let Some(same) = all.iter().find(|l| l.rule.eq_ignore_ascii_case(rule) && l.project == project) {
return Ok(same.clone());
}
let next = all.iter().filter_map(|l| l.id.strip_prefix('L')?.parse::<u32>().ok()).max().unwrap_or(0) + 1;
let lesson = Lesson { id: format!("L{next}"), rule: rule.into(), why: why.trim().into(), project };
all.push(lesson.clone());
save(store, &all)?;
Ok(lesson)
}
/// Remove a lesson; false when no lesson has that id.
pub fn remove(store: &Store, id: &str) -> Result<bool, String> {
let mut all = load(store);
let before = all.len();
all.retain(|l| l.id != id);
if all.len() == before {
return Ok(false);
}
save(store, &all)?;
Ok(true)
}
/// A reviewer's point of view: who they are, what they ask, and how they look.
pub struct Persona {
pub id: &'static str,
pub role: &'static str,
pub asks: &'static str,
pub method: &'static str,
}
/// The reviewers, the person's vision first: a critique judges the design against what it is
/// for. Sources: Connor and Irizarry's objective/element/effect/rationale critique, Nielsen's
/// heuristics, severity scale and cognitive walkthrough (NN/g), W3C's POUR principles.
pub const PERSONAS: &[Persona] = &[
Persona {
id: "vision",
role: "The person's vision (product owner)",
asks: "Does each screen achieve the objective, for the audience, as the brief, references and feedback notes describe?",
method: "For each key element: the objective it serves, the element, its effect on that objective, and why. Read the person's notes (get_feedback) and references first; flag anything the brief asked for that is missing.",
},
Persona {
id: "ux",
role: "UX designer",
asks: "Can people understand and use it without help?",
method: "Nielsen's 10 heuristics: system status, real-world language, control and freedom (undo, exit), consistency, error prevention, recognition over recall, efficiency, minimalism, error recovery, help. Cite the heuristic for each finding.",
},
Persona {
id: "flow",
role: "Flow reviewer",
asks: "Do the screens make one coherent journey for each top task?",
method: "Walk each top task across screens (the `flow` graph, else screen order and names): a clear entry, a way forward and a way back or out on every screen, no dead ends or orphan screens, the same navigation and labels in the same place throughout, what is entered on one screen shown on the next, a confirmation, success and error screen for each action, a first-run or empty entry. At each step ask: will they try this, notice the control, connect it to their goal, see progress?",
},
Persona {
id: "qa",
role: "QA tester",
asks: "What breaks with real data and real states?",
method: "A matrix per screen, each item pass, fail or n/a: empty, loading, error, disabled, focus, long text and names, minimum content, zero, one and many items, missing images, every variable mode, the narrow and wide screen sizes. Overflow and clipping from get_bounds or lint. A state with no design is an open question, not a pass.",
},
Persona {
id: "visual",
role: "Visual designer",
asks: "Does the eye go to the right thing first, and does it hold together?",
method: "Scale and hierarchy (one focal point per screen), balance, contrast between roles, gestalt proximity and alignment, a steady spacing rhythm on the 4px grid, the type scale, every colour a variable, consistent radii and components.",
},
Persona {
id: "accessibility",
role: "Accessibility reviewer",
asks: "Can people with low vision, colour blindness, motor or cognitive limits and keyboard or screen-reader users use it?",
method: "W3C POUR for a design. Perceivable: text contrast 4.5:1 (3:1 for large text and for control borders and icons), colour never the only signal, real text, the layout holds at 320px wide and 200% text. Operable: targets 44px (24px minimum), a focus state designed for every control, headings and a visible current location, undo or confirm on destructive actions, an alternative to every gesture. Understandable: fields keep a visible label (not only a placeholder), errors say how to fix, the same navigation and labels across screens. Robust: controls named for their role in layers and code links.",
},
Persona {
id: "copy",
role: "Content designer",
asks: "Is every word clear, specific and kind?",
method: "Plain language in the users' words, specific buttons (verbs, not OK), no placeholder or lorem text, errors that name the problem and the fix, empty states that say what to do next, neutral wording about people whose gender is unknown.",
},
Persona {
id: "end-user",
role: "A user from the audience",
asks: "As this user, doing my top task, where do I get stuck or give up?",
method: "Take the audience given (else ask): their goal, context and constraints (first visit, in a hurry, on a phone, low vision). Walk the top task screen by screen: what you see, what you think, where you hesitate, the first point you would give up.",
},
];
/// Severity of a finding (Nielsen): rate on frequency, impact and persistence.
pub const SEVERITY: &[&str] = &[
"0 not a problem",
"1 cosmetic: fix if time allows",
"2 minor: low priority",
"3 major: fix before handing over",
"4 catastrophe: blocks the task, fix now",
];
pub const FINDING: &str = "persona, heuristic or check, element (layer name), what was seen, its effect on the objective, evidence (the tool result or screenshot region), severity 0-4, suggestion (kept apart from the observation)";
/// What the agent does with a critique's evidence, in order.
pub const STEPS: &[&str] = &[
"Objective: without `objective` (what this must achieve, for whom, the top tasks) ask the person first; a critique without one is opinion.",
"Evidence: fix every lint error and warning above and lint again; get_screenshot each artboard at scale 1 (2 for small text) in every variable mode; read the person's notes (get_feedback) and the `flow` graph.",
"Review each persona independently: with subagents, one per persona given only its brief and the evidence; alone, one pass per persona, writing its findings before starting the next. Never let reviewers see or debate each other's findings before rating.",
"Each persona lists findings in the finding format and at least one thing that works. Check every lesson; a broken lesson is a finding.",
"Merge: one list, duplicates joined, how many personas found each (two or more is confirmed), severity the mean of their independent ratings.",
"Fix every severity 3 and 4 finding with the smallest edit and check it again; the work is ready when none is open and lint is clean.",
"Report to the person: what works, then findings by severity (observation, evidence, suggestion, fixed or open). Phrase open ones as questions about the objective.",
"Ask the person with ask_user which findings to remember (one question per finding: every project, this project, or not). Save only the approved ones with design_lessons {add}: a one-line rule and its reason.",
];
/// The screens of a page and the arrows drawn between them: the flow a critique walks.
pub fn flow(doc: &Document) -> Value {
let mut screens = crate::editor::screens::declared(doc);
if screens.is_empty() {
screens = doc
.root
.iter()
.copied()
.filter(|id| doc.get(*id).is_some_and(|n| n.is_frame() && crate::editor::screens::device_of(n.rect.w).is_some()))
.collect();
}
let screen_of = |id: NodeId| std::iter::once(id).chain(doc.ancestors(id)).find(|a| screens.contains(a));
let mut links: Vec<(NodeId, NodeId)> = doc
.nodes
.values()
.filter_map(|n| match &n.kind {
NodeKind::Connector { start: Some(s), end: Some(e), .. } => Some((screen_of(s.node)?, screen_of(e.node)?)),
_ => None,
})
.filter(|(a, b)| a != b)
.collect();
links.sort_by_key(|(a, b)| (a.0, b.0));
links.dedup();
let name = |id: &NodeId| doc.get(*id).map_or(String::new(), |n| n.name.clone());
let mut v = json!({
"screens": screens.iter().map(name).collect::<Vec<_>>(),
"links": links.iter().map(|(a, b)| [name(a), name(b)]).collect::<Vec<_>>(),
});
if links.is_empty() {
v["note"] = json!("no arrows between screens: walk the flow by screen order and names, and ask the person for the intended flow");
} else {
let from = |id: &NodeId| links.iter().any(|(a, _)| a == id);
let to = |id: &NodeId| links.iter().any(|(_, b)| b == id);
v["deadEnds"] = json!(screens.iter().filter(|s| to(s) && !from(s)).map(name).collect::<Vec<_>>());
v["unreached"] = json!(screens.iter().filter(|s| !to(s) && !from(s)).map(name).collect::<Vec<_>>());
}
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lessons_are_kept_per_project_and_removed_by_id() {
let store = Store { root: std::env::temp_dir().join(format!("papercraft-lessons-{:016x}", fastrand::u64(..))) };
std::fs::create_dir_all(&store.root).unwrap();
let all = add(&store, "Screens scroll; they never grow", "", None).unwrap();
let brand = add(&store, "Headlines use the accent colour", "brand book", Some("p1".into())).unwrap();
assert_eq!(add(&store, "screens scroll; they never grow", "", None).unwrap().id, all.id, "a repeat is not stored twice");
assert_eq!(applying(&store, Some("p1")).len(), 2);
assert_eq!(applying(&store, Some("p2")).len(), 1, "a project's lesson stays in it");
assert!(remove(&store, &brand.id).unwrap());
assert!(!remove(&store, &brand.id).unwrap());
assert_eq!(load(&store).len(), 1);
assert!(add(&store, &"x".repeat(MAX_RULE + 1), "", None).is_err());
std::fs::remove_dir_all(&store.root).unwrap();
}
}
+25 -3
View File
@@ -533,7 +533,7 @@ fn set_text_flag(n: &mut Node, f: impl Fn(&mut crate::model::TextSpan)) {
fn set_size(n: &mut Node, axis: usize, v: &str, ctx: &Context, a: &mut Applied, key: &str) {
let fs = n.kind.font_size().unwrap_or(16.0);
let v = v.trim();
let v = if full_viewport(v) { "100%" } else { v.trim() };
let is_text = matches!(n.kind, NodeKind::Text { .. });
match v {
"fit-content" | "auto" | "max-content" | "min-content" => {
@@ -574,6 +574,11 @@ fn set_size(n: &mut Node, axis: usize, v: &str, ctx: &Context, a: &mut Applied,
}
}
/// `100vh` and its kin: the whole screen, which is the frame a page is drawn in.
fn full_viewport(v: &str) -> bool {
matches!(v.trim(), "100vh" | "100dvh" | "100svh" | "100lvh" | "100vw" | "100dvw" | "100svw" | "100lvw")
}
fn resize_axis(n: &mut Node, axis: usize, size: f64) {
let mut r = n.rect;
if axis == 0 {
@@ -1090,7 +1095,8 @@ fn apply_resolved(n: &mut Node, styles: &[(String, String)], ctx: &Context) -> A
None => false,
},
"flexGrow" | "flex" => {
let grow = split_ws(v)
let parts = split_ws(v);
let grow = parts
.first()
.and_then(|g| g.parse::<f64>().ok())
.unwrap_or(0.0);
@@ -1101,6 +1107,12 @@ fn apply_resolved(n: &mut Node, styles: &[(String, String)], ctx: &Context) -> A
} else {
1
};
// `flex: 0 0 120px`: a fixed 120 on the main axis.
if grow == 0.0
&& let Some(basis) = parts.get(2).filter(|b| length(b, fs).is_some())
{
set_size(n, ma, basis, ctx, &mut a, k);
}
if grow > 0.0 {
axis_set(n, ma, Sizing::Fill);
if ma == 0
@@ -1188,7 +1200,11 @@ fn apply_resolved(n: &mut Node, styles: &[(String, String)], ctx: &Context) -> A
},
"minWidth" | "minHeight" => {
let axis = usize::from(k == "minHeight");
if matches!(lower.as_str(), "none" | "auto" | "0") {
if full_viewport(&lower) && ctx.parent_layout.is_some() {
// `min-height: 100vh` on a page shell: fill the screen.
axis_set(n, axis, Sizing::Fill);
true
} else if matches!(lower.as_str(), "none" | "auto" | "0") {
n.layout_child.min_size[axis] = None;
true
} else if let Some(px) = length(v, fs) {
@@ -1220,6 +1236,12 @@ fn apply_resolved(n: &mut Node, styles: &[(String, String)], ctx: &Context) -> A
false
}
}
// A length basis is the size on the parent's main axis (`auto`, `0%` change nothing).
"flexBasis" if ctx.parent_layout.is_some() && length(v, fs).is_some() => {
let horizontal = ctx.parent_layout.is_some_and(|pl| pl.direction == Direction::Horizontal);
set_size(n, if horizontal { 0 } else { 1 }, v, ctx, &mut a, k);
true
}
"flexShrink" | "flexBasis" | "boxSizing" | "zIndex" | "cursor" | "whiteSpace"
| "fontFamily" | "wordBreak" | "overflowWrap" => {
// Accepted without an equivalent; harmless. fontFamily: Inter is the only face.
+13 -6
View File
@@ -34,7 +34,9 @@ pub fn stop(chat: &str) {
/// Runs the helper `command` (`{prompt}` is passed as `$PAPERCRAFT_PROMPT`) for one task.
/// `chat`: the chat that asked, so its Stop button ends the helper too.
pub fn run(command: &str, chat: Option<&str>, args: &serde_json::Value) -> ToolResult {
/// `agent`: the helper's name and the session of the agent that delegated it, passed to its
/// `papercraft-cli` calls so they are attributed to it and its claims.
pub fn run(command: &str, chat: Option<&str>, agent: (&str, &str), args: &serde_json::Value) -> ToolResult {
if command.trim().is_empty() {
return Err("No helper agent is set up. The user can choose one in Settings, Chat, Helper; do the work yourself.".into());
}
@@ -56,6 +58,8 @@ pub fn run(command: &str, chat: Option<&str>, args: &serde_json::Value) -> ToolR
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
let mut child = cmd
.env("PAPERCRAFT_PROMPT", &prompt)
.env("PAPERCRAFT_AGENT", agent.0)
.env("PAPERCRAFT_PARENT", agent.1)
// An app opened from Finder has a bare PATH: give the helper the user's shell PATH.
.env("PATH", crate::chat::path::resolved_path())
.current_dir(std::env::temp_dir())
@@ -147,16 +151,19 @@ mod tests {
}
// The task tries to run a command; it must arrive as plain text.
let task = "check Home\"; touch pwned; echo \"";
let out = run("printf '%s' {prompt} | tail -c 40", None, &json!({"role": "qa", "task": task})).unwrap();
let out = run("printf '%s' {prompt} | tail -c 40", None, ("Helper", ""), &json!({"role": "qa", "task": task})).unwrap();
let Out::Text(t) = &out[0] else { panic!() };
assert!(t.ends_with(task), "{t}");
assert!(!std::env::temp_dir().join("pwned").exists());
assert!(run("", None, &json!({"role": "qa", "task": "x"})).unwrap_err().contains("Settings"));
assert!(run("echo", None, &json!({"role": "design", "task": "x"})).is_err());
assert!(run("exit 3", None, &json!({"role": "read", "task": "x"})).is_err());
assert!(run("", None, ("Helper", ""), &json!({"role": "qa", "task": "x"})).unwrap_err().contains("Settings"));
assert!(run("echo", None, ("Helper", ""), &json!({"role": "design", "task": "x"})).is_err());
assert!(run("exit 3", None, ("Helper", ""), &json!({"role": "read", "task": "x"})).is_err());
let who = run("printf '%s|%s' \"$PAPERCRAFT_AGENT\" \"$PAPERCRAFT_PARENT\"", None, ("Chat / build 1", "s1"), &json!({"role": "qa", "task": "x"})).unwrap();
let Out::Text(t) = &who[0] else { panic!() };
assert_eq!(t, "Chat / build 1|s1", "the helper's CLI calls carry its identity");
assert_eq!(tail("héllo", 4), "llo");
// Stop ends a running helper, and the process it started, at once.
let t = std::thread::spawn(|| run("sleep 30", Some("chat-stop-test"), &json!({"role": "qa", "task": "x"})));
let t = std::thread::spawn(|| run("sleep 30", Some("chat-stop-test"), ("Helper", ""), &json!({"role": "qa", "task": "x"})));
std::thread::sleep(Duration::from_millis(500));
let begun = Instant::now();
stop("chat-stop-test");
+394 -31
View File
@@ -238,6 +238,27 @@ fn resolve(ed: &Editor, key: &str, default_page: usize) -> Result<(usize, NodeId
Ok((page, id))
}
/// The existing layers a call names (`nodeId`, `nodeIds`, `targetNodeId`, `parentId`, and the
/// same keys inside `updates`, `moves` and `nodes`): what the swarm checks claims and conflicts on.
pub(crate) fn named_layers(ed: &Editor, args: &Value) -> Vec<(usize, NodeId)> {
let Some(m) = args.as_object() else { return Vec::new() };
let def = page_arg(ed, &Args(m)).unwrap_or(ed.active_page);
let nested = ["updates", "moves", "nodes"].into_iter().flat_map(|l| m.get(l).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_object));
let mut keys: Vec<&str> = Vec::new();
for o in std::iter::once(m).chain(nested) {
for k in ["nodeId", "targetNodeId", "parentId"] {
keys.extend(o.get(k).and_then(Value::as_str));
}
if let Some(a) = o.get("nodeIds").and_then(Value::as_array) {
keys.extend(a.iter().filter_map(Value::as_str));
}
}
let mut out: Vec<(usize, NodeId)> = keys.into_iter().filter(|k| *k != ROOT).filter_map(|k| resolve(ed, k, def).ok()).collect();
out.sort();
out.dedup();
out
}
/// Resolve several ids that must all live on one page.
fn resolve_all(
ed: &Editor,
@@ -261,6 +282,11 @@ fn resolve_all(
/// Run one tool. Errors are returned as messages for the agent.
pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
let r = dispatch(host, name, args);
super::incremental::after_call(host.editor(), name, args, r)
}
fn dispatch(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
let empty = Map::new();
let a = Args(args.as_object().unwrap_or(&empty));
match name {
@@ -288,6 +314,7 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
// The first content on the page the user is looking at is brought into view.
let was_empty = ed.doc.root.is_empty();
let covered = if GUARDED.contains(&name) { screen_guard(ed, &a)? } else { None };
let boards = super::room::snapshot(ed.page_doc(scope));
let r = match name {
"create_page" => create_page(ed, &a),
"rename_pages" => rename_pages(ed, &a),
@@ -297,6 +324,7 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
"get_selection" => selection(ed),
"get_node_info" => node_info(ed, &a),
"get_children" => children(ed, &a),
"get_bounds" => get_bounds(ed, &a),
"get_tree_summary" => tree_summary(ed, &a),
"get_screenshot" => screenshot(host, &a),
"get_jsx" => jsx(host, &a),
@@ -325,7 +353,7 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
super::imagegen::generate(host.project().map(|p| p.dir.clone()).as_deref(), None, &provider, &Value::Object(a.0.clone()))
}
#[cfg(not(target_arch = "wasm32"))]
"delegate" => super::delegate::run(&crate::ui::settings::ChatPrefs::load().helper_command, None, &Value::Object(a.0.clone())),
"delegate" => super::delegate::run(&crate::ui::settings::ChatPrefs::load().helper_command, None, ("Helper", ""), &Value::Object(a.0.clone())),
"find_nodes" => find_nodes(ed, &a),
"set_component_props" => set_component_props(ed, &a),
"set_instance_props" => set_instance_props(ed, &a),
@@ -334,6 +362,11 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
"set_screens" => set_screens(ed, &a),
"export" => export(host, &a),
"export_combined_pdf" => export_pdf(host, &a),
"export_presentation" => export_presentation(host, &a),
"mark_handoff" => super::handoff::mark(host, args),
"list_handoffs" => super::handoff::list(host),
"get_handoff_changes" => super::handoff::get_changes(host, args),
"export_handoff" => export_handoff(host, args),
"create_artboard" => create_artboard(ed, &a),
"write_html" => write_html(ed, &a),
"create_shape" => create_shape(ed, &a),
@@ -341,6 +374,7 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
"set_text_content" => set_text_content(ed, &a),
"get_variables" => get_variables(ed, &a),
"lint_design" => lint_design(ed, &a),
"get_changes" => super::incremental::get_changes(ed, a.0),
"get_feedback" => get_feedback(ed, &a),
"add_feedback" => add_feedback(ed, &a),
"resolve_feedback" => resolve_feedback(ed, &a),
@@ -363,6 +397,11 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
"rename_nodes" => rename_nodes(ed, &a),
"set_code_link" => set_code_link(ed, &a),
"apply_ui_kit" => apply_ui_kit(host, &a),
"critique_design" => critique_design(host, &a),
"claim_nodes" | "release_claims" | "list_claims" => {
Err("claims are shared through the running PaperCraft app; offline there is one writer at a time".into())
}
"design_lessons" => design_lessons(host, &a),
"delete_nodes" => delete_nodes(ed, &a),
"duplicate_nodes" => duplicate_nodes(ed, &a),
"move_nodes" => move_nodes(ed, &a),
@@ -371,7 +410,11 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
"undo" | "redo" => undo_redo(ed, &a, name == "undo"),
"finish_working_on_nodes" => {
host.save()?;
text(json!({"ok": true, "saved": host.project().is_some()}))
let mut v = json!({"ok": true, "saved": host.project().is_some()});
if mark_critiqued(host) {
v["next"] = json!("The design changed since its last critique: ask the person (ask_user) whether to critique it now; on yes call critique_design.");
}
text(v)
}
_ => Err(format!("unknown tool `{name}`")),
};
@@ -379,16 +422,36 @@ pub fn call(host: &mut dyn Host, name: &str, args: &Value) -> ToolResult {
if r.is_ok() && was_empty && !ed.doc.root.is_empty() && name != "set_viewport" {
ed.zoom_to_fit();
}
let pushed = if r.is_ok() { make_room(ed, scope, &boards) } else { None };
r.map(|mut out| {
if let Some(v) = covered {
out.push(Out::Text(serde_json::to_string_pretty(&v).unwrap_or_default()));
}
out.extend(pushed.map(Out::Text));
out
})
}
}
}
/// Frames that grew into the ones under them push those down (`room`), as one more undo step;
/// a note for the tool's output names them.
fn make_room(ed: &mut Editor, page: usize, before: &std::collections::HashMap<NodeId, Rect>) -> Option<String> {
let moves = super::room::moves(ed.page_doc(page), before);
if moves.is_empty() {
return None;
}
let names: Vec<String> = moves.iter().filter_map(|(id, _)| ed.page_doc(page).get(*id).map(|n| n.name.clone())).collect();
ed.with_page(page, |ed| {
ed.edit("Make room", |tx| {
for (id, dy) in &moves {
tx.node_mut(*id).unwrap().rect.y += dy;
}
})
});
Some(format!("moved down to clear a frame that grew: {}", names.join(", ")))
}
/// Projects match by manifest id, name or folder path.
fn find_project(store: &Store, key: &str) -> Result<PathBuf, String> {
let key = key.trim().trim_start_matches("/file/");
@@ -515,8 +578,9 @@ fn set_screens(ed: &mut Editor, a: &Args) -> ToolResult {
let role = match a.str("role").unwrap_or("screen") {
"screen" => Role::Screen,
"overlay" => Role::Overlay,
"section" => Role::Section,
"none" => Role::None,
r => return Err(format!("role `{r}` is not screen, overlay or none")),
r => return Err(format!("role `{r}` is not screen, overlay, section or none")),
};
let (page, ids) = resolve_all(ed, &a.strs("nodeIds")?, page_arg(ed, a)?)?;
ed.with_page(page, |ed| ed.set_role(&ids, role))?;
@@ -528,6 +592,9 @@ fn set_screens(ed: &mut Editor, a: &Args) -> ToolResult {
fn screen_json(ed: &Editor, page: usize, id: NodeId) -> Option<Value> {
let doc = ed.page_doc(page);
let n = doc.get(id)?;
if n.section {
return Some(json!({"isSection": true}));
}
if n.screen {
return Some(json!({"isScreen": true, "device": crate::editor::screens::device_of(n.rect.w).unwrap_or("Custom")}));
}
@@ -703,6 +770,10 @@ fn basic_info(host: &mut dyn Host, a: &Args) -> ToolResult {
p.dir.clone(),
)
});
let lessons: Vec<Value> = super::critique::applying(host.store(), project.as_ref().map(|p| p.0.as_str()))
.into_iter()
.map(|l| json!({"id": l.id, "rule": l.rule}))
.collect();
let ed = host.editor();
// Reports every page's node count (also reached right after `open_file`).
ed.finish_loading();
@@ -745,6 +816,8 @@ fn basic_info(host: &mut dyn Host, a: &Args) -> ToolResult {
"page": {"id": ed.pages[page].id, "name": ed.pages[page].name, "isActive": page == ed.active_page},
"pages": pages,
"nodeCount": doc.nodes.len(),
"rev": ed.changes.rev(),
"lessons": lessons,
"artboards": artboards,
"screens": crate::editor::screens::declared(doc).iter().map(|id| {
let n = doc.get(*id).unwrap();
@@ -1086,6 +1159,38 @@ fn children(ed: &mut Editor, a: &Args) -> ToolResult {
text(json!({"children": kids}))
}
fn get_bounds(ed: &mut Editor, a: &Args) -> ToolResult {
let def = page_arg(ed, a)?;
let targets: Vec<(usize, NodeId)> = match a.get("nodeIds") {
Some(_) => a.strs("nodeIds")?.iter().map(|k| resolve(ed, k, def)).collect::<Result<_, _>>()?,
None => ed.page_doc(def).root.iter().map(|id| (def, *id)).collect(),
};
let depth = a.num("depth").filter(|d| *d >= 1.0).map(|d| d as usize);
let mut rows: Vec<Value> = Vec::new();
let mut pending: Vec<String> = Vec::new();
for (page, id) in targets {
let room = super::bounds::MAX_ROWS - rows.len();
if room == 0 {
pending.push(node_key(ed, page, id));
continue;
}
let key = |n: NodeId| node_key(ed, page, n);
let got = super::bounds::collect(ed.page_doc(page), &[id], depth, room, &key);
rows.extend(got.rows);
pending.extend(got.pending.into_iter().map(key));
}
let mut out = json!({"columns": super::bounds::COLUMNS, "rows": rows});
if !pending.is_empty() {
out["truncated"] = json!(true);
out["continueWith"] = json!(pending);
out["note"] = json!(format!(
"Stopped at {} rows. Call get_bounds again with nodeIds = continueWith (same depth) for the rest.",
super::bounds::MAX_ROWS
));
}
text(out)
}
/// Text shown per text layer in `get_tree_summary` unless `fullText` is set.
const TREE_TEXT_CHARS: usize = 40;
@@ -1220,7 +1325,7 @@ fn screenshot(host: &mut dyn Host, a: &Args) -> ToolResult {
let (page, roots) = match a.str("nodeId").filter(|k| !k.is_empty() && *k != ROOT) {
Some(k) => {
let (p, id) = resolve(ed, k, def)?;
(p, vec![id])
(p, crate::io::export::with_layers_on_top(ed.page_doc(p), &[id]))
}
None => (def, ed.page_doc(def).root.clone()),
};
@@ -1479,7 +1584,7 @@ fn fill_image(ed: &mut Editor, a: &Args) -> ToolResult {
fn ask_user(a: &Args) -> ToolResult {
let qs = a.arr("questions")?;
if !(1..=ASK_MAX_QUESTIONS).contains(&qs.len()) {
return Err(format!("ask 1 to {ASK_MAX_QUESTIONS} questions"));
return Err(format!("questions has {} items; provide 1 to {ASK_MAX_QUESTIONS} questions and retry", qs.len()));
}
for (i, q) in qs.iter().enumerate() {
let n = q["options"].as_array().map_or(0, Vec::len);
@@ -1714,9 +1819,10 @@ fn guide(a: &Args) -> ToolResult {
}
"html" | "write_html" => tools::GUIDE_HTML,
"whiteboard" | "excalidraw" => tools::GUIDE_WHITEBOARD,
"skill" | "papercraft" => include_str!("../../skills/papercraft/SKILL.md"),
_ => {
return Err(format!(
"unknown topic `{t}`; topics: papercraft-mcp-instructions, html, whiteboard"
"unknown topic `{t}`; topics: papercraft-mcp-instructions, html, whiteboard, skill"
));
}
};
@@ -2419,6 +2525,64 @@ fn export_pdf(_: &mut dyn Host, _: &Args) -> ToolResult {
Err(NO_DISK.into())
}
#[cfg(target_arch = "wasm32")]
fn export_presentation(_: &mut dyn Host, _: &Args) -> ToolResult {
Err(NO_DISK.into())
}
/// A presentation deck of pages (default all): cover, contents, a divider per page, a slide
/// per screen, closing slide (`io::deck`).
#[cfg(not(target_arch = "wasm32"))]
fn export_presentation(host: &mut dyn Host, a: &Args) -> ToolResult {
let project_name = host.project().map(|p| p.manifest.name.clone());
let ed = host.editor();
ed.finish_loading();
let pages: Vec<usize> = match a.strs("pageIds") {
Ok(keys) if !keys.is_empty() => keys.iter().map(|k| find_page(ed, k)).collect::<Result<_, _>>()?,
_ => (0..ed.pages.len()).collect(),
};
let sections: Vec<crate::io::deck::Section> = pages
.iter()
.map(|&p| crate::io::deck::Section { name: ed.pages[p].name.clone(), doc: ed.page_doc(p), screens: crate::io::deck::screens_of(ed.page_doc(p)) })
.collect();
let screens: usize = sections.iter().map(|s| s.screens.len()).sum();
if screens == 0 {
return Err("no screens to present: these pages have no declared screens and no top-level frames of 300 × 300 or more".into());
}
let title = a.str("title").map(str::to_owned).or(project_name).unwrap_or_else(|| "Presentation".into());
let language = match a.str("language") {
Some(code) => Some(crate::io::deck::Lang::parse(code).ok_or_else(|| format!("language `{code}` is not one of en, pt, es, fr, de, it"))?),
None => None,
};
let meta = crate::io::deck::Meta {
title: title.clone(),
subtitle: a.str("subtitle").map(str::to_owned),
author: a.str("author").map(str::to_owned),
now_ms: crate::project::format::now_ms(),
language,
};
let path = match a.str("path") {
Some(p) => PathBuf::from(p),
None => {
let dir = out_dir(a);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
unique_path(&dir, &title, "pdf")
}
};
crate::io::atomic::write(&path, &crate::io::deck::build(&meta, &sections)).map_err(|e| e.to_string())?;
text(json!({"file": path, "screens": screens, "pages": sections.iter().filter(|s| !s.screens.is_empty()).count()}))
}
#[cfg(not(target_arch = "wasm32"))]
fn export_handoff(host: &mut dyn Host, a: &Value) -> ToolResult {
super::handoff::bundle::export(host, a)
}
#[cfg(target_arch = "wasm32")]
fn export_handoff(_: &mut dyn Host, _: &Value) -> ToolResult {
Err(NO_DISK.into())
}
#[cfg(not(target_arch = "wasm32"))]
fn export(host: &mut dyn Host, a: &Args) -> ToolResult {
use crate::io::export::{Format, Item, Scope, Spec};
@@ -2935,6 +3099,10 @@ impl Builder<'_, '_> {
/// Positioning that needs the final size (right/bottom).
fn place(&mut self, id: NodeId, a: &css::Applied, parent: &Parent) {
if let (Some(ps), true) = (parent.size, a.right.is_some() || a.bottom.is_some()) {
// An absolute box is not laid out with its parent: hug its content before measuring.
if self.tx.doc().get(id).is_some_and(|n| n.layout.is_some()) {
crate::layout::layout_frame(self.tx, id);
}
let n = self.tx.node_mut(id).unwrap();
if let Some(r) = a.right {
n.rect.x = ps.0 - n.rect.w - r;
@@ -2952,7 +3120,23 @@ impl Builder<'_, '_> {
let explicit = get(styles, if ca == 0 { "width" } else { "height" }).is_some()
|| get(styles, "alignSelf").is_some_and(|v| v != "stretch")
|| matches!(get(styles, "position"), Some("absolute" | "fixed"));
if parent.stretch && parent.definite[ca] && !explicit {
// A text in a column that centres or aligns its children still wraps at the column's
// width, as a browser's block does: fill it and align its lines instead.
let text_in_column = ca == 0 && matches!(n.kind, NodeKind::Text { .. });
if text_in_column
&& !parent.stretch
&& parent.definite[0]
&& !explicit
&& let (Some(l), NodeKind::Text { align, .. }) = (parent.layout, &mut n.kind)
&& get(styles, "textAlign").is_none()
{
*align = match l.align_cross {
crate::model::Align::Center => TextAlign::Center,
crate::model::Align::End => TextAlign::Right,
_ => TextAlign::Left,
};
}
if (parent.stretch || text_in_column) && parent.definite[ca] && !explicit {
n.layout_child.sizing[ca] = Sizing::Fill;
if ca == 0
&& let NodeKind::Text { auto_width, .. } = &mut n.kind
@@ -3303,9 +3487,14 @@ impl Builder<'_, '_> {
index: &mut Option<usize>,
) -> Option<NodeId> {
let raw = el.raw.clone().unwrap_or_default();
// `color: var(--on-accent)` on the <svg> is what its currentColor strokes take, bound to
// that variable so a theme change reaches them.
let color_var = get(own, "color")
.or_else(|| get(inherited, "color"))
.and_then(|c| c.trim().strip_prefix("var(--")?.split([')', ',']).next().map(|v| v.trim().to_owned()));
let color = get(own, "color")
.or_else(|| get(inherited, "color"))
.and_then(css::color)
.and_then(|c| css::color(&css::substitute_vars(c).0))
.unwrap_or(Color::BLACK);
let fs = 16.0;
let size_of = |k: &str| {
@@ -3390,6 +3579,14 @@ impl Builder<'_, '_> {
for mut s in shapes {
s.id = self.tx.alloc_id();
s.children.clear();
if let Some(var) = &color_var {
if s.style.stroke == Some(color) {
s.bindings.insert("stroke".into(), var.clone());
}
for p in s.style.fills.iter_mut().filter(|p| matches!(p, Paint::Solid { color: c, .. } if *c == color)) {
*p = Paint::solid_var(color, var);
}
}
self.tx.insert(s, Some(fid), None);
}
self.place(fid, &a, parent);
@@ -4066,7 +4263,7 @@ fn create_artboard(ed: &mut Editor, a: &Args) -> ToolResult {
return Err("styles.width and styles.height are required (e.g. \"1440px\")".into());
}
let page_id = ed.pages[page].id.clone();
let (id, ignored) = ed.with_page(page, |ed| {
let (id, ignored, device) = ed.with_page(page, |ed| {
ed.edit("Create artboard", |tx| {
let mut n = Node::new(
NodeId(0),
@@ -4084,6 +4281,14 @@ fn create_artboard(ed: &mut Editor, a: &Args) -> ToolResult {
});
let a = css::apply(&mut n, &styles, &Context::default());
let mut ignored = a.ignored.clone();
// A screen keeps its device's height and what does not fit scrolls (`screen_fit`);
// `overflow: visible` keeps a hugging board (a long landing page drawn in full).
let device = super::screen_fit::device_height(n.rect.w)
.filter(|_| n.layout_child.sizing[1] == Sizing::Hug && get(&styles, "overflow").is_none_or(|o| o != "visible"));
if let Some(h) = device {
n.layout_child.sizing[1] = Sizing::Fixed;
n.rect.h = h;
}
if let Some((src, mode)) = &a.image {
match image_asset(src) {
Ok(asset) => n.style.fills.push(Paint::Image {
@@ -4102,10 +4307,15 @@ fn create_artboard(ed: &mut Editor, a: &Args) -> ToolResult {
let id = tx.insert(n, None, None);
remember_stretch(&page_id, id, &styles);
relayout(tx, Some(id));
(id, ignored)
(id, ignored, device)
})
});
let mut v = json!({"id": node_key(ed, page, id), "name": name, "pageId": ed.pages[page].id});
if let Some(h) = device {
v["note"] = json!(format!(
"height set to the device's {h}px; content taller than the screen scrolls inside it (the main column, else the screen). Pass overflow: \"visible\" to let the board grow instead."
));
}
if !ignored.is_empty() {
v["ignoredStyles"] = json!(ignored);
}
@@ -4141,7 +4351,8 @@ fn write_html(ed: &mut Editor, a: &Args) -> ToolResult {
{
return Err("insert-children needs a frame or group target; use mode \"replace\" or target its parent".into());
}
let tree = html::parse(src);
let mut tree = html::parse(src);
let rewritten = super::rewrite::rewrite(&mut tree);
#[cfg(not(target_arch = "wasm32"))]
crate::plugins::prefetch(&tree, &crate::ui::settings::ChatPrefs::load().plugins);
let page_id = ed.pages[page].id.clone();
@@ -4216,10 +4427,17 @@ fn write_html(ed: &mut Editor, a: &Args) -> ToolResult {
}
}
relayout(b.tx, parent_id.or(made.first().copied()));
let (ig, w) = (b.ignored, b.warnings);
let (ig, mut w) = (b.ignored, b.warnings);
if let Some(screen) = parent_id.or(made.first().copied()).and_then(|id| artboard_of(b.tx.doc(), id)) {
let scrolled = super::screen_fit::fit(b.tx, screen, relayout, &|n| stretches(&page_id, n));
if !scrolled.is_empty() {
w.push(format!("content is taller than the screen, so it scrolls in: {} (the rest stays fixed)", scrolled.join(", ")));
}
}
(made, ig, w)
})
});
let warnings: Vec<String> = rewritten.into_iter().chain(warnings).collect();
if created.is_empty() && !warnings.is_empty() {
return Err(warnings.join("; "));
}
@@ -5012,18 +5230,35 @@ fn lint_design(ed: &mut Editor, a: &Args) -> ToolResult {
Some(v) => v.iter().filter_map(Value::as_f64).collect(),
None => super::lint::DEFAULT_SCALE.to_vec(),
};
let whole_page = a.str("nodeId").is_none_or(|n| n.is_empty() || n == "root");
let since = a.num("since").filter(|s| *s >= 0.0).map(|s| s as u64);
let scope = super::incremental::lint_scope(ed, page, &roots, since, a.bool("changedOnly").unwrap_or(false));
let total: usize = roots.iter().map(|r| ed.page_doc(page).subtree(*r).len()).sum();
let fixed = if a.bool("fix").unwrap_or(false) {
ed.with_page(page, |ed| {
ed.edit("Auto-fix design lint", |tx| {
super::lint::autofix(tx, &roots, &scale)
ed.edit("Auto-fix design lint", |tx| match &scope.ids {
None => super::lint::autofix(tx, &roots, &scale),
Some(ids) => {
let mut ids: Vec<_> = ids.iter().copied().collect();
ids.sort();
ids.into_iter().filter(|id| super::lint::autofix_node(tx, *id, &scale)).count()
}
})
})
} else {
0
};
// The next `changedOnly` lint starts from here. A subtree lint leaves the rest unchecked.
if whole_page {
let page_id = ed.pages[page].id.clone();
ed.changes.note_lint(&page_id);
}
let doc = ed.page_doc(page);
let mut issues = super::lint::lint(doc, &roots, &scale);
issues.extend(super::lint::not_an_instance(doc, &roots, &super::lint::component_mains(ed)));
if let Some(ids) = &scope.ids {
issues.retain(|i| ids.contains(&i.node));
}
// Layers hidden behind a drawer or modal in their screen are not fix-me findings: nobody sees them.
let before = issues.len();
issues.retain(|i| !crate::editor::screens::coverage(doc, i.node).is_some_and(|c| c.is_hidden()));
@@ -5042,9 +5277,13 @@ fn lint_design(ed: &mut Editor, a: &Args) -> ToolResult {
"name": doc.get(i.node).map(|n| n.name.clone()), "message": i.message, "fix": i.fix})
})
.collect();
let checked = scope.ids.as_ref().map_or(total, |ids| ids.len());
text(json!({
"errors": count("error"), "warnings": count("warning"), "info": count("info"),
"fixedNodes": fixed,
"rev": ed.changes.rev(),
"covered": {"checked": checked, "total": total, "since": scope.since,
"partial": scope.ids.is_some(), "fullPassBecause": scope.fallback},
"byRule": by_rule, "issues": list,
"truncated": issues.len() > 200,
"skippedHidden": skipped_hidden,
@@ -6445,6 +6684,90 @@ fn call_json(host: &mut dyn Host, name: &str, args: Value) -> Result<Value, Stri
serde_json::from_str(t).map_err(|e| format!("{name}: {e}"))
}
/// The revision each project was last critiqued or offered a critique at, so a finish with no
/// edits since does not offer it again.
fn critiqued() -> &'static Mutex<HashMap<String, u64>> {
static S: OnceLock<Mutex<HashMap<String, u64>>> = OnceLock::new();
S.get_or_init(Default::default)
}
/// Records the current revision; true when it differs from the last critiqued or offered one.
fn mark_critiqued(host: &mut dyn Host) -> bool {
let key = host.project().map(|p| p.manifest.id.clone()).unwrap_or_default();
let rev = host.editor().changes.rev();
critiqued().lock().unwrap().insert(key, rev) != Some(rev)
}
/// What a critique judges by (`critique`): the objective, the reviewers, the lint, the flow
/// between the page's screens, the person's lessons that apply here and the steps, ending with
/// the offer to keep findings as lessons.
fn critique_design(host: &mut dyn Host, a: &Args) -> ToolResult {
use super::critique::{FINDING, MAX_ISSUES, PERSONAS, SEVERITY, STEPS};
let wanted = match a.get("personas") {
Some(_) => a.strs("personas")?,
None => PERSONAS.iter().map(|p| p.id.to_string()).collect(),
};
if let Some(bad) = wanted.iter().find(|w| !PERSONAS.iter().any(|p| p.id == w.as_str())) {
let all: Vec<&str> = PERSONAS.iter().map(|p| p.id).collect();
return Err(format!("no persona `{bad}` (personas: {})", all.join(", ")));
}
let mut args = json!({});
for k in ["pageId", "nodeId"] {
if let Some(v) = a.str(k) {
args[k] = json!(v);
}
}
let lint = call_json(host, "lint_design", args)?;
let project = host.project().map(|p| p.manifest.id.clone());
let lessons = super::critique::applying(host.store(), project.as_deref());
mark_critiqued(host);
let ed = host.editor();
let page = page_arg(ed, a)?;
let flow = super::critique::flow(ed.page_doc(page));
let issues: Vec<Value> = lint["issues"].as_array().map(|i| i.iter().take(MAX_ISSUES).cloned().collect()).unwrap_or_default();
let personas: Vec<Value> = PERSONAS
.iter()
.filter(|p| wanted.iter().any(|w| w == p.id))
.map(|p| json!({"id": p.id, "role": p.role, "asks": p.asks, "method": p.method}))
.collect();
text(json!({
"objective": a.str("objective").unwrap_or("missing: ask the person what this must achieve, for whom, and the top tasks"),
"audience": a.str("audience").unwrap_or("missing: take it from the objective or ask"),
"personas": personas,
"findingFormat": FINDING,
"severity": SEVERITY,
"lint": {"errors": lint["errors"], "warnings": lint["warnings"], "issues": issues},
"flow": flow,
"lessons": lessons,
"steps": STEPS,
}))
}
/// List, add or remove the person's design lessons.
fn design_lessons(host: &mut dyn Host, a: &Args) -> ToolResult {
let project = host.project().map(|p| p.manifest.id.clone());
let store = host.store();
let mut v = json!({});
if let Some(add) = a.get("add") {
let add = add.as_object().ok_or("`add` is {rule, why, scope}")?;
let s = |k: &str| add.get(k).and_then(Value::as_str).unwrap_or("");
let scope = match s("scope") {
"" | "all" => None,
"project" => Some(project.clone().ok_or("no project is open to keep a project lesson in")?),
o => return Err(format!("scope is \"all\" or \"project\", not `{o}`")),
};
v["added"] = json!(super::critique::add(store, s("rule"), s("why"), scope)?);
}
if let Some(id) = a.str("remove") {
if !super::critique::remove(store, id)? {
return Err(format!("no lesson `{id}`"));
}
v["removed"] = json!(id);
}
v["lessons"] = json!(super::critique::applying(store, project.as_deref()));
text(v)
}
/// Build a "UI Kit / <name>" page from a kit (`crate::ui_kits`): its variables (Light and Dark),
/// tokens, and its components, each a main component linked to the library's code.
fn apply_ui_kit(host: &mut dyn Host, a: &Args) -> ToolResult {
@@ -6459,24 +6782,42 @@ fn apply_ui_kit(host: &mut dyn Host, a: &Args) -> ToolResult {
call_json(host, "set_variables", json!({"pageId": pid, "variables": map(kit.light), "mode": "Light"}))?;
call_json(host, "set_variables", json!({"pageId": pid, "variables": map(kit.dark), "mode": "Dark"}))?;
call_json(host, "set_tokens", json!({"pageId": pid, "tokens": map(kit.tokens)}))?;
let body: String = kit.components.iter().map(|c| c.html).collect();
let html = format!(
r#"<div layer-name="UI Kit / {}" style="display:flex;flex-wrap:wrap;gap:32px;align-items:flex-start;padding:48px;width:1200px;background:var(--{})">{body}</div>"#,
r#"<div layer-name="UI Kit / {}" style="display:flex;flex-wrap:wrap;gap:32px;align-items:flex-start;padding:48px;width:1200px;background:var(--{})"></div>"#,
kit.name, kit.surface
);
let written = call_json(host, "write_html", json!({"pageId": pid, "targetNodeId": "root", "html": html}))?;
let board = written["createdNodeIds"][0].as_str().ok_or("write_html made no frame")?.to_owned();
let kids = call_json(host, "get_children", json!({"pageId": pid, "nodeId": board}))?;
let mut made = Vec::new();
for c in kit.components {
let Some(node) = kids["children"].as_array().into_iter().flatten().find(|k| k["name"] == c.name).and_then(|k| k["id"].as_str()) else { continue };
let comp = call_json(host, "create_component", json!({"pageId": pid, "nodeId": node}))?;
let cid = comp["id"].as_str().unwrap_or(node).to_owned();
call_json(host, "set_code_link", json!({"pageId": pid, "nodeId": cid, "kit": kit.id, "import": c.import, "react": c.react, "egui": c.egui}))?;
made.push(json!({"name": c.name, "id": cid}));
// Components built from other components (a dialog's buttons) come once those are mains.
let (plain, composed): (Vec<_>, Vec<_>) = kit.components.iter().partition(|c| !c.html.contains("<x-paper-instance"));
for pass in [plain, composed] {
let body: String = pass.iter().map(|c| c.html).collect();
let w = call_json(host, "write_html", json!({"pageId": pid, "targetNodeId": board, "html": body}))?;
let ids = w["createdNodeIds"].as_array().cloned().unwrap_or_default();
for (c, node) in pass.iter().zip(ids.iter().filter_map(|i| i.as_str())) {
let comp = call_json(host, "create_component", json!({"pageId": pid, "nodeId": node}))?;
let cid = comp["id"].as_str().unwrap_or(node).to_owned();
let (import, react) = match kit.code {
[] => (c.import, c.react),
code => code.iter().find(|(n, ..)| *n == c.name).map_or(("", ""), |(_, i, r)| (*i, *r)),
};
call_json(host, "set_code_link", json!({"pageId": pid, "nodeId": cid, "kit": kit.id, "import": import, "react": react, "egui": c.egui}))?;
made.push(json!({"name": c.name, "id": cid}));
}
}
// Screen layouts from the components, in a row under the kit's board.
let below = call_json(host, "get_node_info", json!({"pageId": pid, "nodeId": board}))?;
let top = below["y"].as_f64().unwrap_or(0.0) + below["height"].as_f64().unwrap_or(0.0) + 160.0;
let mut layouts = Vec::new();
for (i, (name, html)) in kit.layouts.iter().enumerate() {
let w = call_json(host, "write_html", json!({"pageId": pid, "targetNodeId": "root", "html": html}))?;
let Some(id) = w["createdNodeIds"][0].as_str() else { continue };
call_json(host, "update_styles", json!({"pageId": pid, "updates": [{"nodeIds": [id], "styles": {"left": i as f64 * 1600.0, "top": top}}]}))?;
layouts.push(json!({"name": name, "id": id}));
}
text(json!({
"pageId": pid, "frame": board, "kit": kit.id, "components": made,
"pageId": pid, "frame": board, "kit": kit.id, "components": made, "layouts": layouts,
"next": "Place these with <x-paper-instance component=\"Name\" overrides='{\"Label\":\"Text\"}'/>; the code export and the AI spec use the library components for them. Use the kit's variables (var(--primary) and so on) for everything else."
}))
}
@@ -6894,16 +7235,38 @@ fn set_viewport(ed: &mut Editor, a: &Args) -> ToolResult {
fn undo_redo(ed: &mut Editor, a: &Args, undo: bool) -> ToolResult {
let page = page_arg(ed, a)?;
let label = ed.with_page(page, |ed| {
let me = ed.changes.client.as_ref().map(|w| w.key.clone());
// An agent takes back its own steps unless it asks for the page's; the person's
// undo is always the page's.
let mine = match (a.get("scope").and_then(Value::as_str), &me) {
(Some("page"), _) | (_, None) => None,
(Some("mine") | None, Some(me)) => Some(me.clone()),
(Some(other), _) => return Err(format!("scope must be \"mine\" or \"page\", not \"{other}\"")),
};
let label: Result<Option<String>, Vec<String>> = ed.with_page(page, |ed| {
let before = ed.history.generation();
if undo {
ed.undo();
} else {
ed.redo();
match (&mine, undo) {
(None, true) => ed.undo(),
(None, false) => ed.redo(),
(Some(me), true) => ed.undo_by(me)?,
// Only the caller's own undone step comes back; someone else's stays undone.
(Some(me), false) => {
if ed.history.redo_author() == Some(me.as_str()) {
ed.redo();
}
}
}
(ed.history.generation() != before).then(|| ed.status.clone())
Ok((ed.history.generation() != before).then(|| ed.status.clone()))
});
text(json!({"done": label.is_some(), "what": label}))
match label {
Ok(label) => text(json!({"done": label.is_some(), "what": label})),
Err(blocked) => text(json!({
"done": false,
"reason": "undo_blocked",
"blockedBy": blocked,
"hint": "later steps by others touched the same layers; fix it forward, or pass scope \"page\" to undo the page's last step",
})),
}
}
#[cfg(test)]
+248
View File
@@ -0,0 +1,248 @@
//! `export_handoff`: the folder a code base builds from, written in one call. Files are read
//! on demand by agents billed per token, so the bundle is many small files behind a one-line-
//! per-screen index, every file's size in tokens is in the manifest, and a run that changes
//! nothing writes nothing (a diff of the folder is the change).
use super::super::exec::{self, Host};
use super::super::{Out, ToolResult};
use super::{markdown, report_since, str_arg, text};
use crate::model::{Color, Document, NodeId, NodeKind};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::path::Path;
const MANIFEST: &str = "manifest.json";
/// Bumped when a file's layout changes, so a reader can refuse a bundle it does not know.
const FORMAT: u32 = 1;
/// Characters per token, near enough to budget a brief.
const CHARS_PER_TOKEN: usize = 4;
/// The page holding the team's question table, by name.
const HANDOFF_PAGE: &str = "handoff";
pub fn export(host: &mut dyn Host, a: &Value) -> ToolResult {
let dir = Path::new(str_arg(a, "dir").ok_or("`dir` is required: the folder to write the bundle into")?).to_path_buf();
let images = a.get("images").and_then(Value::as_bool).unwrap_or(true);
let mut files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
let mut inv: Value = serde_json::from_str(&call(host, "get_inventory", json!({}))?).map_err(|e| e.to_string())?;
let project = host.project().map_or_else(|| "Untitled".into(), |p| p.manifest.name.clone());
let questions = handoff_rows(host);
inv["project"] = json!(project);
inv["handoffQuestions"] = json!(questions);
files.insert("inventory.json".into(), pretty(&inv)?);
files.insert("tokens.json".into(), call(host, "get_variables", json!({"format": "json"}))?.into_bytes());
files.insert("tokens.css".into(), call(host, "get_variables", json!({"format": "css"}))?.into_bytes());
files.insert("tokens.tailwind.css".into(), call(host, "get_variables", json!({"format": "tailwind"}))?.into_bytes());
files.insert("components.json".into(), call(host, "get_components", json!({}))?.into_bytes());
files.insert("open-questions.md".into(), open_questions(&inv, &questions).into_bytes());
let gpu = if images { host.gpu().map(Ok).unwrap_or_else(crate::render::gpu::Headless::new) } else { Err("images: false".into()) };
let mut index = Vec::new();
let mut shots = 0;
for page in inv["pages"].as_array().into_iter().flatten() {
let (page_id, page_name) = (page["id"].as_str().unwrap_or_default(), page["name"].as_str().unwrap_or_default());
let screens = page["screens"].as_array().into_iter().flatten().collect::<Vec<_>>();
if screens.is_empty() {
continue;
}
index.push(format!("\n## {page_name} (screens/{}/)", slug(page_name)));
let mut used = Vec::new();
for s in screens {
let (key, name) = (s["id"].as_str().unwrap_or_default(), s["name"].as_str().unwrap_or_default());
let mut stem = format!("screens/{}/{}", slug(page_name), slug(name));
if used.contains(&stem) {
stem = format!("{stem}-{}", key.rsplit(':').next().unwrap_or_default());
}
used.push(stem.clone());
let spec = call(host, "get_design_spec", json!({"pageId": page_id, "nodeId": key, "format": "compact"}))?;
let (w, h, class) = (s["width"].as_f64().unwrap_or(0.0), s["height"].as_f64().unwrap_or(0.0), s["class"].as_str().unwrap_or_default());
let spec = format!("<!-- {key} {w}x{h} {class} -->\n{spec}");
index.push(format!("- {name} · {class} {w}×{h} · `{key}` · {}.txt ~{}", stem.rsplit('/').next().unwrap_or_default(), tokens(spec.len())));
files.insert(format!("{stem}.txt"), spec.into_bytes());
if let Ok(g) = &gpu {
let ed = host.editor();
let Some(p) = ed.pages.iter().position(|p| p.id == page_id) else { continue };
let id = key.rsplit(':').next().and_then(|n| n.parse().ok()).map(NodeId).ok_or("bad screen key")?;
files.insert(format!("{stem}.png"), shot(g, ed.page_doc(p), id)?);
shots += 1;
}
}
}
let changes = match str_arg(a, "since") {
Some(since) => {
let r = report_since(host, since)?;
files.insert("changes.md".into(), markdown(&r, None).into_bytes());
files.insert("changes.json".into(), pretty(&serde_json::to_value(&r).map_err(|e| e.to_string())?)?);
Some(json!({"tokens": r.tokens.len(), "components": r.components.len(), "screens": r.screens.len()}))
}
None => None,
};
let screens = inv["screens"].as_u64().unwrap_or(0);
let head = format!(
"# {project}: design handoff\n{screens} screens · {} components. Build from these files, not the live app. Tokens: tokens.json (DTCG, modes), tokens.css, tokens.tailwind.css. Components: components.json. Questions: open-questions.md.{}\nEach screen: compact spec (.txt, ~tokens) and a reference image (.png) beside it; a scrolling screen's image shows its whole content.\n",
inv["components"].as_array().map_or(0, Vec::len),
if changes.is_some() { " Changes since the handoff point: changes.md (index), changes.json." } else { "" },
);
files.insert("index.md".into(), (head + &index.join("\n") + "\n").into_bytes());
let (written, removed) = write(&dir, files.clone())?;
let mut out = json!({"dir": dir, "files": files.len() + 1, "written": written, "removed": removed, "screens": screens, "images": shots});
if let Err(e) = gpu {
out["imagesSkipped"] = json!(e);
}
if let Some(c) = changes {
out["changes"] = c;
}
text(out)
}
fn call(host: &mut dyn Host, tool: &str, args: Value) -> Result<String, String> {
exec::call(host, tool, &args)?
.into_iter()
.find_map(|o| match o {
Out::Text(t) => Some(t),
Out::Image { .. } => None,
})
.ok_or_else(|| format!("{tool} returned no text"))
}
fn pretty(v: &Value) -> Result<Vec<u8>, String> {
serde_json::to_vec_pretty(v).map_err(|e| e.to_string())
}
fn tokens(bytes: usize) -> usize {
bytes.div_ceil(CHARS_PER_TOKEN)
}
/// FNV-1a: stable across builds, which `DefaultHasher` is not.
fn hash(bytes: &[u8]) -> String {
let h = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3));
format!("{h:016x}")
}
/// The screen at scale 1 on white, unrolled when its content scrolls (as the deck shows it).
fn shot(g: &crate::render::gpu::Headless, doc: &Document, id: NodeId) -> Result<Vec<u8>, String> {
let unrolled = crate::io::deck::unroll::unrolled(doc, &[id]);
let doc = unrolled.as_ref().unwrap_or(doc);
let roots = crate::io::export::with_layers_on_top(doc, &[id]);
crate::io::export::encode_png(&crate::io::png::render(g, doc, Some(&roots), 1.0, Some(Color::WHITE))?)
}
/// Writes the files whose bytes differ and the manifest, and removes files the last manifest
/// listed that this one does not (nothing else in the folder is touched). Returns how many
/// files were written and removed.
fn write(dir: &Path, mut files: BTreeMap<String, Vec<u8>>) -> Result<(usize, usize), String> {
let old: Value = std::fs::read(dir.join(MANIFEST)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(Value::Null);
let entries: BTreeMap<&String, Value> = files
.iter()
.map(|(k, v)| {
let mut e = json!({"hash": hash(v)});
if !k.ends_with(".png") {
e["tokens"] = json!(tokens(v.len()));
}
(k, e)
})
.collect();
let manifest = pretty(&json!({"format": FORMAT, "files": entries}))?;
files.insert(MANIFEST.into(), manifest);
let mut written = 0;
for (rel, bytes) in &files {
let path = dir.join(rel);
if std::fs::read(&path).is_ok_and(|b| &b == bytes) {
continue;
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
crate::io::atomic::write(&path, bytes).map_err(|e| format!("{}: {e}", path.display()))?;
written += 1;
}
let mut removed = 0;
for rel in old["files"].as_object().into_iter().flat_map(|m| m.keys()).filter(|k| !files.contains_key(*k)) {
// Only paths this tool wrote: never climb out of the folder.
if rel.split('/').any(|p| [".", ".."].contains(&p) || p.is_empty()) {
continue;
}
if std::fs::remove_file(dir.join(rel)).is_ok() {
removed += 1;
}
}
Ok((written, removed))
}
/// A file name from a layer name, as `shipcraft/bin/pc-freeze.py` writes it: word characters
/// kept, runs of spaces, `/` and `·` as one `-`, lower case.
fn slug(s: &str) -> String {
let kept: String = s.chars().filter(|c| c.is_alphanumeric() || c.is_whitespace() || "_/·.-".contains(*c)).collect();
let mut out = String::new();
for part in kept.trim().split(|c: char| c.is_whitespace() || c == '/' || c == '·').filter(|p| !p.is_empty()) {
if !out.is_empty() {
out.push('-');
}
out.push_str(part);
}
let out = out.trim_matches('-').to_lowercase();
if out.is_empty() { "unnamed".into() } else { out }
}
/// The question table on a page named "Handoff": rows of (id like `C7`, question, where,
/// proposed default) text layers, in layer order.
fn handoff_rows(host: &mut dyn Host) -> Vec<Value> {
let ed = host.editor();
let Some(p) = ed.pages.iter().position(|p| p.name.trim().eq_ignore_ascii_case(HANDOFF_PAGE)) else { return Vec::new() };
let doc = ed.page_doc(p);
let mut texts = Vec::new();
let mut stack: Vec<NodeId> = doc.root.iter().rev().copied().collect();
while let Some(id) = stack.pop() {
let Some(n) = doc.get(id).filter(|n| n.visible) else { continue };
if let NodeKind::Text { text, .. } = &n.kind {
texts.push(text.trim().to_owned());
}
stack.extend(n.children.iter().rev());
}
let is_id = |s: &str| {
let letters = s.chars().take_while(char::is_ascii_uppercase).count();
let digits = s.len() - letters;
(1..=3).contains(&letters) && (1..=3).contains(&digits) && s[letters..].chars().all(|c| c.is_ascii_digit())
};
let mut rows = Vec::new();
let mut i = 0;
while i + 3 < texts.len() {
if is_id(&texts[i]) {
rows.push(json!({"id": texts[i], "question": texts[i + 1], "where": texts[i + 2], "default": texts[i + 3]}));
i += 4;
} else {
i += 1;
}
}
rows
}
fn open_questions(inv: &Value, table: &[Value]) -> String {
let mut q = vec!["# Open questions".to_owned(), "Build with the proposed default; change it only when the owner answers otherwise.".into()];
if !table.is_empty() {
q.push("\n## Handoff table\n| # | Question | Where | Proposed default |\n|---|---|---|---|".into());
q.extend(table.iter().map(|r| format!("| {} | {} | {} | {} |", r["id"].as_str().unwrap_or_default(), r["question"].as_str().unwrap_or_default(), r["where"].as_str().unwrap_or_default(), r["default"].as_str().unwrap_or_default())));
}
for p in inv["pages"].as_array().into_iter().flatten() {
let open = p["openQuestions"].as_array().into_iter().flatten().collect::<Vec<_>>();
if open.is_empty() {
continue;
}
q.push(format!("\n## {}: notes marked `? (team)`", p["name"].as_str().unwrap_or_default()));
q.extend(open.iter().map(|n| format!("- **{}**: {}", n["layer"].as_str().unwrap_or("detached"), n["text"].as_str().unwrap_or_default().replace('\n', " — "))));
}
q.join("\n") + "\n"
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs_match_the_freeze_script() {
assert_eq!(slug("Consultor / Primeiro acesso · Pronto"), "consultor-primeiro-acesso-pronto");
assert_eq!(slug("Pedidos (PDVs)!"), "pedidos-pdvs");
assert_eq!(slug(" "), "unnamed");
}
}
+391
View File
@@ -0,0 +1,391 @@
//! What changed since a handoff point, sorted the way the code side acts on it: token values
//! once (regenerate the theme), main components once (their instances follow), then screens.
//! Built on [`diff_pages`]; what this adds is dropping what code never sees (sizes that follow
//! content, positions set by auto layout, instance fields that follow their main, a token's
//! new value repeated on every node using it) and naming the action for each kind.
use crate::mcp::diff::{NodeDiff, PropChange, diff_pages};
use crate::model::{Document, Node, NodeId, NodeKind, Paint, Sizing, Source};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Copy,
Binding,
Style,
Layout,
Structure,
Instance,
Note,
Added,
Removed,
Renamed,
}
impl Kind {
pub fn name(self) -> &'static str {
match self {
Kind::Copy => "copy",
Kind::Binding => "binding",
Kind::Style => "style",
Kind::Layout => "layout",
Kind::Structure => "structure",
Kind::Instance => "instance",
Kind::Note => "note",
Kind::Added => "added",
Kind::Removed => "removed",
Kind::Renamed => "renamed",
}
}
}
/// What each kind asks of the code; printed once at the top of a report.
pub const ACTIONS: &str = "Actions: copy = update the string · binding/style = restyle that node · layout/structure = rebuild that subtree (get_design_spec {nodeId, format: compact}) · instance = swap the component or its props · note = review the rule · added = build from its spec · removed = delete it · renamed = rename the symbol or layer id.";
/// A move or resize smaller than this is noise.
const MIN_PX: f64 = 1.0;
#[derive(Debug, Serialize)]
pub struct Line {
pub kind: Kind,
pub key: String,
/// Layer names from the screen (or main) down, without it.
pub path: String,
pub field: String,
pub before: String,
pub after: String,
}
/// The changes of one screen or one main component.
#[derive(Debug, Serialize)]
pub struct Group {
pub page: String,
pub key: String,
pub name: String,
pub kinds: BTreeSet<Kind>,
pub lines: Vec<Line>,
/// Screens using a main component.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub used_by: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct Token {
pub name: String,
pub before: String,
pub after: String,
/// Screens drawing with it.
pub screens: Vec<String>,
}
#[derive(Debug, Default, Serialize)]
pub struct Report {
pub since: String,
pub tokens: Vec<Token>,
pub components: Vec<Group>,
pub screens: Vec<Group>,
}
impl Report {
pub fn is_empty(&self) -> bool {
self.tokens.is_empty() && self.components.is_empty() && self.screens.is_empty()
}
}
/// One page at the handoff point and now (None where it did not exist).
pub struct PagePair<'a> {
pub id: &'a str,
pub name: &'a str,
/// Prefix of its node keys (`<prefix>:<id>`).
pub prefix: String,
pub before: Option<&'a Document>,
pub after: Option<&'a Document>,
}
/// The pages of one side, by page id, to find main components across pages.
type Side<'a> = BTreeMap<&'a str, &'a Document>;
pub fn report(since: &str, pairs: &[PagePair]) -> Report {
let empty = Document::default();
let before: Side = pairs.iter().filter_map(|p| Some((p.id, p.before?))).collect();
let after: Side = pairs.iter().filter_map(|p| Some((p.id, p.after?))).collect();
let mut groups: BTreeMap<(bool, usize, u64), Group> = BTreeMap::new();
let mut tokens: BTreeMap<String, Token> = BTreeMap::new();
for (pi, p) in pairs.iter().enumerate() {
let (b, a) = (p.before.unwrap_or(&empty), p.after.unwrap_or(&empty));
let key = |id: NodeId| format!("{}:{}", p.prefix, id.0);
let mut push = |doc: &Document, id: NodeId, line: Option<Line>, kind: Kind| {
let Some((main, owner)) = owner_of(doc, id) else { return };
let g = groups.entry((main, pi, owner.0)).or_insert_with(|| Group {
page: p.name.to_owned(),
key: key(owner),
name: doc.get(owner).map(|n| n.name.clone()).unwrap_or_default(),
kinds: BTreeSet::new(),
lines: Vec::new(),
used_by: Vec::new(),
});
g.kinds.insert(kind);
g.lines.extend(line);
};
let d = diff_pages(b, a);
for nd in d.groups.iter().flat_map(|g| &g.nodes) {
let removed = nd.status == "removed";
let (doc, id) = if removed { (b, nd.id_a) } else { (a, nd.id_b) };
let Some(id) = id else { continue };
let owner = owner_of(doc, id).map(|(_, o)| o);
let path = path_of(doc, id, owner);
if owner == Some(id) && nd.status != "modified" {
push(doc, id, None, if removed { Kind::Removed } else { Kind::Added });
continue;
}
if nd.status != "modified" {
let what = format!("{} \"{}\"", nd.kind, nd.name);
let (before, after) = if removed { (what, String::new()) } else { (String::new(), what) };
let line = Line { kind: Kind::Structure, key: key(id), path, field: nd.status.into(), before, after };
push(doc, id, Some(line), Kind::Structure);
continue;
}
let (Some(na), Some(nb)) = (b.get(id), a.get(id)) else { continue };
for (kind, c) in classify(nd, na, nb, a, &after) {
let kind = if owner == Some(id) && c.field == "name" { Kind::Renamed } else { kind };
let line = Line { kind, key: key(id), path: path.clone(), field: c.field.into(), before: c.before, after: c.after };
push(a, id, Some(line), kind);
}
}
// Instance swaps and property values: not part of a node's own properties.
for (id, nb) in &a.nodes {
let Some(na) = b.get(*id) else { continue };
let (Some(la), Some(lb)) = (&na.instance, &nb.instance) else { continue };
if !is_instance_root(nb, a, &after) {
continue;
}
let path = path_of(a, *id, owner_of(a, *id).map(|(_, o)| o));
let line = |field: &str, before: String, after: String| Line { kind: Kind::Instance, key: key(*id), path: path.clone(), field: field.into(), before, after };
if la.target() != lb.target() {
let name = |side: &Side, l: &crate::model::InstanceLink, doc: &Document| main_of(side, l, doc).map_or("?".into(), |m| m.name.clone());
push(a, *id, Some(line("component", name(&before, la, b), name(&after, lb, a))), Kind::Instance);
}
if na.prop_values != nb.prop_values {
let show = |v: &BTreeMap<String, String>| v.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(", ");
push(a, *id, Some(line("props", show(&na.prop_values), show(&nb.prop_values))), Kind::Instance);
}
}
for ad in &d.annotations {
let (old, new) = (b.annotations.iter().find(|n| n.id == ad.id), a.annotations.iter().find(|n| n.id == ad.id));
let Some((doc, target)) = new.and_then(|n| Some((a, n.target?))).or_else(|| old.and_then(|n| Some((b, n.target?)))) else { continue };
let show = |n: Option<&crate::model::annotation::Annotation>| n.map_or(String::new(), |n| format!("{} — {}", n.label, n.body.lines().next().unwrap_or("")).trim_end_matches(" — ").to_owned());
let line = Line { kind: Kind::Note, key: key(target), path: path_of(doc, target, owner_of(doc, target).map(|(_, o)| o)), field: "note".into(), before: show(old), after: show(new) };
push(doc, target, Some(line), Kind::Note);
}
token_changes(b, a, &mut tokens);
}
// Who uses each changed main, and each changed token.
let screens_using = |hit: &dyn Fn(&str, &Document, &Node) -> bool| -> Vec<String> {
let mut names = BTreeSet::new();
for (pid, doc) in &after {
for n in doc.nodes.values().filter(|n| hit(pid, doc, n)) {
if let Some((false, s)) = owner_of(doc, n.id) {
names.insert(doc.get(s).map(|s| s.name.clone()).unwrap_or_default());
}
}
}
names.into_iter().collect()
};
for ((main, pi, owner), g) in groups.iter_mut() {
if !*main {
continue;
}
let (page, owner) = (pairs[*pi].id, NodeId(*owner));
g.used_by = screens_using(&|pid, doc, n| {
n.instance.as_ref().is_some_and(|l| {
let (m, src) = l.target();
m == owner && match src {
None => pid == page,
Some(Source::Page(p)) => p == page,
Some(Source::Library(_)) => false,
}
}) && is_instance_root(n, doc, &after)
});
}
for t in tokens.values_mut() {
t.screens = screens_using(&|_, _, n| uses_var(n, &t.name));
}
let (components, screens): (Vec<_>, Vec<_>) = groups.into_iter().partition(|((main, ..), _)| *main);
Report {
since: since.into(),
tokens: tokens.into_values().collect(),
components: components.into_iter().map(|(_, g)| g).collect(),
screens: screens.into_iter().map(|(_, g)| g).collect(),
}
}
/// Who a node's change belongs to: `(true, main)` inside a main component, else `(false,
/// screen)`, the nearest declared screen above it or its top-level frame.
fn owner_of(doc: &Document, id: NodeId) -> Option<(bool, NodeId)> {
let chain: Vec<NodeId> = std::iter::once(id).chain(doc.ancestors(id)).collect();
if let Some(m) = chain.iter().find(|i| doc.get(**i).is_some_and(|n| n.component)) {
return Some((true, *m));
}
let top = *chain.last()?;
let screen = chain.iter().find(|i| doc.get(**i).is_some_and(|n| n.screen)).copied();
doc.get(top).filter(|n| n.is_frame() || screen.is_some()).map(|_| (false, screen.unwrap_or(top)))
}
fn path_of(doc: &Document, id: NodeId, owner: Option<NodeId>) -> String {
let mut names = Vec::new();
let mut cur = Some(id);
while let Some(n) = cur.filter(|c| Some(*c) != owner).and_then(|c| doc.get(c)) {
names.push(n.name.as_str());
cur = n.parent;
}
names.reverse();
names.join(" > ")
}
fn main_of<'a>(side: &Side<'a>, l: &crate::model::InstanceLink, own: &'a Document) -> Option<&'a Node> {
let (m, src) = l.target();
match src {
None => own.get(m),
Some(Source::Page(p)) => side.get(p.as_str()).and_then(|d| d.get(m)),
Some(Source::Library(_)) => None,
}
}
/// The top of an instance: its link points at a main component itself (a library main counts).
fn is_instance_root(n: &Node, doc: &Document, side: &Side) -> bool {
n.instance.as_ref().is_some_and(|l| matches!(l.target().1, Some(Source::Library(_))) || main_of(side, l, doc).is_some_and(|m| m.component))
}
/// The changes of a node present on both sides that code sees, by kind.
fn classify(nd: &NodeDiff, na: &Node, nb: &Node, doc: &Document, side: &Side) -> Vec<(Kind, PropChange)> {
// Inside an instance a field follows its main unless overridden; the main reports it.
let inner = nb.instance.is_some() && !is_instance_root(nb, doc, side);
let follows = |key: &str| inner && !nb.instance.as_ref().is_some_and(|l| l.overrides.iter().any(|o| o == key));
let mut out = Vec::new();
for c in &nd.changes {
let (kind, key) = match c.field {
"text" => (Kind::Copy, "text"),
"fills" => {
let (x, y) = (fills(na), fills(nb));
if x == y || follows("fills") {
continue;
}
let kind = if x.contains("--") || y.contains("--") { Kind::Binding } else { Kind::Style };
out.push((kind, PropChange { field: "fills", before: x, after: y }));
continue;
}
"stroke" => {
let (x, y) = (stroke(na), stroke(nb));
if x == y || follows("stroke") {
continue;
}
let kind = if x.contains("--") || y.contains("--") { Kind::Binding } else { Kind::Style };
out.push((kind, PropChange { field: "stroke", before: x, after: y }));
continue;
}
"corner_radius" => (Kind::Style, "radius"),
"opacity" => (Kind::Style, "opacity"),
"font_size" => (Kind::Style, "font"),
"size" if !sized_by_hand(na, nb) => continue,
"size" => (Kind::Layout, "size"),
"position" if !placed_by_hand(nb, doc) || moved_less(na, nb) => continue,
"position" => (Kind::Layout, "position"),
"layout" => (Kind::Layout, "layout"),
"visible" => (Kind::Structure, "visible"),
"name" => (Kind::Structure, "name"),
"parent" | "order" => (Kind::Structure, ""),
"comments" => continue,
_ => (Kind::Style, ""),
};
if !key.is_empty() && follows(key) {
continue;
}
out.push((kind, c.clone()));
}
out
}
/// A size code sets: an axis that is fixed and changed by a pixel or more (hug and fill sizes,
/// and auto-width text, follow their content or parent).
fn sized_by_hand(na: &Node, nb: &Node) -> bool {
let auto_text = matches!(nb.kind, NodeKind::Text { auto_width: true, .. });
let s = nb.layout_child.sizing;
let w = s[0] == Sizing::Fixed && !auto_text && (na.rect.w - nb.rect.w).abs() >= MIN_PX;
let h = s[1] == Sizing::Fixed && !matches!(nb.kind, NodeKind::Text { .. }) && (na.rect.h - nb.rect.h).abs() >= MIN_PX;
w || h
}
/// A position code sets: not a top-level frame on the canvas, not placed by auto layout.
fn placed_by_hand(n: &Node, doc: &Document) -> bool {
n.parent.and_then(|p| doc.get(p)).is_some_and(|p| p.layout.is_none() || n.layout_child.absolute)
}
fn moved_less(na: &Node, nb: &Node) -> bool {
(na.rect.x - nb.rect.x).abs() < MIN_PX && (na.rect.y - nb.rect.y).abs() < MIN_PX
}
/// Fills as code writes them: a token name, or a value when there is none.
fn fills(n: &Node) -> String {
let all: Vec<String> = n
.style
.fills
.iter()
.map(|p| match p {
Paint::Solid { var: Some(v), .. } => format!("--{v}"),
Paint::Solid { color, var: None } => color.to_hex(),
Paint::Image { .. } => "image".into(),
Paint::Linear { .. } => "linear-gradient".into(),
Paint::Radial { .. } => "radial-gradient".into(),
})
.collect();
if all.is_empty() { "none".into() } else { all.join(", ") }
}
fn stroke(n: &Node) -> String {
let Some(c) = n.style.stroke.filter(|_| n.style.stroke_width > 0.0) else { return "none".into() };
let color = n.bindings.get("stroke").map_or_else(|| c.to_hex(), |v| format!("--{}", v.trim_start_matches("--")));
format!("{color} {}px", n.style.stroke_width)
}
fn uses_var(n: &Node, name: &str) -> bool {
let bare = name.trim_start_matches("--");
n.style.fills.iter().any(|p| matches!(p, Paint::Solid { var: Some(v), .. } if v == bare)) || n.bindings.values().any(|v| v.trim_start_matches("--") == bare)
}
/// Variable values (each mode) and dimension tokens that changed, once per name across pages.
fn token_changes(b: &Document, a: &Document, out: &mut BTreeMap<String, Token>) {
let mut values = |name: &str, mode: Option<&str>, x: Option<String>, y: Option<String>| {
if x == y {
return;
}
let show = |v: Option<String>| v.unwrap_or_else(|| "none".into());
let label = |v: String| mode.map_or(v.clone(), |m| format!("{m} {v}"));
let t = out.entry(format!("--{name}")).or_insert_with(|| Token { name: format!("--{name}"), before: String::new(), after: String::new(), screens: Vec::new() });
let (bx, ay) = (label(show(x)), label(show(y)));
if !t.before.split("; ").any(|s| s == bx) {
t.before = [t.before.as_str(), bx.as_str()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("; ");
t.after = [t.after.as_str(), ay.as_str()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("; ");
}
};
// With modes, the base values are only the active mode's: switching modes is no change.
if b.modes.is_empty() && a.modes.is_empty() {
let names: BTreeSet<&String> = b.variables.keys().chain(a.variables.keys()).collect();
for n in names {
values(n, None, b.variables.get(n).map(|c| c.to_hex()), a.variables.get(n).map(|c| c.to_hex()));
}
}
let modes: BTreeSet<&String> = b.modes.keys().chain(a.modes.keys()).collect();
for m in modes {
let (x, y) = (b.modes.get(m), a.modes.get(m));
let names: BTreeSet<&String> = x.into_iter().chain(y).flat_map(|v| v.keys()).collect();
for n in names {
values(n, Some(m), x.and_then(|v| v.get(n)).map(|c| c.to_hex()), y.and_then(|v| v.get(n)).map(|c| c.to_hex()));
}
}
let names: BTreeSet<&String> = b.tokens.keys().chain(a.tokens.keys()).collect();
for n in names {
values(n, None, b.tokens.get(n).cloned(), a.tokens.get(n).cloned());
}
}

Some files were not shown because too many files have changed in this diff Show More