Files
chandra/docs/ARCHITECTURE.md
T
Claude f2e870c251
CI / test (push) Failing after 16s
Task manager: draw each app's real icon from its .desktop file
Each pill now shows the icon the app's .desktop file names (Icon=), looked up in the
freedesktop icon themes, instead of the letter tile. The tile stays as the fallback for
windows with no app id, no desktop file or no icon the host can read.

- WIT: a new `icons` capability (`app-icon(app-id) -> u32`, a handle, never a path or pixels)
  and an `image(image-op)` draw op (appended, so existing modules keep their ABI).
  taskbar-widget and plasmoid-host import `icons`. Host raster gains `load-image(path)` and a
  `draw-image` op; the plasmoids host gets an icons table (6: app id, handle).
- Compositor (shell/icons.mbt): window app id -> desktop file (resolve_app_id, so StartupWMClass
  and last-dotted-part matches work) -> Icon= -> theme lookup (XDG data dirs, ~/.icons,
  flatpak exports; hicolor, Adwaita, breeze; 48/64/32 px PNG first, then scalable SVG when the
  host can draw it, then other sizes, then /usr/share/pixmaps). Absolute Icon= paths are used as
  they are. Results are cached per app id; the table is published only when a module imports
  `icons`.
- wasm host (host-wasm): PNG via the png crate, SVG via resvg (rendered sharp at each size),
  PNGs area-averaged to the drawn size; loads cached by path.
- Native build: a small PNG decoder (compositor/renderer/png.mbt: inflate + filters, 1-16 bit,
  palettes with tRNS) and the Image op in the software renderer. SVG-only icons fall back to the
  tile there. The wasmer stub serves `icons.app-icon` from the same table.
- Tests: PNG decoder fixtures (all filters, fixed/dynamic/stored blocks, palette), image scaling
  and drawing, icon lookup order, Icon= parsing, task module icon-or-tile (native and wasmtime),
  host raster PNG+SVG loading and drawing. Checked end to end with the wasm host: foot's
  hicolor icon shows on its pill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhmtDt52EjaW8jevGU
2026-11-25 18:52:58 +00:00

278 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# chandra architecture
> Status legend used throughout: **[M0]** implemented in this repository today,
> **[designed]** interface sketched here but not in `wit/` yet, **[open]** needs a decision.
chandra is a KDE-Plasma-like desktop in which **every part is a WebAssembly
component** (Component Model, WIT-defined interfaces, written in MoonBit) running
on top of a deliberately tiny trusted **host**. The point is not to clone Plasma
pixel for pixel; it is to take Plasma's *decomposition* (shell / window manager /
runner / settings / notifications / tray / session …) and make each seam a typed,
versioned, permission-checked, hot-swappable interface.
## 1. Plasma → component-model map
| Plasma piece | What it does | chandra counterpart | Component or host? |
|---|---|---|---|
| `plasmashell` (containments, panels) | Hosts the desktop & panels, loads plasmoids | `shell` component exporting `desktop-surface` + `panel-layout` **[M0]** | component |
| Plasmoids / widgets (QML + C++/JS) | Clock, task manager, kickoff… | `widget` world exporting `plasmoid` **[M0]**: `digital-clock`, `binary-clock`, `launcher` | component, one instance per widget |
| Plasma Look-and-Feel, colour schemes, Breeze, Kirigami theme | Design tokens, icons, cursors, fonts | `theme` interface (`tokens`) **[M0]**; app icons through the `icons` interface + an `image` draw op (the host resolves .desktop Icon= in the freedesktop icon themes and decodes PNG/SVG) **[M1]**; cursor/font interfaces **[designed]**; a "look-and-feel" bundle = theme tokens + default layout + wallpaper | tokens served by a `theme-provider` component (M0: static JSON in host) |
| KWin (WM policy: stacking, focus, tiling, rules, virtual desktops) | Decides where windows go | `window-manager` world: exports `wm-policy` (place/resize/focus decisions), imports `window-registry` **[designed]** | component |
| KWin (compositing: scene graph, damage, scanout) | Draws windows to screen | Rasteriser/scanout of the **render-list** | **host** (only because it touches GPU/DRM) |
| KWin decorations (Aurorae etc.) | Titlebar/borders | `decoration` interface: returns draw-ops + hit regions for a window state **[designed]** | component |
| KWin effects / scripts | Overview, blur, wobbly… | `effect` interface: declarative per-frame transform of the scene (no raw shaders in M-early) **[designed]** | component (+ host primitives like blur) |
| KRunner / Kickoff search | Query many backends, ranked results | `search-provider` interface (`query(text) → list<match>`, `run(match)`); `runner` component fans out to providers **[designed]**. Launcher widget does substring search locally in M0 | components |
| System Settings + KCM modules | Config UIs per area | `settings-page` interface: a KCM is a component with grants only for its own config groups **[designed]** | components |
| KConfig / kconfig XT | Hierarchical typed config, cascading, immutable keys | `config-store` interface: `group/key → value` variant, change events, layered (system < user < activity) **[designed]** | store in **host** (needs durable FS), policy in components |
| KNotifications / `plasma-workspace` notification server | `org.freedesktop.Notifications`, history, DND | `notifications` interface (apps `notify`), `notification-center` component renders toasts + history **[designed]** | components |
| StatusNotifierItem / system tray | Tray icons + menus from apps | `tray-registry` (items register `tray-item` exports), `system-tray` widget **[designed]** | components |
| `ksmserver` / `startplasma` / systemd integration | Session start, restore, logout | `session` interface (logout, suspend, lock; power events) **[designed]**; **init sequence** = host reads `session.json`, starts a `session-manager` component which starts the rest | host (bootstrap only) + component |
| KGlobalAccel / KWin shortcuts | Global shortcuts | `shortcuts` interface: components register accelerators → action ids; host matches raw key events against the table **[designed]** | table in host (input path), policy in component |
| Activities (`kactivitymanagerd`) | Per-activity layouts/history | `activities` component holding current activity; `config-store` layering keys on it **[designed]** | component |
| KIO / Dolphin | URL-based VFS, file manager | `vfs` interface with URL schemes; `vfs-provider` components (`file`, `trash`, `sftp`…); Dolphin = a component app using `vfs` + `plasmoid`-style render lists **[designed]** | providers: components atop host `fs`/`net` capabilities |
| Klipper | Clipboard manager | `clipboard` interface (read/write typed MIME list; separate read/write grants) **[designed]** | host owns the system clipboard; history = component |
| Powerdevil, solid | Power & hardware | `power`/`devices` interfaces **[designed]** | host (hardware), policy = component |
| KScreen | Output config | `outputs` interface **[designed]** | host (display), UI = KCM component |
| KWallet | Secrets | `secrets` interface; separate trust level **[designed]** | component with a very narrow grant |
| Baloo | File index | `search-provider` over `vfs` **[designed]** | component |
| SDDM | Login | `login` world: a full shell variant that gets `auth` capability **[open]** | component |
## 2. What is in the host, and nothing else
The host is the trusted computing base. Rule of thumb: **if it can be expressed as
"a pure function of its inputs + capabilities we hand it", it is a component.**
The host only does what a component *cannot* do by construction:
1. **Engine & lifecycle** – compile/instantiate components, supervise them
(trap → visible fault + restart policy), enforce resource limits
(fuel/epoch deadlines on wasmtime; **not available under jco** — a looping
component can hang the M0 host, a known limitation), hot-swap instances.
2. **Capability broker** – owns the *only* path from components to the outside
world; wires each instance with exactly the interface implementations it is
granted (§6).
3. **Device ownership** – display/DRM/GPU, input devices (libinput), audio,
network sockets, real filesystem, clipboard, D-Bus/portal bridges. Components
see these only through narrow WIT interfaces.
4. **Render-list rasteriser / scanout** – turns the composed render-list into
pixels (Canvas2D in M0). It interprets a *closed vocabulary* of draw-ops; it
has no policy.
5. **Input demux & delivery** – reads raw events, applies the shortcut table,
delivers the rest to the focus/grab target the `window-manager`/shell
component names (§5).
6. **Bootstrap** – reads `session.json` (which components, which grants) and
starts the session-manager component.
Everything else – panel layout, window placement, focus policy, decorations,
theming, search, notifications, settings UIs, tray, the launcher – is a component
and can be replaced by a different `.wasm` that implements the same world.
```mermaid
flowchart TB
subgraph host["host (trusted, small)"]
eng["engine + supervisor + hot-swap"]
cap["capability broker"]
ras["render-list rasteriser / scanout"]
inp["input demux"]
dev["devices: display, input, fs, net, clipboard"]
end
subgraph comps["components (sandboxed, swappable)"]
shell["shell (desktop-surface, panel-layout)"]
wm["window-manager policy"]
w1["widget: clock"]
w2["widget: launcher"]
run["runner + search providers"]
notif["notification-center"]
kcm["settings pages"]
end
comps -- "typed WIT calls\n(host-mediated)" --> host
host -- "render-list" --> ras --> dev
dev -- "raw input" --> inp --> comps
cap --- comps
```
## 3. Component-to-component communication: host-mediated calls (decision)
Options considered:
| | static composition (`wasm-tools compose`/WAC) | dynamic linking / shared-everything | **host-mediated typed calls (chosen)** |
|---|---|---|---|
| Hot-swap one part | re-link and restart the composite | not available in toolchains yet | swap one instance; others keep state |
| Per-link capability attenuation | none (composed = same trust) | none | yes: each instance gets its own import wiring |
| Fault isolation | one trap kills the composite | n/a | per-instance |
| Third-party/untrusted widgets | no | no | yes |
| Cost | none (direct calls) | none | host call per hop (JS: ~µs; fine for UI-rate calls) |
| Maturity today | good (`wac`, `wasm-tools compose`) | immature | works now (what M0 does) |
**Decision:** components never call each other directly. The host holds the
instances and routes: today it is hub-and-spoke (host → shell for layout, host →
widget for render/events, as in `host/src/desktop.mjs`), later through a
**service registry**: a component *exports* a typed interface (e.g.
`search-provider`), the host lets *importers* with the matching grant call it,
via a host-owned `registry` interface (`lookup(interface-name) → handle`).
Messages stay typed WIT values (records/variants); no stringly-typed JSON bus.
Event broadcast (theme changed, activity changed) is a `subscribe/poll` pair
until component-model async (WASI p3) is usable in our hosts.
Static composition remains available as a **build-time optimisation inside one
trust domain** (e.g. fusing `shell` with a built-in tray into one `.wasm`), never
across grants.
## 4. Rendering: shared render-list, not per-component textures (decision)
Components return **render-lists** (`list<draw-op>`, see `wit/types.wit`) in
their own local coordinates; the host/compositor translates, clips, orders and
rasterises them. Components never receive pixels or GPU handles.
Why: it is sandbox-friendly (no shared memory, nothing to leak or overrun),
serialisable (record/replay, remote desktop, golden-file tests — the ASCII and
scene-JSON dumps in M0 are exactly this), host-agnostic (Canvas2D now,
Skia/wgpu/software later, all from the same WIT), and cheap for UI-sized scenes.
Costs and mitigations: (a) copying lists across the boundary each frame →
add a revision counter and let `render` return "unchanged" so the host reuses the
cached list; add damage rects; (b) text needs metrics → M0 uses a fixed 0.6 em
advance contract; a host `text` interface (`measure`, shaping, fonts) is the next
step; (c) content that is *not* vector (video, foreign Wayland/X clients, WebGL
canvases) → add a second surface kind: a WIT **resource** `buffer-surface`
(dmabuf/shm handle owned by the host, written by a granted producer) which the
render-list references via a `draw-surface` op **[designed, M5]**.
The UI toolkit question: components can link any MoonBit library into
themselves. `moon-gpui` (GPUI port) is a natural fit because its scene/geometry/
colour packages map almost 1:1 onto our draw-op vocabulary; in that arrangement
GPUI runs *inside each component* and its scene is flattened into
`list<draw-op>`. This is **[open]**: `/workspace/moon-gpui` currently only has a
README, so nothing was verified.
## 5. Input routing
* The host reads raw device events and (a) matches them against the global
shortcut table, (b) otherwise hands them to the **routing component**:
`window-manager`/`shell` returns the target (surface id, local coordinates,
grab/focus changes). This keeps focus-follows-mouse, click-to-raise, tiling
gestures, etc. as replaceable policy.
* **[M0 shortcut, stated honestly]** the host itself does hit-testing against the
placements the shell returned, and routes: popup > widget under pointer;
pointer-down outside an open popup sends `focus-lost` to the popup owner, then
falls through. Keyboard goes to the popup owner. This is ~60 lines of host code
and is the first thing to move into the shell component (M2).
* Events are values (`input-event` variant), delivered with surface-local
coordinates, so a component never learns screen geometry it was not given.
## 6. Permission / capability model
WASI-style, deny-by-default:
1. A component's **imports are its declared needs.** `scripts/build.sh` records
them in `build/components/<n>.meta.json` (derived from the binary).
2. The **desktop config** (`config/desktop.json`) *grants* capabilities per
component instance. **[M0]** The host refuses to start a component whose
imports are not all granted (`PermissionError`), rejects unknown capability
names, and wires only granted interfaces into the import object.
Tests: `host/test/desktop.test.mjs`.
3. **Attenuation, not just on/off [designed]:** a grant supplies the host's
implementation of the interface *for that instance*: a `vfs` granted to
System Settings is rooted at `~/.config`, the same interface granted to a
file manager is rooted at `$HOME`; `config-store` is scoped to named groups;
`net` carries a host allowlist.
4. **Unforgeable handles:** capabilities that are objects (an open file, a
`buffer-surface`, a notification handle) are WIT `resource`s — a component can
only use handles the host gave it.
5. **User consent [designed]:** requests outside the manifest go to a
`permission-prompt` component (itself heavily restricted); decisions persist in
`config-store`.
6. **Supervision [M0 partial]:** a trapping component becomes a *visible* error
tile + a recorded fault (never swallowed); the CLI exits non-zero when faults
exist. Automatic restart/backoff is **[designed]**.
## 7. Versioning WIT packages
* Packages are semver'd (`chandra:desktop@0.1.0`). While `0.x`, any minor may
break; components pin the exact package version in their world.
* From `1.0`: **additive-only minors** – new interfaces, new functions, new
worlds, new variant cases at the *end* only when consumers are required to
handle unknown cases. WIT records cannot grow compatibly, so anything likely to
grow (e.g. `plasmoid-info`, `tokens`) should become `record` + `option`/`list`
extension points before 1.0, or be replaced by a new interface version
(`plasmoid@1.1`) that the host serves alongside the old one.
* Split by domain so versions move independently: `chandra:desktop` (types,
theme, plasmoid, panel), later `chandra:wm`, `chandra:search`,
`chandra:notify`, `chandra:config`, `chandra:session`, `chandra:vfs`.
* The host advertises the set of interface versions it implements and may
serve N and N-1 side by side via adapters; a component declares what it
targets and fails to load otherwise (no silent downgrade).
* CI gate **[M0]**: every component must pass `wasm-tools component targets
--world <w> wit <component>`; generated bindings must match `wit/`
(`scripts/gen-bindings.sh --check`). Registry publication (OCI/warg) **[open]**.
## 8. Host strategy (decision and feasibility)
| Option | What it is | Time-to-pixels | Fits the "everything is a component" goal | Main risks |
|---|---|---|---|---|
| **(a) Browser/Node host with jco** | components transpiled to JS+core wasm; host in JS; Canvas2D now, WebGPU later | **hours — done in M0** | components yes; host = JS runtime (large TCB: browser) | no real windows/devices; JS can't pre-empt a looping component; browser is not a desktop session |
| **(b) Native host embedding wasmtime** | Rust host using `wasmtime::component` + `bindgen!`; software/GPU rendering into a window (winit/SDL) or DRM | days–weeks | best: small native TCB, fuel/epoch limits, real FS/net/devices | host is Rust, not MoonBit; wasmtime's C API cannot instantiate components with host imports as conveniently, so a MoonBit-native host via FFI is **unverified** and probably not worth it |
| **(c) Nested compositor in an existing session** | (b) running as a window/Wayland client first, later a real compositor (smithay) hosting foreign Wayland apps | weeks–months | needed to run real apps | scope; Wayland/EGL/input details |
**Recommendation:** (a) for M0–M2 (done: it is the fastest way to prove the WIT
design with real MoonBit components), then (b) as the *reference host* in M3–M4
using the **same WIT and the same build outputs** (the components are standard;
only `host/` changes), then (c) from M5 as the path to real windows. The WIT stays
host-agnostic: nothing in `wit/` mentions JS, a browser or a window system. What
does **not** transfer is `host/src/desktop.mjs`; it is intentionally small
(~200 lines) and is the executable spec for the Rust host.
## 9. Interface catalogue
Implemented in `wit/` (package `chandra:desktop@0.1.0`):
| Interface | Purpose |
|---|---|
| `types` | geometry, colour, `draw-op` render-list vocabulary, `input-event`, `datetime`, `app-entry` |
| `theme` | `get-tokens()` – palette + metrics (read per render so theme swaps are live) |
| `plasmoid` (export) | `info`, `render(size)`, `popup`, `on-event(surface, event)` |
| `panel-layout` (export) | `compute-layout`, `render-panel`, `popup-position` |
| `desktop-surface` (export) | `render-background` |
| `clock`, `app-catalog`, `app-launch` (imports) | host capabilities used by the PoC widgets |
Worlds: `widget` (theme + plasmoid), `clock-widget`, `launcher-widget`, `panel`, `shell`.
Designed next (no WIT yet): `window-registry`/`wm-policy`/`decoration`, `search-provider`,
`config-store`, `notifications`, `tray-registry`, `shortcuts`, `clipboard`, `session`/`power`,
`vfs`, `activities`, `settings-page`, `registry`, `buffer-surface`, `text`.
## 10. What is a PoC stub today
* Host does hit-testing/routing (see §5), time and app list are host-provided statics.
* `app-launch.launch` records the id and logs; it does not start anything.
* Text uses a fixed-advance contract; no font/shaping/icon interfaces (glyph letters stand in for icons).
* No window manager, compositor, notifications, settings, tray, session, shortcuts, clipboard, files.
* Theme is a JSON file read by the host, not a `theme-provider` component.
* No resource limits under jco; no hot reload on file change (swap is an API call).
## 11. Roadmap
| M | Goal | Status |
|---|---|---|
| **M0** | Toolchain proof, WIT v0.1 (`widget`/`panel`/`shell`), host (Node+browser), 4 components, tests, CI, swap/theme/permission demos | **done (this PR)** |
| M1 | `config-store` + `theme-provider` component; persisted settings; hot reload of `.wasm` on change; `text` interface (measure/fonts) and icon theme | next |
| M2 | Move input routing + focus policy into the shell/WM component; more widgets (task manager stub, system tray, notifications toasts); `search-provider` + KRunner component | |
| M3 | Native reference host: Rust + wasmtime (`bindgen!`), software rasteriser into a winit window, fuel/epoch limits, restart supervision; CI runs the *same* integration tests against both hosts | |
| M4 | Window-manager world with synthetic windows (no real apps yet): stacking/tiling policies as swappable components, decorations, virtual desktops, activities | |
| M5 | Nested compositor (smithay) hosting real Wayland clients; `buffer-surface` resource; GPU rasteriser | |
| M6 | Settings (KCM-style) framework, notifications daemon bridge (D-Bus portal), tray (SNI bridge), clipboard, power/session | |
| M7 | `vfs` + file manager component; search/indexer; look-and-feel packages | |
| M8 | Standalone session (DRM/KMS + libinput), login manager world, packaging/registry for components | |
## 12. Open design questions (with recommendations)
1. **Host language/long-term host** — Rust+wasmtime native host vs trying to keep even the host in MoonBit. *Recommend Rust+wasmtime for M3; revisit MoonBit-native host only if wasmtime's C API gains full component embedding.*
2. **Render-list vs textures** — *Recommend render-list as the default, `buffer-surface` resource only for non-vector content (§4).*
3. **UI toolkit inside components** — adopt `moon-gpui` or a tiny immediate-mode helper (`lib/ui`)? *Recommend `lib/ui` until moon-gpui has a stable scene package and a flatten-to-draw-op adapter, then migrate widget internals; keep the WIT draw-op vocabulary as the stable boundary.*
4. **Text and fonts** — host-provided shaping (`text` interface) vs components bundling a shaper. *Recommend host-provided: layout needs metrics from the same engine that rasterises.*
5. **Async** — wait for WASI p3 async in jco/wasmtime/wit-bindgen-moonbit or keep sync + poll. *Recommend sync + poll through M3; the backend support exists but hosts are not uniformly ready.*
6. **Who owns hit-testing** — move to the shell/WM component at M2 (§5). *Recommend yes, host only for grabs it must enforce (shortcuts, secure attention).*
7. **Config format & ownership** — KConfig-like INI layering vs structured store. *Recommend a typed `config-store` with layered scopes (system/user/activity) and change events; INI import/export as a component.*
8. **Packaging & trust** — signed component bundles with manifests (grants requested, WIT versions targeted) vs bare `.wasm` + config. *Recommend a manifest custom section in the `.wasm` + signature, host shows requested grants; M3+.*
9. **Foreign-app strategy** — nested Wayland (M5) vs only native components. *Recommend nested Wayland; otherwise the desktop is not usable day to day.*
10. **Plasma compatibility** — try to load real plasmoid QML/KPackages? *Recommend no; mimic concepts (containments, plasmoids, KCM, KRunner plugins) but not binary/QML compatibility.*