Skip to content

Latest commit

 

History

History
326 lines (267 loc) · 43.8 KB

ARCHITECTURE.md

File metadata and controls

326 lines (267 loc) · 43.8 KB

Architecture

anomalyco/opencode-rune uses progressive disclosure in its folder layout so contributors and agents can ship features without navigating core internals.

1. Progressive-Disclosure Layout

Start at the top and go deeper only when a feature needs lower-level control. Every workspace member in the root Cargo.toml (plus the excluded apps/browser-engine sidecar) is listed once below.

Tier 1: plugins/

Built-in Psychoscript JS plugins (plugins/<id>/*.js, CommonJS, typed via plugins/opencode.d.ts) targeting opencode-plugin-spec (contract.json), hot-reloaded in place without Rust compiles. apps/desktop/build.rs embeds every plugins/<id>/ directory containing a plugin.toml into the binary as embedded JS source; non-headless debug builds load and watch the repository's plugins/ folders directly. See crates/opencode-plugin-spec/docs/writing-a-plugin.md (including the worked modal-dialog example in plugins/usage/).

  • Contract surface rule (contract.json is additive in 1.x): existing engine-specific native nodes (terminalSurface, terminalTabLabel, browserSurface, codeView, diffView, fileTree, panelSidebar, openInButton, officePages, officeSheet, genUi) stay for compatibility, but new contract additions must be reusable UI primitives or general-purpose services — do not add new engine-specific ui.* nodes or 1-to-1 engine wrapper services to put a thin JS shell around a Rust feature. A new pure-UI dialog, popover, panel, or settings page should need no contract.json change at all; if a feature needs a new Rust engine, keep its UI in Lane B (features/<id>/) rather than paying the triple cost of feature crate, host adapter, and contract entry.

Tier 2: features/

Decoupled Rust feature crates in a flat, parallel layer with zero cross-feature dependencies. Entrypoints use concrete types or object-safe &dyn *Host / &mut dyn *Host boundaries (keeping thin generic H: *Host + 'static wrappers only at rune::El / Tx callback edges).

Path Crate Scope
features/annotations opencode-feature-annotations Timeline/terminal quote toolbar, composer comment cards, floating quote-comment editor, and code/diff line comments
features/composer-input opencode-feature-composer-input Composer attachments, remote upload runner/toast, file dropzone overlay, suggestions state machine, history popover, slash commands, and prompt history
features/connect opencode-feature-connect Provider and integration connect dialog, catalog sync, picker catalog reads, and ChatGPT plan welcome
features/dictation opencode-feature-dictation Hex voice dictation state machine, presence watcher, and composer toolbar controls
features/egg opencode-feature-egg New-session wordmark Easter egg (lodger, 3D pin board, Brick Breaker, synthesized sounds; GPU/FFI unsafe allowlisted)
features/files opencode-feature-files Workspace file tree, file viewer, Markdown/HTML/table/Mermaid/image/video previews, inline-code link resolution, and file watcher
features/find opencode-feature-find Session timeline Find (Cmd/Ctrl+F) state machine, incremental transcript search index, match highlighting, and find bar
features/history opencode-feature-history Session timeline message navigation, Jump to message dialog, Rewind (/undo, /redo), and Fork from message dialog
features/inbox opencode-feature-inbox Session prompt queue strip, drag/edit/rewrite state machines, durable prompt outbox, and delivery receipt checks
features/mcp opencode-feature-mcp MCP server toggle state machine, MCPs dialog, and browser OAuth sign-in dialog
features/mentions opencode-feature-mentions Composer @ mentions popover, search state machine, badges, session chips, and wire encoding
features/narrow opencode-feature-narrow Narrow-window (< 768 px) layout mode, view switcher, tabs/More drawers, and draggable sheets
features/notifications opencode-feature-notifications System notifications, actionable permission/question toasts, coordinator, and activation helpers
features/office opencode-feature-office Word, Excel, and PowerPoint previews: lazy opencode-office-engine sidecar installer/manager, WGPU bitmap compositor, and spreadsheet grid (optional office feature; Windows Job Object unsafe allowlisted)
features/open-in opencode-feature-open-in External editor/terminal detection, launching, preferred app persistence, and URL opening (OS FFI unsafe allowlisted)
features/panels opencode-feature-panels Session side, split, and bottom panel strip, drag/resize/closing state machines, launchers, menus, and persistence
features/projects opencode-feature-projects Project tracking, Home across servers, session JSON import, sidebar organize/customize/recent state, and remote directory picker dialog
features/restore opencode-feature-restore Window state restoration, composer drafts, blob attachments, timeline places, boot previews, offline transcript copies, and draft undo persistence
features/review opencode-feature-review Review changes engine, untracked folder loader, narrow Changes view, focus anchoring, and shared file-panel chrome
features/session-menu opencode-feature-session-menu Session right-click context menus, inline and dialog rename, undoable delete, export, and read/mute/hide preferences
features/settings opencode-feature-settings Settings two-pane shell, preferences persistence, search index, and built-in settings pages
features/subagents opencode-feature-subagents Running-work activity capsule, background shells state machine and output followers, and subagent reply bar
features/switcher opencode-feature-switcher Command/file/session palette switcher, shared session search index, and project/worktree/branch switcher
features/tab-groups opencode-feature-tab-groups Experimental side tab groups: saved tabs.groups state, server/project/manual grouping, 4-intent drag machine (with 220 ms dwell combine), and inline rename
features/terminal-surface opencode-feature-terminal-surface Ghostty-VT terminal pane, workspace tabs, persistence, shell integration, inline rename, find, links, and paste guard
features/timeline-extras opencode-feature-timeline-extras Agent todo pill/list, permission/question reply state machines, live subagent step rows, auto-accept, and timeline capture helpers
features/tips opencode-feature-tips Paced one-time onboarding tip queue state machine and persistence
features/updater opencode-feature-updater Release feed, verification, and platform update engine for macOS, Windows, and Linux (OS FFI unsafe allowlisted)
features/workspace-tools opencode-feature-workspace-tools New-worktree branch picker, per-folder rune client MCP hub, Home session search, and local SQLite full-text message search

Tier 3: crates/

Shell kernel, UI foundation, headless runtime, platform utilities, and embeddable libraries shared with other Rune apps.

Path Crate Scope
crates/authenticode authenticode Windows Authenticode verification (WinVerifyTrust) and signer lookup for the updater and browser engine
crates/browser-extensions browser-extensions Pure-Rust (#![forbid(unsafe_code)]) MV3 extension manager: CRX3 signature verification, bounded safe ZIP unpacker, SHA-256 tree digest, manifest & compatibility classification, permissions review, and explicit install state machine
crates/browser-pane browser-pane Pure-Rust Rune client for the on-demand OpenCode Browser Engine CEF sidecar (behind the engine feature)
crates/browser-policy browser-policy Shared browser URL policy, workspace file:// confinement, address resolution, and CDP allow-list used by both browser-pane and opencode-browser-engine (#![forbid(unsafe_code)])
crates/hex-client hex-client Local HTTP/capture client for driving Hex voice dictation
crates/office-protocol office-protocol Versioned binary-framed stdio protocol and metadata types shared by opencode-feature-office and opencode-office-engine
crates/office-preview office-preview Read-only Word, Excel, and PowerPoint layout and Vello display-list engine over BetterOffice (standalone sidecar dependency of apps/office-engine, excluded from root workspace)
crates/opencode-code-view opencode-code-view Virtualized syntax-highlighted code and diff viewers plus review, delimited table, and label-find data models (built on opencode-ui, zero session-view dependency)
crates/opencode-i18n opencode-i18n Desktop message catalogs and Rune strings with compile-time validated keys (t!, plural!, locale date/number formatting)
crates/opencode-kernel opencode-kernel Shell kernel registries (StateSlots/Slot, OverlayStack/OverlayDispatcher, LifecycleScheduler, CommandRegistry), shared host traits (AppEnv, AppFeedback, AppOverlays), and Feature<S> (#![forbid(unsafe_code)])
crates/opencode-kit opencode-kit Reusable OpenCode HTTP/SSE/WS client, local service.json discovery, general server primitives (servers/{key,probe,fs,link,sync}), and session/transcript model (free of app-specific concepts)
crates/opencode-platform opencode-platform OS and WASM host utilities: wall, telemetry, askpass, web_fetch, host (PlatformPaths/PlatformInfo), and storage (StoragePort, zero opencode-storage dependency) (#![forbid(unsafe_code)])
crates/opencode-plugin-runtime opencode-plugin-runtime App-independent Psychoscript JS plugin runtime primitives (askpass, boot, bytes, catalogs, chunk, console, contracts, contribs, dormant, flyout, hot, i18n, icons, js, machines, native_icons, open_path, power, qr, redraw, reveal, secrets, server_sources, sources, tasks, theme, ui_nodes, watcher)
crates/opencode-plugin-spec opencode-plugin-spec Engine-agnostic plugin contract (contract.json), TypeScript .d.ts/JSON-schema/Rust codegen, and host decoders (#![forbid(unsafe_code)])
crates/opencode-runtime opencode-runtime Headless runtime primitives and explicit state machines (catalog, composer_mode, detail, draft, idle, pairing, server_machine, server_pool, window, types, and machines/{fork,pages,queue,rewind,send_failed,send_reason}) (#![forbid(unsafe_code)])
crates/opencode-search opencode-search Headless full-text, fuzzysort, model search, path index, file ranking, tokenizer, and URL query primitives (#![forbid(unsafe_code)], zero Rune/UI deps)
crates/opencode-servers opencode-servers Headless desktop shell multi-server machines, registry, window tabs schema, and legacy persistence migration (controllers, health, home, home_load, migration, plugin_server, registry, resolution, settings, sidecar, tab_load, tabs) (#![forbid(unsafe_code)], zero UI/storage deps)
crates/opencode-storage opencode-storage Persistence engine: SQLite with write-behind and draft journal on native; localStorage/IndexedDB on wasm32; process-wide StorageOp runner hook
crates/opencode-ui opencode-ui Bottom-layer UI design-system foundation: palette, themes, style, dialog, scroller, odometer, sheet, popover, provider_mark, keymap, widgets, panel_chrome, popup, prompt_history, toast (#![forbid(unsafe_code)], zero session-view dependency)
crates/otlp-lite otlp-lite Lightweight OTLP/HTTP trace exporter for local collectors
crates/project-icon project-icon Procedural CPU-shaded project icons and custom icon loader
crates/rune-drive rune-drive OpenCode Drive's simulation frontend endpoint (OPENCODE_DRIVE) for any rune::Runtime: a headless wall-clock host, the protocol's handshake and ui.* requests over WebSocket, the element tree as ui.state/ui.snapshot, and offscreen pixels as ui.captureImage (the image surface)
crates/rune-parts rune-parts Generative UI (```ui) outline catalog, parser, checker, HTML renderer, and optional Rune view feature (skills/rune-ui/SKILL.md)
crates/session-view session-view Embeddable virtualized session timeline built on opencode-ui (TimelineHost + composable sub-traits in traits.rs, ViewState, examples/read_only.rs; re-exports core opencode-ui modules for embedder compatibility; free of desktop shell assumptions)
crates/tar-zst tar-zst Pure-Rust (#![forbid(unsafe_code)]) streaming .tar.zst unpacker (ustar/PAX/GNU, bounded 8 MiB zstd window, traversal and symlink-chain confinement) shared by the updater and Windows setup
crates/terminal terminal Ghostty-VT (libghostty-vt) terminal core and PTY WebSocket worker
crates/update-delta update-delta Pure-Rust (#![forbid(unsafe_code)]) ocpatch-v1 (bidiff/bipatch + Zstd) bundle delta applier (default) and CI patch generator (--features cli)
crates/ureq-web ureq-web wasm32 ureq-compatible HTTP shim over browser fetch / synchronous XMLHttpRequest
crates/win-install win-install Windows per-user install identity, shortcuts, uninstall/URL-scheme registration, and exe resource embedding

Note: rune-psychoscript (the app-agnostic pure-Rust PsychoScript JS engine for Rune UIs) lives upstream in anomalyco/rune alongside rune, rune-kit, etc., and is consumed via [workspace.dependencies].

Tier 4: apps/

Host shells, installer, and sidecar binary.

Path Crate Scope
apps/desktop opencode-desktop Shared desktop library (opencode_desktop) plus thin native binary (src/main.rs)
apps/web opencode-web Thin wasm32/WebGPU browser entrypoint depending directly on opencode-desktop (src/lib.rs, src/web.rs, src/browser_history.rs) with zero duplicated features/* dependencies
apps/installer opencode-rune-setup Windows per-user setup bootstrapper
apps/desktop-thin opencode-desktop-thin The exe of a packaged Windows build (opencode-desktop.exe in an install): loads the app from the library beside it. Windows Defender checks a new exe before its first process exists at 30-36 ms per MiB, and a library not at all
apps/desktop-library opencode-desktop-library opencode-desktop as a library (opencode-desktop.dll in an install): apps/desktop/src/main.rs with an export in place of main. Empty off Windows
apps/browser-engine opencode-browser-engine Standalone out-of-process CEF sidecar bundle (OpenCode Browser Engine), excluded from the Cargo workspace in root Cargo.toml

Inside apps/desktop/src/:

apps/desktop/src/
├── lib.rs          # Shared library root (`opencode_desktop`), fonts, AppSpec/rune_app, `run_native()`, and wasm32 `web_api`
├── main.rs         # Thin native binary (`#[global_allocator]` + `opencode_desktop::run_native()`)
├── app.rs          # `pub struct App` (ratcheted <= 94 effective fields across `app.rs` and `shell/app_state.rs`), launch/fixture/live loading, shortcuts, `App::rest`
├── tick.rs         # 4-phase per-frame `poll` (Ingest -> Derive -> React -> Persist), `setup`, and `visibility`
├── kernel.rs       # `AppEnv`/`AppFeedback`/`AppOverlays` impls, `Feature` wiring, core slots/overlays/Escape/commands
├── exports.rs      # Internal `crate::*` re-export index across the domain folders
├── shell/          # Window chrome, `app_state.rs` (App field clusters), appearance, commands, diag, input, menus, narrow, nav, panels, tabs, view
├── session/        # Composer, SSE/WS events, inbox/queue, session menu, meta, pages, timeline adapters
├── workspace/      # Lifecycle (launch, restore, storage, jobs, reconnect, rune_mcp, tips, new_worktree), projects, search, servers, system, windows
├── surfaces/       # Thin host adapters for browser, code_view, egg, files, glitch, office, review, terminal, updater
├── dialogs/        # Thin host adapters for connect, mcp, model_picker, model_prefs, settings
├── plugin_host/    # Psychoscript JS plugin host split into `runtime/`, `ui/`, `bridge/`, `services/`, and `native/`
└── stories/        # Storybook playground, scenes, demo playback, and standalone story modules (`stories` Cargo feature)
  • apps/desktop/src/shell/app_state.rs groups shell-owned and per-server swapped App clusters into plain structs whose individual fields keep their own rune::Tracked cells (FixtureRun, DiagState, WorkspacePanes, ShellGestures, TimelineFx, AppearanceState, ComposerExt, QueueState, PlatformServices). Feature-owned state lives in tracked opencode_kernel::StateSlots registered in each feature's Feature::register.
  • apps/desktop/src/plugin_host/ is split into runtime/ (VM boot, app halves, lifecycle, dormancy, hot reload, trust, memory, sources, CLI types), ui/ (surfaces, host nodes, editors, panels, widgets, settings views), bridge/ (commands, requests, contributions, context/deps, server sources, servers, stores, console), services/ (ctx.GetService host bindings), and native/ (host-rendered native UI nodes such as diffView, codeView, fileTree, terminalSurface, and browserSurface).

2. The Three-Lane Feature Rule

Pick the first lane that fits. Do not add fields to struct App or edit central dispatch chains when a feature can register through opencode-kernel or run as a Psychoscript JS plugin.

Lane Location When to use Compile cost
Lane A (Default) plugins/<id>/ Dialogs, panels, settings pages, composer pills, popovers, commands, slash actions, MCP tools, server sources 0 ms Rust (JS hot reload)
Lane B features/<id>/ GPU shaders, frame recorders, heavy local indexing, OS-specific engines, or sub-ms hot paths Leaf crate only
Lane C crates/<id>/ Reusable libraries or embeddable surfaces shared with other Rune apps Leaf crate only

Do not bridge a new Lane B Rust engine through a thin Lane A JS shell: keep engine-backed UI in Lane B and reserve contract.json additions for reusable primitives and general services (see Tier 1: plugins/).

Scaffolding a new feature

Use scripts/new-feature.sh (macOS/Linux) or pwsh scripts/new-feature.ps1 (Windows). <id> must be lowercase kebab-case (^[a-z][a-z0-9-]*$, max 64 chars, no trailing or repeated hyphens):

scripts/new-feature.sh plugin <id> [Title]    # Lane A (default): creates plugins/<id>/{plugin.toml,init.js,locales/en.json}
scripts/new-feature.sh feature <id> [Title]   # Lane B: creates features/<id>/{Cargo.toml,src/lib.rs}, apps/desktop/src/surfaces/<snake>.rs, and wires Cargo/desktop/kernel
  • Lane A (plugin): ready to run immediately with scripts/dev-fast.sh (or pwsh scripts/dev-fast.ps1); no Rust edits required.
  • Lane B (feature): generates opencode-feature-<id> with #![forbid(unsafe_code)], an explicit state machine (<Pascal>Phase / <Pascal>Event / <Pascal>Effect + step), a tracked StateSlots state struct, an object-safe <Pascal>Host: AppEnv + AppFeedback + AppOverlays trait returning &<Pascal>State / &mut <Pascal>State, and a non-generic poll(&mut dyn <Pascal>Host, &mut Tx) -> bool; generates the desktop adapter apps/desktop/src/surfaces/<snake>.rs declaring a static <UPPER>: Slot<<Pascal>State> = Slot::new();, implementing <Pascal>Host via self.kernel.slots.get(&<UPPER>) / get_mut(&<UPPER>), and registering builder.register_slot(&<UPPER>) in Feature<App>::register; and wires "features/<id>" into root Cargo.toml, opencode-feature-<id> into apps/desktop/Cargo.toml, pub mod <snake>; into apps/desktop/src/surfaces/mod.rs, <snake> into apps/desktop/src/exports.rs, and b.with_feature(&crate::surfaces::<snake>::<Pascal>Feature); into apps/desktop/src/kernel.rs::build() (never duplicating features/* deps in apps/web/Cargo.toml). Move the adapter to dialogs/, session/, shell/, or workspace/ if it belongs in another domain folder.

3. Where New Code Goes ("Which file do I touch?")

Existing Rust features put domain logic and UI in features/<id>/ and a thin host adapter implementing <Name>Host and Feature<App> in apps/desktop/src/{dialogs,surfaces,session,shell,workspace}/ (for example features/mcp/ + apps/desktop/src/dialogs/mcp.rs), registered once in apps/desktop/src/kernel.rs::build().

Adding… Lane A (Psychoscript JS) Lane B (Rust feature) How the shell dispatches it
Modal dialog / overlay ctx.AddDialog or ctx.AddPopover in plugins/<id>/init.js (e.g. plugins/usage/) Build state + view in features/<id>/ using opencode_ui::dialog::DialogSize (opencode_ui::widgets::{sized, sized_modal}) and calling AppOverlays::{on_overlay_opened, on_overlay_closed} for modal dialogs. In Feature::register (e.g. apps/desktop/src/dialogs/mcp.rs, apps/desktop/src/dialogs/connect.rs), call builder.register_overlay(OverlayRegistration::new(id).with_render(crate::overlays::layer::DIALOG, ...).with_key(...).with_dismiss(...)) (or OverlayRegistration::dialog(id, crate::overlays::layer::DIALOG, ...)). Chain .above("other") / .after_key("other") only where intra-layer order matters, or .with_key_in(band, ...) when key precedence intentionally differs from the layer's default key band. KernelBuilder::build() validates every layer/band/edge and pre-sorts all dispatch lists once. apps/desktop/src/shell/view/mod.rs renders all overlays inside the zoomed shell via overlay_dispatcher.render_all(s, cx) (knobs::layer stays outside glitch::wrap(zoomed(inner))); shell/input/keys.rs routes keys via handle_key_band(key_band::...); shell/input/escape.rs pops OverlayStack and invokes .with_dismiss(...). No edits to view/mod.rs, keys.rs, or escape.rs.
Dismissible page Escape layer (inline bar, panel, toolbar) Handled by plugin popover/dialog APIs Call builder.register_escape_layer(EscapeLayer::<App>::new(id, crate::overlays::escape_band::<BAND>, is_open, on_escape)) in Feature::register (chain .after("dep") within a band when order matters; e.g. apps/desktop/src/session/timeline/find.rs, apps/desktop/src/session/timeline/todos.rs, or apps/desktop/src/kernel.rs for core shell layers). apps/desktop/src/shell/input/escape.rs steps the topmost OverlayStack entry first, then runs overlay_dispatcher.handle_escape(...) across pre-sorted Escape bands (CHROME -> SESSION_ACTION -> PAGE_POPOVER -> FALLBACK).
Command (palette and/or /slash) ctx.AddCommand in plugins/<id>/init.js (supports order for palette placement, e.g. plugins/usage/) Add a palette slot constant in apps/desktop/src/shell/commands/order.rs, then call builder.add_command(CommandEntry::from_key(id, key, crate::commands::order::..., run)...) in Feature::register (chain .describe, .slash, .when, .section, .hidden, .titled, .keybind, or .bind_id; e.g. apps/desktop/src/dialogs/mcp.rs, apps/desktop/src/session/timeline/message_nav.rs). Core shell and window commands live in register_shell_commands in apps/desktop/src/shell/commands/mod.rs. Gate native-only commands with #[cfg(not(target_arch = "wasm32"))]. apps/desktop/src/shell/commands/mod.rs reads the single kernel.commands registry and plugin commands, merging them by order into App::commands(), App::palette_commands(), and App::catalog().
Keyboard shortcut Pass bind: "mod+..." on ctx.AddCommand in plugins/<id>/init.js Feature command with default chord: chain .keybind("mod+...") on CommandEntry in Feature::register (un-overridden defaults are dispatched by shell/commands/mod.rs::key, Settings › Shortcuts overrides are dispatched once by settings::pages::shortcuts::run_bound, and all entries appear in App::catalog()). Static keymap entry (needed for native menus, tooltips, terminal takes_from_pane, browser claim policy, or per-OS chords): add a Bind variant and row in crates/opencode-ui/src/keymap/mod.rs, link the command with .bind_id(Bind::X.id()), and add one row to TABLE in apps/desktop/src/shell/input/shortcuts.rs with its Phase (WindowAccelerator, BeforePlugins, AfterPlugins, or Global) and claims_from_browser policy. Overlay-local keys: attach .with_key(...) (or .with_key_in(band, ...)) on OverlayRegistration. apps/desktop/src/shell/input/keys.rs runs overlay key bands (POPUP, MODAL, MID, LOW, interleaved with glitch/demo and dictation/knobs), panels/question/add_menu/draft_location, shortcuts::run_window_accelerators, App::shortcut_without_dictation (run_bound overrides -> background -> find -> commands::key (BeforePlugins + un-overridden .keybind(...) defaults) -> plugin_host::key -> PastePlain -> history::bracket -> shortcuts::run (AfterPlugins)), picker_key, shortcuts::run_global (Global), and escape::key. Focused inputs call App::shortcut (which includes dictation::key), and composer / Home search also check keys::global ahead of field editing.
Per-frame poll or lifecycle hook Signals / timers inside plugin half Call builder.schedule(crate::tick::stage::<STAGE>, name, f) in Feature::register (chain .after("dep") / .after_all(&[...]) for explicit ordering within a stage, and .per_server(bg_f) when the system must also tick on parked server halves; e.g. apps/desktop/src/session/timeline/find.rs, apps/desktop/src/surfaces/egg.rs), or add_setup, add_rest, add_visibility, add_close. Core shell systems live in apps/desktop/src/kernel.rs. KernelBuilder::build() validates stages, unique system names, after targets, and acyclicity, resolving every (Phase, Stage) via Kahn's algorithm (lexicographical system-name tie-break, registration-order independent). apps/desktop/src/tick.rs runs Phase::Ingest -> Derive -> React -> Persist each frame, plus run_setup and run_visibility; servers::runtime::background runs run_per_server; app.rs::rest runs run_rest; lib.rs on_close runs run_close.
Per-window state Local state in init.js + ctx.BindHotState / Store Declare a static typed handle static MY_STATE: opencode_kernel::Slot<MyState> = Slot::new(); in the feature's desktop adapter, register it in Feature::register via builder.register_slot(&MY_STATE) (or register_slot_with), and read/write with s.kernel.slots.get(&MY_STATE) / get_mut(&MY_STATE) (plus untracked, touch, version, cell_id, get_two_mut when needed; e.g. apps/desktop/src/dialogs/mcp.rs, apps/desktop/src/surfaces/files/mod.rs, apps/desktop/src/workspace/servers/dialog.rs). Do not add feature fields to struct App. Every slot wraps its value in rune::Tracked<T> inside App::kernel.slots, indexed in O(1) via Slot<T>'s dense index (zero hashing; works in plain fn(&mut App) -> &mut T lenses); reads inside rune::region / rune::tracked_reads subscribe and writes invalidate identically to a Tracked<T> field on App.

Per-frame tick scheduling (opencode-kernel::LifecycleScheduler)

The desktop app declares named [Stage] barriers in apps/desktop/src/tick.rs::stage and registers them via b.add_stages(crate::tick::stage::ALL) in apps/desktop/src/kernel.rs::build():

  • Phase::Ingest: ingest.hydrate -> ingest.servers -> ingest.local -> ingest.dispatch -> ingest.session_pre -> ingest.pages -> ingest.stream
  • Phase::Derive: derive.timeline -> derive.search -> derive.composer
  • Phase::React: react.panels -> react.status -> react.shell
  • Phase::Persist: persist.flush

Adding a system from a feature:

  1. Pick the stage matching when the system's inputs are ready and when downstream consumers need its writes; call builder.schedule(crate::tick::stage::<STAGE>, "<feature>.<name>", |s, now, tx| ...) in Feature::register.
  2. Add .after("<other>") (or .after_all(&[...])) whenever two systems in the same stage read or write shared state; document whether the edge is a known data dependency or a shared-state precaution.
  3. If the system also needs to run on parked (non-active) server halves during servers::runtime::poll, chain .per_server(|s, now, tx| ...) so the parked-server sub-schedule is derived automatically in the global resolved order (return true only when the parked server requires an immediate window redraw beyond tab-mark changes).
  4. Startup validation: KernelBuilder::build() panics immediately on duplicate stage names, undeclared stages, duplicate system names, missing after targets, after edges pointing to a later phase/stage, or cycles. Independent systems within a stage tie-break lexicographically by system name, so feature registration order never affects execution order.

Overlays & keyboard shortcuts (opencode-kernel::OverlayDispatcher, shell/overlays.rs, shell/input/shortcuts.rs)

The desktop app declares all overlay stacking layers, key-dispatch bands, and page-Escape bands in one module, apps/desktop/src/shell/overlays.rs, registered once in apps/desktop/src/kernel.rs::build():

  • Visual layers (overlays::layer::ALL, bottom-to-top): SURFACE_POPOVER -> SWITCHER -> MEDIA_LIGHTBOX -> ACTION_DIALOG -> FLOATING_CHROME -> DIALOG -> ELEVATED_DIALOG -> CHROME_POPUP -> PLUGIN_TOP -> TOAST. Every overlay inside the zoomed shell renders via overlay_dispatcher.render_all(s, cx) in apps/desktop/src/shell/view/mod.rs; only knobs::layer(s) stays outside glitch::wrap(zoomed(inner)) so it draws above the glitch scrubber.
  • Key-dispatch bands (overlays::key_band::ALL, first-to-last): POPUP -> MODAL -> (glitch, demo) -> MID -> (dictation, knobs) -> LOW. Every OverlayLayer names its default_key_band (TOAST/CHROME_POPUP -> POPUP; PLUGIN_TOP/ELEVATED_DIALOG/DIALOG -> MODAL; FLOATING_CHROME/ACTION_DIALOG/MEDIA_LIGHTBOX -> MID; SWITCHER/SURFACE_POPOVER -> LOW), and within each band higher visual layers handle keys first automatically unless overridden with .after_key(...). apps/desktop/src/shell/input/keys.rs asserts key_band::ALL.len() == 4 at compile time so no band can be declared without being dispatched.
  • Page-Escape bands (overlays::escape_band::ALL, first-to-last dismissed after OverlayStack): CHROME -> SESSION_ACTION -> PAGE_POPOVER -> FALLBACK.

Adding an overlay from a feature:

  1. Pick the visual layer in crate::overlays::layer (default layer::DIALOG for modal dialogs) and call builder.register_overlay(OverlayRegistration::<App>::new(id).with_render(layer, ...)) in Feature::register.
  2. Attach .with_key(...) to inherit the layer's default_key_band, or .with_key_in(band, ...) (with a comment explaining why) when key priority intentionally differs from visual stacking or the overlay has no render layer (like full-page settings). Chain .above("dep") / .after_key("dep") only when relative intra-band order matters.
  3. For modal dialogs in apps/desktop or features/*, attach .with_dismiss(...) and call AppOverlays::{on_overlay_opened, on_overlay_closed} on open/close so OverlayStack tracks Escape dismissal and focus restoration.
  4. Startup validation & zero per-frame sorting: KernelBuilder::build() resolves OverlayDispatcher once via Kahn's algorithm and panics on duplicate layer/band/overlay/Escape IDs, undeclared layers or bands, missing or backward above/after_key/after edges, key/render edges attached without a callback, or cycles.

Adding a shortcut from a feature:

  1. For a feature command with a default chord, chain .keybind("mod+...") on CommandEntry in Feature::register.
  2. When a static Bind is required (native menus, tooltips, terminal takes_from_pane, browser claim policy, or OS-specific chords), add the Bind row to crates/opencode-ui/src/keymap/mod.rs, link any palette command via .bind_id(Bind::X.id()), and add one entry to TABLE in apps/desktop/src/shell/input/shortcuts.rs under its Phase (WindowAccelerator, BeforePlugins, AfterPlugins, or Global). Duplicate Binds fail to compile, and shortcuts::validate(&kernel.commands) panics at start-up if a Target::Command row has no registered command carrying that bind_id.

4. Dependency Layers & Guardrails

Dependencies flow strictly downward so the workspace stays wide and shallow for parallel Rust compilation:

flowchart TB
  subgraph T4["Tier 4: apps/"]
    WEB["apps/web<br/>(opencode-web, wasm32)"]
    DESKTOP["apps/desktop<br/>(opencode-desktop lib + bin)"]
    INSTALLER["apps/installer<br/>(opencode-rune-setup)"]
  end

  subgraph T2["Tier 2: features/ (no cross-feature deps)"]
    FEATS["features/*<br/>(decoupled feature crates)"]
  end

  subgraph T3["Tier 3: crates/"]
    subgraph T3_TOP["Embeddable views &amp; surfaces"]
      SV["session-view"]
      CV["opencode-code-view"]
      PR["opencode-plugin-runtime"]
      SURF["terminal · browser-pane · office-preview"]
    end
    subgraph T3_MID["Kernel, UI foundation &amp; runtime"]
      KERNEL["opencode-kernel"]
      UI["opencode-ui"]
      RT["opencode-runtime"]
      SRVS["opencode-servers"]
      PLAT["opencode-platform"]
      STOR["opencode-storage"]
    end
    subgraph T3_BASE["Protocol, search, spec &amp; leaf crates"]
      KIT["opencode-kit"]
      SEARCH["opencode-search"]
      I18N["opencode-i18n"]
      SPEC["opencode-plugin-spec"]
      PARTS["rune-parts"]
      DELTA["update-delta"]
      WIN["win-install"]
    end
  end

  WEB --> DESKTOP
  WEB --> UI
  DESKTOP --> FEATS
  DESKTOP --> T3_TOP
  DESKTOP --> T3_MID
  INSTALLER --> WIN

  FEATS --> KERNEL
  FEATS --> UI
  FEATS --> RT
  FEATS --> SRVS
  FEATS --> PLAT
  FEATS --> SV
  FEATS --> CV

  SV --> UI
  SV --> RT
  SV --> PARTS
  SV --> KIT
  SV --> SEARCH
  CV --> UI
  CV --> SEARCH
  CV --> KIT
  PR --> PLAT
  PR --> SPEC
  STOR --> KIT
  STOR --> SEARCH
  STOR --> SRVS
  SRVS --> KIT
  UI --> KIT
  UI --> I18N
  RT --> KIT
  RT --> I18N
  KERNEL --> I18N
Loading

Running guardrails

Run the single cheap guardrail entry point before pushing (works on macOS, Linux, and Windows via Bun or Node.js 18+; no Python required; fails loudly if no working JS runtime is on PATH):

scripts/guardrails.sh         # macOS / Linux / Git Bash
pwsh scripts/guardrails.ps1   # Windows PowerShell

scripts/guardrails.sh runs scripts/arch-check.sh, scripts/file-size.sh, scripts/folder-shape.sh, scripts/dialog-size.sh, and scripts/tables-check.sh, exiting non-zero on any failure. Slow compile/lint checks (scripts/clippy.sh, cargo check -p session-view --examples, and pwsh scripts/web.ps1 -Check) stay separate so the pre-push check finishes in a few seconds.

Rules enforced by scripts/arch-check.sh

  1. Strict downward layers and zero cycles (Rules 1 & 1b): computed transitively from the resolved dependency graph (cargo metadata --format-version 1 --all-features, normal and build dependencies; comments ignored, workspace-inherited dependencies resolved, [dev-dependencies] excluded). crates/* never depend on features/* or apps/*; features/* never depend on apps/*; full workspace DFS (excluding apps/browser-engine) confirms zero cycles.
  2. Zero cross-feature dependencies and core-crate isolation (Rules 2 & 2b): computed transitively from the resolved graph. features/* crates never depend on sibling features/* crates (communicate via opencode-kernel or plugin Contracts). Core crates enforce downward isolation (named temporary exceptions, if any, live in scripts/arch-check-exceptions.txt):
    • opencode-kernel: no session-view, terminal, browser-pane, office-preview, or opencode-storage.
    • opencode-runtime: headless; no session-view, terminal, browser-pane, office-preview, or opencode-storage.
    • opencode-ui: pure UI foundation; no session-view, opencode-storage, terminal, browser-pane, office-preview, or opencode-runtime.
    • opencode-code-view: no session-view, opencode-storage, terminal, browser-pane, office-preview, or opencode-runtime.
    • opencode-search: strictly headless; no session-view, opencode-ui, opencode-code-view, opencode-storage, terminal, browser-pane, office-preview, opencode-runtime, or transitive rune / rune-* crates.
    • opencode-plugin-runtime: App-independent; no session-view, opencode-storage, terminal, browser-pane, or office-preview.
  3. Core crate #![forbid(unsafe_code)] (Rule 3): crates/opencode-kernel, crates/opencode-platform, crates/opencode-plugin-spec, crates/opencode-runtime, crates/opencode-search, and crates/opencode-ui must declare #![forbid(unsafe_code)] in src/lib.rs (outside comments).
  4. apps/desktop/src/ root breadth (Rule 4): at most 10 tracked top-level .rs files in apps/desktop/src/; domains live in subfolders.
  5. struct App effective field-count ratchet (Rule 5): pub struct App in apps/desktop/src/app.rs is capped at <= 94 effective fields (APP_FIELD_CEILING = 94; ceilings only go down), expanding plain field-cluster wrapper structs in apps/desktop/src/shell/app_state.rs (and any other apps/desktop/src struct holding Tracked<...> fields) so moving fields into wrappers cannot bypass the ceiling. New per-window feature state belongs in opencode_kernel::StateSlots or a Psychoscript JS plugin.
  6. Unified web library (Rule 6): verified from cargo metadata — opencode-web (apps/web/Cargo.toml) must have a direct normal dependency on opencode-desktop and must not duplicate any features/* dependencies.
  7. Zero automated tests (Rule 7): no #[test] or #[cfg(...test...)] (outside comments/strings) and no tracked test file paths (tests.rs, *_tests.rs, *_test.rs, tests/) under apps/, crates/, or features/ (see AGENTS.md).
  8. Hard <= 800-line cap (Rule 8): every tracked .rs file in apps/desktop/, features/, and hand-written workspace crates/ (excluding crates/opencode-plugin-spec/src/generated/ and crates/browser-pane/) is hard-capped at <= 800 lines.
  9. Pure feature crate #![forbid(unsafe_code)] (Rule 9): every features/*/src/lib.rs must declare #![forbid(unsafe_code)] (outside comments) outside the explicit FFI/GPU allowlist (egg, office, open-in, updater), and allowlist entries are validated against disk.
  10. No use crate::*; wildcards (Rule 10): zero use crate::*; (including pub use crate::*;) imports in apps/desktop/src/ (outside comments/strings).
  11. Structural workspace invariants (Rule 11): features/<id> package names must equal opencode-feature-<id>; every tracked {apps,crates,features}/*/Cargo.toml except apps/browser-engine/Cargo.toml must be a workspace member; every anomalyco/rune dependency and patch in root Cargo.toml must pin the same rev; and every .js source inside a built-in plugins/<id>/ directory with plugin.toml must use CommonJS (require / module.exports), not ESM import/export.

Other cheap guardrail scripts (included in scripts/guardrails.sh)

  • scripts/file-size.sh: repo-wide line-count monitor and 1,500-line ratchet across every tracked .rs file under apps/, crates/, and features/ — including files excluded from scripts/arch-check.sh Rule 8 (apps/web/, apps/installer/, apps/browser-engine/, crates/browser-pane/, and crates/opencode-plugin-spec/src/generated/). Warns above 800 lines and errors above 1500 unless listed in scripts/file-size-exceptions.txt (ceilings only go down; currently empty). scripts/arch-check.sh Rule 8 enforces the stricter <= 800 hard cap (no exceptions) on apps/desktop/, features/, and hand-written workspace crates/.
  • scripts/folder-shape.sh: checks tracked .rs, .ts, .tsx, and .swift sources (skipping generated/vendored/test files and Rust examples/, benches/, bin/). Errors on prefix families (x.rs or x/ plus 2+ x_*.rs siblings, or 3+ x_*.rs alone; move into x/) and flags folder breadth (> 40 files warn, > 60 error) unless listed in scripts/folder-shape-exceptions.txt (currently empty).
  • scripts/dialog-size.sh: scans every tracked .rs file under apps/, crates/, and features/ containing role("dialog") or role("alertdialog") (except crates/opencode-ui/src/dialog.rs) and errors on dialog-scale literals (>= 380) passed to .w/.h/.max_w/.max_h or W/H/WIDTH/HEIGHT consts, and on window-derived dimensions, unless marked // dialog-size: ok. Every dialog must take an opencode_ui::dialog::DialogSize preset (Normal 480 × 368, Large 680 × 600, XLarge 880 × 680).
  • scripts/tables-check.sh: verifies hand-maintained tables and generated bindings:
    • apps/desktop/src/stories/order.rs matches every story registered in STORY_LIST (no duplicates, stale entries, or unordered stories).
    • apps/desktop/src/shell/commands/order.rs assigns a unique order constant to every registered built-in CommandEntry (no raw literals, duplicate values, shared slots, unused constants, or duplicate command IDs).
    • crates/opencode-i18n/locales/rune/*.json reports translation coverage against rune/en.json and fails on invalid JSON or keys present in another locale that do not exist in rune/en.json (permitting valid CLDR plural sibling keys).
    • cargo run -q -p opencode-plugin-spec -- --check confirms all generated contract files match crates/opencode-plugin-spec/contract.json. It is the one step that starts cargo (and a compiler when that crate changed); OPENCODE_GUARDRAILS_NO_CARGO=1 skips it and says so, for a machine that must not compile. CI never sets it.

Slow / compile checks (run separately)

  • scripts/clippy.sh: runs cargo clippy --no-deps --all-targets -- -D warnings over the workspace and over each feature set that compiles code the default build does not (opencode-desktop with --no-default-features --features knobs and with --features alloc-sites, session-view --features open-bench, browser-pane with --no-default-features and with --features faults, win-install --features resources). The lints it enforces are the [workspace.lints] tables in the root Cargo.toml plus clippy.toml (disallowed-methods pointing feature/UI code at opencode_platform and opencode_kernel::AppEnv). Extra arguments pass through to cargo.
  • cargo check -p session-view --examples: keeps session-view's standalone embedder examples building.
  • pwsh scripts/web.ps1 -Check: runs cargo check -p opencode-web --lib --target wasm32-unknown-unknown and bun scripts/web-clock.ts (verifies std::time::Instant and SystemTime::now do not enter the browser build).

Architectural conventions (enforced by review, not scripts)

  • Non-generic (dyn) crate boundaries: keep features/* entrypoints concrete or &dyn *Host / &mut dyn *Host (limiting generic H: *Host + 'static wrappers to rune::El / Tx callback edges) so apps/desktop does not re-monomorphize leaf feature codegen on every edit (see docs/fast-builds.md).
  • Semantic crate scoping: keep session-view free of opencode-desktop-only window/tab/sidebar assumptions and opencode-kit free of app-specific concepts.
  • Explicit state machines & official parity: model modal/phased behaviour with an explicit enum State and step(&mut State, Event) -> Effects, and match official OpenCode desktop behaviour with source-file citations (see AGENTS.md).
  • Rune dev branch policy: pin anomalyco/rune only to revs on Rune's dev branch and land upstream fixes there first (rev equality across Cargo.toml is enforced by Rule 11).
  • Non-Rust test artefacts & sensitive data: keep mocks, fuzzers, golden/snapshot files, motion audits, test benchmarks, CI test steps, personal paths, tailnet hostnames, real session IDs, and credentials out of the repository.