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.
18 KiB
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.rsbuilds both and holds theWindowsregistry; the identities window is chrome (data/resources/ui/keys.blp) around the existingKeysView. A secondAppStatewould mean a second registry and a second signer on one device key (see M5, src/store/AGENTS.md), so the registry is created once inapplication.rsand 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'sautomode uses a bottom sheet when the window ismax-width: 450px or max-height: 360px— seeadw-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(astate.listencallback) 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 everynotify()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", andapp.focus,app.lockandpresent_preferencesall go through it. Do not reintroduceapp.windows().first()— it is creation order — and note thatapp.focusused 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 throughWindows::visible_parent()(active_window(), elseprimary()): anAdwDialoginside a hidden window is silently invisible, sopresent_preferences/present_about/present_connect/pair_urimust never parent to a window that is off screen.- The identities window is created once and
set_hide_on_close(true):AppState::listencannot unregister and its closures capture widgets, so a window destroyed and rebuilt would leave listeners pointing at dead widgets.present_identitiesmakes 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 anAdwPreferencesDialog— libadwaita 1.6 deprecatedAdwPreferencesWindowin favour of it — built once and re-presented (AdwDialogre-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 holdsconfig.relaysfrom start, the bunker URI advertises them andget_relaysserves them, so a mid-run edit would mean "changed, but not until restart, and the paired clients were told otherwise". Reachable byCtrl+,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 theasyncwas vestigial from the removed keyring — so the launch decision can depend on it andstate.store()is no longer anOption. A vault that exists but cannot be read is fatal:application::runprints and exits non-zero beforeapp.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, defaultask) picks:askshows anAdwAlertDialog(Cancel / Keep Running / Quit) with a "Remember this choice" checkbox;backgroundhides;quitends 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_closealways returnsPropagation::Stop— GTK must never destroy the window — and the choice is only offered whileSignerRunner::status()isRunning: 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 reachesclose_requestat 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.PrimaryHandleis the main window plus oneautoflag:present/hide/toggleare user-initiated and clear it;present_for_promptpresents a hidden window and sets it; the responder'sNotice::RequestAnsweredcallsrestore_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 whenpresent_questionreturns would flicker and strand the unlock dialog on a window it just hid. - Notifications still fire while hidden.
notify_pendingruns beforepresent_for_prompt, so the user is away (the window is hidden) and a notification goes out; a click lands onapp.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), notActivate: the GNOME AppIndicator extension waits out the double-click interval on every click when anActivatemethod exists, so the menu-only interface is what makes it open at once. It holds onlySendstate and talks to the main loop over anasync_channel; visibility/status/pending go back through a sharedArc<Mutex<TrayModel>>andHandle::update.show-tray-icon(default true) gates it. A missing host (stock GNOME without the AppIndicator extension) is not an error:watcher_offlinelogs (once per offline event) and returnstrue, so the icon appears the moment a host does. A start is asynchronous, sotray_startingguards 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.Backgroundportal — hiding the window alone does not list the app.portal::request_backgroundis a hand-rolledgioD-Bus call (notashpd, which would pull a second zbus major in beside ksni's). Called when hiding to the background and at startup whenautostartis set.--backgroundstarts with no window (the autostartExec); the flag is stripped from the argv GApplication parses. g_application_quit()never emitsclose_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 --headlessruns the signer with no window (and no display): it is a plain tokio program, deliberately not aGtkApplication.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
Denyimmediately (not after the timeout). Pre-approve with "Allow always" in the GUI, then run headless.get_public_key/ping/get_relaysstay automatic. - CLI pairing is the client-initiated (
nostrconnect://) flow: parse the URI, subscribe to the client's relays (kept inSignerConfig::extra_relays, not inconfig.relays, so they never leak into the bunker URI orget_relays), register the app, then send theconnectresponse whoseresultis the client's secret, p-tagged to the client and signed by the device key. Running--pairis 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 inargvor history. Thebunker://query is percent-encoded withurl::form_urlencoded(I3), so a relay URL cannot smuggle a second query parameter. Client-supplied relays arewss://only and at mostMAX_CLIENT_RELAYS(5), and a literal IP that is not globally routable is refused — aws://or169.254.x/loopback relay would otherwise turn a hostile URI into a local-network probe. TheREGENT_RELAYStest override skips both checks (as it already lets a test point the signer atws://127.0.0.1); the relays that survive are shown in the pairing dialog's Details. - The responder answers
connectwith"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 thebunker://config.uri) are sharedArc<Mutex<String>>s; a successful new pairing — the responder'sconnectarm afterapprove, andpair_clientaftercomplete_pairing— callsrotate_secret, which mints a fresh 96-bit secret and rebuilds the URI. So a copied/shoulder-surfedbunker://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()infrom_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 nameorg.kosmos.raucao.Regent, soNameHasOwneris 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'sstartuphandler) and headless (headless::serve) therefore take an unconditional exclusiveflockonregent.lock(mode 0600) throughinstance::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 instartup, which GLib emits only for the primary instance, so a secondary forwarding anostrconnect://link still reaches the primary; a refused instance also short-circuitsactivate/open, becausequit()alone does not stop them being emitted. The kernel drops the lock on exit, so it cannot go stale. - Errors are loud:
--headless/--pairprint 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 viatake(4097)into aZeroizingbuffer, and never logged. Without it a locked vault simply denies the sensitive methods.--pairneeds 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 serializedApproverqueue (Approver::ask_pairing; L4). On allow, the client's relays are added to the running signer andsigner::pair_clientregisters + answers. If the signer is stopped, it is started with the client's relays first. TheSignerRunnerhas aStopped | Starting | Runningstate 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_errortherefore falls back toWindows::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'snostrconnect://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 inpair_now; the bunker-URI direction has no code path in the dialog at all — the client connects from outside — soConnectDialogsnapshots the current identity's app count onpresent()and closes when the registry grows past it (thechangespingrecord()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_relaysmirrorsstart: add withverify_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 plusconfig.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 sendsconnectimmediately, which a new client cannot do without the bunker secret.- Known limitation: a manual stop/start drops the client's relays
(
extra_relaysare per-run). Spec-compliant clients recover viaswitch_relays; others need re-pairing. Persisting per-app relays inapps.jsonis 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
.servicefile +DBusActivatable).
Verified API traps (do not rediscover these)
Numbering is global across the three
Verified API trapslists (here,src/signer/AGENTS.md,src/ui/AGENTS.md); only the traps relevant to this area are listed.
-
The crate is
gtk4but must be aliased:gtk = { package = "gtk4", … }. -
A
matchscrutinee is a temporary scope that lasts to the end of the match, somatch self.cell.borrow().clone() { … None => *self.cell.borrow_mut() = … }panics with "RefCell already borrowed" — theRefis still held. Bind the clone to a local first (let existing = self.cell.borrow().clone();) and match on that. Anifcondition is its own temporary scope, so theif self.cell.borrow().is_none() { *self.cell.borrow_mut() = … }form inWindows::buildis fine. This bitpresent_preferenceson the first click; the acceptance test now activatesapp.preferencestwice over D-Bus for it.