ziran docs ARCHITECTURE.md
15 kB 258 lines
Markdown
at main

Ziran — Desktop App Architecture #

Ziran is a Deno desktop app (CEF backend, Deno ≥ 2.9) following Blastile's shell patterns and Tenet's tile-management patterns. One process: a Deno backend owns all state and serves HTTP + WebSocket on 127.0.0.1; the CEF window loads the UI from it; tiles render in isolated *.localhost iframes.

Shell (from Blastile) #

  • main.ts binds Deno.serve FIRST (under deno desktop, to the runtime-assigned DENO_SERVE_ADDRESS; else 127.0.0.1:4180), then deletes DENO_SERVE_ADDRESS before the express-based tile server starts — the node-compat listener honors that env var and would steal the address.
  • Main window via Deno.BrowserWindow (the desk shell). No Deno Desktop bindings are ever registered: the bindings proxy leaks into cross-origin tile frames, so all IPC is HTTP (/api/*) + one WebSocket (/api/events).
  • CEF (not the platform webview) because tiles need *.localhost secure contexts for their service workers.
  • Plain deno task dev runs the same app in a normal browser (the printed URL carries the key; see below).
  • API auth: 127.0.0.1 is reachable by every local process, so the server mints a random bearer token at launch (ZIRAN_KEY overrides for tests) and refuses any /api/* request or WebSocket upgrade without it (constant-time compare, 401). The token travels only in the URLs the server navigates its own windows to; pages send it as an x-ziran-key header, or as a ?key= query param where headers are impossible (img icons, the tile bundle URL, WebSocket, beacons). Tile frames never see it: they are cross-origin and no host→tile payload contains it. Static assets are served without auth (nothing secret; the app is inert without the key). The Origin check remains as a second gate against tile-frame WebSockets.

Tiles (format from Blastile, engine ported from Tenet) #

A .tile is a CARv1: varint-prefixed dCBOR MASL manifest (with version: 1, roots: []), then blocks of varint(36+len) + CID bytes + resource bytes. Resource CIDs are CIDv1 / raw 0x55 / sha2-256. resources[path].src is a CID link ({$link} / Tag 42 with the 0x00 identity prefix — handled by @atcute/cbor); icons[].src is a plain path into resources. The / resource is the tile's index.html; the tile IS its own editor.

src/server/tilefile.ts (TS port of Tenet's car.rs against Blastile's byte format, built on @atcute/{car,cbor,cid} + @dasl/tile-writer):

  • parseTile(path) → manifest + CID→offset index; verifies every block's CID against its bytes (ziran adds the integrity check both references skip — a mismatch marks the document damaged, feeding the UI's calm failure state).
  • readResource(path) / readStorage(name) — lazy block reads.
  • writeTileData(name, bytes) — upsert /.well-known/web-tiles-storage/<name> and atomically rebuild (tmp + rename in the same dir).
  • writeModelTile(src, dest) — Tenet semantics: require model.id; hoist model.* over top-level name/description/icons; strip all /.well-known/web-tiles-storage/* resources and any blocks only they referenced; keep the model field so instances stay model-backed.
  • safeModelStem(id) — slug + first 8 hex of sha256(id); models upsert by id.

Storage (from Tenet) #

App data dir (src/server/paths.ts): macOS ~/Library/Application Support/com.berjon.ziran/, Linux $XDG_DATA_HOME/com.berjon.ziran/, Windows %APPDATA%\com.berjon.ziran\.

com.berjon.ziran/
├── documents/     # app-managed documents (create-from-model copies here)
├── models/        # <slug>-<hash8>.tile — standalone stripped model tiles
├── imports/       # drag-and-dropped .tile files
├── recents.json   # [{path, lastOpened, name, hasIcon, modelName}]
├── session.json   # desk layout: windows/panes/tabs by doc id + base position

Creating from a model = copy the model tile into documents/ (no dialog; local-first means it exists and is recoverable from Recent immediately). External tiles can be opened via picker (macOS osascript, else manual path) or drag-and-drop import. Starter models ship in tiles/ and seed models/ on first run.

Rendering & self-storage #

@dasl/tile-server + vendored web-tiles/{shuttle,data}.js serve the tile runtime; a LocalTileMothership mints a random <20 letters>.localhost:<port> origin per render; CARTileLoader fetches /api/docs/:id/bundle.tile. Tiles persist through /.well-known/web-tiles/store.js (loadData/putData, Tenet's contract) implemented over tp-data postMessage → host → GET/PUT /api/docs/:id/data/:name → writeTileData.

UI — real OS windows #

Every page is one real OS window (Deno.BrowserWindow; window.open popups in browser mode). / is the base window; /?win=<id> is a document window. The server owns window layout (windows: DocWindowRec[] — panes, tabs, split ratio) alongside documents; every window mirrors state over its own WS connection (/api/events?win=<id>) and forwards actions as window ops (POST /api/windows/:id/op). When a window's last socket drops and no reload reclaims it within 2s, its record is closed and unreferenced docs released; conversely, when a window's record empties (merge, last tab closed), the page calls window.close().

Tabs and vertical splits live inside each document window. Cross-window combination is menu-driven (merge into / tile into / move tab to / tear off — tear-off spawns a new OS window); there is no cross-window drag, because real OS windows offer no drop orchestration. Session restore reopens last session's windows server-side at boot (desktop mode only), including geometry: each window page reports its own bounds (screenX/outerWidth — the desktop API has no bounds events) to POST /api/windows/:id/bounds, persisted in session.json; restores pass bounds as constructor options and the page re-applies them via moveTo/resizeTo. The base window centres itself when no stored bounds exist.

Window navigation (a sharp edge): deno desktop loads the served root itself, before anything of ours runs, and that load carries no API key; BrowserWindowOptions has no url field and there is no ready/load event, so a navigate() issued straight after new BrowserWindow() silently no-ops. navigateUntilArrived() (src/server/windows.ts) therefore retries on a backoff until the window's WebSocket connects (store.hasArrived). A keyless GET / serves a splash rather than booting a UI that would 401 on everything; a wrong key still gets the real UI so it can say the window is out of date. The API key itself persists at <app-data>/api-key (0600) so a window that outlives a restart keeps working.

OS integration #

App + document icons are generated by tools/make-icons.ts (headless-Chrome rasterization of the brand SVGs; Windows .ico is a PNG-embedded single-image wrapper). .tile / application/web-tile association + the ziran:// URL scheme: on macOS, tools/mac-bundle.ts post-processes the built .app (CFBundleDocumentTypes + UTExportedTypeDeclarations for UTI ing.dasl.tile, CFBundleURLTypes for ziran://, document icns via sips/iconutil, lsregister) — wired into the build/build:mac* tasks; on Windows/Linux, src/server/register.ts registers at first run (HKCU registry / XDG mime + desktop entry + x-scheme-handler). File paths and ziran://invite/<token> links passed on the command line are handled at boot. Known gap: macOS Finder/browser open-events (Apple Events) don't reach Deno.args; opening a .tile or deep link while ziran runs needs runtime support Deno desktop doesn't expose yet. deno task build:all chains every platform target.

Documents and models carry real tile metadata — name, icon (served from the tile's own resources via /api/docs/:id/icon, surfaced in recents, models, window bars, and tabs), model provenance, verified/damaged state. zn-doc-canvas is the tile frame (shuttle iframe) with skeleton/damaged states wired to real load/verify.

Starter tiles (tiles/) #

Collaborative starters, each demonstrating a different sync shape; all built by deno task build:tiles (which first vendors third-party bundles into the tiles that use them — tiles are self-contained) and seeded per model id, so new starters reach existing profiles:

  • note — solo self-saving text (the original demo).
  • checklist — idempotent ops over the ordered echo; no CRDT needed.
  • tictactoe — document-defined roles end to end: manifest declares x (owner/admin), o (write, max 1), watcher (read, sees players); the tile enforces turn/legality deterministically (attribution is runtime-attested), the relay enforces write/caps.
  • form — roles as a division of labour (a Google-Forms shape): the creator is the owner, labelled Editor, and may invite more editors (collaborator) and respondents. Editors build the form, preview it and read the results (summary, one by one, CSV); a respondent sees only the form, answers once, and then sees their own answer. State is the set of ops and everything is a fold over it (tiles/form/logic.js): form edits count only from an editing role (last-writer-wins per field), a response counts only once per runtime-attested author (the earliest), and an editor's delete names every response seen from that person so they can answer afresh. respondent is deliberately the first non-owner role, so it is what defaultRoleOf hands a newcomer. Responses live in the document's self-storage (form: the ops, plus the folded form and responses for tools that read the file). Being unable to see the results is a property of the tile's interface, not of the space: under Spaces every member can read every record, so a respondent who goes looking can read other people's answers.
  • livetext — the tile picks Yjs as its CRDT (vendored ~91 KB); updates ride the durable log, cursor presence rides the ephemeral lane (mirror-div rendering, relative positions preserve the local caret).
  • paper — Markdown that reads like print, and the first multi-mode tile: "modes": ["view", "edit"] in the manifest (first = default). View is a typeset page (serif sheet, print stylesheet); edit is the plain manuscript plus style controls (typeface/size, persisted as style.json). The content lives as raw doc.md in self-storage, so any tool — or model — reading the .tile file gets plain Markdown while humans get the page.
  • richtext — ProseMirror (~230 KB vendored) with the ordered log as collab authority: steps-ops are valid iff their base version matches at arrival (deterministic accept/ignore under total order; rejected senders rebase via prosemirror-collab and resend). Toolbar, comments (marks + synced threads), suggestion mode (insertions marked by an appendTransaction pass, deletions by keymap; accept/reject in the sidebar), images as data URLs, remote selections/carets. On first share (ready at version 0) it rebases pending solo steps into the baseline so the snapshot and log never double-apply.

Hard-won invariant from these: MlsGroup serializes every state-advancing op through one promise chain — concurrent encrypts would reuse a ratchet generation (nonce reuse; receivers drop the frames). Rapid per-keystroke sends surfaced this.

tp-mode (modes protocol): a tile may declare "modes": ["view", "edit", …] in its manifest; the first is the default it boots into. The runtime chrome owns the switcher (doc-window banner, shown only for >1 mode) and tells the tile over vendor/web-tiles/mode.js (mode.current() / mode.onChange()); the flow is one-way by design — tiles render the mode they're given and never control it. Mode is per-window, in-memory, and survives tile reloads within a window (the hub replays it on the tile's hello).

Collaboration (E2EE live sessions) #

Full design in docs/SYNC-DESIGN.md; research in docs/SYNC-OPTIONS.md.

  • Relay (relay/): standalone dumb Delivery Service — per-document server-ordered log, ephemeral presence lane, snapshot blob, inbox/<did> invitation mailboxes, KeyPackage directory (stand-in for PDS records), and the /i/<token> share-link landing page. Enforces only write-permission, membership/caps, and per-role presence visibility from the document's declared roles; payloads are opaque MLS ciphertext. deno task relay, or the app embeds one on :4191 when ZIRAN_RELAY is unset (a second local instance joins the first's — same-machine collaboration works out of the box).

  • Crypto (src/sync/mls.ts): ts-mls behind a narrow façade; MLS runs in the Deno process only. src/sync/mls-transport.ts wraps the plaintext relay client so the relay never sees plaintext; group state persists under app-data sync/groups/ (debounced after every ratchet advance).

  • Runtime (src/server/sync.ts): SyncManager owns identity (dev DID in sync/identity.json; ZIRAN_DID/ZIRAN_HANDLE override — the AT-sign-in swap point), the shared-doc registry (sync/docs.json, localId↔syncId), live sessions with per-tile replay buffers, invitations, and snapshots: the tile's own putData persistence doubles as the catch-up snapshot (ackedSeq advances on write, snapshot uploads after).

  • Tile protocol (vendor/web-tiles/sync.js): send/onMessage (attributed, server-ordered, dupes dropped), sendEphemeral/onEphemeral, roster/me. No membership surface, by construction. The UI bridges frames between tp-data and the backend (src/ui/data-protocol.ts ↔ /api/docs/:id/sync/*).

  • UI: connections panel "Live Session" section (go live, roster, invite by DID + role), invitation strip in the base window (Accept = download → verify → open → join), live badge + member count in the doc banner/chip.

  • Tests: deno task test:sync (relay 18, MLS 15, E2EE transport 9, two-runtime API e2e 20); full-browser two-user flow in the scratchpad harness (ziran-sync-ui.mjs, 13 checks incl. tile-to-tile round-trips).

  • AT identity (src/sync/atproto.ts, src/server/atsession.ts): sign in with an AT handle via atproto OAuth (loopback client; /oauth/callback; sessions in app-data). Signed in, relay tokens are service-auth JWTs minted at the user's PDS and verified by the relay against their DID document (AtprotoVerifier; dev HMAC tokens remain accepted unless ZIRAN_RELAY_DEV_AUTH=off); MLS KeyPackages publish to the user's own repo (space.ziran.keypackage) with the relay directory as fallback; invites take @handle or DID. Signed out, a local dev identity keeps everything working. Tests: src/sync/atproto.test.ts (offline, all three curves + relay door); live PAR against bsky.social verified.

Deferred: kick/role-change UI, presence lanes in tiles, log compaction, relay reconnect, KeyPackage pools (consumed-once), Atmosphere publish. Known dev gap: dev-identity KeyPackages are per-run, so invitations to a dev identity need the invitee's app running since its last restart (PDS records fix this for signed-in users).

Build: deno bundle --platform browser → static/app.js; CSS linked from static/index.html. Vite/package.json remain for browser-only UI iteration and node tooling (contrast checks), but the app's toolchain is Deno.