Docs / Concepts
proposed design, not built
Proto Studio: concept and build plan
Status: proposed design, not built. Decision record: ADR 0034. Target: the 1.3.x releases. This page is the reference for the people (and agents) who build it: what Proto is, how its document is shaped, how it renders, how agents, the CLI, the Code studio and collaboration reach it, and the task list.
Contents#
- Vision
- Competitive analysis
- Document model
- Rendering
- Tools, modes and panels
- Prototyping and the player
- AI: Vibe tools
- MCP server and client
- CLI
- Code export, code import and the Code studio link
- Imports and the
.figquestion - File format
- Collaboration
- Security
- Build plan
- Open questions
- Sources
1. Vision#
Proto is where application interfaces are designed, prototyped and handed to code, by people and agents together, in a document whose meaning is CSS.
- Design. Frames on an infinite canvas, auto layout (flex) and grid layout, constraints, components with variants and properties, instances with overrides, variables with modes (light and dark, brands, densities), text and effect styles. The feature set of a modern UI design tool, not an illustration tool.
- Prototype. Interactions on any layer, flows, overlays, scrolling and fixed layers, variables and conditions for state, smart animate. A player in its own window, shareable in a collaboration room, exportable as a single HTML file.
- Agent-native. The Vibe assistant creates frames and components from a prompt, a screenshot or a URL, edits them, checks them (contrast, touch targets, unbound values) and generates code. External agents (Claude Code, Cursor, Codex) reach the same document through an MCP server. The assistant inside the app can call other MCP servers (a code base, a component library, an icon set).
- Code-native. What the canvas shows is what the browser does, because the canvas is the browser's layout
engine. Export to HTML + CSS, React, Tailwind and SwiftUI; import HTML; share a
tokens.jsonand components with the Code studio. - Terminal-native.
ofini protoexports code, tokens and assets, lints, renders and serves MCP over stdio, so CI can check a design system the way it checks code. - Together from day one. Live editing, cursors, comments on layers and follow mode through the existing end-to-end encrypted rooms. No account, no server of ours.
- Open. The document is versioned JSON inside
.ofini, tokens are W3C DTCG JSON, exports are plain files. Nothing is locked in.
Non-goals for 1.3.x: whiteboarding (the Whiteboard app covers it), print layout (Layout studio), illustration depth (Vector studio: Proto embeds SVG from it), hosting websites (Code studio publishing covers it), a plug-in API of its own (extensions reach Proto through the operation layer later).
2. Competitive analysis#
State as of November 2026, from public product pages, documentation and reviews (see Sources). Observation of public behavior only, as the clean-room policy requires.
| Figma | Penpot | Paper | Sketch | Proto (plan) | |
|---|---|---|---|---|---|
| Platform | Browser + desktop wrapper, cloud files | Browser, self-hostable server | Browser + desktop app | macOS app, web workspace | Browser, PWA, desktop (Windows, macOS, Linux), offline |
| License | Proprietary | Open source (MPL-2.0) | Proprietary | Proprietary | Open source (MIT) |
| File format | .fig, undocumented | Open; export as ZIP of JSON and assets | HTML and CSS in the app | .sketch, documented ZIP + JSON | .ofini (ZIP + JSON), documented |
| Canvas | Own WebGL/WASM renderer | SVG, moving to a WASM renderer | Real HTML and CSS | Native Metal renderer | Real HTML and CSS (DOM) |
| Layout | Auto layout (flex), wrap, grid auto layout, constraints | Flex and CSS grid layout | CSS flex and grid | Stacks, Smart Layout | Flex, CSS grid, constraints |
| Components | Components, variants, properties (text, boolean, instance swap), slots | Components, variants | Components (early) | Symbols, overrides, variants | Components, variants, properties incl. instance swap and slots |
| Variables / tokens | Variables with modes and extended collections; styles | Design tokens (DTCG-compatible) | CSS variables | Color variables, shared styles | Variables with modes and extending collections, styles as composite tokens, DTCG in and out |
| Prototyping | Rich: smart animate, variables, conditionals, overlays, scroll | Interactions, flows, overlays | Basic | Links, overlays, flows | Interactions, overlays, scroll, variables, conditions, smart animate |
| Dev handoff | Dev Mode, Code Connect, code snippets | Inspect panel with CSS and SVG | Export React/Tailwind | Inspect in the web app | Inspect mode, code panel, export HTML/CSS/React/Tailwind/SwiftUI, Code studio link |
| AI / agents | Figma AI, Make; MCP server, write to canvas (beta) | Official MCP server (Plugins API) | Agents edit the canvas over MCP | Local MCP server (port 31126) | Built-in assistant with the same tool set as a local MCP server; MCP client |
| CLI | None (REST API) | None (API) | None | sketchtool (macOS) | ofini proto … on Linux, macOS, Windows |
| Collaboration | Real time, cloud | Real time, server | Real time | Web workspace | Real time, end-to-end encrypted, relay without accounts |
What we take. Figma's model of components with properties and variables with modes is the industry vocabulary; designers expect it, so Proto uses the same concepts under CSS names. Penpot's insistence that layout is CSS flex and grid. Paper's proof that a DOM canvas is fast enough and makes agents productive (agents write HTML well). Sketch's local-only MCP server and fixed, documented file format.
What we do differently. One operation layer for the editor, the assistant, the MCP server and the CLI (no second-class API). Local-first and end-to-end encrypted collaboration. A terminal workflow for design systems. Export that matches the canvas exactly. Everything in one suite: SVG from Vector, images from Pixel, the code in Code, the deck in Presentation.
Where we will be weaker (honest list): very large files (tens of thousands of visible layers) render slower
than a WebGL engine; no plug-in ecosystem; no community file library; .fig files must come in through SVG or the
REST API.
3. Document model#
Pure modules in app/src/engine/proto/ (no DOM). The model is one immutable JSON value; every change goes through
ops.js and returns a new value with structural sharing, so unchanged nodes keep their identity (the renderer and the
collaboration diff rely on that).
3.1 Top level#
{
"schema": 1,
"meta": { "title": "Checkout", "created": "2026-12-01T10:00:00Z", "unit": "px", "app": "OpenFini 1.3.0" },
"pages": {
"p1": { "id": "p1", "name": "Screens", "ord": "V", "bg": "#f4f4f5", "flows": [{ "id": "f1", "name": "Checkout", "start": "n1" }] },
"p2": { "id": "p2", "name": "Components", "ord": "k", "bg": "#ffffff" }
},
"nodes": { "n1": { "…": "see 3.2" } },
"vars": { "collections": {}, "items": {} },
"styles": {},
"breakpoints": [{ "id": "base", "w": 1280 }, { "id": "md", "w": 991 }, { "id": "sm", "w": 478 }],
"code": { "links": {}, "tokensFile": null },
"media": {}
}
- Flat node map.
nodesmaps id to node; each node hasparent(a node id, ornullfor a top-level node on itspage) andord, a fractional order key (collab/fractional.js: base-62 digits that never end in0, so the first key is"V", not"a0"; equal keys sort by id). A flat map makes lookups O(1), makes moves a two-field change, and maps one to one onto collaboration records. Children lists are derived (cached per revision). - Ids are short random strings (
n+ 8 base-36 characters), unique per document, never reused. - Unknown fields are kept. Readers preserve fields they do not know (forward compatibility within a schema).
- Schema version.
schemais an integer.migrate.jsupgrades older models step by step; a model with a newer schema opens read-only with a notice.validate.jschecks types, references (parent, component, variable, media), cycles and limits, and is used on open, on import, on every MCP write and on every remote collaboration record.
3.2 Nodes#
Common fields:
{
"id": "n7", "type": "frame", "name": "Card", "page": "p1", "parent": "n1", "ord": "a3",
"visible": true, "locked": false, "opacity": 1, "blend": "normal",
"x": 24, "y": 120, "rot": 0,
"w": { "mode": "fill", "min": 240, "max": 480 },
"h": { "mode": "hug" },
"pos": "flow",
"cx": "leftRight", "cy": "top",
"tag": "article",
"a11y": { "label": "Product card", "role": null },
"modes": { "c1": "dark" },
"proto": []
}
| Field | Meaning | CSS meaning |
|---|---|---|
type | frame, rect, ellipse, line, vector, text, image, instance, component, componentSet, slot | element kind |
w, h | { mode: "fixed", value }, { mode: "hug" }, { mode: "fill" }, { mode: "rel", value: 0.5 }, plus min, max | width: 320px / fit-content / flex: 1 1 0 or align-self: stretch / 50%; min-width, max-width |
pos | flow (laid out by the parent's flex or grid) or abs (positioned) | position: relative / absolute |
x, y | position relative to the parent (top-left, unrotated); for flow children it is derived and stored for the overview only | left / top (abs) |
cx, cy | constraints of abs children: left, right, leftRight, center, scale (and top, bottom, topBottom, center, scale) | left / right / both / left: calc(50% + d) + translate / percentages |
rot | rotation in degrees around the center | transform: rotate() |
tag, a11y | semantic element and accessibility name/role for code export; never affects the canvas | HTML element, aria-label, role |
modes | variable mode per collection for this subtree | data-mode-<collection> attribute that switches custom properties |
Containers (frame, component, instance roots) add:
{
"layout": {
"type": "flex", "dir": "row", "wrap": false, "gap": 8, "rowGap": 8,
"pad": [16, 16, 16, 16],
"align": "center", "justify": "space-between", "alignContent": "start",
"reverseZ": false
},
"clip": true,
"scroll": "none"
}
layout.type:none(children areabs, like a classic artboard),flex, orgrid.- Grid:
"grid": { "cols": [{ "fr": 1 }, { "px": 240 }, { "auto": true }, { "minmax": [200, { "fr": 1 }] }], "rows": [...], "areas": null, "autoFlow": "row", "dense": false }and on children"cell": { "col": 1, "colSpan": 2, "row": 1, "rowSpan": 1, "alignSelf": "start", "justifySelf": "stretch" }(omitted = auto-placed). Exactly the CSS grid concepts, minus named lines in schema 1. pad,gapand every numeric or color value may be a binding{ "$var": "v12" }instead of a literal (see 3.4). Spacing tokens therefore survive into code asvar(--space-4).scroll:none,x,y,both(prototype overflow behavior); children may set"sticky": "top"(fixed while scrolling).- Editor aids (added in 1.3.x; the one exception to "every field has a CSS meaning", because they are never
rendered or exported):
guideson frames and components ([{ "axis": "x" | "y", "at": 64 }], relative to the frame) and on pages (world units), and layout gridsgridson frames and components ([{ "type": "columns" | "rows" | "grid", "count", "size", "gutter", "margin", "align": "stretch" | "start" | "center" | "end", "color", "visible" }]). They are model fields so undo and collaboration (recordn:<id>/lay, the page record) carry them; the geometry isengine/proto/guides.js, the canvasproto/rulers.js. Grid styles (CSS grid definitions, §3.4) are unrelated.
Appearance (all visual nodes):
{
"fills": [
{ "type": "solid", "color": { "$var": "v1" }, "opacity": 1 },
{ "type": "linear", "angle": 135, "stops": [{ "at": 0, "color": "#6366f1" }, { "at": 1, "color": "#a855f7" }] },
{ "type": "image", "media": "m3", "fit": "cover", "pos": [0.5, 0.5] }
],
"strokes": [{ "color": "#e4e4e7", "w": 1, "align": "inside", "dash": null, "sides": [1, 1, 1, 1] }],
"radius": [12, 12, 12, 12],
"effects": [{ "type": "shadow", "x": 0, "y": 4, "blur": 16, "spread": -2, "color": "#0000001f" }],
"style": { "fill": "s4", "effect": "s9" }
}
Fills map to background layers (gradients: linear-gradient, radial-gradient, conic-gradient), strokes to
border (inside, uneven sides) or outline / box-shadow (center, outside), effects to box-shadow, filter: blur()
and backdrop-filter. Anything the CSS mapping cannot express is not in the schema; that is the rule that keeps the
canvas and the export identical.
Text:
{
"type": "text",
"text": {
"runs": [{ "t": "Total ", "s": {} }, { "t": "$42.00", "s": { "weight": 700 } }],
"style": { "font": "Inter", "size": 16, "weight": 400, "lineHeight": { "pct": 150 }, "tracking": 0, "align": "left", "case": "none", "decoration": "none", "color": { "$var": "v3" } },
"autoSize": "height",
"maxLines": null
},
"style": { "text": "s2" }
}
autoSize: width (hug), height (fixed width, wraps), fixed; maxLines → -webkit-line-clamp. Text content can
be bound to a string variable or a component text property.
Vector and image: vector stores SVG path data (d, fill rule) in its own box and renders as inline SVG; it is
where boolean results, icons and drawings from the Vector studio land. image is a frame with one image fill and
"alt"; media bytes live in media (the doc.office media contract).
3.3 Components, variants, properties, instances, overrides#
{
"n20": { "id": "n20", "type": "componentSet", "name": "Button", "props": {
"size": { "type": "variant", "options": ["sm", "md", "lg"], "default": "md" },
"state": { "type": "variant", "options": ["default", "hover", "disabled"], "default": "default" },
"label": { "type": "text", "default": "Button" },
"icon": { "type": "swap", "default": "n90", "preferred": ["n90", "n91"] },
"showIcon": { "type": "bool", "default": false },
"content": { "type": "slot" }
} },
"n21": { "id": "n21", "type": "component", "parent": "n20", "variant": { "size": "md", "state": "default" }, "bind": { "n22.text": "label", "n23.visible": "showIcon", "n23.of": "icon" } },
"n50": { "id": "n50", "type": "instance", "of": "n20", "variant": { "size": "lg" }, "props": { "label": "Pay now" }, "over": { "n22": { "fills": [{ "type": "solid", "color": "#ffffff" }] } } }
}
- A
componentis a container; acomponentSetgroups variants and declares the properties. A single component without variants may declarepropsitself. - Property types:
variant(one axis of the set),text,bool,swap(instance swap, with preferred components),number,slot(a container whose children the instance provides; exported aschildrenor a named React prop). bindconnects properties to fields inside the component (<nodeId>.<field>).- An
instancereferences the set or component (of), picks variant values, sets property values and stores overrides inover, keyed by the path of source node ids ("n22", or"n31/n22"through nested instances). Paths stay valid when the main component's other layers change; overrides of removed layers are kept but inactive and reported by lint. - Instances are not expanded in storage.
resolve.jsexpands an instance into a virtual subtree (cached by the identity of the component, the instance and the variables) for rendering, hit testing, export and agents. Detaching an instance is an operation that materializes that subtree. - Remote components (from another
.ofinifile or a library) are a later step; schema 1 reserves"of": "lib:<libraryId>/<componentId>".
3.4 Variables, modes and styles#
{
"vars": {
"collections": {
"c1": { "name": "Color", "modes": [{ "id": "light", "name": "Light" }, { "id": "dark", "name": "Dark" }], "default": "light" },
"c2": { "name": "Brand B", "extends": "c1", "modes": [{ "id": "light", "name": "Light" }, { "id": "dark", "name": "Dark" }] },
"c3": { "name": "Space", "modes": [{ "id": "base", "name": "Base" }] }
},
"items": {
"v1": { "name": "color/bg/surface", "coll": "c1", "type": "color", "values": { "light": "#ffffff", "dark": "#18181b" }, "scopes": ["fill"], "code": { "css": "--color-bg-surface" } },
"v2": { "name": "color/brand", "coll": "c1", "type": "color", "values": { "light": "#4f46e5", "dark": { "$var": "v7" } } },
"v9": { "name": "space/4", "coll": "c3", "type": "number", "unit": "px", "values": { "base": 16 } }
}
},
"styles": {
"s2": { "name": "Body/Regular", "kind": "text", "value": { "font": "Inter", "size": 16, "weight": 400, "lineHeight": { "pct": 150 } } },
"s9": { "name": "Elevation/2", "kind": "effect", "value": [{ "type": "shadow", "x": 0, "y": 4, "blur": 16, "spread": -2, "color": { "$var": "v12" } }] }
}
}
- Types:
color,number(with an optional unit:px,%,ms, none),string,bool. Values per mode may alias another variable. Aliases must not form cycles (validated). - Extending collections (
extends) override some values of a base collection for a brand or theme, the way Figma's extended collections and DTCG theming work. - Mode resolution walks up from a node to the first ancestor with
modes[coll], then the page, then the collection's default. In CSS this is exactly the cascade of custom properties: the renderer and the exporter emit:rootvalues for defaults and[data-mode-color="dark"]rules for other modes. - Styles are composite tokens (typography, shadow, gradient, grid). Nodes reference them (
style.text); local edits detach the field, which lint reports. - DTCG interchange (
tokens.js): variables and styles export to and import from Design Tokens Community Group JSON ($value,$type, aliases{color.brand}, groups from the/-separated names, modes as one file per mode or as$extensions["org.openfini.modes"]). Round trip is tested.
3.5 Prototype data#
Stored on nodes (proto) and pages (flows); described in section 6.
3.6 Limits#
Validated on open, import, MCP and collaboration: 200,000 nodes per document, 64 KiB per record value (collaboration
limit), nesting depth 64, 64 options per variant property, 2,000 variables per collection, 20 modes per
collection, 16 MiB per media item (the .ofini limits apply on top).
4. Rendering#
4.1 Architecture#
model ──resolve.js──▶ resolved tree (instances expanded, variables bound per mode)
│
├─ css.js ──▶ declarations per node ──▶ view.js: keyed DOM in a shadow root per top-level frame
│ └─▶ codegen (same declarations)
└─ layout.js (pure solver, Node only: CLI render, lint, headless MCP)
DOM ──measure.js──▶ geometry cache (boxes in canvas space) ──▶ hit testing, snapping, overlay, agents
overlay.js: one Canvas 2D layer above the stage: selection, handles, guides, redlines, padding and gap handles, remote cursors
css.jsis the single source of CSS. It turns a resolved node into a list of declarations (width,display: flex,gap,background, …) with variable references kept asvar(--…). The renderer applies them withstyle.setProperty(neverinnerHTML); the exporter prints them. A test asserts that both see the same declarations for every fixture.- Stage. The canvas is a positioned world element transformed by
translate() scale(). Each top-level frame is a host element with its own shadow root holding the frame's subtree and a small reset stylesheet plus the variable rules. Shadow roots isolate the design from the app's CSS (Shoelace, themes) and give each frame its own style scope; they cost far less than one iframe per frame. Free-floating layers on the page (not in a frame) live in one extra root. - Keyed incremental patching. Each node id has one element. After a commit, the view compares node objects by identity (the model shares structure) and patches only changed elements: changed declarations, moved or reordered children, added and removed nodes. No virtual DOM library.
- Geometry. After patching,
measure.jsreadsgetBoundingClientRectfor the changed subtrees only (batched in one read phase per frame, insiderequestAnimationFrame, so there is no layout thrashing) and converts boxes into canvas coordinates. AResizeObserveron frame hosts catches reflow caused by fonts loading. Hit testing, marquee selection, snapping and the overlay use this cache, not the DOM. - Text editing happens in place in a
contenteditableelement that replaces the text node's element while editing (plain text with runs; paste is sanitized to text), committing runs on blur or Escape. - Fonts. Fonts come from
core/fonts.js(bundled Inter, system fonts, fonts added to the document as media). Exports list the fonts they need; nothing is fetched from the network without the network policy allowing it.
4.2 Zoom, pan, culling and level of detail#
- Pan and zoom change only the world transform. While a gesture is active the stage has
will-change: transform(GPU scaling of the existing raster, very fast); 150 ms after the gesture ends it is removed so the browser re-rasterizes crisp text at the new scale. - Culling. Frames whose box is outside the viewport plus a margin get
content-visibility: hidden(layout and paint skipped, state kept). Frames far outside are detached from the DOM after 10 s and re-attached on approach. - Level of detail. Below 25 % zoom, frames whose on-screen size is under 160 px render as their cached geometry: a box with the fill and blocks for text lines, drawn on the overlay canvas. Below 5 %, frames are drawn as filled rectangles with their names. The DOM of those frames is detached.
- Prototype player renders with the same
view.js, without overlay and without editing affordances.
4.3 Performance targets#
Measured by tests/proto/perf/ on a generated fixture in Chromium (CI) and by hand in WebView2, WKWebView and
WebKitGTK before each release. Reference machine: a 2020 mid-range laptop (4 cores, integrated GPU).
| Scenario | Target |
|---|---|
| Pan and zoom, 50 frames and 5,000 visible nodes | 60 fps (p95 frame time ≤ 16.7 ms) |
| Pan and zoom, 200 frames and 20,000 nodes, level of detail active | ≥ 30 fps |
| Hover highlight and selection change | ≤ 8 ms |
| Property edit (padding, fill) to painted frame, 10,000-node document | p95 ≤ 50 ms |
| Drag-resize an auto layout container with 500 children | ≥ 30 fps |
| Open a 10,000-node document (warm cache) to first paint | ≤ 1.5 s |
| Memory, 10,000-node document | ≤ 300 MB for the tab |
| Smart animate in the player, 200 matched layers | 60 fps |
| Start-up bundle growth | ≤ 1 KiB gzip (studio definition and menu rows) |
| Lazy Proto code over 1.3.x | ≤ 160 KiB gzip in total, budgeted per task in scripts/size-budget.json |
4.4 The pure solver (layout.js)#
Used where there is no browser: ofini proto render (SVG), ofini proto lint (overlaps, overflow, touch target
sizes), and headless MCP (proto_get_geometry). It implements the CSS flex algorithm (single and multi-line,
grow, shrink, min/max, alignment), grid track sizing for px, fr, auto and minmax, absolute positioning with
constraints, and text boxes measured with engine/layout/measurers.js ▸ approxMeasurer (AFM metrics). Results carry
approximate: true. Conformance tests compare it to geometry recorded from Chromium for every fixture; tolerance
1 px for boxes without text, and a documented tolerance for text.
5. Tools, modes and panels#
5.1 Modes#
- Design — editing (default).
- Prototype — connections, interactions and flows on the canvas; the Prototype panel replaces the Design panel.
- Inspect — read-only handoff: redlines on hover, the Code panel, measurements, tokens per value, asset export. Also the default for viewers in a room who were given view rights.
5.2 Tools#
| Tool | Key | Notes |
|---|---|---|
| Move / select | V | Click, Shift-click, marquee, Ctrl/Cmd-click selects deep, Enter selects children, Shift+Enter the parent; drag in auto layout reorders with an insertion line; Alt-drag duplicates |
| Scale | K | Scales a subtree including text sizes, strokes and effects |
| Frame | F | Draw, or choose a device preset (phone, tablet, desktop, watch, custom presets) |
| Rectangle, Ellipse, Line | R, O, L | |
| Pen | P | Reuses engine/vector/path.js; creates a vector node |
| Text | T | Click for auto width, drag for fixed width |
| Image | Shift+Ctrl/Cmd+K | Place images as image frames; also drop and paste |
| Hand | H, Space | |
| Comment | C | Pins anchored to layers (see 13) |
| Connect | (Prototype mode) | Drag from a layer to a frame to create a navigate interaction |
| Measure | Alt (hold) | Redlines between the selection and the hovered layer |
| Ask Vibe | / | Inline prompt bar on the canvas that sends the selection as context |
Auto layout shortcuts. Shift+A wraps the selection in a flex frame (direction guessed from positions); Ctrl/Cmd+Alt+G wraps in a grid; padding and gap are adjustable by dragging handles on the canvas; Alt while resizing a child switches between hug, fill and fixed. Smart selection (several equal siblings) adjusts spacing for all of them.
Snapping. To pixel grid, layout grids, sibling edges and centers, equal spacing, and (with Shift) 15° angles. Snap lines come from the geometry cache.
5.3 Panels#
All panels are dockable through the docking engine (ADR 0033); studios/proto.js declares essentials presets.
| Panel | Default dock | Contents |
|---|---|---|
| Pages | left, top | Pages, flows (jump to a flow's start frame) |
| Layers | left | Tree of the page, type icons, lock and hide, rename, drag to reorder and reparent, search |
| Assets | left (tab) | Components and sets of this document and linked libraries, styles, variables, icons; drag to insert |
| Design | right | Position, sizing (fixed/hug/fill/rel with min and max), constraints, auto layout or grid, appearance, fills, strokes, effects, text, export settings, variable binding on every field (a small button opens the variable picker) |
| Prototype | right (Prototype mode) | Interactions of the selection, flow starting points, scroll and sticky, overlay settings |
| Variables | bottom or floating | Collections as tables (rows variables, columns modes), alias picker, scopes, code names, import and export DTCG |
| Code | right (Inspect mode), dockable anywhere | Live code of the selection (HTML+CSS, React, Tailwind, SwiftUI), copy, "Export…", "Open in Code" |
| Comments | right (tab) | Threads of the document (existing comments host) |
| Vibe | right (tab) | The assistant (existing panel), with Proto skills |
| History | floating | Undo history and named versions (existing) |
6. Prototyping and the player#
6.1 Model#
"proto": [
{ "on": { "type": "click" }, "do": [{ "act": "navigate", "to": "n40", "tr": { "type": "smart", "dur": 300, "ease": "ease-out" } }] },
{ "on": { "type": "hover" }, "do": [{ "act": "variant", "set": { "state": "hover" }, "tr": { "type": "smart", "dur": 150, "ease": { "spring": [1, 300, 20] } } }] },
{ "on": { "type": "key", "key": "Escape" }, "do": [{ "act": "closeOverlay" }] },
{ "on": { "type": "afterDelay", "ms": 2000 }, "do": [{ "act": "if", "cond": { "var": "v30", "op": "==", "value": true }, "then": [{ "act": "navigate", "to": "n41" }], "else": [] }] }
]
- Triggers:
click,doubleClick,press(while pressed),hover(while hovering),mouseEnter,mouseLeave,drag,key(with modifiers),afterDelay,variableChange. - Actions:
navigate,back,scrollTo,openOverlay(position, background dim, close on outside click),swapOverlay,closeOverlay,variant(change the instance's variant),set(variable),if(condition withthenandelse),openUrl(through the app's external link confirmation),media(play/pause a video fill, later). - Conditions and expressions are a tiny data language (
==,!=,<,>,and,or,not, arithmetic, string concatenation), evaluated by a pure interpreter; nevereval, neverFunction. - Transitions:
instant,dissolve,moveIn,moveOut,push,slide(with direction),smart; easinglinear, the CSS keywords,cubic-bezier, orspring [mass, stiffness, damping](sampled into alinear()easing). - Smart animate matches layers of the outgoing and incoming frames by source id (instances of the same component), then by name path. The player uses the FLIP technique: measure both states in the DOM, render the target, animate transforms, opacity, colors, radius and size with the Web Animations API. Unmatched layers fade. This is natural for a DOM renderer and is one reason for that choice.
6.2 Player#
- Preview window: a separate OS window on the desktop (multi-window), a new tab in the browser; device frame (optional), scale to fit, restart, flow picker, hotspot hints on misclicks, keyboard shortcuts (R restart, arrows between flows), the current frame's comments.
- Present in a room: the presenter's player state (frame, overlay stack, variables) travels as presence data; followers see the same screen and can take control.
- Export as HTML:
ofini proto export --target prototypeor File ▸ Export ▸ Prototype (HTML) writes one self-contained HTML file (resolved frames, the player runtime of a few KiB, media as data URIs or a folder), viewable offline in any browser. No analytics, no external requests.
7. AI: Vibe tools#
Group Proto in vibe/tools/proto.js (static definitions; logic loads on first call). Every write tool is one undo
step ("Vibe: …") through ops.js. Each tool lands with the task that provides its capability (section 15). Names
match the MCP tools (section 8) where they overlap, so skills and prompts
work in both places.
| Tool | Kind | What it does |
|---|---|---|
proto_describe | read | Compact outline of the active document or a subtree: pages, frames, one line per node (id, type, name, size mode, layout, key styles, bindings), components and variants, variables summary |
proto_get_node | read | Full JSON of nodes (resolved or raw) |
proto_screenshot | read | PNG of a node or frame at a scale, for the model to look at |
proto_search | read | Find nodes by name, text, type, component, variable use, unbound values |
proto_create | write | Create nodes from a compact JSON spec (nested, with layout, styles, variable names) under a parent |
proto_write_html | write | Create nodes from HTML + CSS (agents write HTML fluently); runs the HTML importer (10.4) |
proto_update | write | Patch fields of nodes (layout, sizing, fills, text, bindings, name, tag, a11y) |
proto_move / proto_delete / proto_duplicate | write | Structural edits, reorder, reparent, wrap in auto layout or grid |
proto_component | write | Make component, combine as variants, add properties, bind fields, create instances, set variant and properties, reset or detach |
proto_variables | write | Create collections, modes, variables, aliases; set values; bind fields; switch a frame's mode |
proto_styles | write | Create and apply text, effect and fill styles |
proto_interaction | write | Add, change or remove interactions and flows |
proto_from_screenshot | write | Places the image as a locked reference layer, extracts a palette and text (engine registry OCR where available) as hints; the model then builds with proto_create / proto_write_html and checks with visual_diff |
proto_lint | read | Contrast (WCAG), touch target size, unbound colors and spacings, detached styles, overrides of removed layers, empty frames, naming, overflowing text (engine/proto/lint.js, machine-applicable fixes) |
proto_fix | write | Applies lint fixes |
proto_to_code | read | Generated code for a node and target (10.1) |
proto_tokens | read/write | Export or import DTCG tokens; sync with the linked tokens file |
proto_responsive | read | Resizes a frame to breakpoints and reports overflow and clipped text |
proto_content | write | Fills text layers with realistic content (names, prices, dates) or data from a sheet range |
proto_rename | write | Semantic layer names and tag values (button, nav, h1…) for better code |
Skills (lazy skill pack proto): design a screen from a brief, screenshot to editable design, build a component
with variants, set up tokens and dark mode, prototype a flow, prepare for handoff, design system audit.
Existing tools combine with these: visual_diff, run_script (code mode), plan_work (orchestration), image
generation for placeholder art, Office sheet data for content.
From a screenshot. The assistant sees the image (vision model), calls proto_from_screenshot for reference and
hints, writes the structure with auto layout as HTML or JSON, then compares proto_screenshot with the reference
through visual_diff and corrects. Layers come out editable, with auto layout, not as one flat image.
8. MCP server and client#
8.1 Server design#
engine/proto/mcp/ is a transport-neutral handler: handle(jsonRpcMessage, session) → response | notifications.
It implements the MCP 2025-11-25 lifecycle (initialize, capabilities, ping), tools/list, tools/call,
resources/list, resources/read, resources/subscribe and prompts/list / prompts/get. Tools call ops.js
through a document host interface with two implementations: the running app (active and opted-in documents, with
undo and collaboration) and a file host for headless use (one .ofini file, written back atomically on save).
8.2 Tools#
Read tools (scope read):
| Tool | Result |
|---|---|
proto_list_documents | Documents available to this client: id, title, pages, kind, whether writes are allowed |
proto_get_tree | Outline of a page or subtree (depth, fields), the same format as proto_describe |
proto_get_node | Raw or resolved JSON of nodes |
proto_get_selection | Current selection in the app (app host only) |
proto_get_geometry | Boxes of nodes (exact in the app, approximate headless) |
proto_screenshot | PNG of a node (app host only; headless returns an SVG render, marked approximate) |
proto_get_tokens | Variables and styles as DTCG JSON, or CSS / Tailwind / Swift |
proto_get_components | Components, variant axes, properties, code links, usage counts |
proto_generate_code | Code for a node and target (html, react, react-tailwind, tailwind, swiftui), options as in 10.1 |
proto_lint | Lint report |
proto_search | As the Vibe tool |
proto_get_comments | Open comment threads with anchors (only when the user allows comments for agents) |
Write tools (scope write, off until the user allows it per client and document): proto_create,
proto_write_html, proto_update, proto_move, proto_delete, proto_component, proto_variables,
proto_styles, proto_interaction, proto_set_tokens (import DTCG), proto_fix, proto_reply_comment. Every
call is one undo step labeled with the client's name ("MCP · Claude Code: …") and appears in the AI log.
Resources: ofini-proto://<doc>/tree, …/page/<id>, …/node/<id>, …/tokens.json, …/components,
…/code/<node>/<target>. resources/subscribe sends notifications/resources/updated after commits (debounced
500 ms), so an agent implementing a screen sees design changes.
Prompts: implement_frame (generate code for a frame into the client's project, using its components and tokens),
sync_tokens, review_design.
8.3 Transports#
| Where | Transport | How a client connects |
|---|---|---|
| Desktop app | Streamable HTTP on 127.0.0.1:<port> served by the Tauri shell (src-tauri/src/mcp_server.rs, std-only like preview_server.rs) | URL and token shown in Settings ▸ AI ▸ MCP server, with ready-to-copy configuration for Claude Code, Cursor, VS Code and Codex |
| Terminal, app running | stdio: ofini mcp reads the endpoint file the app writes (port and token, user-only permissions) and proxies | claude mcp add openfini -- ofini mcp |
| Terminal, headless | stdio: ofini mcp --file design.ofini [--write] serves one file with the file host | Same, in CI or without the app |
| Browser / PWA | None: a web page cannot listen on a port | Use the CLI on a saved file, or the in-app assistant |
The Rust side terminates HTTP, enforces the security rules in 14.3 and forwards JSON-RPC to the web view over a Tauri event channel with request ids and a 30 s timeout; the JavaScript handler does all MCP logic, so there is one implementation to test. Server-sent events carry notifications. Port: random by default, fixed if the user sets one.
8.4 Client#
Proto adds nothing new on the client side: the Vibe assistant already connects to MCP servers (ai/mcp.js, OAuth in
ai/mcp-oauth.js). Proto skills describe useful pairings: the user's code base server (read existing components
before designing), a component library's documentation server, an icon set server, a design tool's own MCP server the
user is entitled to (for example to pull SVG or tokens). Results are untrusted data as everywhere in Vibe.
9. CLI#
ofini proto <command> in cli/lib/proto.mjs, reusing engine/proto/ (ADR 0032 rules: --json, exit codes, no
overwrite without --force, wildcards, - for stdin and stdout).
| Command | What it does |
|---|---|
ofini proto info <file> | Pages, frames, nodes by type, components, variables, styles, media, flows |
ofini proto tree <file> [--page] [--node] [--depth] | Prints the outline (the proto_describe format) |
ofini proto validate <file> | Schema, references, limits; exit 1 on errors |
ofini proto lint <file> [--rules] [--fix] | Design lint; --fix writes machine-applicable fixes; SARIF with --format sarif for CI annotations |
ofini proto export <file> --target html|react|react-tailwind|tailwind|swiftui|prototype [--node] [--out dir] | Code export (10.1) |
ofini proto tokens <file> [--format dtcg|css|tailwind|swift|json] [--mode] | Token export |
ofini proto tokens import <file> <tokens.json> | Token import (DTCG) |
ofini proto assets <file> [--node] [--format svg] [--out dir] | Exports vectors and marked layers as SVG and embedded media as files; PNG needs the app (exit 4, as ADR 0032) |
ofini proto render <file> --node <id> [--out x.svg] | SVG render through the pure solver (approximate) |
ofini proto import <in> <out.ofini> | From HTML (static path), SVG, Sketch, Penpot export, DTCG |
ofini proto diff <a> <b> | Structural diff: nodes added, removed, changed fields, variables, components |
ofini mcp [--file f] [--write] | MCP over stdio (8.3) |
ofini new proto <file> [--template] and ofini info, validate, doctor, unpack --pretty work through the existing
commands once the kind is known.
10. Code export, code import and the Code studio link#
10.1 Export pipeline#
resolved tree ─lower.js─▶ IR ─▶ emit/html.js index.html + styles.css
├▶ emit/react.js Component.tsx (+ .module.css) per component, screens
├▶ emit/tailwind.js class lists; tokens as @theme (Tailwind v4)
└▶ emit/swiftui.js Views, Color/Font extensions
- IR:
{ el, tag, name, classes, decls, tokens, children, component?: { name, props }, slot? }.lower.jschooses tags (tagfield, otherwise inferred: text with a heading style →h2, frame with a click interaction →buttonora, image →imgwithalt), turns layer names into class names (kebab case, deduplicated), and collapses wrappers that add nothing. - CSS is what
css.jsproduced for the canvas. Absolute positioning appears only forabsnodes; hug and fill become intrinsic sizing and flex, never fixed pixels. Variables become custom properties with fallbacks; modes become[data-mode-…]blocks and, for a collection named like a color scheme, optionally@media (prefers-color-scheme: dark). - Responsive. Frames may be grouped as breakpoint variants of one screen (same component or a
responsivelink). The exporter emits the base frame and@mediaoverrides for the differences, desktop-first, with the same breakpoints as the Code studio's designer, so an exported page edits naturally there. - React. One component per main component; variant axes become union-typed props,
boolandtextprops become props,swapandslotbecomeReactNodeprops; instances become JSX usages; screens import components. Styling: CSS Modules (default) or Tailwind. TypeScript or JavaScript. - SwiftUI (best effort, documented limits): flex →
HStack/VStackwith spacing and alignment, grid →Grid, absolute →ZStackwith offsets, padding, frame modifiers,background,overlayfor strokes,shadow,Textwith font modifiers; variables →Color/CGFloatextensions with light and dark values. Not mapped: CSS-only features without SwiftUI equivalents (listed in the output as comments). - Determinism. Same model, same options → byte-identical output (stable ordering, no timestamps). Snapshot tests per emitter and fixture.
- Code links. A component may carry
code: { react: { path: "src/ui/Button.tsx", export: "Button", props: {…} } }(like Code Connect): the exporter then uses the existing component instead of generating one, and the Code panel shows the real usage snippet.
10.2 Tokens shared with the Code studio#
A Code studio project may contain a DTCG file (default tokens/tokens.json). Link tokens file in the Variables panel
binds the Proto document to it (code.tokensFile: project-relative path plus, on the desktop, the folder handle).
While linked, the file is the source of truth: Proto reads it on open and on file change (the Code studio's watcher),
and Variables panel edits write the file (debounced, one Code studio undo step). Generated companions
(tokens.css, tailwind.css with @theme) are regenerated next to it on change if enabled. Conflicts (both changed
since the last sync) open a small merge dialog per variable.
10.3 Live component link#
Export to Code project writes generated files into a Code studio project. Generated content sits between
markers (/* @ofini-proto begin <id> hash=<h> */ … /* @ofini-proto end */); code outside the markers is the
developer's. Re-export replaces regions whose hash still matches and asks for regions edited by hand (keep, overwrite,
or show diff). With Live link on, re-export happens automatically after design commits (debounced 1 s) while both
documents are open, and the Code studio preview reloads. The Code studio shows a gutter badge on linked regions that
opens the component in Proto.
10.4 Import from HTML and CSS#
- In the app: the HTML (a Code studio file, a pasted snippet, an agent's
proto_write_html, a URL fetched by the existing web access tools) is rendered in the sandboxed preview frame at a chosen viewport width. The probe kit walks the DOM and reports computed styles and boxes; the mapper turnsdisplay: flex/gridinto layout, sizes into fixed/hug/fill where the computed values show it, positioned elements intoabswith constraints, text into runs,imgandsvginto image and vector nodes, repeated sibling structures into component candidates (offered, not forced), and CSS custom properties into variables. Scripts never run (the preview sandbox already blocks them for this mode). - In the CLI: static parsing with
engine/web(HTML and CSS parsers, a simple cascade for class and element selectors); unsupported selectors and properties are reported. Results are marked approximate. - Elements exported with
data-proto-id(off by default, on for live links) map back to their nodes, which makes the HTML round trip lossless for what Proto can express.
11. Imports and the .fig question#
| Source | Route | Status in the plan |
|---|---|---|
| SVG | Existing SVG import → vector, frame and text nodes; groups become frames without layout | T8 |
| Clipboard | SVG and HTML on the clipboard (design tools put SVG or HTML there); images | T8 |
| Sketch | Existing engine/formats/sketch.js (public file format reference), extended: artboards → frames, symbols → components, symbol instances and overrides → instances, stacks → flex layout | T8 |
| Penpot | Penpot's export (ZIP with JSON and assets) of an open-source product: shapes, flex and grid layout, components, tokens. Written from the format's published structure, no Penpot code copied (Penpot is MPL-2.0; reading a format is not using code) | T8 |
| HTML / CSS | 10.4 | T8 |
| DTCG tokens (Tokens Studio, Style Dictionary, Penpot, Figma variable exports) | tokens.js | T5 |
Figma .fig | Read only, best effort, behind Labs (ADR 0034 amendment A, 2026-11-26): import/fig.js with kiwi.js and zstd.js | 1.3.x (after T8) |
| Figma via REST API | Optional later importer: the user pastes a file URL and their own personal access token; we call the documented GET /v1/files/:key and /images endpoints and map the JSON node tree | After 1.3.x, after a review of Figma's developer terms |
Amendment (2026-11-26). The owner decided to read .fig files after all, read only, best effort and behind
Labs, for interoperability; the reader is written from public, openly licensed descriptions only (Kiwi, MIT;
Sketch's fig2sketch, MIT; Grida's notes; RFC 8878 for Zstandard) and OpenFini never writes .fig. See ADR 0034,
amendment A, and clean-room.md. The original reasoning
below is kept for the record; its technical point (the format changes without notice) is why the import stays best
effort and reports everything it does not map.
Why no .fig (original ruling). Legal: the clean-room policy (rule 4) admits proprietary formats only with an official public
specification; .fig has none, and existing community parsers are built by reverse engineering. Implementing one
would contradict our own policy and invite a takedown. Technical: the container (a Kiwi-encoded schema embedded in the
file) changes without notice, so a reader would break silently. The REST API is the supported, documented route and
returns the same node tree as JSON.
12. File format#
- A Proto document is a normal
.ofinifile (ADR 0006):document.jsonhas"studio": "proto"and"office": { "kind": "proto", …model }; media bytes live underoffice/proto/media/<id>.<ext>(thedoc.officecontract,core/office.js). The type marker and the container version rule are unchanged; older OpenFini versions that do not know the kind keep the object unchanged and save it back as it was. - The model carries its own
schemainteger (3.1). Migrations live inengine/proto/migrate.jsand are tested with stored fixtures of every schema. - Stable serialization: keys in a fixed order, nodes sorted by id, so
ofini unpack --prettygives small Git diffs. - Thumbnails: the first flow's start frame (or the first frame) as
preview.png, rendered by the app. docs/file-format.mdgets a Proto section when task 1 lands.
13. Collaboration#
-
Adapter
app/src/proto/collab.js(collabAdapterfor kind"proto", added toLIVE_OFFICE_KINDSincore/live-kinds.js). Records:Key Value n:<id>structure: type,page,parent,ord,name,visible,lockedn:<id>/geox,y,rot,w,h,pos,cx,cy,celln:<id>/laylayout,clip,scroll,stickyn:<id>/lookfills,strokes,radius,effects,opacity,blend,stylen:<id>/texttext(runs and style)n:<id>/compprops,variant,bind,of,over,coden:<id>/protoproto(interactions),tag,a11y,modesp:<id>page vc:<id>,v:<id>,s:<id>variable collections, variables, styles meta:*title, breakpoints, code links Two people changing a node's fill and its padding at the same time both win (different records); the same record resolves by Lamport clock (last writer wins), with the existing lost-update notice. Moves are conflict-free through parent + fractional key; cycles are broken deterministically, as in the tree CRDT. Text edits are record level in 1.3.0 (a text layer is short); an RGA binding for long text is a later improvement.
-
Validation: every remote record goes through
validateRecordOpand the Proto schema validator for its key type, so a malicious peer cannot inject unknown fields, scripts or oversized values. -
Presence: cursors and selections in canvas coordinates (page id + point), viewport for follow, the player state when presenting (6.2).
-
Comments: the existing comments system with anchor kind
proto({ kind: "node", node, page, at: [x, y] relative to the node }); pins follow layers when they move; comments on removed layers become page comments. -
Media: image bytes travel with the snapshot and on Resync, as for other kinds.
14. Security#
14.1 Canvas and player#
- No script execution in the design: the renderer creates elements with
createElement, sets text withtextContentand styles withstyle.setPropertyfromcss.js, which only emits declarations from an allow-list of properties with validated values.url()values only reference the document's own media (blob URLs). - Imported HTML and SVG are sanitized before mapping (no scripts, event handlers,
javascript:URLs, iframes, external resources without the network policy). openUrlin the player goes through the app's external link confirmation; prototype HTML exports contain no external requests.
14.2 Expressions#
Prototype conditions are data interpreted by a pure evaluator with a step limit; no eval, no Function, no
property access on host objects.
14.3 MCP server#
- Off by default. Enabled in Settings ▸ AI ▸ MCP server; a status indicator in the title bar while it runs; one click stops it and drops all sessions.
- Loopback only: binds
127.0.0.1(and::1), never a LAN address. - Authentication: a 256-bit bearer token, generated per installation, rotatable, required on every request; the
endpoint file for
ofini mcphas user-only permissions. - DNS rebinding and browser protection: the
Hostheader must be127.0.0.1:<port>orlocalhost:<port>; requests with anOriginheader are refused unless the origin is the app itself (MCP security best practice). - Per-client approval: the first connection of a client (by its
clientInfoname) asks the user in the app: deny, allow read, allow read and write; per document or all Proto documents; remembered until revoked in Settings. - Scope: only Proto documents that are open and allowed; no file system access, no other studios, no app settings, no network.
- Limits: request size 4 MiB, 2,000 nodes per create call, 60 write calls per minute per client, 30 s timeout.
- Accountability: every write is one undo step labeled with the client name and is recorded in the AI log; the user can undo an agent's whole session through the existing tag-based run undo (ADR 0008).
- Prompt injection: design content (layer names, text, comments) is untrusted for the receiving agent too. Tool results put document text in clearly delimited JSON fields; comments are only exposed when the user allows it. We cannot prevent an external agent from following instructions it reads; the README of the feature says so.
- Headless
ofini mcp --file: read-only unless--write; writes go to a temporary file renamed over the original onsave, with the.ofinivalidation first.
14.4 Collaboration, imports and tokens#
The existing end-to-end encryption and op validation apply (13). ZIP limits of core/ofini.js apply to Sketch and
Penpot imports. The optional Figma REST importer stores the token only in the OS credential store on the desktop and
only in memory in the browser, and contacts only api.figma.com under the network policy.
15. Build plan#
Fourteen tasks, each one PR, each independently mergeable once its dependencies are merged. Sizes: S ≤ 1 day,
M 2–4 days, L 5–8 days of focused agent work including tests and docs. Every task: US English, German strings
at 100 %, npm test, npm run build && npm run check:size with its budget increase recorded in
scripts/size-budget.json, docs updated, no new runtime dependency, no attribution lines in commits or PRs.
Waves and releases#
Waves are the build order; at most four agents work in parallel, and a wave starts when the dependencies of its tasks are merged. Each release ships the waves completed before it.
| Wave | Tasks (parallel) | Release |
|---|---|---|
| A | T1 | 1.3.0 (Proto preview) |
| B | T2 | 1.3.0 |
| C | T3, T5 | 1.3.0 |
| D | T4, T10, T11, T13 | 1.3.0: model, renderer, core tools, components and variables in the engine, live collaboration, assistant, CLI |
| E | T6, T7, T8, T9 | 1.3.1: Assets and Variables panels, code export, imports, prototyping and player |
| F | T12, T14 | 1.3.2: MCP server, Code studio live link; the preview label is removed |
Dependencies at a glance:
T1 → T2 → T3 → T4 ──────┬→ T6 → T14
│ └→ T9
└→ T10
T2 → T5 → T6, T8, T9, T11, T13
T13 → T7 → T12, T14
T11 → T12
Until 1.3.0 is released the studio is reachable only with the Labs ▸ Proto Studio preference, so tasks can merge to
main as soon as their dependencies allow.
Tasks#
T1 · Document model, schema, operations — M — deps: none
- Scope:
engine/proto/schema.js(types, defaults),validate.js,migrate.js(schema 1 plus fixture),ids.js,ops.js(create, update with a field allow-list, move and reparent with fractional keys, delete with subtree, duplicate, wrap in flex or grid, pages),tree.js(children cache, traversal), stable serialization; kind"proto"in thedoc.officecontainer with its media folder. - Files:
app/src/engine/proto/*,tests/proto/model.test.js,tests/proto/ops.test.js,docs/file-format.md. - Acceptance: property tests (random op sequences keep the model valid, no cycles, order keys sorted);
validaterejects every malformed fixture; serialize → parse → serialize is byte-identical; imports in plain Node. - As built (deviations and decisions the later tasks build on):
- Two more modules:
serialize.js(canonical,stringify,parse) andformat.js(loadModelstrips the container fields, migrates and validates;storeModelreturns the canonical model fordoc.office). - Operations are JSON objects
{ op, …args }applied withapply(model, op, { random })→{ model, inverse, ids, map? };inverserestores the input exactly (deep-equal), a no-op returns the input model itself, and a failing operation throwsOpErrorand changes nothing. Names:node.create(nestedchildren),node.insert,node.update(setandunsetwith dotted paths such as"layout.gap"; list items are replaced as a whole),node.move,node.place(exact placement, the inverse of moves),node.delete,node.duplicate,node.wrap(flexguesses direction, order and gap from positions;grid;none),page.create/update/move/delete,meta.update,batch. Later tasks add their own operations (components, variables, interactions) to the same table. - The grid definition lives in
layout.grid. Colors in schema 1 are hex literals or{ "$var" }bindings. Effects areshadow(withinset),blurandbackgroundBlur. - Interactions and flows that point at a removed layer and fills whose media is missing are warnings, so deleting a
frame never fails; deleting a component (or its page) that instances or swap properties still use is refused
(
in-use). Extending collections are checked for references and cycles only; their value semantics come with T5. - The File Doctor checks Proto designs (
proto-invalid,proto-newer), soofini info(with a design summary) andofini validaterecognize them now;ofini new protoand theofini protocommands stay in T13. - Each operation copies the node map once (copy on write; a batch copies once) and hands its updated child index to
the cache, so a property edit never re-sorts children. Until T3 imports it,
ops.jsships as an unminified source file (recorded inscripts/size-budget.json).
- Two more modules:
T2 · Resolver, CSS compiler and pure layout solver — L — deps: T1
- Scope:
resolve.js(plain nodes and variable references, extension points for instances),css.js(node → declarations, property allow-list),layout.js(flex, grid, constraints, approximate text), recorded Chromium geometry fixtures andscripts/proto-record-geometry.mjsto re-record them by hand (results committed). - Files:
app/src/engine/proto/{resolve,css,layout}.js,tests/proto/{css,layout}.test.js,tests/proto/fixtures/geometry/*.json,scripts/proto-record-geometry.mjs. - Acceptance: every schema field has a CSS mapping test; solver within 1 px of the recorded boxes for fixtures without text; no DOM access (import test in Node).
- As built (deviations and decisions the later tasks build on):
resolve.js:createResolver(model, { modes, instance, applyStyles, variableValue })→.tree(id),.page(pageId),.modesAt(id),.variable(id, modes),.value(v, modes),.cssName(id),.warnings. A resolved node is{ key, id, type, node, children, modes, bound, instance, parent }:nodeis plain JSON with styles and overrides applied and every{ "$var" }replaced by its value;boundmaps the field paths that were bound ("layout.gap","fills.0.color") to variable ids, so one tree serves both literal output (solver) andvar()output (canvas, export). Layers inside an instance are keyed"<instanceKey>/<sourceId>"("n50/n23/n91"). Problems (missing variables or components, cycles) are warnings, never exceptions.- Modes resolve node → ancestors → page → the resolver's
modes→ collection default → first mode; aliases are followed in the same modes. Extending collections are not applied yet (T5, through thevariableValuehook). - Styles: text (merged over the local text style), effect, fill and stroke references apply over the local fields;
grid styles are not applied (they have no CSS meaning yet). T5 can replace this with the
applyStyleshook. - Instances (beyond the T2 scope, as a baseline T5 extends through the
instancehook): the variant of a set is picked (set defaults, then the instance's values, best partial match), the main component's fields lie under the instance's own fields, its layers become virtual children, andoverapplies by source-id path through nested instances (outer instances win). Not yet:propsandbind, swap, slots, detach, caches. css.js:nodeCss(r, { parent, index, count, vars: "value"|"css", resolver, root, scroll, mediaUrl, designSize })→{ decls: [[property, value]], attrs, text?: { runs }, svg? },treeCss(root, opts)→Map,boxModel,PROPERTIES(the allow-list). In"css"mode a bound value prints asvar(--name, <value in this node's modes>), so the canvas is correct before T5 emits the custom property rules; modes becomedata-mode-<collection slug>attributes. Vector and line layers return SVG presentation attributes (inline SVG), text layers their runs.- Mapping decisions that keep the canvas, the export and the solver identical:
box-sizing: border-box; flow children get explicit minimum sizes (min-width: <min or 0>), fixed and hug layersflex: 0 0 auto, fill layersflex: 1 1 0pxon the main axis andalign-self: stretchon the cross axis, so CSS automatic minimum sizes never apply; hug and fixed layers never stretch.gapis the main-axis gap (column gap in a grid),rowGapthe gap between lines (row gap in a grid) and defaults togap.relvalues are percentages (0 to 100, as validate.js checks), not fractions as in the example of §3.2. The firstinsidestroke is the CSS border (it takes layout space, and absolute children are offset by it), the firstcenterstroke an outline with a negative offset, further strokes box-shadow rings;sidesare per-side widths. Fills and effects are listed bottom to top. Constraints other than left/top need fixed design-time sizes of the layer and its parent on that axis (or thedesignSizehook) and fall back to left/top otherwise;centeriscalc(50% + offset)without a transform.scrollclips on the canvas and scrolls withscroll: true(player, export). Line-height percentages follow CSS (a run without its own line height inherits the layer's computed pixels). layout.js:layout(resolvedRoot, { measurer, viewport, origin, designSize })→{ approximate: true, root, boxes: Map<key, { x, y, w, h, px, py, rot, lines? }> },layoutNode(model, id, opts). Text boxes carry their lines (segswith run indexes, baselines) for the SVG render of T13. The measurer is the{ measure, metrics }seam ofcore/fonts.js(defaultapproxMeasurer). Baseline alignment is implemented for rows; grid baseline alignment falls back to start.- Geometry fixtures: 16 models in
tests/proto/fixtures/geometry/(13 without text: flex sizing, justify and align, column fill with min/max freezing, wrap with align-content, nested hug, grid tracks, flow and dense placement, hug grids, constraints, absolute layers in flex, strokes, instances, variables; 3 with text), recorded in Microsoft Edge 158 on Windows. Measured agreement: within 0.02 px without text; within 1.6 px with text (the browser kerns, the base-14 widths do not), tested with 1 px and 2 px tolerances.
T3 · Studio shell and DOM renderer — L — deps: T1, T2
- Scope:
studios/proto.js(definition, menus,essentialsdocking preset,newDocument,newBlank, Labs flag),proto/host.js(mount, commits throughcommitOffice, autosave),proto/view.js(stage, shadow roots, keyed patching, pan and zoom, culling, level of detail),proto/measure.js,proto/overlay.js(selection and hover), new / open / save, start screen entry, first user guidedocs/proto-studio.md, German strings. - Files:
app/src/studios/{proto.js,index.js},app/src/proto/{host,view,measure,overlay}.js,app/styles/proto.css,tests/proto/view-patch.test.js(the patch planner is pure),tests/proto/perf/,docs/proto-studio.md. - Acceptance: start-up bundle +≤ 1 KiB; open and save round trip; the 5,000-node fixture pans at 60 fps in Chromium (perf script), manual checks in WebView2 and WebKitGTK recorded in the PR.
- As built (deviations and decisions the later tasks build on):
- Labs switch: the preference
labsProto(Settings ▸ Labs ▸ Proto Studio);studios/proto.js ▸ installProtoLabsregisters the studio at start-up and as soon as the switch turns on (the registry cannot unregister, so off takes effect at the next start). Opening a design while it is off shows a notice with Turn on.newDocumentcreates a design with one desktop frame,newBlankan empty page; both come from the registry (File ▸ New, New Blank). - Modules:
proto/host.js(mount, start screen),proto/workspace.js(the instance,app.protoUI, with input and panels),proto/view.js(stage, shadow roots, culling, level of detail),proto/patch.js(the pure planner:changedRoots,entriesFor,planPatch,cullState),proto/geometry.js(cache,hitTest,pickAt,marqueeSelect),proto/measure.js,proto/overlay.js,proto/camera.js,proto/controller.js(selection andopStep),proto/panels.js,commands/proto.js(registered on first mount). Tests:tests/proto/view-patch.test.js,controller.test.js,perf/pipeline.test.js; the browser benchmark istests/proto/perf/bench.htmldriven byscripts/proto-perf.mjs. - Undo:
controller.run(op, label)turns an operation into one document history step (doc.tx). Undo and redo restore the stored models when nothing else changed in between, and otherwise apply the operation's inverse (and the inverse of that replay for redo, which keeps created ids) to the current model, so T10 can rebase on top of remote edits withoutprj.rebase. Updates that set a field to its current value are not recorded. - Saving:
workspace.js ▸ ensureProtoloads the model once (format.js ▸ loadModel; a newer or invalid model opens read-only with a banner) and makesdoc.office.manifest()write the canonical model, so saved files are stable. - Rendering: one host with its own shadow root per top-level layer (also free-floating layers; the concept's
single extra root for them was not needed), a shared constructable reset sheet, declarations from
css.jswithvars: "css"androot: "origin"(the host carriesleft,topand the page z-order asz-index). Changed top-level layers are found by node identity (changedRoots; a change inside a component re-resolves every frame with an instance), re-resolved whole, and patched per element (style, attributes, text runs, SVG, child order). Detached layers keep their elements and are patched when they come back. Geometry is measured in the animation frame after a patch (and when a root'sResizeObserverordocument.fonts.readyfire), rounded to 1/100 px. - Culling and level of detail as in §4.2 with the constants in
patch.js(LOD_ZOOM0.25,BLOCK_ZOOM0.05,LOD_PIXELS160,DETACH_AFTER10 s, live margin half a viewport). A layer that was never measured renders once to learn its size. The overlay draws the simplified layers from the geometry cache (fills, ellipses, text as line blocks). - Selection semantics (
geometry.js ▸ pickAt): a click selects the top-level layer's child under the point (or the top-level layer itself); with a selection, its siblings; Ctrl/Cmd deep; layers inside instances select the outermost instance. The marquee selects top-level layers (T4 adds marquees inside frames with the Move tool). - Panels:
proto-layers(tree, top of the list in front, keyboard navigation, at most 2,000 rows until the virtualized tree of T4) andproto-inspector(read-only name, type and box). The workspace API in the header ofproto/workspace.js(run,select,pickAt,setTool,view.overlay.addLayer,on("change" | "selection" | "camera" | "geometry")) is what T4 tools and T10 collaboration build on. - Small engine fix:
node.duplicateoffsets layers whose position is omitted (the default 0) as well. - Measured with
scripts/proto-perf.mjs(Microsoft Edge 158 headless, 1920 × 1080, Windows 11 on the development machine, not the reference laptop): pan with 5,000 visible layers p95 17.0 ms (57–60 fps), zoom p95 17.3 ms; 20,000 layers at 10 % with level of detail 60 fps; selection change p95 1.8 ms, hover 0.5 ms; property edit to painted frame in 10,000 layers p95 20.4 ms; 10,000 layers to first paint 188 ms, JS heap 27 MB. Manual checks in WebView2, WKWebView and WebKitGTK are still open.
- Labs switch: the preference
T4 · Core tools and panels — L — deps: T3
- Scope: tools Move/select, Scale, Frame (device presets), Rectangle, Ellipse, Line, Pen, Text (in-place editing), Image, Hand, Measure; snapping and smart guides; padding and gap handles; hug / fill / fixed switching; panels Pages, Layers and Design (every field of 3.2, variable binding buttons hidden until T6); shortcuts, context menu, copy and paste inside Proto.
- Files:
app/src/proto/tools/*.js,app/src/proto/panels/{pages,layers,design}.js,app/src/commands/proto.js,tests/proto/{snap,tools-math}.test.js. - Acceptance: every tool action is one undo step; Layers and Design usable by keyboard alone (tab order, ARIA); manual checks in Chromium and Firefox listed in the PR.
- As built (deviations and decisions the later tasks build on):
- Modules:
proto/tools/(index.jsregistry and toolbar,select.jsMove tool,draw.jsFrame, Rectangle, Ellipse, Line and Zoom,pen.js,text.jswith in-place editing,presets.js,common.js) with two pure modules tested in Node:math.js(handles, resize, rotation, constraints, insertion points, padding and gap handles, grid track text, text runs after an edit) andsnap.js(snap targets, guides, distance labels);tools/edit.jsbuilds every edit of the tools, panels and commands as oneops.jsoperation (a batch for several layers), also pure and tested. Panels:proto/panels/{pages,layers,design}.js;proto/panels.jsof T3 is gone. The Design panel keeps the dock idproto-inspector(saved layouts keep working) and is titled Design. - Workspace additions (header of
proto/workspace.js):apply(op, label)(a refused op becomes a notice),preview(op)(a drag renders the operation's result without recording it; the drop runs the operation once, so every gesture is one undo step and collaboration sees one change),box(id),tools,setHover,setMarquee,setCursor,editText,rename,copy/cut/paste(an in-app clipboard), and thetoolevent. Tools getdown/move/up/hover/key/draw/deactivate.view.jsgainedelementOf(key),remeasure(rootId)andinvalidate(rootId)for in-place text editing. No engine change was needed. - Resizing a frame applies its absolute children's constraints to their stored boxes in the same batch, because the
CSS of
right,centerandscaleconstraints is computed from the design-time size (T2). Rotated layers resize by their axis-aligned box (no rotated handles yet). - A new text is previewed while typing and created with its text on finish (one step; nothing when it stays empty);
a text layer named after its content keeps following it. Editing uses
contenteditable="plaintext-only"(falls back totruewith plain-text paste) and keeps run styles outside the edited range (math.js ▸ editRuns). - Undo and redo shortcuts now reach the Proto Studio (
ui/shortcuts.jstreats it like the Office Suite). - Not in this task: the Scale tool (K), the Image tool (added by T8), the Comment tool (T10) and Alt-toggling hug, fill and fixed while resizing; alignment of auto layout children is the 3 × 3 matrix in the Design panel (padding and gap have canvas handles); equal-spacing snapping; copy and paste stay inside OpenFini (T8 added the system clipboard); multi-selection fields show the first layer's value.
- Modules:
T5 · Components, variables, styles and DTCG tokens (engine) — L — deps: T2
- Scope: component and component set ops, property definitions and bindings, instance resolution with overrides by
source-id path, swap, slot, detach, reset; variable collections, extending collections, modes, aliases with cycle
check, scopes, styles as composite tokens, mode resolution in
resolve.jsandcss.js;tokens.js(DTCG import and export, CSS custom properties, Tailwind v4@theme, Swift). Instances render on the canvas through T3 once both are merged; no new panels. - Files:
app/src/engine/proto/{components,variables,tokens}.js,resolve.js,css.js,tests/proto/{components,variables,tokens}.test.js,tests/proto/fixtures/tokens/*.json. - Acceptance: nested instances, overrides surviving edits of the main component, swap with a preferred list, slot content, detach equal to the resolved subtree; DTCG round trip of the specification's examples; alias cycles rejected; 1,000 instances resolve in under 50 ms.
- As built (deviations and decisions the later tasks build on):
- Modules:
components.js(helpers and operation handlers for components and instances),variables.js(families, mode selection, value lookup, scopes, references, style application and the variable, mode and style operations),tokens.js(DTCG, CSS, Tailwind v4, Swift). The handlers are registered in the one operation table ofops.js(applystays the only entry point). Their inverse is one generic exact operation,restore { nodes?, pages?, collections?, items?, styles? }({ id: object | null }), recorded by a journal in the draft;restorerefuses orphans and cycles. New operations:component.create(a frame becomes a component in place, anything else is wrapped),component.combine("size=md, state=hover" names become variant axes, other names onevariantaxis; component properties move to the set),component.addVariant,prop.define/prop.rename/prop.delete(cascading to variants'variant,bindand instance values),prop.bind,instance.create(the main component's size applies),instance.set,instance.swap,instance.override(top-level fields per path),instance.reset,instance.detach,collection.*,mode.*,var.create/var.update/var.delete(detach: truereplaces bindings by their values in each user's modes; without it a used variable is refused),node.bind(binds list items such asfills.0.color, checks scopes unlessforce;var: nullwrites the value),style.create(alsofroma layer) /update/delete/apply/detach,tokens.import(the result has areport). - Properties: a text property bound to
textreplaces the content (first run's style kept); every other binding sets the field (visible,ofof a nested instance for swap properties). Bindings apply to the layers of the instance's own component; overrides apply after them. Main components render their stored layers (defaults are not applied). - Slots: an instance's stored children are slot content (
props.<slot>lists ids; unlisted children go to the first slot property); a slot property is connected bybind: { "<slotLayer>.children": prop }, else the first freeslotlayer. Content of a real instance keeps its own key; resolved nodes carryslot(the providing instance),src(stored node with properties and overrides) andbase(after expansion, still with bindings and style references). New layers created inside an instance flow (pos: "flow").r.nodemay be the stored object itself when nothing changed it (treat it as immutable). - Detach materializes the resolved subtree with new ids; the instance keeps its id and becomes a frame; slot layers become frames; nested instances stay instances and receive the outer overrides that reached into them; slot content of the detached instance keeps its ids. Instance children that fill no slot stay children of the frame.
- Extending collections: overrides live on the variable (
ext[collection][mode]); an extending collection has its base's modes (validated, kept in step by the mode operations, which run on the base only). Selecting any collection of a family selects the family; a deeper selection replaces the inherited one, and inside onemodesobject the most derived collection wins (mergeModes). The resolver'sopts.modesapply over the page's modes (as in T2). - Grid styles are CSS grid definitions; a container with a grid style becomes a grid (the style wins).
css.js:varRules/varSheetemit:root(or:host) defaults and one[data-mode-<collection slug>="<mode>"]rule per collection and mode with every variable of its family (base collections first). Aliases inside a family are written as values; aliases into another family stayvar()(they follow that family through the cascade; a cross-family alias whose own family also switches modes deeper is a known CSS limitation). A unitless number variable bound to a length printscalc(var(--x, n) * 1px).- Resolve cache:
createResolveCache()passed asopts.cachereuses resolved real instances (the same objects) while the stored nodes and children lists they read,vars,stylesand the parent's modes are unchanged. Measured: 1,000 two- to four-layer instances resolve in about 11 ms without the cache (Node 24, Windows laptop); the test asserts 50 ms for the best of five runs. - DTCG: export in the 2025.10 shapes (sRGB color objects with
hex, dimension and duration objects,$roottokens for names that are also groups); modes in$extensions["org.openfini.modes"], collections, ids, scopes, code names and brand overrides in$extensions["org.openfini"]; styles as typography, shadow, gradient or color tokens with the exact style in the extension. Import reads both the 2025.10 objects and the older strings,$typeinheritance,$root, group$extends,{a.b}and$refaliases, HSL and sRGB-linear colors; rem becomes px (×16) and s becomes ms, both reported; cubicBezier, strokeStyle, border, transition, unreadable colors and broken aliases are skipped and reported. Golden files:tests/proto/fixtures/tokens/(UPDATE_GOLDEN=1rewrites them). - Like
ops.js, the new modules have no app importer until T3 and ship as unminified source files (budget +39 KiB gzip, recorded inscripts/size-budget.json).
- Modules:
T6 · Assets, components and variables UI — M — deps: T4, T5
- Scope: Assets panel (components, sets, styles, drag to insert), component section of the Design panel (create component, combine as variants, properties, variant pickers and property fields on instances, go to main, reset, detach), Variables panel (collections as tables, modes, aliases, scopes, code names, DTCG import and export), binding picker on every Design field, mode switcher per frame.
- Files:
app/src/proto/panels/{assets,variables,binding}.js,app/src/proto/panels/design.js,tests/proto/panels-model.test.js(pure view models). - Acceptance: every action one undo step; a mode switch repaints only affected frames; keyboard access as in T4.
- As built (deviations and decisions the later tasks build on):
- Modules:
proto/panels/model.js(pure view models and the operations every panel action runs:assetList,insertInstanceOp,instanceInfo,componentInfo,propBindTargets,bindCandidates,bindOp,variableTable,cellOp,resetCellOp,modeChoices,modeOp,styleSlotInfo, the style operations,tokenExport; tested intests/proto/panels-model.test.js),panels/binding.js(the shared popover, the variable picker andbindable, the bind button or bound chip of a Design field),panels/assets.js(dock idproto-assets, a tab next to Layers),panels/variables.js(dock idproto-variables, bottom dock). No engine operation was added; every action is one operation (a batch for several layers) throughws.apply, so one undo step. The workspace gainedgoTo(id),comments,commentAnchor()andrevealComment(anchor); the Proto layout now gives the bottom dock its height (it was fixed at 0) and the Window menu shows in the studio. - Component section: create (a frame becomes the component in place) and combine come from the selection; properties
are edited in place (rename, defaults, variant options as a comma list); an inner layer binds its
text,visible,of(nested instance) orchildren(slot) to a property in a Component property section. Text property defaults start as “Text”. - Instance section: swap lists every component and set; variant pickers start from the variant an instance of one variant keeps; overrides count active and inactive paths plus set property values. Overrides of inner layers are not edited from the panel (canvas clicks select the outer instance, T3); they come from the assistant and reset here.
- Bindings: opacity, corner radius (also per corner), gap, row gap, padding sides, fill, stroke and shadow colors,
stroke width, font, font size, weight, letter spacing, text color and visibility. Width and height and line height
are not bindable from the panel yet (
w.valueworks throughnode.bind). Variables outside their scopes are listed disabled. Editing a list (fills, padding) keeps bindings of the other items. - Variables panel: a brand table shows the chain's variables; editing a cell writes
ext[brand][mode]; Reset to the base value removes it. Deleting a used variable or collection detaches (layers keep their values) after a confirmation. Tokens import merges into the shown collection (a base collection) or the file's own collections. - Styles: a palette button per section (fill, stroke, effect, text, grid layout); while a style is applied the section shows the style chip instead of the local fields. A stroke uses fill styles, so a stroke style is created from the layer's fills.
- Mode switcher: one select per collection family with more than one mode or a brand (
Autoinherits); a frame'smodeschange re-renders only that top-level layer (T3'schangedRoots). - Comments (T10 follow-up): anchor kind
proto(protocol.js ▸ ANCHOR,anchors.js ▸ protoAnchor:page,pinin world coordinates,nodeandofffor the deepest layer under the point,quote);proto/comments.jsdraws the pins over the canvas (DOM buttons of the comment UI, two frames after a change so they follow the measured boxes), drags them (reanchor), and adds the Comment tool (C).comments-hostasksapp.protoUI.commentAnchor()for Add Comment and revealsprotoanchors in the workspace;comment-context.jsresolves them for the assistant. The assistant'sadd_commentwith alayer_idstill resolves only layers of the classic studios. - Lint (T11/T13 follow-up):
cli/lib/proto-lint.mjsrunsengine/proto/lint.jsfor the design rules; the CLI-only checks areschema,unresolvedandclipped.stale-overrideandtext-overfloware aliases; the CLI's own touch-target and empty-frame checks are gone in favor of the engine's. Safe fixes become one operation or batch; unsafe ones asuggestion. - Assets previews are the solver's display list painted into a canvas (
ai-render.js), cached per component and the identities of its subtree, variables and styles.
- Modules:
T7 · Code export — L — deps: T5, T13
- Scope:
codegen/lower.js(IR, tag inference, class names), emitters HTML + CSS, React (CSS Modules or Tailwind, TS or JS), Tailwind, SwiftUI; responsive breakpoint merge; code links; Code panel (Inspect mode) with copy and an export dialog;ofini proto exportandofini proto tokens. - Files:
app/src/engine/proto/codegen/*,app/src/proto/panels/code.js,cli/lib/proto.mjs,tests/proto/codegen/*.test.jswith snapshots. - Acceptance: deterministic snapshots; exported HTML rendered in Chromium matches T2's recorded geometry per fixture; generated React passes a syntax check (TypeScript compiler only if it is already a dev dependency).
- As built (deviations and decisions the later tasks build on):
- Modules:
engine/proto/codegen/withlower.js(lower(model, { ids, page, modes, assetUrl, dataIds, collapse })→ IR{ screens, components, assets, vars, fonts, warnings, breakpoints }; the IR node shape is in its header:{ key, id, type, name, base, el, decls, attrs, text?, svg?, image?, children, box, r, instance?, bind?, slot?, href? }), the emittershtml.js(emitHtml, alsohtmlMarkup,svgMarkup,svgFile,RESET_CSS),react.js(emitReact(ir, { styling: "modules" | "tailwind", ts })),tailwind.js(emitTailwind,twClasses(decls)),swiftui.js(emitSwiftUI) andindex.js(exportCode(model, { format, ids, page, modes, ts, dataIds, collapse })→{ format, files: [{ path, text } | { path, bytes, mime }], entry, warnings, ir },FORMATS,zipEntries). The emitters load on demand per format. T12 (proto_to_codeover MCP) and T14 (export into a Code project) callexportCode; T14 adds the guarded regions around the files it writes (dataIds: truegives thedata-proto-idattributes of §10.4). The concept'semit/folder andclasses/tokensIR fields became one flat folder andbase(class names are made unique per stylesheet by the emitters) plusdeclswithvar()references. - Declarations are css.js's (
vars: "css",root: "none",scroll: true) withoutbox-sizing(every export sets border-box globally: a reset, Tailwind's preflight); four-valuepadding,border-radiusandborder-widthare shortened; roots getposition: relative. Verified in Chromium 156 withscripts/proto-export-roundtrip.mjs: all 16 geometry fixtures within 1 px (2 px with text);tests/proto/codegen/roundtrip.test.jsruns it withPROTO_ROUNDTRIP=1. - Tags: the
tagfield (checked against a list of HTML elements; void elements with children fall back), else text from the text style's name (H1…H6, heading, title, display) or size (32 px h1, 24 px h2, 20 px semibold h3, else p), click interactions (navigateto an exported screen oropenUrlwith http, https, mailto or tel →a, elsebutton), images with one image fill and no hug size →imgwithobject-fit, vectors → inlinesvg, names (button, nav, header, footer, form, card/section). Phrasing-only parents turn children into spans. Hidden layers are left out (bound visibility is a conditional instead). Wrappers that draw nothing, hug a single flow child and sit in a flex parent are collapsed (collapse: falsekeeps them). - Classes: kebab-case layer names; equal name and equal declarations share one class. Responsive merge: top-level
frames with the same name on one page and the same shape; the media query uses the smallest design breakpoint at or
above the narrower frame's width (else its width). There is no
responsivelink field yet. - React components: variants that share one structure print one tree with the declarations common to all variants on
the layer's class and the rest under
[data-variant="<slug>"](CSS Modules) or aVARIANT_CLASSEStable (Tailwind); aVARIANTStable maps every combination of axis values (up to 256) to the best-matching variant likepickVariant. Different structures render aswitch. Usages pass non-default variant values and properties and aclassNamewith the instance's differences from the component root (Tailwind marks overriding classes!). Instances withoverare written out (warningoverrides). A single slot ischildren. Code links (code.react.path,export,propsmapping) import instead of generating. - SwiftUI: components are
<Name>Viewstructs with enum axes,switchover variants, swap and slot properties asAnyView; vectors are written as SVG assets; breakpoint variants are not exported. The app's Code studio formatter is not run over the output: the emitters print formatted code themselves (two-space indentation), which keeps the output deterministic and the exporter usable in Node. - UI:
proto/panels/code.js(dock idproto-code, a tab next to Design in Essentials; format remembered inlocalStorage), the Design panel's Export section (exportSection), ZIP download through fflate andplatform.saveFile. Vibe toolproto_to_code(read-only;fileandmaxCharsfor long exports). CLIofini proto exportwith--format(alias--target, so T9 can addprototype),--node,--page,--out(-prints),--js,--data-ids,--keep-wrappers,--mode.ofini proto tokenshad already moved to T13. - Tests:
tests/proto/codegen/codegen.test.js(golden files for the sample design andfixtures/codegen/kit.jsonin all five formats, determinism, Lezer syntax checks of TSX, JSX and CSS, balanced Swift, the IR equals the canvas declarations, tag and component lowering, breakpoints, code links, Tailwind mapping); CLI and Vibe tool tests. Budget +29 KiB gzip, all lazy.
- Modules:
T8 · Imports: HTML and CSS, SVG, clipboard, Sketch, Penpot — L — deps: T5
- Scope:
import/html.js(computed-style mapper in the app, static path for the CLI), SVG through the existing importer, clipboard handlers, Sketch reader extension (symbols → components, overrides, stacks → flex), Penpot export reader, import report (core/import-report.js),ofini proto import. - Files:
app/src/engine/proto/import/*,app/src/proto/paste.js,cli/lib/proto.mjs,tests/proto/import/*.test.jswith synthetic fixtures built from public format descriptions only. - Acceptance: export → import → export is stable for the HTML fixtures; sanitizer tests (scripts, event handlers,
javascript:URLs); every importer reports what it skipped. - As built (deviations and decisions the later tasks build on):
- Modules:
engine/proto/import/(pure, plain Node):common.js(limits,safeUnzipwith declared-size and ratio checks before inflating, the builder that pre-assigns ids against the target model and deduplicates media, colors, image sniffing and sizes),sanitize.js,html.js(importHtml,mapProbe,tracks),html-static.js(staticProbe: user agent defaults, a cascade with specificity,!important, inheritance,@mediawidths,var()and shorthand expansion; unsupported selectors skip their rule and are counted),svg.js,sketch.js,penpot.jsandindex.js(detectFormat,importInto,importImage,applyImport,designFromImport). The app side isproto/paste.js,proto/html-probe.jsandproto/tools/image.js; the import report iscore/import-report.js(existing), attached to the document, so File ▸ Import Report… shows it. - Every importer returns engine operations (
media.put,page.create,collection.create/var.create,node.createwith nested children and pre-assigned ids), so an import is one validated undo step everywhere. Components are created before their instances;node.createstarts from the type's defaults, so the importers set every field they mean (fills, clip) explicitly. - HTML: the app renders the sanitized page in a hidden
sandbox="allow-scripts"frame (opaque origin) with its own CSP (only the probe'sdata:script,data:images and fonts, no network) instead of the Code studio's preview pane, which is bound to a Code project; the probe waits until the frame has its viewport (a sandboxed frame runs in its own process and gets its size afterload). The probe reports computed styles, boxes and the declared width, height, flex basis and grid templates (from the matching rules), because computed values are always pixels. Sizing rules:flex-growor 100 % → fill, auto in a stretching cross axis → fill,fit-contentand auto → hug, lengths → fixed (border-box). Blocks become column auto layouts (gap = the most common space between children, first and last margins and equal side margins become padding; uneven spacing is reported), inline-only blocks wrapping rows; a text-only element with decoration becomes a frame around a text layer; a fragment with one element (pasted HTML) becomes that element, a page becomes a frame named after its<title>.data-proto-idkeeps ids. Custom properties of:rootbecome the collection CSS variables; colors equal to exactly one of them are bound. Repeated sibling structures (three or more) are reported as component candidates, not converted. - Round trip:
tests/proto/import/_export.jsprintscss.jsdeclarations as style attributes (what T7's HTML export and the live link write); export → import → export is byte-identical for the fixtures, also on a second pass. - SVG is a new pure importer (
office/xml.jsparser,vector/path.jsfor path math), notvector/svg-import.js, which needs the DOM and canvas; groups become frames without layout, axis-aligned rectangles and ellipses stay shapes, everything else becomes vectors with all transforms applied. - Sketch:
engine/formats/sketch.js ▸ readSketch(input, { symbols: true })adds object ids, symbol masters withsymbolID, instances with override values, image fills, shadows, blurs, text runs, stacks (MSImmutableFlexGroupLayout: direction, justify, align, gap, wrap, padding, children's fixed / fit / fill sizing) and Smart Layout (direction, gap from positions); without the option the Vector importer's result is unchanged. Overrides_stringValue,_symbolID(empty hides),_imageand_isVisiblemap tooverby the path of Proto ids; shared style and color overrides are reported. - Penpot: the export format version 3 (Penpot 2.x) as described in Penpot's technical guide; shapes in page
coordinates are made relative;
layoutItemHSizing/VSizingmap to fill, hug and fixed; copies of components become instances whose overrides are the differences of theirshapeRefchildren (text, fills, visibility). Tokens are reported (import them with DTCG); the binary v1 format is refused. - Clipboard: copy writes an OpenFini MIME type (
application/x-openfini-proto+json), HTML with the same payload in adata-openfini-protoattribute (survives other apps and the async Clipboard API) and the layer names as text; the payload carries the images its layers use (16 MiB). Ctrl/Cmd+C, X and V on the canvas pass through to the browser's clipboard events (the workspace stops the shortcut there); Edit ▸ Paste reads the system clipboard and falls back to the in-app clipboard. Proto layers pasted into the same design without a target keep T4's placement (next to the originals). Text becomes a text layer. - Image tool (from T4's open list):
Shift+Ctrl/Cmd+K, click where the pictures go; Insert ▸ Image…; media go in throughmedia.put. proto_write_htmluses the browser probe when the app window exists and the static path in Node; it returns the import report.ofini proto import <file> [--from] [-o] [--width] [--into <design> --in-place|--out](the concept's<in> <out.ofini>form is-o).- Limits (
IMPORT_LIMITS): HTML 8 MiB, SVG 16 MiB, archives 256 MiB, 20,000 entries, 128 MiB per entry, 512 MiB unpacked and at most 200× the archive size above 64 MiB, 50,000 layers per import; media keep the 16 MiB schema limit. - Not done: the Figma REST importer (as planned, after 1.3.x); HTML from a URL (the web access tools can fetch it
and pass it to
proto_write_html); converting repeated structures into components automatically. - Follow-up (ADR 0034 amendment A, 2026-11-26):
import/fig.jsreads Figma.figfiles read only and best effort behind the Labs switchlabsFigImport(importInto(…, { allowFig }); the CLI needs--from fig). The container (ZIP withcanvas.figandimages/<sha1>, or a bare "fig-kiwi" canvas) is unpacked within the T8 limits; chunks are raw DEFLATE (fflate, with an output bound) or Zstandard (zstd.js, a pure RFC 8878 decoder with an output bound, verified against Node's zstd);kiwi.jsdecodes the file's own schema and message (value, depth and length limits; field names that would touch prototypes are renamed). The mapper reads fields by name (READin fig.js) and lists every other non-empty field in the report with its layer count, so the report shows what was not mapped. Transforms are taken as relative to the direct parent (groups included) and converted to Proto's unrotated box and rotation around the center; mirroring is reported. Instances keep their component's layers (layers stored inside instances are ignored); override paths are the guid paths mapped to Proto ids (overrideKeytoo). Fixtures are synthetic (tests/proto/import/fig-fixture.js: a hand-written Kiwi schema, an encoder for tests only, and the container); tests also flip random bits in files and require an import or an ImportError.
- Modules:
T9 · Prototyping and the player — L — deps: T4, T5
- Scope: interaction ops, Prototype mode and panel, Connect tool, expression evaluator, player runtime (navigation stack, overlays, scroll and sticky, transitions, smart animate with FLIP and WAAPI, springs), preview window (multi-window on the desktop), presenting in a room, HTML prototype export.
- Files:
app/src/engine/proto/{interactions,expr}.js,app/src/proto/player/*,app/src/proto/panels/prototype.js,tests/proto/{interactions,expr}.test.js. - Acceptance: the evaluator accepts only the data language (fuzz test); the exported prototype contains no external URLs (test) and works offline; smart animate at 60 fps for the 200-layer fixture (manual check in the PR).
- As built (deviations and decisions the later tasks build on):
- Engine:
engine/proto/interactions.js(the interaction and flow model, checks, transitions with springs sampled into CSSlinear(), connections, the flow graph,describe,interactionsOf,flattenandmatchLayersfor smart animate) andexpr.js(the data language with a step and depth limit;{ var },{ op, args }and the shorthand{ var, op, value }). Operations in the one table ofops.js:interaction.add/set/delete,interaction.connect(the Connect handle: one click navigation per trigger,to: nullremoves it),flow.create/update/delete; their inverses arenode.update/page.update, and they refuse invalid interactions, missing or nested targets and unknown variables (validate.js keeps warning only, so deleting a frame never fails). Shapes: transitions{ type, dir, dur, ease }witheasea keyword,{ bezier }or{ spring: [mass, stiffness, damping] }(a spring withoutdurtakes its settle time); overlays{ pos, dim, closeOutside };variantactions{ set, target? }; flows may carry adescription. - Interactive components: an instance without interactions of its own uses those of the variant it shows
(
interactionsOf), so a hover defined onstate=defaultworks on every instance. Avariantaction on a layer inside a nested instance writes an overridevarianton the outermost real instance in the player (withVariants); this path is only unit tested. - Player:
proto/player/state.js(pure state machine: history with the transition of each step, back plays it reversed, overlay stack, variables and variants, while-hovering and while-pressing holds that restore what they changed,variableChangecascades limited to 8 levels and 256 actions per event),render.js(one screen throughcss.jswithscroll: trueand literal variable values, own shadow root,data-of-keyon every element),animate.js(dissolve, move in and out, push, slide, smart animate as FLIP with the Web Animations API: matched layers animate position, width and height, colors, opacity and radius; layers of the old screen fade out above the new one; reduced motion turns transitions off) andplayer.js(toolbar, device frames, hotspot hints, keys, timers, input mapping). The player is one object in the main window; Preview in New Window moves its element into a window opened byui/docking/windows.js(the tear-off window: a native window on the desktop, a pop-up in the browser). Edits made while it plays show from the next screen. - Editor: Prototype mode is a workspace state (
ws.mode,setMode, themodeevent, kept in the view state), the inspector has Design and Prototype tabs (panels/prototype.js ▸ createInspector, so the Design panel itself is unchanged), the Connect tool is the Move tool plus the handle (tools/connect.js, chosen by the mode; no toolbar button), and connections are drawn on the overlay. Flows are edited in the Pages panel and the Prototype panel. Commands and the Prototype menu: Preview Prototype (Mod+Alt+Enter), Preview in New Window, Design Mode, Prototype Mode, Switch (Shift+E), Add Flow Starting Point. - Assistant and CLI: the Vibe tool
proto_interaction(list, add, set, delete, connect, addFlow, updateFlow, deleteFlow; names resolve to ids) and the skillproto-prototype-flow;ofini proto flowslists each flow's screens (breadth first from the start, layers in document order) and interactions, exit code 1 when a start or a target is missing. - Not in this task (follow-ups): presenting in a room (player state as presence), the HTML prototype export (
ofini proto export --target prototype, which needs T7's export command), the current frame's comments in the player,mediaactions, and a measured 60 fps check of smart animate on the 200-layer fixture.
- Engine:
T10 · Live collaboration — M — deps: T3
- Scope:
proto/collab.jsrecords adapter (section 13),"proto"inLIVE_OFFICE_KINDS, per-record validation, presence on the canvas (cursors, selections, follow), comment anchor kindprotowith pins on the overlay. - Files:
app/src/proto/collab.js,app/src/core/live-kinds.js,app/src/collab/anchors.js,tests/proto/collab.test.js,docs/collaboration.md. - Acceptance: convergence property test (thousands of seeded random concurrent histories through the adapter); malformed records rejected; two-window manual test over BroadcastChannel.
- As built (deviations and decisions the later tasks build on):
proto/collab.js(protoCollabAdapter) runs on the existing records engine (collab/office-sync.js, op kindoffice);"proto"is inLIVE_OFFICE_KINDSandui/collab/live.jsloads the adapter for the kind. Records as in §13 with these choices: the structure recordn:<id>also carriesname,visibleandlocked;n:<id>/textcarries the content of every layer kind (text,d,rule,alt);opacityandblendare inlook,stickyinlay,tag,a11yandmodesinproto; fields this version does not know travel inn:<id>/x. A group record exists only when the layer has one of its fields. Values are canonical (sorted keys) and cached per node object, so unchanged layers cost nothing per flush.- Generic over the model (for T5 and later tasks):
COLLECTIONSlists the id-keyed maps that sync per entry (p:pages,vc:vars.collections,v:vars.items,s:styles,media:media without bytes); every other top-level key (meta, breakpoints, code, and anything a later task adds) is onemeta:<key>record, so new data syncs without code changes. A new id-keyed map that should merge per entry is one line inCOLLECTIONS; a new node field is one entry inGROUPS(until then it travels inn:<id>/x). Components and instances are nodes, so T5's component operations sync through the node records as they are. - Validation: remote node records go through
validate.js ▸ nodeProblems, the other records throughvalidate()on the model without layers. Shape errors reject a record (when a layer fails as a whole its records are tried one by one, so one bad record does not hold back the others of the layer); reference problems (missing-*, cycles, limits, binding types) are accepted, because rejecting them depends on arrival order and would make replicas diverge, and the resolver treats them as warnings. - Tree repair, the same on every replica: layers of a missing page are hidden; layers whose parent is missing, is no
container, is on another page, or is a component set while the layer is no component, go to the top level of their
page (a move into a concurrently deleted frame keeps the layer); a parent cycle from concurrent moves is broken at
the layer with the smallest id (the tree CRDT undoes the newest move instead, but the record adapter has no clocks).
A text layer whose text record was removed by a concurrent delete while someone renamed it gets the default text.
The children index is updated incrementally for the changed layers (
adoptIndex), asops.jsdoes locally. office-sync.jschange for every adapter: records the model changed as a side effect of a remote op (not only the keys of the op) are compared with the view and retried when they differ. Without it, a layer that came back (undo of a delete) missed a group record that had survived in the view, and a repaired placement was never retried.- Undo: nothing new; the workspace's
opStepreplays the inverse on the current model, which keeps remote edits (the binding'sprj.rebasehook is installed but the Proto history does not use it). - A snapshot opened by a late joiner still has the container fields; the adapter's
prepareloads it (format.js ▸ loadModel) before the binding starts. - Presence:
proto/presence.jspublishes the Proto page, the pointer and the visible rect in world units and the selected ids (the existing presence message;studio: "proto"), draws the others' pointers and selection outlines in their colors throughview.overlay.addLayer(added once per workspace byui/collab/overlay.js, redrawn on presence changes), and Follow sets the page and the camera that fits the member's visible rect. The workspace needed no new hooks: the runtime listens to the stage's pointer events and tows.on("selection" | "camera" | "page"). - Not done in T10 (added with T6): the comment anchor kind
protowith pins on the overlay (comments on a Proto design are document comments for now); it needs the comment composer's canvas hooks, which T4 is changing, and follows as its own task. - Tests:
tests/proto/collab.test.js(two and three peers with the real controller, shuffled delivery, late joiner, chunked media, malformed records, 300 seeded random histories in CI; 2,000 checked withPROTO_COLLAB_SEEDS=2000). Manual check: two tabs of the dev server in a This device room (share live, open live, concurrent fill and move of one layer, Undo of the fill in one tab keeps the other's move, pointer and selection outline of the other tab, Follow).
T11 · Vibe tools, lint and skills — M — deps: T5
- Scope:
vibe/tools/proto.jswith the tools of section 7 whose capability exists (describe, get, screenshot, search, create, update, move, delete, duplicate, component, variables, styles, lint, fix, tokens, responsive, content, rename, from_screenshot);write_html,to_codeandinteractionare added by T8, T7 and T9. Tool group and verify hints,engine/proto/lint.jswith fixes, skill pack, studio guide. - Files:
app/src/vibe/tools/{proto.js,index.js},app/src/engine/proto/lint.js,app/src/ai/packs/proto.js,app/src/ai/packs/studio-guides.js,tests/proto/lint.test.js,tests/vibe/proto-tools.test.js. - Acceptance: every write tool is one undo step and validated; each lint rule has positive and negative fixtures; a scripted agent run (mock provider) builds a login screen with auto layout.
- As built (deviations and decisions the later tasks build on):
- Modules:
vibe/tools/proto.js(20 static definitions, group Proto, verify hint "proto_describe and proto_screenshot"),proto/ai-ops.js(pure:describe,nodeLine,getNodes,search,createOps,updateOps,fieldsOf,names,renameOps,contentOps,responsive),proto/ai-render.js(pure display list from the solver,paintCanvas),proto/ai-runtime.js(protoTarget,renderImage,readImage,imageHints) andengine/proto/lint.js(lint,fixOps,suggestName,suggestTag,contrastRatio). Like the Scene Studio's tools (scene/ai-ops.js), the pure part lives next to the studio, not invibe/. - Commits:
protoTarget(app).run(ops, label)applies a tool's operations as onebatchthroughapp.protoUI.runwhen the design is mounted (the same path as the editor), else through the sameopStepundo step on the document history; labels are "Vibe: …". A failing operation throws the engine'sOpErrorand nothing changes. - Specs:
createOpsturns nested specs with shorthands (sizes as numbers, "hug", "fill", "50%";layout: "row";gap,pad,justify: "between";fill,stroke,shadow: "md"; text style keys;{ "$var": name }; type aliases row, column, stack, box) intonode.create/instance.createoperations with pre-assigned ids, so redo and collaboration replay the same ids and the tool can return them (refs). Nested frames default to a transparent column that hugs (a div), text layers without a name take their first words. Names of variables, styles and components resolve to ids everywhere. - Additions beyond the section 7 table:
proto_new(a design from the tools, likescene_new);proto_screenshothascompare(side by side with a reference image and a mean pixel difference), which stands in forvisual_diffon designs. Tool namesproto_variablesandproto_stylestake anaction, likeproto_component. - Engine addition: the operation
media.put { id?, media | null }(add, replace or remove one media item; the inverse puts the previous item back; bytes are shared, never copied).proto_from_screenshotuses it for the reference image; the Image tool of T4 and the importers of T8 can use it too. - Screenshots: the canvas DOM cannot be rasterized portably (an SVG foreignObject taints the canvas in WebKit and
loses the app fonts), so
proto_screenshotpaints the solver's boxes (fills, gradients, images, strokes, drop shadows, blur, text lines with the app's fonts and the canvas measurer) and says it is approximate. In Node the tools work without it (it needs the app window). - Lint rules (
RULES): contrast (WCAG 2, against the composited solid backgrounds; gradients and images skip), touch-target (under 24 px warning, under 44 px info; interactive = tag, a11y role, click interaction or a button-like name), unbound-color and unbound-spacing (only when variables exist; a value equal to exactly one variable gets anode.bindfix), off-grid (gap and padding off 4 px), detached-style (local values equal to a style), inactive-override (components.overridePaths), detached-instance (a frame named like a component; the fix replaces it with an instance and runs only when its id is named), empty-frame, naming (default names with a suggested name), overflow-text (fixed text boxes, text past a clipping container), unused-token (variables and styles nobody uses; deleting runs only when named). Layers inside instances are reported by key and never fixed directly. Touch targets, overflow and contrast use the solver, so they are approximate in the same way. - Skills: lazy pack
proto(app/src/ai/packs/proto.js): proto-screen-from-brief, proto-screen-from-screenshot, proto-component-variants, proto-tokens-dark-mode, proto-handoff, proto-design-audit; prototype a flow follows with T9. Studio guidestudio-guide-proto; the system prompt note, compact tool list (contextproto), plan_work studioprotoand the sub-agent tool setprotoknow the studio. - OCR in
proto_from_screenshotuses only local engines of the registry (no data leaves the device); colors and text need the app window. - AI tools, 1.3.x follow-up: design-level tools on top of the T11 set, logic in
proto/ai-design.js(pure, tested intests/proto/ai-design.test.js), each write one batch:proto_design_systemandproto_apprun the template builder (proto/templates/builder.js, explicit ids, so the recorded operations replay as one step) withtemplates/system.js; existing collections, variables, styles and pages are reused by name and existing components kept (merge instead of duplicate names, which would make$varnames ambiguous).proto_restylerewrites token values (orextoverrides of a new extending brand collection), text styles and the radius scale.proto_responsive_variantinserts an exact copy (node.insertwith new ids; main components inside become instances) adapted by rules, then wraps or stacks rows the solver still sees overflowing.proto_extract_componentsgroups frames by a structural signature (types, layout, child structure).proto_a11ybuilds on the lint rules contrast and touch-target and adds alt text, icon-button names, headings and small text.proto_copy,proto_critique(pictures throughrenderImageplus pure facts and a rubric) andproto_template(templates ofproto/templates/index.js) complete the set.proto_from_screenshotadds a pure segmentation (segment: background, bands, blocks with kinds) and an auto layout skeleton (skeleton); pixels are read in the app window only. Skills: proto-app-from-brief, proto-rebrand, proto-responsive-variants, proto-extract-components, proto-accessibility, proto-copywriting, proto-critique.
- Modules:
T12 · MCP server — L — deps: T7, T11
- Scope:
engine/proto/mcp/handler (lifecycle, tools, resources with subscribe, prompts), app document host, file host,src-tauri/src/mcp_server.rs(loopback HTTP, token, Host and Origin checks, limits, event bridge), Settings UI (enable, port, token, approved clients, copyable client configurations), approval prompt, AI log entries,ofini mcp(stdio proxy and headless file mode). - Files:
app/src/engine/proto/mcp/*,app/src/proto/mcp-host.js,app/src/ui/vibe/settings-mcp-server.js,src-tauri/src/{mcp_server.rs,lib.rs},cli/lib/mcp.mjs,tests/proto/mcp.test.js, Rust unit tests,docs/security.md,docs/proto-studio.md. - Acceptance: handler conformance in Node (initialize, tools/list, tools/call errors, resources, subscribe); a stdio session against the headless file host; Rust tests for the Host, Origin and token checks and the size limits; manual connection from Claude Code and Cursor described in the PR.
- As built (deviations and decisions the later tasks build on):
- Modules:
engine/proto/mcp/server.js(the transport-neutral handler: lifecycle with version negotiation 2025-11-25 / 2025-06-18 / 2025-03-26,tools/*,resources/*with subscribe and templates,prompts/*, the tool catalogCATALOG, limits) andengine/proto/mcp/data.js(the tools without an assistant counterpart: geometry from the solver, variables, components, SVG import). The document host interface is in the header ofserver.js; its two implementations areproto/mcp-host.js(the app: open designs, approval prompt, AI log, status bar indicator, the Tauri bridge) andcli/lib/mcp.mjs(one file, plus the stdio transport and the relay). The concept'sui/vibe/settings-mcp-server.jsis a new tab MCP server of Settings ▸ Artificial intelligence. - Reuse: MCP tools are the T11 tool objects of
vibe/tools/proto.js, bound per design and client.protoTools(app, { labelPrefix })andprotoTarget(app, { labelPrefix })gained the label prefix, so a write is one undo step "MCP · <client>: …"; the app host binds them to any open design through a prototype ofappwhosedocis that design. MCP names follow §8.2 (proto_get_tree=proto_describe,proto_generate_code=proto_to_code,proto_get_tokens/proto_set_tokens= the two halves ofproto_tokens); descriptions are reused with the names rewritten. Added beyond §8.2:proto_get_variables,proto_write_svg,proto_apply_ops(raw operations, one batch),proto_duplicate,proto_content,proto_rename,proto_responsive. - Comments (1.3.x follow-up):
proto_get_comments(read;describeThreadofcollab/comment-context.js, so the targets match the assistant'slist_comments) andproto_reply_comment(write) are implemented inserver.json a host interfacehost.comments(doc, session)→{ threads(), authorId, env, commit(op), blocked?(), shared }: the app binds it to the comments host (ui/collab/comments-host.js▸commentOp: marks the design modified, broadcasts in a room;blockedwhen the room role may not comment), the file host todocument.json ▸ commentsof an.ofini(saved through the same atomic write as design changes; a bare model JSON has no comments). The reply is a message byMCP · <client>(32 characters at most) withai: true; like every comment it is not an undo step, and the call is one AI log record. It skips the design's read-only check (comments are not design changes) but needs write access. - Per-design approval (1.3.x follow-up):
engine/proto/mcp/grants.js(pure, tested intests/proto/mcp-grants.test.js).mcpServer.clients[name] = { at, blocked?, docs: { [docId]: { scope, title, at } } }withmcpServer.grants: 2; the document id (saved in the.ofini) identifies a design. The host interface gaineddocAccess(session, doc);documents(session)returns the granted designs plus the active one while undecided (access: "ask"); the session scope is the best grant (it decides which tools are listed), each call checks its design. One prompt per client and design at a time, naming the design. 1.3.0 grants migrate to grants for the designs open at the first start (a 1.3.0 deny becomes blocked). Settings lists each client's designs with scope and Revoke, plus Block and Revoke all. - Approval: asked on
initialize(no blocking of the handshake);tools/listand calls wait up to 20 s for the answer; write tools are listed only with write access, andnotifications/tools/list_changedfollows a change. Decisions are stored per client name in the Vibe settings (mcpServer.clients, with the port); the token is a secret of the Vibe key store (mcp-server-token, sealed with the API keys when they have a passphrase); the preferencemcpServerstarts the server at launch (boot.js, one dynamic import when it is on). - Transport:
src-tauri/src/mcp_server.rs(std only, likepreview_server.rs) forwards each POST as the eventopenfini://mcpto the main window and waits up to 30 s formcp_server_reply; sessions are created by the page's answer toinitializeand checked natively; GET opens a server-sent event stream fed bymcp_server_notify; DELETE ends a session. The token comes from the page (crypto.getRandomValues, 256 bits) because std Rust has no CSPRNG. Binds127.0.0.1and, best effort,[::1]on the same port (bind_loopback; no IPv6 or a taken port leaves IPv4 alone; the status reportsipv6); peers that are not loopback are closed (loopback_peer); the Host check accepts exactly[::1]:<port>as the IPv6 spelling; the advertised URL stays127.0.0.1, andofini mcpalso accepts an endpoint URL on[::1]. - Headless writes are saved after every successful write call (not on an explicit
save), validated first, through an exclusively created temporary file renamed over the original. Screenshots are SVG renders ofproto-svg.mjs. - Tests:
tests/proto/mcp.test.js(handler conformance against the file host, a spawnedofini mcp --filestdio session, the relay against an in-process endpoint, the endpoint file) and the Rust unit tests ofmcp_server.rs(Host, Origin, token, method, size, protocol version and session header checks; IPv6 Host spellings, loopback peers and the dual bind). Manual connections from Claude Code and Cursor to the desktop app are still open.
- Modules:
T13 · CLI ofini proto — M — deps: T5
- Scope:
cli/lib/proto.mjswithinfo,tree,validate,lint(schema checks; design rules once T11 is merged),render(SVG through the solver),assets(SVG and embedded media),diff; help, completion,ofini new proto. T7 addsexportandtokens, T8import, T12ofini mcp. - Files:
cli/lib/{proto.mjs,main.mjs,completion.mjs},tests/packaging/ofini-proto.test.js,docs/cli.md. - Acceptance: every command runs in plain Node on the fixtures;
--jsonshapes tested; exit codes as ADR 0032. - As built (deviations and decisions the later tasks build on):
- Modules:
cli/lib/proto.mjs(the command tablePROTO_COMMANDS, a command group:main.mjsdispatches the first word afterprotoand parses that subcommand's options; help, completion and the interactive mode know groups),proto-model.mjs(reading designs from.ofini,document.jsonor a bare model; writing back the same container; page, layer and mode lookups;withModes),proto-svg.mjs(renderSvg),proto-lint.mjs(LINT_RULES,lintModel,applyFixes) andio.mjs(the file helpers moved out ofmain.mjs). No engine module changed. T7 addsexporttoPROTO_COMMANDS, T8import. - Beyond the scope:
inspect(raw and resolved layers, CSS, solver box),tokensandtokens import(moved here from T7 becausetokens.jsexists: DTCG, CSS, Tailwind, Swift and plain JSON values),apply(engine operations from JSON, standard input or--ops, one batch,--seedfor reproducible ids),validate --strict. - The SVG render lays out the layer inside its top-level layer and draws from the resolved fields (not from the CSS
declarations); it is approximate (base-14 metrics; conic gradients as their first color; no inner shadows, shadow
spread by growing the outline, no background blur; per-side strokes ignore radii). PNG exits 4.
--modeis set on the top-level layer, because a layer's ownmodeswin over the resolver'smodes. - Lint rules until T11's
engine/proto/lint.js:schema,unresolved,stale-override(fix:instance.resetwith the path),text-overflow,clipped,touch-target(24 px, WCAG 2.5.8),empty-frame; the geometry rules are marked approximate; SARIF 2.1.0 output. T11 can add its rules toLINT_RULES/lintModel. - Assets: no layer field marks layers for export yet, so
assetswrites every vector layer (or the--nodelayers). - Writing a changed design needs
--out,--in-place(atomic rename, no backup) or--dry-run;lint --fixdefaults to<name>.fixed.ofinilike the Doctor's.repairedcopies.
- Modules:
T15 · Figma plugin compatibility layer — L — deps: T5 (ADR 0034 amendment B, owner decision 2026-11-26)
- Scope: the
figma.*plugin API over the Proto model and operations, sandboxed main code and UI, manifest loading, network allowlist with approval, install from a folder or ZIP, the Plugins menu, one undo step per batch. - Files:
app/src/engine/proto/plugins/{runtime,bridge,manifest}.js,app/src/proto/plugins/host.js,app/src/commands/proto.js,tests/proto/plugins/*,docs/figma-plugins.md. - As built:
- The runtime is one self-contained function serialized into the worker (like the extension relay), so Node tests
run the identical code in a
vmcontext. It mirrors the design from snapshots (model without media bytes, selection, page, measured boxes relative to the parent and absolute, viewport) and keeps children lists itself;node.updatewrites to the same layer are merged, and updates to a layer created in the same batch go into itsnode.create. Snapshots that arrive while the plugin has unsent or unacknowledged writes are ignored; the next acknowledgement brings a fresh one. - Batches flush on
setTimeout 0(a whole synchronous run, including writes after awaited promises that resolve before the next task, is one undo step) and onfigma.commitUndo(); selection, page and viewport changes are sent with the batch and run after it. - Ids are Proto ids; rotation is converted to Figma's counter-clockwise sense;
x/y/width/heightof flow, hug and fill layers come from the canvas measurement. Text writes requireloadFontAsynclike Figma. - Inline scripts of plugin UIs become
data:URLs (the app's policy, inherited bysrcdocframes, forbids inline code); inline event handler attributes therefore do not run. - Not done: vector networks, boolean operations,
createNodeFromSvg, text ranges, team libraries, shared plugin data, parameters and quick actions, instance sublayers as nodes,documentchangedetails.
- The runtime is one self-contained function serialized into the worker (like the extension relay), so Node tests
run the identical code in a
T14 · Code studio live link — M — deps: T6, T7
- Scope: tokens file link with two-way sync (10.2), export into a Code project with guarded regions and hash checks (10.3), live link mode, gutter badges in the Code studio, Open in Proto and Open in Code, importing selected HTML from the Code studio into Proto (uses T8 when merged).
- Files:
app/src/proto/code-link.js,app/src/ui/code/proto-link.js,app/src/engine/proto/regions.js,tests/proto/regions.test.js,docs/code-studio.md. - Acceptance: region merge tests (unchanged, edited by hand, markers removed); a token edit in either studio appears in the other within 1 s; nothing is written outside markers.
- As built (deviations and decisions):
- Modules:
engine/proto/regions.js(pure:hashTextFNV-1a, markers per comment syntax,parseRegions,mergeFilewith the statuses created, updated, unchanged, edited, conflict, detached and stale,resolveRegionkeep or design,lineDiff),engine/proto/link.js(pure:linkOf, the tokens plan, the file plan throughexportCodewithdataIds: true,locateNode/nodeIdAt,refreshOpsfor code → design),proto/code-link.js(the controller between the two open documents, the Link and conflict dialogs, the jumps),proto/panels/link.js(the Code project section of the Code panel: status per file),ui/code/proto-link.js(region badges, Explorer states, Open in Proto), the Vibe toolproto_code_link, andofini proto link(cli/lib/proto-link.mjs). - The link lives in the model's existing
codefield, changed by the new operationcode.update(fieldsproject { name, path? },tokensFile(""= no tokens sync, missing or null =tokens/tokens.json),dir,format,live,css,links { layerId: {} },sync). The project is another open document with a website, found by its file path, else its name; the concept's desktop folder handle is not used (a project opened from a folder is a document like any other). - Tokens: a three-way merge per token.
sync.tokensstores"<design hash>:<file hash>"per token path from the last sync; each side is compared with its own hash, so the design's DTCG export and a hand-written file never have to print a token identically. One side changed → that side wins; both → a conflict (kept on both sides until decided); deletions count. A new link has no state, so tokens on one side are copied and differing ones are conflicts (the Link dialog asks which side wins, or asks later). The import document is the file with the design's version of the tokens the design keeps; tokens of a plain file get the design variable's id and collection so they update it instead of creating a "Tokens" collection.syncis written withprj.set(…, { origin: "link" }), not as an undo step: undoing a variable edit then syncs the undone value again instead of reverting the sync state. The tokens sync runs 300 ms after a change on either side;tokens.cssis a guarded region file next to the tokens file (css: falseturns it off). - Files: one export of all linked layers (
exportCode(model, { ids, dataIds: true })) written underdir. Each text file is one region, id = the firstdata-proto-idin it, else its path; HTML pages guard only the<body>content, so the<head>belongs to the developer after creation. Files without comment syntax (JSON) are written only when missing; images when missing or different. The markers' end carries the id (end <id>); the parser also accepts the concept's bareend. Keep my edits rewrites the marker hash to the design's text, so the region only conflicts again when the design changes again. - Code studio side: the vendored CodeMirror has no custom gutters, so the "gutter badge" is a widget at the start of the
begin marker line (layer name, edited); marker lines are tinted. Writes use
WebProject#setText(…, "proto"): an open editor applies them as one undo step of that file; the live preview patches them (PR #163). - Code → design (Update Layer from Code, HTML + CSS only): the region's HTML and the generated CSS go through T8's
importer (the sandboxed probe in the app, the static path in Node) against the model without the layer, so
data-proto-idids are reused; the layer keeps its id, place and top-level position; the importer's:rootvariables are rebound to the design's variable with the same CSS name, others become values. Components are not reconstructed (instances come back as frames). - Commands (palette and canvas context menu, no new menu rows: start-up unchanged): Link to Code Project…, Sync with Code Project, Resolve Code Link Conflicts…, Open in Code, Update Layer from Code, Link / Unlink Selection to Code; in the Code studio Open in Proto and Sync with Linked Proto Designs (registered when a linked design is open).
- Not done: per-component regions inside one shared file (one region per generated file instead); a three-way text merge of regions (the dialog offers keep, overwrite and a diff, as the concept says); syncing while the design's tab was never opened in this session unless the Code studio of the linked project was shown (the controller starts from either side).
- Modules:
16. Open questions#
- Name. Decided: Proto Studio (final; the studio id and document kind are
proto). - Libraries across files. Publishing components from one
.ofinito others (reservedlib:references) needs a library cache and update notifications; after 1.3.x. - Variable fonts and OpenType features in the Design panel: CSS supports them; UI scope to be decided in T4.
- Vector networks (Figma) versus SVG paths: Proto keeps SVG paths (what code can express).
- Penpot format stability. Penpot's export format has changed between major versions; the reader targets the current format and states its version.
- Figma REST importer. Needs a terms review; may be dropped if the terms forbid this use.
17. Sources#
Public pages consulted (November 2026); product names are trademarks of their owners.
- Figma MCP server and write to canvas: https://developers.figma.com/docs/figma-mcp-server/, https://developers.figma.com/docs/figma-mcp-server/write-to-canvas
- Penpot MCP server and features: https://penpot.app/ai/mcp-server, https://penpot.app/design
- Paper: https://paper.design/, https://paper.design/docs/mcp
- Sketch MCP server: https://www.sketch.com/docs/mcp-server/, https://www.sketch.com/blog/sketch-in-2025/
- Design Tokens Community Group format: https://www.designtokens.org/
- Model Context Protocol specification (2025-11-25), security best practices: https://modelcontextprotocol.io/specification
- Figma
.figformat notes (why we do not read it): file-format-research.md
Edit on GitHub → docs/concepts/proto-studio.md