anomalyco/opencode-rune uses progressive disclosure in its folder layout so contributors and agents can ship features without navigating core internals.
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.
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.jsonis 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-specificui.*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 nocontract.jsonchange 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.
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 |
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 inanomalyco/runealongsiderune,rune-kit, etc., and is consumed via[workspace.dependencies].
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.rsgroups shell-owned and per-server swappedAppclusters into plain structs whose individual fields keep their ownrune::Trackedcells (FixtureRun,DiagState,WorkspacePanes,ShellGestures,TimelineFx,AppearanceState,ComposerExt,QueueState,PlatformServices). Feature-owned state lives in trackedopencode_kernel::StateSlotsregistered in each feature'sFeature::register.apps/desktop/src/plugin_host/is split intoruntime/(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.GetServicehost bindings), andnative/(host-rendered native UI nodes such asdiffView,codeView,fileTree,terminalSurface, andbrowserSurface).
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/).
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 withscripts/dev-fast.sh(orpwsh scripts/dev-fast.ps1); no Rust edits required. - Lane B (
feature): generatesopencode-feature-<id>with#![forbid(unsafe_code)], an explicit state machine (<Pascal>Phase/<Pascal>Event/<Pascal>Effect+step), a trackedStateSlotsstate struct, an object-safe<Pascal>Host: AppEnv + AppFeedback + AppOverlaystrait returning&<Pascal>State/&mut <Pascal>State, and a non-genericpoll(&mut dyn <Pascal>Host, &mut Tx) -> bool; generates the desktop adapterapps/desktop/src/surfaces/<snake>.rsdeclaring astatic <UPPER>: Slot<<Pascal>State> = Slot::new();, implementing<Pascal>Hostviaself.kernel.slots.get(&<UPPER>)/get_mut(&<UPPER>), and registeringbuilder.register_slot(&<UPPER>)inFeature<App>::register; and wires"features/<id>"into rootCargo.toml,opencode-feature-<id>intoapps/desktop/Cargo.toml,pub mod <snake>;intoapps/desktop/src/surfaces/mod.rs,<snake>intoapps/desktop/src/exports.rs, andb.with_feature(&crate::surfaces::<snake>::<Pascal>Feature);intoapps/desktop/src/kernel.rs::build()(never duplicatingfeatures/*deps inapps/web/Cargo.toml). Move the adapter todialogs/,session/,shell/, orworkspace/if it belongs in another domain folder.
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. |
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.streamPhase::Derive:derive.timeline->derive.search->derive.composerPhase::React:react.panels->react.status->react.shellPhase::Persist:persist.flush
Adding a system from a feature:
- 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| ...)inFeature::register. - 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. - 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 (returntrueonly when the parked server requires an immediate window redraw beyond tab-mark changes). - Startup validation:
KernelBuilder::build()panics immediately on duplicate stage names, undeclared stages, duplicate system names, missingaftertargets,afteredges 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 viaoverlay_dispatcher.render_all(s, cx)inapps/desktop/src/shell/view/mod.rs; onlyknobs::layer(s)stays outsideglitch::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. EveryOverlayLayernames itsdefault_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.rsassertskey_band::ALL.len() == 4at compile time so no band can be declared without being dispatched. - Page-Escape bands (
overlays::escape_band::ALL, first-to-last dismissed afterOverlayStack):CHROME->SESSION_ACTION->PAGE_POPOVER->FALLBACK.
Adding an overlay from a feature:
- Pick the visual layer in
crate::overlays::layer(defaultlayer::DIALOGfor modal dialogs) and callbuilder.register_overlay(OverlayRegistration::<App>::new(id).with_render(layer, ...))inFeature::register. - Attach
.with_key(...)to inherit the layer'sdefault_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-pagesettings). Chain.above("dep")/.after_key("dep")only when relative intra-band order matters. - For modal dialogs in
apps/desktoporfeatures/*, attach.with_dismiss(...)and callAppOverlays::{on_overlay_opened, on_overlay_closed}on open/close soOverlayStacktracks Escape dismissal and focus restoration. - Startup validation & zero per-frame sorting:
KernelBuilder::build()resolvesOverlayDispatcheronce via Kahn's algorithm and panics on duplicate layer/band/overlay/Escape IDs, undeclared layers or bands, missing or backwardabove/after_key/afteredges, key/render edges attached without a callback, or cycles.
Adding a shortcut from a feature:
- For a feature command with a default chord, chain
.keybind("mod+...")onCommandEntryinFeature::register. - When a static
Bindis required (native menus, tooltips, terminaltakes_from_pane, browser claim policy, or OS-specific chords), add theBindrow tocrates/opencode-ui/src/keymap/mod.rs, link any palette command via.bind_id(Bind::X.id()), and add one entry toTABLEinapps/desktop/src/shell/input/shortcuts.rsunder itsPhase(WindowAccelerator,BeforePlugins,AfterPlugins, orGlobal). DuplicateBinds fail to compile, andshortcuts::validate(&kernel.commands)panics at start-up if aTarget::Commandrow has no registered command carrying thatbind_id.
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 & 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 & 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 & 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
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 PowerShellscripts/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.
- 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 onfeatures/*orapps/*;features/*never depend onapps/*; full workspace DFS (excludingapps/browser-engine) confirms zero cycles. - Zero cross-feature dependencies and core-crate isolation (Rules 2 & 2b): computed transitively from the resolved graph.
features/*crates never depend on siblingfeatures/*crates (communicate viaopencode-kernelor plugin Contracts). Core crates enforce downward isolation (named temporary exceptions, if any, live inscripts/arch-check-exceptions.txt):opencode-kernel: nosession-view,terminal,browser-pane,office-preview, oropencode-storage.opencode-runtime: headless; nosession-view,terminal,browser-pane,office-preview, oropencode-storage.opencode-ui: pure UI foundation; nosession-view,opencode-storage,terminal,browser-pane,office-preview, oropencode-runtime.opencode-code-view: nosession-view,opencode-storage,terminal,browser-pane,office-preview, oropencode-runtime.opencode-search: strictly headless; nosession-view,opencode-ui,opencode-code-view,opencode-storage,terminal,browser-pane,office-preview,opencode-runtime, or transitiverune/rune-*crates.opencode-plugin-runtime:App-independent; nosession-view,opencode-storage,terminal,browser-pane, oroffice-preview.
- Core crate
#:crates/opencode-kernel,crates/opencode-platform,crates/opencode-plugin-spec,crates/opencode-runtime,crates/opencode-search, andcrates/opencode-uimust declare#![forbid(unsafe_code)]insrc/lib.rs(outside comments). apps/desktop/src/root breadth (Rule 4): at most10tracked top-level.rsfiles inapps/desktop/src/; domains live in subfolders.struct Appeffective field-count ratchet (Rule 5):pub struct Appinapps/desktop/src/app.rsis capped at<= 94effective fields (APP_FIELD_CEILING = 94; ceilings only go down), expanding plain field-cluster wrapper structs inapps/desktop/src/shell/app_state.rs(and any otherapps/desktop/srcstruct holdingTracked<...>fields) so moving fields into wrappers cannot bypass the ceiling. New per-window feature state belongs inopencode_kernel::StateSlotsor a Psychoscript JS plugin.- Unified web library (Rule 6): verified from
cargo metadata—opencode-web(apps/web/Cargo.toml) must have a direct normal dependency onopencode-desktopand must not duplicate anyfeatures/*dependencies. - 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/) underapps/,crates/, orfeatures/(seeAGENTS.md). - Hard
<= 800-line cap (Rule 8): every tracked.rsfile inapps/desktop/,features/, and hand-written workspacecrates/(excludingcrates/opencode-plugin-spec/src/generated/andcrates/browser-pane/) is hard-capped at<= 800lines. - Pure feature crate
#: everyfeatures/*/src/lib.rsmust declare# outside the explicit FFI/GPU allowlist (egg,office,open-in,updater), and allowlist entries are validated against disk. - No
use crate::*;wildcards (Rule 10): zerouse crate::*;(includingpub use crate::*;) imports inapps/desktop/src/(outside comments/strings). - Structural workspace invariants (Rule 11):
features/<id>package names must equalopencode-feature-<id>; every tracked{apps,crates,features}/*/Cargo.tomlexceptapps/browser-engine/Cargo.tomlmust be a workspace member; everyanomalyco/runedependency and patch in rootCargo.tomlmust pin the samerev; and every.jssource inside a built-inplugins/<id>/directory withplugin.tomlmust use CommonJS (require/module.exports), not ESMimport/export.
scripts/file-size.sh: repo-wide line-count monitor and 1,500-line ratchet across every tracked.rsfile underapps/,crates/, andfeatures/— including files excluded fromscripts/arch-check.shRule 8 (apps/web/,apps/installer/,apps/browser-engine/,crates/browser-pane/, andcrates/opencode-plugin-spec/src/generated/). Warns above800lines and errors above1500unless listed inscripts/file-size-exceptions.txt(ceilings only go down; currently empty).scripts/arch-check.shRule 8 enforces the stricter<= 800hard cap (no exceptions) onapps/desktop/,features/, and hand-written workspacecrates/.scripts/folder-shape.sh: checks tracked.rs,.ts,.tsx, and.swiftsources (skipping generated/vendored/test files and Rustexamples/,benches/,bin/). Errors on prefix families (x.rsorx/plus 2+x_*.rssiblings, or 3+x_*.rsalone; move intox/) and flags folder breadth (> 40files warn,> 60error) unless listed inscripts/folder-shape-exceptions.txt(currently empty).scripts/dialog-size.sh: scans every tracked.rsfile underapps/,crates/, andfeatures/containingrole("dialog")orrole("alertdialog")(exceptcrates/opencode-ui/src/dialog.rs) and errors on dialog-scale literals (>= 380) passed to.w/.h/.max_w/.max_horW/H/WIDTH/HEIGHTconsts, and on window-derived dimensions, unless marked// dialog-size: ok. Every dialog must take anopencode_ui::dialog::DialogSizepreset (Normal480 × 368,Large680 × 600,XLarge880 × 680).scripts/tables-check.sh: verifies hand-maintained tables and generated bindings:apps/desktop/src/stories/order.rsmatches every story registered inSTORY_LIST(no duplicates, stale entries, or unordered stories).apps/desktop/src/shell/commands/order.rsassigns a unique order constant to every registered built-inCommandEntry(no raw literals, duplicate values, shared slots, unused constants, or duplicate command IDs).crates/opencode-i18n/locales/rune/*.jsonreports translation coverage againstrune/en.jsonand fails on invalid JSON or keys present in another locale that do not exist inrune/en.json(permitting valid CLDR plural sibling keys).cargo run -q -p opencode-plugin-spec -- --checkconfirms all generated contract files matchcrates/opencode-plugin-spec/contract.json. It is the one step that starts cargo (and a compiler when that crate changed);OPENCODE_GUARDRAILS_NO_CARGO=1skips it and says so, for a machine that must not compile. CI never sets it.
scripts/clippy.sh: runscargo clippy --no-deps --all-targets -- -D warningsover the workspace and over each feature set that compiles code the default build does not (opencode-desktopwith--no-default-features --features knobsand with--features alloc-sites,session-view --features open-bench,browser-panewith--no-default-featuresand with--features faults,win-install --features resources). The lints it enforces are the[workspace.lints]tables in the rootCargo.tomlplusclippy.toml(disallowed-methodspointing feature/UI code atopencode_platformandopencode_kernel::AppEnv). Extra arguments pass through to cargo.cargo check -p session-view --examples: keepssession-view's standalone embedder examples building.pwsh scripts/web.ps1 -Check: runscargo check -p opencode-web --lib --target wasm32-unknown-unknownandbun scripts/web-clock.ts(verifiesstd::time::InstantandSystemTime::nowdo not enter the browser build).
- Non-generic (
dyn) crate boundaries: keepfeatures/*entrypoints concrete or&dyn *Host/&mut dyn *Host(limiting genericH: *Host + 'staticwrappers torune::El/Txcallback edges) soapps/desktopdoes not re-monomorphize leaf feature codegen on every edit (seedocs/fast-builds.md). - Semantic crate scoping: keep
session-viewfree ofopencode-desktop-only window/tab/sidebar assumptions andopencode-kitfree of app-specific concepts. - Explicit state machines & official parity: model modal/phased behaviour with an explicit
enum Stateandstep(&mut State, Event) -> Effects, and match official OpenCode desktop behaviour with source-file citations (seeAGENTS.md). - Rune
devbranch policy: pinanomalyco/runeonly to revs on Rune'sdevbranch and land upstream fixes there first (rev equality acrossCargo.tomlis 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.