Files
Lumotia/docs/architecture-map/02-tauri-runtime/commands/power-and-security.md
jars a1f3f3f134 docs: architecture map (initial 5-slice generation, 105 pages)
Five-slice navigable map of the entire codebase under
docs/architecture-map/. Each slice is a self-contained
breadcrumbed sub-tree:

  01-frontend (16)              Svelte/SvelteKit UI
  02-tauri-runtime (26)         src-tauri commands + lifecycle
  03-audio-transcription (16)   audio + transcription crates
  04-llm-formatting-mcp (19)    llm, ai-formatting, mcp, cloud
  05-core-storage-hotkey-build  core, storage, hotkey, workspace,
                          (26) CI, dev glue

Plus master README.md and data-flow-end-to-end.md tracing
audio bytes from microphone to FTS5 search to MCP read.

Generated by 5 parallel subagents on 2026/05/09 against
HEAD 3c47000. Each page has YAML frontmatter, file:line code
refs, sibling cross-links, plain-English summaries.

Aggregated debt surfaced (full lists in master README):
RB-08 macOS power assertion, schema head drift v14 vs v15,
VAD blocked on ort version conflict, streaming primitives
not wired into live.rs, no prompt versioning, MCP has no
auth, cloud-providers in-memory keystore, SettingsPage
2 484 LOC, commands/live.rs 1 737 LOC, dual theme system,
brand rename to Lumenote pending across the codebase.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 14:04:13 +01:00

102 lines
6.8 KiB
Markdown

---
name: Power assertions and security helpers
type: architecture-map-page
slice: 02-tauri-runtime
last_verified: 2026/05/09
---
# `commands::power` and `commands::security`
> **Where you are:** [Architecture map](../../README.md) → [Tauri runtime](../README.md) → [Commands](README.md) → Power and security
**Plain English summary.** Two utility modules that the rest of the command files lean on. `power.rs` is the macOS App Nap power-assertion guard (no-op on Linux and Windows today). `security.rs` is `ensure_main_window`, the one-liner defence-in-depth check that several commands stamp at the top to reject calls from secondary windows even if the ACL ever drifted.
## At a glance
- Paths: `src-tauri/src/commands/power.rs` (208 LOC), `src-tauri/src/commands/security.rs` (30 LOC).
- Tauri commands exposed: none. Both are pure Rust utilities.
- Events emitted: none.
- Depends on:
- `power.rs`: macOS only — `objc2::rc::Retained`, `objc2::runtime::ProtocolObject`, `objc2_foundation::{NSActivityOptions, NSObjectProtocol, NSProcessInfo, NSString}`.
- `security.rs`: nothing.
- Called from: every long-running command that wants to keep the OS awake (live transcription, LLM cleanup, content-tag extraction, task decomposition); every command that wants the extra firewall (intentions CRUD, nudges, updater stub, lots of Settings-only commands).
## `commands::power`
### `PowerAssertionSnapshot` (`src-tauri/src/commands/power.rs:28`)
Cloneable snapshot for the diagnostics report: `id, reason, backend, acquired`.
### `PowerAssertion` (`src-tauri/src/commands/power.rs:41`)
A `#[must_use]` guard. Holding it keeps the macOS App Nap pin alive; dropping it ends the assertion. Fields: `id`, `reason`, `backend`, `acquired`, plus a macOS-only `Option<ActivityHandle>`.
### `PowerAssertion::begin(reason)` (`src-tauri/src/commands/power.rs:73`)
Allocates a new id from a `NEXT_ID: AtomicUsize`, calls into `objc_bridge::begin_activity` on macOS, registers a snapshot in the global `assertion_registry()`. Returns the guard. Errors are logged; failure to acquire still returns a "no-op" guard (so the caller's code path is unchanged) with `acquired = false`.
On non-macOS, this is a no-op. The doc comment promises Linux logind inhibitors and Windows `SetThreadExecutionState`, but neither is wired up. See debt note in the slice README.
### `Drop for PowerAssertion` (`src-tauri/src/commands/power.rs:124`)
End the macOS activity if present, remove the registry entry. Logs the end on macOS so the diagnostics bundle has a breadcrumb.
### `assertion_registry()` (`src-tauri/src/commands/power.rs:53`)
Process-global `Mutex<HashMap<usize, PowerAssertionSnapshot>>` using `OnceLock`. `active_assertions_snapshot()` (`:58`) returns a sorted vector of clones for the diagnostic-report bundler.
### `objc_bridge` module (`src-tauri/src/commands/power.rs:140`)
macOS-only. Wraps `NSProcessInfo::processInfo().beginActivityWithOptions_reason(options, reason)` and `endActivity(handle)`. Options: `NSActivityOptions::UserInitiated | NSActivityOptions::LatencyCritical`. The activity object is `Retained<ProtocolObject<dyn NSObjectProtocol>>` and is `unsafe impl Send` (the activity is a process-wide pin and thread-safe).
### Tests (`:168`)
`power_assertion_is_a_no_op_drop` confirms the registry entry is added on `begin` and removed on `drop`. `multiple_assertions_get_unique_ids` confirms the id allocator works.
### Where `PowerAssertion::begin` is called
- `commands::live::run_live_session` (`live.rs:660`) — `"magnotia live dictation session"`.
- `commands::llm::cleanup_transcript_text_cmd` (`llm.rs:394`) — `"magnotia LLM cleanup"`.
- `commands::llm::extract_content_tags_cmd` (`llm.rs:417`) — `"magnotia LLM content-tag extraction"`.
NOT called from `commands::tasks::decompose_and_store` or `commands::tasks::extract_tasks_from_transcript_cmd`, even though both run multi-second LLM inference. Flag for follow-up.
## `commands::security`
### `ensure_main_window(window)` (`src-tauri/src/commands/security.rs:1`)
One-liner: `ensure_main_window_label(window.label())`.
### `ensure_main_window_label(label)` (`src-tauri/src/commands/security.rs:5`)
Returns `Ok(())` when label is `"main"`, `Err("This command is only available from the main window (got <label>).")` otherwise.
### Tests (`:15`)
`accepts_main_window` and `rejects_secondary_windows` (the latter checks `tasks-float`, `transcript-viewer`, and `transcription-preview` are all rejected).
### Where `ensure_main_window` is called
Approximately 30 commands. The Settings flows (model loads, LLM lifecycle, hotkey wiring, intentions CRUD), most of the diagnostics report flows, the transcription / live commands, the windows-builder commands, the audio-capture commands, the prefs save, the updater stubs.
NOT called from: profiles, transcripts, tasks (most), feedback, hardware, meeting, fs, clipboard, hardware, tts, hotkey-status probe, llm-status probe, llm content-tag extraction, get_os_info. Each omission is intentional today (secondary windows need to call them) but document the choice when adding new commands.
## Data flow
Both modules are passive utilities. `PowerAssertion` is RAII: hold it for the duration of the work, drop it (explicitly or by leaving scope) to end the pin. `ensure_main_window` is a synchronous gate at the top of a command body.
## Watch-outs
- **`PowerAssertion` is a no-op on Linux and Windows.** Long sessions on those platforms can be idled. Document this in the user-facing Settings → AI page if you ship without a Linux logind / Windows `SetThreadExecutionState` implementation. The macOS objc2 binding requires `objc2 = "0.6.4"` and `objc2-foundation = "0.3.2"` — bumping them is an ABI move.
- **The registry is process-wide and locked behind a `Mutex`.** Acquiring or releasing an assertion takes the mutex. Acceptable for single-digit assertions per session; if you ever spam-create assertions, this will contend.
- **`ensure_main_window` rejects with a static message containing the offending label.** Include the label so debugging via the frontend toast is obvious; do not log the full window or any secret data.
- **The ACL plus `ensure_main_window` is two layers.** Removing the second layer is "defence-in-depth removal", which the in-repo code review (`docs/code-review-2026-04-22.md`) flags as a non-trivial security regression. Don't.
## See also
- [App lifecycle](../app-lifecycle.md) — the panic hook and runtime warnings live alongside power.
- [Diagnostics](diagnostics.md) — the report bundler reads `active_assertions_snapshot()`.
- [Capabilities and ACL](../capabilities-and-acl.md) — the ACL is the first layer; this is the second.
- [Live](live.md), [LLM](llm.md) — the main consumers of `PowerAssertion`.
- [Tests](../tests.md) — `accepts_main_window` and `rejects_secondary_windows` plus `power_assertion_is_a_no_op_drop`.