PaprikaPaprikaDocs
HomeGitHubPortuguês

Reference

Architecture

text
 agent (Claude Code, Cursor…)              human (browser)
        │ MCP stdio | Streamable HTTP /mcp        │ WebSocket /ws
        ▼                                         ▼
 ┌──────────────────────── server (paprika) ────────────────┐
 │ MCP (JSON-RPC) ──┐                       ┌── HTTP API + /ws  │
 │                  ▼                       ▼                   │
 │        Store  (internal/core: applyOps + History, SQLite)    │
 └───────────────────────────┬─────────────────────────────────┘
                             ▼
                    paprika.db (SQLite) ── import/export ── design.paprika.json (git)

 ┌──────────────── @paprika/core (TypeScript) ─────────────────┐
 │ schema (zod) · applyOps (transaction) · History (undo/redo)  │
 │ nodeStyle → React canvas · renderHTML · exportReact          │
 │ lintDocument · outline/queryNodes      (reference for Go)    │
 └──────────────────────────────────────────────────────────────┘

#Decisions

  1. Flat node map + children on containers (frame, group, page). O(1) access by id for the agent, an explicit tree for rendering. parseDocument checks integrity (no orphans, no duplicates, consistent parentId, pages only at the top and, once there is a page, only pages at the top).

  2. One write path: applyOps. The canvas, MCP and POST /api/ops produce the same operations. A transaction runs on a clone and only replaces the document if every operation succeeds. Each transaction yields its inverse operations, which feed the shared undo/redo.

  3. Reject unknown fields. Zod would drop them silently (colour instead of color); for agents, an explicit error is cheaper than a wrong design.

  4. One style engine. nodeStyle produces the CSS used by the canvas, the screenshot HTML and the React export. What the agent checks in the PNG is what the human sees. For path nodes, pathAttrs plays the same role for the <svg>/<path> attributes, and packages/core/src/path.ts (parser, normalization, exact bezier/arc bounds) runs the same way on the server, in the canvas and in tests; invalid d is rejected with the character position.

  5. SQLite is the source of truth. Documents, tokens and the undo/redo history live in SQLite (ADR 0001); every change is one transaction committed before the answer. .paprika.json goes in and out only through paprika import/export.

  6. Stateless MCP over HTTP. No per-connection server state to leak (the Mcp-Session-Id only carries the client name); state lives in the store. Write tools only reply after the change is committed.

  7. Local first. Loopback bind with Host/Origin validation. No authentication or multi-user support in this version.

  8. Composite operations expand inside the transaction. group, ungroup and add_page are operations too, but applyOps turns them into create/move/update/delete against the document as it is at that moment (packages/core/src/structure.ts), so a canvas or an agent working from a slightly old copy still gets a correct result and one undo step. A group's box is derived: at the end of every transaction fitGroups fits each group to its children (deepest first) and shifts them so nothing moves on screen; the inverse only stores positions, and width/height of a group are rejected as input.

  9. Instances are derived copies. A component is a frame with component: true; it may declare componentProps (text, boolean, variant) and contain frames or groups named with slot. An instance is a frame with instanceOf, an optional scale, propValues, slots and overrides (by component node id or the path instance/copy, only fill, color, text, src, alt, visible, opacity on copies; fill on the root; propValues and slots on a nested instance path). A node inside the component can bind a text prop to its text, a boolean to visible, or a variant map that omits the node unless every pair matches (a pair may list several options, and any of them matches; on the component itself only the default variant is drawn, the others stay hidden in the document; checked when the transaction ends, so a component and its bound children can be created in one call). Slot fills clone existing nodes into the slot. Instances may nest; a cycle is rejected. At the end of every transaction syncInstances (packages/core/src/component.ts) checks the rules and rebuilds each instance's children from the component, with deterministic ids (copyId, FNV-1a of instance + source id, the same in Go) and sourceId on each copy. Copies are ordinary nodes, so every renderer, export and lint works unchanged; because they are derived, undo never stores them: undoing the change to the component or instance and syncing again is enough. An update on a copy is turned into an override on the outermost instance, keyed by the joined path; moving, deleting or adding children inside an instance is rejected. detach turns an instance into a plain frame with the same ids, dropping bind from the copies. detach_tokens on an instance or a copy only touches the overrides it owns and reports the derived fields it skipped.

  10. Import and SVG export are pure functions in the core. importSVG and importHTML (packages/core/src/svgImport.ts, htmlImport.ts, over a small tolerant reader in markup.ts) return NodeInput trees plus warnings, and the caller writes them with ordinary create ops, so pasting is one undo step and goes through the same validation. importSVG turns <text> into text nodes and expands <use>/<symbol> sprites; images, gradients, masks and <style> stay warnings. importHTML is the inverse of nodeStyle: HTML from renderHTML (which tags each element with data-paprika-type) comes back with the same types and fields. The pure function only reads inline styles. import_html with computed: true is server-side only: the Go handler renders the HTML in Chromium, writes computed author styles inline, then calls the same importHTML. A missing Chromium is an error, not a fallback. exportSVG builds the SVG from boxes of core layout(doc) (auto layout, hug/fill); text splits on \n (glyph wrap stays approximate). An optional Measure still overrides boxes and lines for goldens and legacy paths; MEASURE_SCRIPT remains for that.

  11. Agent presence is implicit and ephemeral. Agents don't call a presence tool: every MCP tool call that reaches its handler reports {agent, actor, tool, nodes} to the store's PresenceHub (server/internal/server/presence.go), and /ws broadcasts it as {type: "presence", agent, actor, tool, nodes, idle}. nodes are the ids the call created or, if none, the ids named in its arguments (that still exist); agent is a hash of the HTTP Mcp-Session-Id (so two sessions of one client are two agents) or the actor on stdio. Presence never touches the document, the history or the disk; a canvas that connects gets each agent's last presence from the past 2 minutes right after the document. The canvas measures the nodes in the DOM (so auto layout and hug are right) and draws the cursor, outline and roster (apps/web/src/components/frontends/canvas/overlays/agent-cursors.tsx). Nodes an agent creates are never hidden or half styled: the document shows them at once, and the client only walks the agent's outline over the created ids (BuildReplay in agents.ts, one walk per actor, at most about 2 s per write, none under prefers-reduced-motion).

  12. Workspace = document, one active per server. The overview lists the documents of the server's database. The Store keeps one active document; openWorkspace swaps it in place and emits a change with kind open, so the WebSocket, the HTTP API and every MCP tool follow without new plumbing. The canvas and the agents share the active workspace on purpose: the human watches what the agent edits. A canvas tab on /w/<id> is the exception: it sends {type:"view", workspaceId} on its WebSocket and the server routes that connection's document, edits and undo to that workspace (ApplyIn/StepIn, with OnAside events for a workspace that is not active), so viewing a URL never switches the active workspace; a connection without a view follows the active one. Undo history belongs to each workspace and is stored in SQLite, so it survives a switch. The active workspace is per process: a separate paprika mcp over stdio keeps its own.

  13. Diagram connectors are derived from their ends. A shape node (rect, ellipse, diamond, triangle, cylinder, parallelogram, cloud, note) is a box with text inside, painted by shapeAttrs (an <svg> outline behind the text, the same in canvas, screenshot, React and SVG export). A connector stores only its ends (from/to: a nodeId with an optional side, or a free x/y in the parent's coordinates), the route (straight, elbow, rounded with radius, or curve with optional control) and its look; x, y, width, height and d are recomputed by routeConnectors (packages/core/src/diagram.ts) at the end of every transaction, after the instance sync, and are rejected as input. Like instance copies, that geometry stores no inverse. Ends are clipped to the shape's outline with only sqrt (no trigonometry), so the Go port gives the same numbers. Deleting a node deletes the connectors attached to it inside the same operation (undo brings both back), and a connector never counts in its group's box. draw_diagram is a pure function of the document (diagramOps): it ranks the shapes by longest path (back edges found by DFS are ignored for ranking), centers each layer and returns plain create ops. Elbow and rounded connectors bend around other shape boxes that share their parent, leaving 8px of clearance; straight and curve routes do not. relayout: true accepts existing shape ids and returns update ops (x/y when given, otherwise the current x) so those connectors are routed again in the same undo step.

  14. Constraints follow a parent resize. A scene node (not a page or a connector) may set constraints: { horizontal: left|right|center|scale, vertical: top|bottom|center|scale }. Omitted means left and top, which is the previous behavior. At the end of a transaction, before fitGroups and syncInstances, a frame whose numeric width or height changed moves or scales each child that is not in the flow (the frame has no row/column layout, or the child is layoutPositioning: "absolute"). left/top keep the box, right/bottom keep the far margin, center keeps the distance to the parent's center, and scale multiplies x/y and a numeric width/height by the parent's size ratio. The math uses the stored box, not the rotated bounds. hug/fill stay as they are (only the position scales). A frame whose own size is fill or hug (on an axis that was not numeric before either) also repositions its pinned non-flow children, by the change of its laid-out size: the pass compares the layout engine's boxes before and after the transaction, so a fill frame in a column gets the full delta of the resized ancestor and one in a row gets its share of the free space. A group's scale constraint scales the boxes of its descendants until a nested frame, whose own children then follow their constraints. An instance's width and height stay with the component, so scale on the instance only moves it. The adjustments are derived, like connector geometry: undo resizes the parent and the pass runs again. The inspector shows the two axes on those children.

  15. /ws sends changes, not the whole document. A connection gets a full {type:"doc", doc, version, actor, label, kind, canUndo, canRedo} snapshot on open, after view (and when the server swaps the active workspace or reloads from the database), and when it falls behind. Every other write is a delta: {type:"delta", id, version, base, actor, label, kind, canUndo, canRedo, name?, rootIds?, nodes?, tokens?, modes?, tokenMeta?, assets?}. id is the workspace, base is the version the delta applies on (always version - 1), and each map patch is {set?: {key: value}, del?: [key]}: nodes.set carries the new value of every changed or created node (a removed id is in nodes.del), rootIds and name appear only when they changed. The server finds the change while it persists the write (writeDocument already compares the previous and the new document row by row), so a delta costs no extra pass over the document. When the change cannot be expressed that way (a map that appears or disappears, an unexpected key order, open, reload, import) the event carries no delta and the server sends a snapshot. The per-connection outbox (wsoutbox.go) never coalesces or drops a delta: they queue in order behind the document slot. A snapshot in the slot supersedes the pending deltas up to its version, and deltas after it apply on top of it. When more than 256 deltas or 2 MiB are pending for a connection, or a delta would leave a gap, they collapse into one fresh snapshot instead of closing the connection. The canvas applies a delta only when base equals its applied version and the workspace matches; otherwise it re-sends view to get a snapshot (apps/web/src/data/live/doc-delta.ts, live-store.ts). Applying a delta copies the nodes map but keeps the identity of every untouched node, and the changed and created ids come from the message, so nothing is serialized to find them. Clients that only understand doc must send view after every delta to keep working; the canvas, the e2e helpers and the perf suite understand both. A tab that sends {type:"hello", pages:true} before view opens one page at a time (ADR 0008, pageview.go): view takes a pageId, the snapshot carries every page node as a stub (with its children), the subtree of each loaded page, the closure of what it references (instanceOf, every id in sourceId, slots, connector ends, recursively, with each master's ancestors) and only the assets those nodes use, plus partial: {loaded}. {type:"page", pageId | nodeId} loads another page (or the page of a node) and is answered by {type:"nodes", id, version, pageId, loaded, nodes, assets?} and an ack with pageId; the tab merges it without changing its version. Deltas to such a connection are filtered against the closure it holds: a node that enters it arrives in nodes.set with its subtree, one that leaves it is in nodes.del, and loaded is sent when a loaded page was deleted. Presence carries pages (the page of each node), so a tab follows an agent onto a page it has not loaded. A client without the capability, MCP, the HTTP API, export and team sync keep working on the whole document.

  16. The app (apps/web) reaches the server only through src/data/. data/api.ts is the HTTP entry (errors as ApiError; a 200 that is not JSON, such as GET /api/team without --team, is an invalid response for api(), while fetchTeamStatus does not go through api() and answers null for a non-JSON 200, a refusal or a network failure, which the editor reads as "no team"), data/live/ is the /ws client with no React (socket.ts connection, backoff of 1 s, 2 s, then 5 s and reqId requests; doc-delta.ts applies a delta copy-on-write; live-store.ts holds the state, batches the frames of a frame into one update and resyncs with view when a base does not match or an ack announces a version that never arrives) and LiveProvider makes one client per app. Containers read it with useLive(selector) and write with useLiveActions().apply(ops, label), a promise settled by the ack or error of its reqId; nothing is applied optimistically. Everything else is layered on top of that: adapters/ are pure functions from server shapes to frontend props, editor/ and overview/ hold the containers (each editor region sits in a RegionProfiler, see src/perf), and src/test/architecture.ts keeps the network (including any /api path written in a string), stores and sockets (also inside an object literal or a function called where it stands) out of every other layer, and keeps adapters free of storage, hooks, impure lib modules and mutable module state (let). The editor's keys that act on the selection (Delete, Backspace, Ctrl+A/G/D, arrows, tool letters, the selection part of Esc) are valid only with the focus on the page, the stage, the layers tree or the stage toolbar (editor/shortcuts.ts, KeyScope); the keys of the app (undo, history, import, export, pins) work anywhere in the editor except inside a dialog, menu or text field. Changes the integration made to the frontends' contracts, all additive: history-step.time and properties-panel ActivityEntry.time accept a ReactNode (a string still works), and the overview sidebar has an inline new-project field.

#Server and core

server/ is the only server; the TypeScript server it was ported from has been removed. server/internal/core is a port of @paprika/core, which the canvas runs and which stays the reference: fixtures generated from the TypeScript core (pnpm go:golden) lock the Go port byte for byte. The MCP contract (tool definitions, instructions) is server/contract/mcp.json, served verbatim; packages/e2e checks the binary from outside (MCP, HTTP, WebSocket, canvas).

HTTP layer. StartHTTP mounts the canvas, /api/*, team routes, /ws and Streamable HTTP /mcp on Gin (gin.New(), release mode, trusted proxies disabled). Panic recovery and the Host/Origin check (AllowedRequest) run as middleware before every route, including 404s. /ws still uses github.com/coder/websocket inside a Gin handler; team.Service.Routes takes a Gin router. The MCP protocol (MCP.Handle, tools, schemas) and stdio (ServeStdio) stay outside Gin.

#Known limitations (v0.1)

#Decision records

Edit this page on GitHub