AI-native design editor. Open-source Figma alternative.
App
Root Tauri/Vite app. Services and state live under src/app/**, views under src/views/**, UI under src/components/** (UI section below). Use @/ for cross-directory imports. Detect desktop with IS_TAURI.
Editor session
src/app/editor/session/create.tswraps Core: it creates reactive state, callscreateEditor(), and assembles document I/O, autosave, export, vector edit, pen resume, flashes, profiler, and mobile clipboard. Tabs live insrc/app/tabs/; active editor access insrc/app/editor/active-store/.- Use editor actions (
clearSelection(),select(),setTool()), never direct state assignments (packages/core/AGENTS.md, Editor). - File System Access APIs are browser APIs, not Tauri-only. Keep the Safari download fallback and defer
revokeObjectURL. - Vectorize provider clients, preferences, and lazy credential resolution live under
src/app/editor/vectorize/; conversion itself is in Core.
Settings, credentials, storage
- Reactive settings workflows live under the owning domain's
settings/folder (for examplesrc/app/ai/models/settings/profile-editor/{use,selection,connection}.ts), not a global composables bucket.use.tsorchestrates; focused siblings hold substantial sub-workflows. Persistence and external operations stay in domain services; pure option projections are ordinary functions. Return operation outcomes rather than importing dialogs, routers, or toasts into workflows. Guard async results against changed targets. - Persistence outcomes (
saved,failed,partial) stay in the domain: preferences and a native credential store cannot transact together. Preserve retryable drafts, reuse already-persisted identities on retries, and surface the partial-save warning. Never render raw credential backend errors or secrets. - New explicit settings forms use headless VeeValidate v5 with native Valibot schemas and existing controlled UI components; form state lives in the owning settings domain. VeeValidate owns validation and submission state; domain workflows keep their own pending/lifecycle guards. Saved secrets and replacement-secret drafts stay outside form snapshots and devtools. A credential-store failure does not make the entered key invalid.
- Credential persistence lives under
src/app/settings/credentials/. Settings components receiveCredentialManagerand may inspect status, replace, or clear; runtime adapters receiveCredentialResolverand resolve secrets at operation time. Components must not read saved secrets or keep them in long-lived reactive refs; keep newly entered secrets short-lived. Non-secret provider preferences stay in normal settings storage. - Tauri stores secrets in the system credential store through
desktop/src/credentials.rs; browsers default to WebCrypto-encrypted IndexedDB and may explicitly opt out to session-only memory. Native failures must never silently fall back to browser or plaintext storage. New integration credentials use stableCredentialRefvalues and join the unified Settings surface rather than feature-local key forms. - Storage-provider schemas and runtime adapters live under
src/app/integrations/storage/; non-secret preferences and credential references stay separate. Local-first document caching and outbox synchronization live undersrc/app/storage/. A remote storage binding augments document source state and must not replace local file identity. - IndexedDB binary rows are written in the form
binaryStorage()returns, taken before the transaction opens, and read withreadStoredBinary(). Chromium caps a single byte array at 127 MiB, and WebKit cannot store Blobs in private contexts (tests/e2e/storage/binary.webkit.spec.ts).
AI, ACP, automation, collaboration
- How a chat reply runs, ends, and reports undone edits to the model, and which file owns each step, is in
packages/docs/development/ai-chat.md; keep it current when that flow changes. src/app/ai/tools/index.tsbinds Core ToolDefs to the active editor'sFigmaAPI. The chat and ACP prompt compose the Core authoring reference rather than copying it (packages/core/AGENTS.md, Tools).- A chat's backends are in
src/app/ai/transports/(the tool loop, ACP, Pi), built on one reply's lifecycle insrc/app/ai/reply/(run, turns, undo, settle, andstream.tsfor an agent's chat parts); every OpenPencil tool call, from the chat, MCP, or WebMCP, runs throughrunEditorToolinsrc/app/ai/tools/runner.ts(tests/app/automation/bridge/agent-replies.test.ts). - Coding agents live in
src/app/ai/agents/:setup/finds and signs them in,acp/andpi/hold each protocol; a chat's agent reaches OpenPencil's MCP server throughlinkChatAgentinsrc/app/integrations/mcp/link.ts. ACP process changes require checkingdesktop/capabilities/**. - Provider definitions are in
packages/core/src/ai/providers.ts, exported from@open-pencil/core/constants; profiles and how a model is called insrc/app/ai/models/**. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. - Browser-native WebMCP registration lives under
src/app/automation/webmcp/, consumes per-tool exposure metadata, and is feature-detected throughdocument.modelContext. App completion undersrc/app/automation/execution/loads fonts after commit. - Collaboration lives under
src/app/collab/**on Yjs and awareness over aCollabRoomTransport: Trystero for peer-to-peer rooms, the Cloud relay (transport/cloud.ts) for Cloud documents. Preserve crypto-safe room IDs and peer cleanup. Room channels are named inCOLLAB_ACTIONSfrom@open-pencil/cloud/contract, because the relay reads the document ones to persist rooms and drop viewer writes (tests/integration/collab/cloud-relay.test.ts). - Outside Cloud's own folders, app code reaches Cloud only through
@/app/cloud/integration(and its/storageprovider list) and components through@/components/cloud/integration; aVITE_OPENPENCIL_CLOUD=offbuild swaps both for theiroffstand-ins, which must keep the same names (tests/app/cloud/integration/off.test.ts), and must bundle no other Cloud module (bun run check:cloud-off). - Cloud servers are profiles of the
openpencil-cloudstorage provider (server = profile, workspace = container) and their sessions its credential; app code reaches a server throughsrc/app/cloud/sessions/connection.ts, never with its own fetch (tests/app/cloud/sessions/connection.test.ts). - An open Cloud document is live in its relay room, and only the elected saver (
electCloudSaverinsrc/app/cloud/rooms/live.ts) uploads its revisions; guests from a link never save (tests/integration/collab/cloud-relay.test.ts). - The Cloud portal is its own entry (
cloud.html,src/cloud/,src/views/cloud/) that the Cloud server serves beside the editor (bun run build:cloud); it must not import editor sessions, CanvasKit, orsrc/app/shell/**, so its pages load without the editor (open-pencil/no-editor-imports-in-cloud-portal,check:arch). - The team's metrics dashboard is its own entry too (
metrics.html,src/metrics/,src/views/metrics/), built bybun run build:metricsintodist-metrics/with base/admin/and served only by the feedback Worker behind Cloudflare Access; it follows the Cloud portal's isolation rule and reads its numbers through@open-pencil/feedback/client(packages/feedback/tests/admin.test.ts). - The app's pages listed in
bootSplashPlugin'spages(vite.config.ts) get the one boot splash fromvite/boot-splash, after their#app, with its stylesheet and theme script built fromsrc/splash/; never copy splash markup, styles, or theme logic into a page. The theme is the stored setting insrc/app/settings/theme.ts, which the editor and the portal both resolve (tests/app/settings/theme.test.ts). - Which portal pages a visitor may open, by sign-in and account standing, is decided in
portalDestinationalone, and whether an editor page opens the editor or the welcome page insiteDestination(tests/app/cloud-portal/navigation.test.ts,site.test.ts). - On a Cloud server's own build (
__OPENPENCIL_CLOUD_SITE__),src/main.tsruns the welcome check (enterCloudSiteinsrc/app/cloud-portal/site.ts) after the support check and beforeboot(), so signed-out visitors never load the editor (tests/app/cloud-portal/site.test.ts). - A room is a document: every room tab owns its session (
src/app/collab/rooms.ts,session.ts), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room throughuseCollab()and publishes cursors through the canvas's own tab (tests/app/collab/session.test.ts,tests/e2e/collab/rooms.spec.ts). - A room's voice call lives in its session (
src/app/collab/voice/room.ts): who is in it and muted travels in awareness, the microphone goes only to peers in the call through the transport'smedia, and speaking comes from WebRTC's reported audio levels. One window holds one call, owned byuseVoiceCall()insrc/app/collab/voice/call.ts, which opens the microphone with VueUse and ends the call when its room goes (tests/app/collab/voice/room.test.ts). - Every agent at work, the built-in chat's and each MCP session's (
src/app/automation/agents.ts), is registered withaddAgentinsrc/app/presence/registry.ts, and presence cursors reach the editor only throughshowCursorsinsrc/app/presence/cursor-motion.ts, which glides them; never assignpresenceCursorsdirectly (tests/app/presence/registry.test.ts). - Agent presence in awareness is metadata only. The one content an agent shares is its streamed
renderJSX, published throughpublishAgentPreview(src/app/presence/preview-stream.ts) and sent on the room'sagent-previewchannel byshareAgentPreviews(src/app/collab/agent-preview.ts), which validates and bounds what peers send and draws it with the chat run's canvas preview; never put prompts or other tool arguments in either (tests/app/collab/agent-preview.test.ts).
Browser baseline
The supported browser baseline lives in src/app/shell/support/baseline.ts and feeds the Vite build.target, the startup gate, and the documented system requirements; change all three together, including desktop/tauri.conf.json minimumSystemVersion. Vite lowers syntax but never polyfills APIs, so two data-driven checks enforce the baseline: the app and browser-shipped packages pin TypeScript lib to ES2023 (the last edition those engines implement fully), so newer built-ins fail type-checking, and compat/compat (eslint-plugin-compat under oxlint, fed the same browsers from settings.browsers) rejects Web APIs they lack. Do not raise the lib to ESNext in those tsconfigs; use createDeferred() from src/app/runtime/deferred.ts instead of Promise.withResolvers(). Node-only packages (cli, mcp, harness) are exempt from both. tests/app/shell/support/baseline.test.ts keeps the tsconfigs and oxlint browsers in step with the baseline. src/main.ts must stay a tiny gate that only dynamically imports src/boot.ts, so an unsupported engine can still render src/app/shell/support/ guidance.
Shell
- Interface size lives in
appearance.interfaceScale;App.vueputs it on the root asdata-interface-scale, andsrc/app.cssmakes it the root font size, which every rem size follows, portals included. The canvas keeps drawing in screen pixels (tests/e2e/settings/interface-scale.webkit.spec.ts). - Browser and native menus share
src/app/shell/menu/schema.ts; handle IDs inuse.tsor editor commands, and regeneratedesktop/generated/menu.jsonwithbun run generate:tauri-menu. - Motion policy lives in
src/app/shell/motion/: resolve the persisted System/Off preference and OS reduction once. The rootdata-motionattribute and the Tailwindmotion-safe/motion-reducevariants represent the effective policy, including portalled content. Use the policy-aware Motion adapters rather than repeating preference conditionals in components. - Canvas shortcuts stop while a dialog, menu, or listbox is open. A dialog that edits the document listens for undo and redo on its own content with
useDocumentShortcuts, so keys in menus it portals never reach it; there is one history, the editor's (src/app/shell/keyboard/document.ts,src/components/variables/VariablesDialog.vue). - System notifications go through
notifyinsrc/app/shell/notifications/: each event has a preference undernotifications, nothing is sent while the person is looking at the tab it concerns, and the click shows that tab. Features describe the event and what to open; they never call the Notification API or the Tauri plugin themselves (tests/e2e/chat/notifications.spec.ts). - Code that can only run inline, such as the code panel's opaque-origin sandbox frame and the
blob:worker it starts, is an ordinary module imported as?script, which bundles it into a string (vite/inline-script.ts); never write it as a source string or serialize functions (src/app/code/sandbox/frame.ts). - Keep the app manifest in
vite/pwa.ts; useBrandMarkfor in-app branding; never symlink web assets to desktop icons (tools/AGENTS.md, Brand assets).
UI
src/components/ui/** is generic, store-free design-system code grouped by family: {binding,button,collapsible,date,dialog,drop,feedback,input,list,menu,overlay,paint,panel,select,table,tabs,toggle}/. Do not create a folder named after a single component. Feature controls stay in their domain. Theme families mirror these under src/theme/; feature themes stay separate. Use explicit imports without old-path forwarding shims.
Naming
- Name a component from the most general word to the most specific, starting with its feature:
ChatMessageQueued,ChatToolCallCard, notQueuedMessageorToolCallCard(src/components/chat/). - A component used only inside one parent starts with that parent's name; existing domains migrate when touched (
src/components/chat/turn/ChatMessageEditor.vue).
Building blocks
- Use Reka UI primitives and typed Tailwind Variants themes under
src/theme/**; merge per-instanceuislot overrides, exposeclassfor single-root components, and do not add one-off class props. UseUIcasing in type names. App wrappers around SDK primitives use shared UI helpers rather than scattered raw classes. - Design tokens, custom variants, and custom utilities live in
src/theme/tokens.css, which the docs site also imports;src/app.csskeeps only the app's document-level rules. - Tailwind 4 and
tw-animate-css; no static inline styling or component<style>blocks. Dynamic:stylebindings are allowed for runtime geometry and CSS variables. - Size the interface in rem so it follows the root font size: Tailwind's scale, the
text-2xs…text-5xstokens, or a rem arbitrary value, never[Npx]; script geometry such as virtualized rows multiplies rem byremToPx(open-pencil/no-px-tailwind-values;src/components/LayerTree/geometry.ts). A field that stands in for something the canvas draws in screen pixels takes the canvas's pixel constants through:styleinstead (src/components/canvas/labels/CanvasLabelEditor.vue). - Colors are the
--color-*tokens insrc/theme/tokens.css, each defined for both themes; statuses use one family each:errorandwarninghave a text color, a-bgtint, and a-border,successa text color;error-fillandsuccess-fillare solid, andwarning-actioncolors buttons on the warning tint. Name the token's utility (text-warning), not[var(--color-warning)]or a default palette color (open-pencil/no-unknown-tailwind-classes). - Bind visual state through semantic
data-*attributes. Steiger rejects template-timeuse*UI(), visual-state utility branches, and raw SVG app icons. Tip, not nativetitle; Lucide/Iconify components, not raw SVG or Unicode icons;e.code, note.key, for modified shortcuts.- A theme file default-exports a plain slots object; the component side wraps it with
tvonce and derives itsUItype withComponentUI(open-pencil/no-tailwind-variants-in-themes,check:arch). - A family of parts keeps one theme in
src/theme/<family>/index.ts, wraps it inui.tsas<family>anduse<Family>UI, and exports its parts fromindex.ts; a single component keepssrc/theme/<family>/<component>.tsand a wrapper of the same name (src/components/ui/table/ui.ts,src/components/ui/feedback/toast.ts). - Compose a family's parts as components whose slots carry content, not data a part could render itself (
src/components/ui/table/). - App dialogs compose the Reka-backed components under
src/components/ui/dialog/and the typed theme insrc/theme/dialog/index.ts. Do not repeat portal, overlay, content, header, or footer infrastructure in feature dialogs. - SDK property primitives, binding fields, commands, and i18n:
packages/vue/AGENTS.md.
Layout
- Lay a component out by the space it is given, not the window: panels, dialogs, and inspectors appear in docks, split views, and phones alike. Restyle with named Tailwind container queries (
@container/name,@2xl/name:) on the element whose width matters, which for a list beside an inspector is the list itself (src/theme/variables/table.ts,src/theme/panel/properties-tabs.ts). - When the width changes structure, such as a side inspector becoming a drill-in, measure the container with VueUse
useElementSizeand keep the threshold beside the theme (TOKENS_PANEL_COMPACT_WIDTH). - Viewport breakpoints (
md:,useViewportKind) are for app-shell decisions only: dock placement, sheets versus popovers, full-screen dialogs (src/theme/dialog/index.ts). - Stories for adaptive components render fixed container widths as separate stories rather than relying on the viewport toolbar (
src/components/variables/TokensPanel.stories.ts).
Settings
- Compose Settings sections with
SettingsSectionand itstitle,description,actions, and default content slots. It owns heading association and internal spacing;SettingsGroupowns bordered row grouping. Do not repeat section, header, or spacing markup per feature. - Settings components own layout, translated copy, confirmation visibility, and emits; small presentation-only computed bindings may stay in components. Workflows, persistence, and credentials:
src/AGENTS.md. SettingsSaveFeedbackmaps domain outcomes (saved,failed,partial) toAppAlert.SettingsLinkowns external-link styling, the icon, and native opening for provider key pages and setup guides; keep arrow glyphs out of translated labels.- A setting with a default offers one Reset to default, the
SettingsResetButtonshown only while it differs:modifiedandreseton itsSettingsRow, or on itsSettingsSectionwhen the section edits one value as a whole (src/components/settings/toolbar/ToolbarSettingsPanel.vue,tests/e2e/settings/reset.spec.ts). Consent and credential choices have no reset, since resetting would grant on the person's behalf. - A section's header-level action (Add, Restart) goes in its
actionsslot; a link to another settings tab is aSettingsRowwith an outlinexsbutton; status, warning, and errorAppAlerts come last inside the section they describe, offering only the fix (src/components/settings/mcp/MCPSettingsPanel.vue). - An integration section links its guide once, as
common.learnMoreat the end of its description; alerts link only to the fix (Node.js, the desktop app), never to docs. Guide URLs live insrc/constants.ts, except the unsupported-browser guidance, which stays self-contained (src/app/shell/support/guidance.ts). - Empty lists use
AppPlaceholder:size="compact" :fill="false"for no results or nothing added yet, an icon, description, and action for a feature that still needs setting up (src/components/assets-panel/AssetsPanel.vue,src/components/chat/ChatProviderSetup.vue).
Feedback and forms
AppButtonandIconButtonset their owndata-slot, which panel themes target (src/theme/panel/header.ts), so adata-slotpassed to them never reaches the DOM; name a button for tests withdata-test-id.AppAlert(src/components/ui/feedback/AppAlert.vue, themesrc/theme/feedback/alert.ts) for persistent contextual errors, warnings, recovery guidance, and informative results, with translatedheading/descriptionand anactionsslot. Do not hand-roll alert markup or colored error paragraphs. Alerts announce changes without taking keyboard focus.- Rows under labelled columns are a TanStack Table drawn by
AppDataTablefrom the table parts (src/components/ui/table/): each column renders its own cell, plain values throughaccessorand anything richer as a cell component throughh(), with widths or container-width hiding in itsmeta; do not hand-roll<ul>rows with aligned spans or pass cells through slots. Portal lists the server pages go throughusePortalListandPortalTable(src/components/cloud-portal/console/PortalPeople.vue). - Content that is loading shows
AppSkeletonplaceholders in its own shape, which fade in after a moment so fast answers replace nothing; a refresh keeps what was shown, and an empty state appears only once a load finished with nothing in it (src/components/ui/table/AppTablePlaceholder.vue,src/components/cloud-portal/layout/PortalPageSkeleton.vue). - The toast service is for transient confirmations without a visible control to carry them, such as a copy from a menu or shortcut, or an action completed after its view closes. Never show a toast and an alert for the same event; partial saves and actionable failures must not disappear in a toast.
- A copy button confirms in place, never with a toast:
AppCopyButton, labelled oricon, turns its copy icon into a check and its label into the copied label. Text built when clicked is passed as a function, and the button emitscopiedandfailed; do not hand-roll the copied state or icon swap (src/components/ui/button/AppCopyButton.vue). - Field validation stays inline in the shared field component with
aria-invalid, error text before hints, and first-invalid-field focus. - Ordinary labels such as Running/Stopped remain status text or badges. Destructive confirmation belongs in the shared confirmation dialog.
Animations
- Tailwind transitions and
tw-animate-cssfor simple state changes and enter/exit; the existingmotion-vdependency for gesture-driven motion, coordinated layout changes, and springs. Do not add another animation library. - Store-free presets live in
src/theme/motion/and compose into owning themes; keep what moves, geometry, and feature-specific spring values local. Share repeated duration and easing values. Policy resolution: Shell above. - Collapsibles use Reka state attributes and measured CSS variables with
animate-collapsible-down/animate-collapsible-up; keep padding and borders inside the animated height wrapper. - Respect
prefers-reduced-motionin CSS and Motion; simplify nonessential motion while preserving state changes and feedback. Verify opening, closing, interrupted transitions, reduced motion, and scroll behavior. Expanding historical chat content must not force the transcript to the bottom. - A dialog keeps drawing what it showed while it animates closed: derive
openfrom the live state, draw the content throughuseHeldContent, and reset fields as it opens, never as it closes. Close it throughopen, never by unmounting it withv-if; popovers, menus, and tooltips close at once (motionStyles.floating) (open-pencil/no-overlay-content-from-open-state,src/components/ui/overlay/held.ts). - An overlay opens on its loaded content: read its data before opening, or keep the last known value, rather than drawing a default that then changes. A neutral loading state is fine; a definite wrong one such as "Needs key" or "0 members" is not (
src/components/cloud/share/CloudShareHost.vue,src/components/libraries/useLibraryManager.ts).
Storybook
- Colocate
ComponentName.stories.tswithComponentName.vue; multipart compositions may use a descriptive family name. Preserve explicit titles and exported story names during moves. Default playgrounds stay static; interaction flows get named stories. Prefer inline story fixtures for small app-local states; use colocatedexamples/<Variant>.vueSFCs for substantial templates or fixtures that need SFC template/slot typing, including app-only fixtures (shared SDK examples followpackages/vue/AGENTS.md, Documentation). Story templates compile at runtime, so they must be plain JavaScript with no TypeScript syntax, andicon-lucide-*tags do not resolve there; import icons from~icons/...and register them. - Titles mirror ownership in Title Case:
Design System/<Family>/<Component>forsrc/components/ui/<family>,App/<Area>/…for app components,Vue SDK/…for SDK primitives. Two files share a title only to keep a heavy example out of the docs page (packages/vue/src/primitives/BindableValue/BindableValueModeEdit.stories.ts); the sidebar order lives in.storybook/preview.ts. - Every story must render, pass its play function, and pass axe in the dark and light themes:
tests/e2e/storybook/stories.spec.tsruns them all inbun run test:storybook, so a play function asserts behavior that stays true, not copy or obsolete markup. Exempt an axe rule only for third-party markup or a deliberate demo state, scoped as narrowly as axe allows and explained where it is set (.storybook/preview.ts,src/components/chat/ChatMarkdown.stories.ts). - Storybook runs with reduced motion, which turns overlay animations off; a spec checking what an overlay draws while it animates opts back in and records each frame with
recordOverlayFrames(tests/e2e/storybook/overlay-states.spec.ts). - Isolated visual states of feedback components belong in stories, not Playwright application screenshots. Do not add automated tests or snapshot baselines for CSS-only changes (spacing, sizing, colors, breakpoints); verify those visually. Settings E2E covers integration behavior: feedback appearance, validation and focus, retained drafts, successful retries.