Skip to content

AI-native design editor. Open-source Figma alternative.

25.8 KB
Raw Blame

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.ts wraps Core: it creates reactive state, calls createEditor(), and assembles document I/O, autosave, export, vector edit, pen resume, flashes, profiler, and mobile clipboard. Tabs live in src/app/tabs/; active editor access in src/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 example src/app/ai/models/settings/profile-editor/{use,selection,connection}.ts), not a global composables bucket. use.ts orchestrates; 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 receive CredentialManager and may inspect status, replace, or clear; runtime adapters receive CredentialResolver and 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 stable CredentialRef values 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 under src/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 with readStoredBinary(). 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.ts binds Core ToolDefs to the active editor's FigmaAPI. 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 in src/app/ai/reply/ (run, turns, undo, settle, and stream.ts for an agent's chat parts); every OpenPencil tool call, from the chat, MCP, or WebMCP, runs through runEditorTool in src/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/ and pi/ hold each protocol; a chat's agent reaches OpenPencil's MCP server through linkChatAgent in src/app/integrations/mcp/link.ts. ACP process changes require checking desktop/capabilities/**.
  • Provider definitions are in packages/core/src/ai/providers.ts, exported from @open-pencil/core/constants; profiles and how a model is called in src/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 through document.modelContext. App completion under src/app/automation/execution/ loads fonts after commit.
  • Collaboration lives under src/app/collab/** on Yjs and awareness over a CollabRoomTransport: 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 in COLLAB_ACTIONS from @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 /storage provider list) and components through @/components/cloud/integration; a VITE_OPENPENCIL_CLOUD=off build swaps both for their off stand-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-cloud storage provider (server = profile, workspace = container) and their sessions its credential; app code reaches a server through src/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 (electCloudSaver in src/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, or src/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 by bun run build:metrics into dist-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's pages (vite.config.ts) get the one boot splash from vite/boot-splash, after their #app, with its stylesheet and theme script built from src/splash/; never copy splash markup, styles, or theme logic into a page. The theme is the stored setting in src/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 portalDestination alone, and whether an editor page opens the editor or the welcome page in siteDestination (tests/app/cloud-portal/navigation.test.ts, site.test.ts).
  • On a Cloud server's own build (__OPENPENCIL_CLOUD_SITE__), src/main.ts runs the welcome check (enterCloudSite in src/app/cloud-portal/site.ts) after the support check and before boot(), 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 through useCollab() 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's media, and speaking comes from WebRTC's reported audio levels. One window holds one call, owned by useVoiceCall() in src/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 with addAgent in src/app/presence/registry.ts, and presence cursors reach the editor only through showCursors in src/app/presence/cursor-motion.ts, which glides them; never assign presenceCursors directly (tests/app/presence/registry.test.ts).
  • Agent presence in awareness is metadata only. The one content an agent shares is its streamed render JSX, published through publishAgentPreview (src/app/presence/preview-stream.ts) and sent on the room's agent-preview channel by shareAgentPreviews (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.vue puts it on the root as data-interface-scale, and src/app.css makes 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 in use.ts or editor commands, and regenerate desktop/generated/menu.json with bun run generate:tauri-menu.
  • Motion policy lives in src/app/shell/motion/: resolve the persisted System/Off preference and OS reduction once. The root data-motion attribute and the Tailwind motion-safe/motion-reduce variants 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 notify in src/app/shell/notifications/: each event has a preference under notifications, 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; use BrandMark for 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, not QueuedMessage or ToolCallCard (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-instance ui slot overrides, expose class for single-root components, and do not add one-off class props. Use UI casing 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.css keeps only the app's document-level rules.
  • Tailwind 4 and tw-animate-css; no static inline styling or component <style> blocks. Dynamic :style bindings 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-5xs tokens, or a rem arbitrary value, never [Npx]; script geometry such as virtualized rows multiplies rem by remToPx (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 :style instead (src/components/canvas/labels/CanvasLabelEditor.vue).
  • Colors are the --color-* tokens in src/theme/tokens.css, each defined for both themes; statuses use one family each: error and warning have a text color, a -bg tint, and a -border, success a text color; error-fill and success-fill are solid, and warning-action colors 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-time use*UI(), visual-state utility branches, and raw SVG app icons.
  • Tip, not native title; Lucide/Iconify components, not raw SVG or Unicode icons; e.code, not e.key, for modified shortcuts.
  • A theme file default-exports a plain slots object; the component side wraps it with tv once and derives its UI type with ComponentUI (open-pencil/no-tailwind-variants-in-themes, check:arch).
  • A family of parts keeps one theme in src/theme/<family>/index.ts, wraps it in ui.ts as <family> and use<Family>UI, and exports its parts from index.ts; a single component keeps src/theme/<family>/<component>.ts and 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 in src/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 useElementSize and 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 SettingsSection and its title, description, actions, and default content slots. It owns heading association and internal spacing; SettingsGroup owns 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.
  • SettingsSaveFeedback maps domain outcomes (saved, failed, partial) to AppAlert. SettingsLink owns 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 SettingsResetButton shown only while it differs: modified and reset on its SettingsRow, or on its SettingsSection when 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 actions slot; a link to another settings tab is a SettingsRow with an outline xs button; status, warning, and error AppAlerts 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.learnMore at the end of its description; alerts link only to the fix (Node.js, the desktop app), never to docs. Guide URLs live in src/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

  • AppButton and IconButton set their own data-slot, which panel themes target (src/theme/panel/header.ts), so a data-slot passed to them never reaches the DOM; name a button for tests with data-test-id.
  • AppAlert (src/components/ui/feedback/AppAlert.vue, theme src/theme/feedback/alert.ts) for persistent contextual errors, warnings, recovery guidance, and informative results, with translated heading/description and an actions slot. 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 AppDataTable from the table parts (src/components/ui/table/): each column renders its own cell, plain values through accessor and anything richer as a cell component through h(), with widths or container-width hiding in its meta; do not hand-roll <ul> rows with aligned spans or pass cells through slots. Portal lists the server pages go through usePortalList and PortalTable (src/components/cloud-portal/console/PortalPeople.vue).
  • Content that is loading shows AppSkeleton placeholders 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 or icon, 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 emits copied and failed; 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-css for simple state changes and enter/exit; the existing motion-v dependency 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-motion in 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 open from the live state, draw the content through useHeldContent, and reset fields as it opens, never as it closes. Close it through open, never by unmounting it with v-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.ts with ComponentName.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 colocated examples/<Variant>.vue SFCs for substantial templates or fixtures that need SFC template/slot typing, including app-only fixtures (shared SDK examples follow packages/vue/AGENTS.md, Documentation). Story templates compile at runtime, so they must be plain JavaScript with no TypeScript syntax, and icon-lucide-* tags do not resolve there; import icons from ~icons/... and register them.
  • Titles mirror ownership in Title Case: Design System/<Family>/<Component> for src/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.ts runs them all in bun 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.