Files
regent/src/AGENTS.md
raucao fe7a164201
CI / test (push) Successful in 1m16s
docs: split AGENTS.md into per-directory notes
The root file was loaded in every session, but most of its ~1,500 lines
are subsystem detail that only matters while working on that subsystem.
OpenCode loads a nested AGENTS.md when the agent explores its directory,
so the detail now lives beside the code it covers.

The root keeps the always-relevant parts (hard rules, layout, conventions
and a verification block) plus a "Where to look" index; the signer, store,
UI, app core, data and build-aux notes moved to their own files. Section
IDs (M1-M12) and trap numbers are unchanged so cross-references still
resolve; the few "see X" pointers were repointed at the new file.
2026-12-01 12:56:46 +04:00

18 KiB
Raw Permalink Blame History

Regent — app core (src/)

The windows, the always-on process, the headless runner and the cross-cutting code in src/*.rs. The subsystems it wires together live beside it: src/signer/AGENTS.md, src/store/AGENTS.md, src/ui/AGENTS.md.

Windows and first run (M10)

  • Two windows, one AppState. window.rs builds both and holds the Windows registry; the identities window is chrome (data/resources/ui/keys.blp) around the existing KeysView. A second AppState would mean a second registry and a second signer on one device key (see M5, src/store/AGENTS.md), so the registry is created once in application.rs and shared. The window is 460×560: tall enough for the first-run empty state and the add/import dialog forms, because GTK never resizes a mapped window, so the default has to fit the tallest thing it shows. The width is deliberate: it is above libadwaita's bottom-sheet threshold (AdwDialog's auto mode uses a bottom sheet when the window is max-width: 450px or max-height: 360px — see adw-dialog.c), so every dialog parented to this window is a centered floating card rather than a sheet docked to the bottom edge.
  • The invariant: the main window is presentable exactly when the responder can serve prompts. The approval dialogs are parented to the main window, so a request must never arrive without it. With no keys there is nothing to sign with and nothing to listen for, so the identities window is the whole app. With a key the main window exists and the signer runs, but it may be hidden in the background (M12): the approval drain presents it for a dialog and hides it again once the request is answered. Closing the main window is no longer a plain quit — see M12 — but with no key, or a stopped signer, it still quits, because a hidden window that can answer nothing is the "signer that answers nothing" this shape exists to avoid.
  • The launch decision (Windows::build + present_primary): no keys ⇒ present the identities window only; keys ⇒ the main window, whose first page is Apps. follow_keys (a state.listen callback) follows the transition: the first key presents the main window and leaves the identities window open, and removing the last key hides the main window and presents the identities window again — first-run mode. Acting on the transition rather than on every notify() is what keeps a profile fetch or a lock from re-presenting a window the user just closed. The choice is logged (no identity key yet, opening the identities window / identity keys found, opening the main window): it is the one part of the launch that cannot be observed from outside, and acceptance asserts on it.
  • Windows::primary() is the single rule for "the window the app is", and app.focus, app.lock and present_preferences all go through it. Do not reintroduce app.windows().first() — it is creation order — and note that app.focus used to present every window, which would pop the hidden identities window open on every notification click. With the window able to be hidden, a dialog is parented through Windows::visible_parent() (active_window(), else primary()): an AdwDialog inside a hidden window is silently invisible, so present_preferences/present_about/present_connect/ pair_uri must never parent to a window that is off screen.
  • The identities window is created once and set_hide_on_close(true): AppState::listen cannot unregister and its closures capture widgets, so a window destroyed and rebuilt would leave listeners pointing at dead widgets. present_identities makes it transient for the main window while that is visible: GNOME Shell's focus-stealing prevention shows a " is ready" notification instead of raising an already-mapped window that has no valid activation token, and a transient is focused with its parent. With no visible main window (first run, last key removed) it stays standalone.
  • Preferences (ui/preferences.rs) is an AdwPreferencesDialog — libadwaita 1.6 deprecated AdwPreferencesWindow in favour of it — built once and re-presented (AdwDialog re-presents after being closed), with its listeners registered once, because the lock state changes while it is open. It holds the signer's run state (Start/Stop), the vault group and the auto-approval limit. The signer moved here from the "Connect an app" dialog: its run state is not what that dialog is for, and Start/Stop sat above a pairing flow it did not belong to. Deliberately not relays: the running signer holds config.relays from start, the bunker URI advertises them and get_relays serves them, so a mid-run edit would mean "changed, but not until restart, and the paired clients were told otherwise". Reachable by Ctrl+, everywhere but by pointer only from the main window — deliberate, since in first-run mode there is nothing to configure yet.
  • The primary menu (main window) carries "Manage identities…", "Preferences…" and "Quit". The identities entry is not redundant with the switcher's: the switcher hides itself while there are no keys, and the last-key-removed state is exactly when the menu is the only pointer route back.
  • The vault loads synchronously — KeyStore::connect() is plain file I/O and the async was vestigial from the removed keyring — so the launch decision can depend on it and state.store() is no longer an Option. A vault that exists but cannot be read is fatal: application::run prints and exits non-zero before app.run(), because starting with an empty vault would let the next save overwrite the real keys (the shape M8 closed).

Running in the background (M12)

  • Closing asks, hides, or quits. close-action (GSettings, default ask) picks: ask shows an AdwAlertDialog (Cancel / Keep Running / Quit) with a "Remember this choice" checkbox; background hides; quit ends the app. The dialog's default and suggested response is Keep Running, and its close response is Cancel, so Escape and the dialog's X mean "stay as you are". Windows::request_close always returns Propagation::Stop — GTK must never destroy the window — and the choice is only offered while SignerRunner::status() is Running: with no key, or a stopped signer, closing quits as before. While a prompt is on screen the close is ignored, so the ask dialog cannot stack on top of it (only a keyboard/WM close reaches close_request at all; the modal prompt blocks pointer closes).
  • The window may be hidden while the signer runs. Hiding a window keeps the process alive (GtkApplication holds while a window exists), so no g_application_hold() is needed. PrimaryHandle is the main window plus one auto flag: present/hide/toggle are user-initiated and clear it; present_for_prompt presents a hidden window and sets it; the responder's Notice::RequestAnswered calls restore_after_prompt, which hides only if the flag is set. The hide follows the request, not the dialog — a locked vault asks twice (approve, then unlock), so hiding when present_question returns would flicker and strand the unlock dialog on a window it just hid.
  • Notifications still fire while hidden. notify_pending runs before present_for_prompt, so the user is away (the window is hidden) and a notification goes out; a click lands on app.focus → present_primary, which is a user-initiated present (it clears the auto flag, so the window stays).
  • The status icon (ui/tray.rs) is a ksni StatusNotifierItem on the shared tokio runtime: Show/Hide Regent, Preferences…, Quit Regent. Left-click opens the menu (MENU_ON_ACTIVATE), not Activate: the GNOME AppIndicator extension waits out the double-click interval on every click when an Activate method exists, so the menu-only interface is what makes it open at once. It holds only Send state and talks to the main loop over an async_channel; visibility/status/pending go back through a shared Arc<Mutex<TrayModel>> and Handle::update. show-tray-icon (default true) gates it. A missing host (stock GNOME without the AppIndicator extension) is not an error: watcher_offline logs (once per offline event) and returns true, so the icon appears the moment a host does. A start is asynchronous, so tray_starting guards against a second activation putting two items on the bus, and the completion re-checks the preference before showing it.
  • GNOME's Background Apps listing (and autostart) needs the org.freedesktop.portal.Background portal — hiding the window alone does not list the app. portal::request_background is a hand-rolled gio D-Bus call (not ashpd, which would pull a second zbus major in beside ksni's). Called when hiding to the background and at startup when autostart is set. --background starts with no window (the autostart Exec); the flag is stripped from the argv GApplication parses.
  • g_application_quit() never emits close_request, so the menu's Quit, Ctrl+Q and the tray's Quit bypass the dialog with no "quitting" flag.

Headless mode and CLI pairing (M6)

  • regent --headless runs the signer with no window (and no display): it is a plain tokio program, deliberately not a GtkApplication. regent --pair nostrconnect://… runs the same way, pairs first, then keeps serving. No options opens the GUI.
  • Headless denies anything not covered by a stored permission. There is no window to ask, so the approval bridge's questions are answered Deny immediately (not after the timeout). Pre-approve with "Allow always" in the GUI, then run headless. get_public_key/ping/get_relays stay automatic.
  • CLI pairing is the client-initiated (nostrconnect://) flow: parse the URI, subscribe to the client's relays (kept in SignerConfig::extra_relays, not in config.relays, so they never leak into the bunker URI or get_relays), register the app, then send the connect response whose result is the client's secret, p-tagged to the client and signed by the device key. Running --pair is the consent; permissions are never auto-granted, and the URI/secret are never printed or logged. --pair - reads the URI from stdin (I1), so it need not appear in argv or history. The bunker:// query is percent-encoded with url::form_urlencoded (I3), so a relay URL cannot smuggle a second query parameter. Client-supplied relays are wss:// only and at most MAX_CLIENT_RELAYS (5), and a literal IP that is not globally routable is refused — a ws:// or 169.254.x/loopback relay would otherwise turn a hostile URI into a local-network probe. The REGENT_RELAYS test override skips both checks (as it already lets a test point the signer at ws://127.0.0.1); the relays that survive are shown in the pairing dialog's Details.
  • The responder answers connect with "ack" for an already approved client even without the secret — a client-initiated pairing proves key possession by receiving our response. A new client still needs the secret.
  • The pairing secret rotates (L1). SignerConfig.secret (and the bunker:// config.uri) are shared Arc<Mutex<String>>s; a successful new pairing — the responder's connect arm after approve, and pair_client after complete_pairing — calls rotate_secret, which mints a fresh 96-bit secret and rebuilds the URI. So a copied/shoulder-surfed bunker:// string stops pairing a new client after the next pairing; every approved client keeps reconnecting through the "ack" path above, unaffected. The secret was already per-run (random_secret() in from_store), so this only shortens its life within a run. The presented secret is compared in constant time (subtle::ConstantTimeEq), never ==.
  • One instance only. Two signers on one device key fight over apps.json. The GUI owns the D-Bus name org.kosmos.raucao.Regent, so NameHasOwner is the friendly first message ("Regent is already running"), but it is not the guard: a headless run owns no name, and with no session bus (a server, an SSH box) neither does a GUI. Both the GUI (application::run's startup handler) and headless (headless::serve) therefore take an unconditional exclusive flock on regent.lock (mode 0600) through instance::claim, which fails closed if the lock file cannot be created or locked. That is what catches two headless runs, a GUI beside a headless one, and a second GUI on a machine with no session bus. The lock is taken in startup, which GLib emits only for the primary instance, so a secondary forwarding a nostrconnect:// link still reaches the primary; a refused instance also short-circuits activate/open, because quit() alone does not stop them being emitted. The kernel drops the lock on exit, so it cannot go stale.
  • Errors are loud: --headless/--pair print a message and exit non-zero for a bad URI, an unreadable vault, no identity key, or a relay that refused the connect response.
  • Unlocking for an unattended run: --passphrase-file <path> (a small regular file, mode 0400/0600 — never argv or the environment), or a systemd credential at $CREDENTIALS_DIRECTORY/regent-passphrase, which wins when present. It is opened once (read_passphrase_file, so no metadata/read TOCTOU), refused if group/other can read it (not merely warned about), read via take(4097) into a Zeroizing buffer, and never logged. Without it a locked vault simply denies the sensitive methods. --pair needs no identity secret and works while locked.
  • In-app pairing (Apps page → "Connect an app…" or the primary menu): paste the nostrconnect:// string, then the same approval dialog used for responder questions, through the same serialized Approver queue (Approver::ask_pairing; L4). On allow, the client's relays are added to the running signer and signer::pair_client registers + answers. If the signer is stopped, it is started with the client's relays first. The SignerRunner has a Stopped | Starting | Running state so a second start cannot put two responders on one device key.
  • Opening a nostrconnect:// link pairs straight away, over the window the app is (Windows::pair_uri), without opening the "Connect an app" dialog — so its errors must not be parented to that dialog, which is never presented on this path. ConnectDialog::report_error therefore falls back to Windows::visible_parent(); otherwise a bad URI, or a build with no identity key (as a fresh nightly has), would fail silently. Only the stable build is the system's nostrconnect:// handler (see dev deploy, build-aux/AGENTS.md).
  • The other direction needs no Start button. "Show Regent's code" is gated on a running signer — the bunker:// URI only exists while it listens — so expanding that row starts the signer if it is stopped. That is why the dialog carries no Start/Stop: the two directions are "paste a code" (auto-starts on pair) and "show a code" (auto-starts on reveal). Start/Stop lives in Preferences.
  • A successful pairing closes the "Connect an app" dialog and brings Apps forward (Windows::show_apps), and there is no "Client paired" confirmation: the new app is already in the list the user lands on. The client-initiated direction closes it in pair_now; the bunker-URI direction has no code path in the dialog at all — the client connects from outside — so ConnectDialog snapshots the current identity's app count on present() and closes when the registry grows past it (the changes ping record() sends). The other place that grows it, a rebind, moves the app into that same identity's list, so it is noticed too.
  • Signer::add_client_relays mirrors start: add with verify_subscriptions, wait until connected, then subscribe an explicit (RelayUrl, Vec<Filter>) target. Subscribing before the connection lands is trap 2 again (src/signer/AGENTS.md), and it looks fine because the pairing itself publishes explicitly — only later requests silently never arrive. The client's relays join the shared, growable listening set (response_targets), but a reply is published to the relay the request arrived on plus config.relays — never to another application's relay, so one app's prompt timing and response sizes are not observable to a client that joined a different relay.
  • pair_client (shared by the GUI and --pair) approves before publishing: the client validates the secret and usually sends connect immediately, which a new client cannot do without the bunker secret.
  • Known limitation: a manual stop/start drops the client's relays (extra_relays are per-run). Spec-compliant clients recover via switch_relays; others need re-pairing. Persisting per-app relays in apps.json is the clean follow-up — and would also let a reply use a client's other relays; today it is the arrival relay plus the configured ones.
  • Still deferred: D-Bus activation (a .service file + DBusActivatable).

Verified API traps (do not rediscover these)

Numbering is global across the three Verified API traps lists (here, src/signer/AGENTS.md, src/ui/AGENTS.md); only the traps relevant to this area are listed.

  1. The crate is gtk4 but must be aliased: gtk = { package = "gtk4", … }.

  2. A match scrutinee is a temporary scope that lasts to the end of the match, so match self.cell.borrow().clone() { … None => *self.cell.borrow_mut() = … } panics with "RefCell already borrowed" — the Ref is still held. Bind the clone to a local first (let existing = self.cell.borrow().clone();) and match on that. An if condition is its own temporary scope, so the if self.cell.borrow().is_none() { *self.cell.borrow_mut() = … } form in Windows::build is fine. This bit present_preferences on the first click; the acceptance test now activates app.preferences twice over D-Bus for it.