Reference
Architecture
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
Flat node map +
childrenon containers (frame,group,page). O(1) access by id for the agent, an explicit tree for rendering.parseDocumentchecks integrity (no orphans, no duplicates, consistentparentId, pages only at the top and, once there is a page, only pages at the top).One write path:
applyOps. The canvas, MCP andPOST /api/opsproduce 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.Reject unknown fields. Zod would drop them silently (
colourinstead ofcolor); for agents, an explicit error is cheaper than a wrong design.One style engine.
nodeStyleproduces 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. Forpathnodes,pathAttrsplays the same role for the<svg>/<path>attributes, andpackages/core/src/path.ts(parser, normalization, exact bezier/arc bounds) runs the same way on the server, in the canvas and in tests; invaliddis rejected with the character position.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.jsongoes in and out only throughpaprika import/export.Stateless MCP over HTTP. No per-connection server state to leak (the
Mcp-Session-Idonly carries the client name); state lives in the store. Write tools only reply after the change is committed.Local first. Loopback bind with Host/Origin validation. No authentication or multi-user support in this version.
Composite operations expand inside the transaction.
group,ungroupandadd_pageare operations too, butapplyOpsturns 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 transactionfitGroupsfits each group to its children (deepest first) and shifts them so nothing moves on screen; the inverse only stores positions, andwidth/heightof a group are rejected as input.Instances are derived copies. A component is a frame with
component: true; it may declarecomponentProps(text,boolean,variant) and contain frames or groups named withslot. An instance is a frame withinstanceOf, an optionalscale,propValues,slotsandoverrides(by component node id or the pathinstance/copy, onlyfill,color,text,src,alt,visible,opacityon copies;fillon the root;propValuesandslotson a nested instance path). A node inside the component canbinda text prop to its text, a boolean tovisible, 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 transactionsyncInstances(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) andsourceIdon 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. Anupdateon 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.detachturns an instance into a plain frame with the same ids, droppingbindfrom the copies.detach_tokenson an instance or a copy only touches the overrides it owns and reports the derived fields it skipped.Import and SVG export are pure functions in the core.
importSVGandimportHTML(packages/core/src/svgImport.ts,htmlImport.ts, over a small tolerant reader inmarkup.ts) returnNodeInputtrees pluswarnings, and the caller writes them with ordinarycreateops, so pasting is one undo step and goes through the same validation.importSVGturns<text>into text nodes and expands<use>/<symbol>sprites; images, gradients, masks and<style>stay warnings.importHTMLis the inverse ofnodeStyle: HTML fromrenderHTML(which tags each element withdata-paprika-type) comes back with the same types and fields. The pure function only reads inline styles.import_htmlwithcomputed: trueis server-side only: the Go handler renders the HTML in Chromium, writes computed author styles inline, then calls the sameimportHTML. A missing Chromium is an error, not a fallback.exportSVGbuilds the SVG from boxes of corelayout(doc)(auto layout,hug/fill); text splits on\n(glyph wrap stays approximate). An optionalMeasurestill overrides boxes and lines for goldens and legacy paths;MEASURE_SCRIPTremains for that.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'sPresenceHub(server/internal/server/presence.go), and/wsbroadcasts it as{type: "presence", agent, actor, tool, nodes, idle}.nodesare the ids the call created or, if none, the ids named in its arguments (that still exist);agentis a hash of the HTTPMcp-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 andhugare 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 (BuildReplayinagents.ts, one walk per actor, at most about 2 s per write, none underprefers-reduced-motion).Workspace = document, one active per server. The overview lists the documents of the server's database. The
Storekeeps one active document;openWorkspaceswaps it in place and emits a change with kindopen, 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, withOnAsideevents 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 separatepaprika mcpover stdio keeps its own.Diagram connectors are derived from their ends. A
shapenode (rect, ellipse, diamond, triangle, cylinder, parallelogram, cloud, note) is a box with text inside, painted byshapeAttrs(an<svg>outline behind the text, the same in canvas, screenshot, React and SVG export). Aconnectorstores only its ends (from/to: anodeIdwith an optional side, or a freex/yin the parent's coordinates), the route (straight,elbow,roundedwithradius, orcurvewith optionalcontrol) and its look;x,y,width,heightanddare recomputed byrouteConnectors(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 onlysqrt(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_diagramis 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 plaincreateops. Elbow and rounded connectors bend around other shape boxes that share their parent, leaving 8px of clearance; straight and curve routes do not.relayout: trueaccepts existing shape ids and returnsupdateops (x/ywhen given, otherwise the currentx) so those connectors are routed again in the same undo step.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, beforefitGroupsandsyncInstances, 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 islayoutPositioning: "absolute").left/topkeep the box,right/bottomkeep the far margin,centerkeeps the distance to the parent's center, andscalemultiplies x/y and a numeric width/height by the parent's size ratio. The math uses the stored box, not the rotated bounds.hug/fillstay as they are (only the position scales). A frame whose own size isfillorhug(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./wssends changes, not the whole document. A connection gets a full{type:"doc", doc, version, actor, label, kind, canUndo, canRedo}snapshot on open, afterview(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?}.idis the workspace,baseis the version the delta applies on (alwaysversion - 1), and each map patch is{set?: {key: value}, del?: [key]}:nodes.setcarries the new value of every changed or created node (a removed id is innodes.del),rootIdsandnameappear only when they changed. The server finds the change while it persists the write (writeDocumentalready 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 whenbaseequals its applied version and the workspace matches; otherwise it re-sendsviewto get a snapshot (apps/web/src/data/live/doc-delta.ts,live-store.ts). Applying a delta copies thenodesmap 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 understanddocmust sendviewafter everydeltato keep working; the canvas, the e2e helpers and the perf suite understand both. A tab that sends{type:"hello", pages:true}beforeviewopens one page at a time (ADR 0008,pageview.go):viewtakes apageId, the snapshot carries every page node as a stub (with itschildren), the subtree of each loaded page, the closure of what it references (instanceOf, every id insourceId,slots, connector ends, recursively, with each master's ancestors) and only the assets those nodes use, pluspartial: {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 withpageId; 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 innodes.setwith its subtree, one that leaves it is innodes.del, andloadedis sent when a loaded page was deleted. Presence carriespages(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.The app (
apps/web) reaches the server only throughsrc/data/.data/api.tsis the HTTP entry (errors asApiError; a 200 that is not JSON, such asGET /api/teamwithout--team, is an invalid response forapi(), whilefetchTeamStatusdoes not go throughapi()and answersnullfor a non-JSON 200, a refusal or a network failure, which the editor reads as "no team"),data/live/is the/wsclient with no React (socket.tsconnection, backoff of 1 s, 2 s, then 5 s andreqIdrequests;doc-delta.tsapplies a delta copy-on-write;live-store.tsholds the state, batches the frames of a frame into one update and resyncs withviewwhen abasedoes not match or an ack announces a version that never arrives) andLiveProvidermakes one client per app. Containers read it withuseLive(selector)and write withuseLiveActions().apply(ops, label), a promise settled by theackorerrorof itsreqId; nothing is applied optimistically. Everything else is layered on top of that:adapters/are pure functions from server shapes to frontend props,editor/andoverview/hold the containers (each editor region sits in aRegionProfiler, seesrc/perf), andsrc/test/architecture.tskeeps the network (including any/apipath 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, impurelibmodules 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.timeandproperties-panelActivityEntry.timeaccept aReactNode(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)
- Two processes on the same database (
serve+mcp) see each other's commits within ~300 ms, but each keeps its own active workspace. To use MCP and the canvas together, preferpaprika serve+ MCP over HTTP. - No boolean operations on paths, point-by-point path editing on the canvas (the pen creates new paths; existing ones are edited through
d), or rotation-aware hit testing. - Groups have no rotation of their own (rotate the children), and children sized
hug/fillcount as a point when the group box is fitted. Nodes inside a row/column frame can't be grouped (their position comes from the flow). layout()followsflex-wrapthe waynodeStyleemits it: items go on a line while they fit (fill counts as 0 wide), lines are as tall as their tallest item and share leftover cross space equally (align-contentstays at its CSS default),justifyandalignapply per line, and onegapis both the column and the row gap. A row that hugs its width never wraps (CSSmax-content); a wrapping frame needs a fixed width, orfillinside a parent that has one, to break lines. Flex shrink and baseline alignment are not modelled.scaledoesn't scale afontSizethat is a token.- The contrast lint ignores gradients and background images.
- Agent presence reaches only canvases of the same process: a
paprika mcp(stdio) whose port was taken runs without a canvas, so its cursor does not show in thepaprika servecanvas. Use MCP over HTTP to be seen. - SVG import skips text, images, gradients/patterns (filled gray), masks, clip paths and
<style>CSS; HTML import only reads inlinestyle=""(no classes or stylesheets). SVG export leaves out CSS gradient strings and background images, emits a structuredgradient(linear and radial as SVG gradients, conic as aforeignObject), draws the shadows of frames, rectangles, ellipses and images as CSS box shadows (spread and inner shadows included, clipped as the browser does), wraps a node withfilterin an SVG filter, paintsbackdropFilteras a filtered copy of what lies behind the node clipped to its box, keeps paths and diagram shapes onfeDropShadowwithout spread or inner shadow (with a warning), and useslayout(doc)(no headless Chromium); text glyph wrap is approximate. - Fonts: a
fontFamilywith no generic family (serif,sans-serif,monospace, ...) gets one appended innodeStyle(sans-serif unless the name looks serif or mono), so a missing face never falls back to the browser's default serif. The Inter that export embeds is also served by the Go server (/fonts/inter.css,/fonts/Inter-*.ttf) and injected into screenshots, soInterlooks the same on the canvas, inrender_screenshotand inexport_image. Other families still depend on the machine. - Dragging on the canvas only moves nodes whose parent has no auto layout (in row/column, order comes from the layout).
- The agent-facing guide and error messages are in Brazilian Portuguese.
#Decision records
- ADR 0001: Go server with SQLite: accepted.
- ADR 0002: Canvas renderer in Rust/WASM (WebGPU with a CPU fallback): accepted as an opt-in hybrid renderer; the DOM stays the default.
- ADR 0003: Tailwind CSS for the canvas app UI: accepted; Tailwind v4, chosen without Preflight so the app CSS never changes how a document renders. Amended by ADR 0009:
apps/webturns Preflight on and protects the document in the canvas world instead. - ADR 0004: Peer-to-peer team sync (Iroh, Loro, Rust sidecar): accepted; protocol in team-sync.md.
- ADR 0005: shadcn components on Paprika's closed theme: superseded by ADR 0009; amended ADR 0003 — copied primitives and
ui-*semantic tokens, still no Preflight; the app it described,web-legacy, was replaced byapps/web, which does not use shadcn. - ADR 0008: Open a workspace one page at a time: accepted, implemented (PAP-A-071); snapshot on open carries the open page and the masters it uses, other pages on demand, additive to the
/wscontract. - ADR 0009: The web app on TanStack Start and the UI SDK: accepted;
apps/webas a TanStack Start SPA served by the Go server, data only throughsrc/data/, per-instance TanStack stores, UI SDK headless on the brand tokens (no shadcn), Tailwind with Preflight, i18next. - ADR 0010: Any shape holds children through a frame outline: accepted, not implemented yet (PAP-A-069); only frames, groups and pages keep
children, and a frame gets ancontour(rect,ellipseorpath) that paints and clips it; one nesting limit of 64 levels. - ADR 0011: Grid layout on frames: accepted (2026-11-30), not implemented yet;
layout.mode: "grid"with column and row tracks (px,fr,hug),gridColumn/gridRowspans on children, one grid engine in each core checked against Chromium. - ADR 0012: Server rendering without Chromium: accepted (2026-11-30, option C) for PAP-A-089; the Rust renderer paints on the server as a native sidecar (
paprika-render), real text measurement in the cores, a 0.99 parity gate before Chrome leaves the image.