rightkit-tauri-shell 0.3.0

Shared Tauri desktop shell for Right Suite apps: webview hardening, window state, native menu, tray, single instance, deep links, autostart, rich clipboard, watchdog and engine wiring.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! Tauri commands the frontend bridge (`@rightkit/tauri-shell`) calls. Register them with
//! [`crate::handler!`]. They are application commands, so they need no ACL capability entry.

use std::collections::BTreeMap;
use std::sync::atomic::Ordering;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tauri::{AppHandle, Manager, State, WebviewWindow, Wry};

use crate::clipboard::{Board, ClipboardContent, ClipboardItem};
use crate::tray::TrayUpdate;
use crate::windows::WindowSpec;
use crate::{b64, Module, ShellState};

/// Refuse a command whose module the app opted out of (see [`crate::modules`]).
pub(crate) fn require(state: &ShellState, module: Module) -> Result<(), ShellError> {
    if state.modules.contains(module) {
        Ok(())
    } else {
        Err(ShellError::Unsupported(format!(
            "module {} is disabled for this app",
            module.name()
        )))
    }
}

#[tauri::command]
pub fn rk_shell_open_external(url: String, state: State<'_, ShellState>) -> Result<(), String> {
    crate::opener::open_checked(state.opener.as_ref(), &url)
}

/// The frontend is listening: deliver queued deep links. Returns launch facts.
#[tauri::command]
pub fn rk_shell_ready(app: AppHandle<Wry>, state: State<'_, ShellState>) -> Value {
    state.frontend_ready.store(true, Ordering::SeqCst);
    crate::lifecycle::flush_links(&app);
    #[cfg(feature = "engine")]
    let engine = state.engine.as_ref().map(|e| e.lifecycle());
    #[cfg(not(feature = "engine"))]
    let engine: Option<Value> = None;
    json!({"background": crate::lifecycle::launched_in_background(), "appId": state.app_id, "appName": state.app_name, "engine": engine})
}

/// Diagnostics for tests and support: menu rows, tray, instance role, nav policy.
#[tauri::command]
pub fn rk_shell_status(app: AppHandle<Wry>, state: State<'_, ShellState>) -> Value {
    let tray = app.tray_by_id(crate::tray::TRAY_ID).is_some();
    // Where the OS placed the status item (screen points). Present only once AppKit/the shell
    // gave the item real geometry, which makes this an OS-derived fact, not a registry entry.
    let tray_rect = app
        .tray_by_id(crate::tray::TRAY_ID)
        .and_then(|t| t.rect().ok().flatten())
        .map(|r| {
            let (p, z) = (
                r.position.to_physical::<f64>(1.0),
                r.size.to_physical::<f64>(1.0),
            );
            json!({"x": p.x, "y": p.y, "w": z.width, "h": z.height})
        });
    let menu: Vec<Value> = state
        .menu_rows
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .map(|(p, l)| json!({"path": p, "label": l}))
        .collect();
    #[cfg(any(
        debug_assertions,
        feature = "content-devtools",
        feature = "dev-inspect"
    ))]
    let devtools_open = app
        .get_webview_window(&state.main_label)
        .map(|w| w.is_devtools_open())
        .unwrap_or(false);
    #[cfg(not(any(
        debug_assertions,
        feature = "content-devtools",
        feature = "dev-inspect"
    )))]
    let devtools_open = false;
    let windows: Vec<Value> = app
        .webview_windows()
        .iter()
        .map(|(label, w)| json!({"label": label, "visible": w.is_visible().unwrap_or(false), "title": w.title().unwrap_or_default(), "native": crate::windows::readback(w).map(|native| json!(native)).unwrap_or_else(|e| json!({"error": e}))}))
        .collect();
    let menu_enabled: BTreeMap<String, bool> = state
        .menu_items
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .map(|(id, i)| (id.clone(), i.is_enabled().unwrap_or(false)))
        .collect();
    json!({
        "appId": state.app_id,
        "instance": *state.single_instance.lock().unwrap_or_else(|e| e.into_inner()),
        "tray": tray,
        "trayRect": tray_rect,
        "menu": menu,
        "windows": windows,
        "menuEnabled": menu_enabled,
        "stateDir": state.windows.dir(),
        "devtoolsOpen": devtools_open,
        "streamScheme": state.stream_scheme,
        "streamSchemes": state.stream_schemes,
        "siteScheme": state.site_scheme,
        "modules": state.modules.names(),
        "clipboardDir": state.clipboard_dir,
        "cacheRepair": state.cache_repair.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(p, o)| json!({"dir": p, "outcome": o})),
    })
}

#[tauri::command]
pub fn rk_shell_window(action: String, window: WebviewWindow<Wry>) -> Result<(), String> {
    let r: Result<(), String> = match action.as_str() {
        "minimize" => window.minimize().map_err(|e| e.to_string()),
        "maximize" => window.maximize().map_err(|e| e.to_string()),
        "unmaximize" => window.unmaximize().map_err(|e| e.to_string()),
        "toggle-maximize" => if window.is_maximized().unwrap_or(false) {
            window.unmaximize()
        } else {
            window.maximize()
        }
        .map_err(|e| e.to_string()),
        "fullscreen" => window
            .set_fullscreen(!window.is_fullscreen().unwrap_or(false))
            .map_err(|e| e.to_string()),
        "hide" => {
            let r = window.hide();
            if window.label() == "main" {
                crate::idle::note_hidden(window.app_handle(), false);
            }
            if r.is_ok() && window.label() == window.app_handle().state::<ShellState>().main_label {
                crate::lifecycle::note_visibility(
                    window.app_handle(),
                    crate::lifecycle::Visibility::Hidden,
                );
            }
            r.map_err(|e| e.to_string())
        }
        "show" => {
            // The guard decides: never-show makes this a silent no-op.
            let r = crate::windows::show_window(
                window.app_handle(),
                &window,
                crate::lifecycle::RevealSource::WindowCommand,
                crate::windows::RevealStyle::ShowFocus,
            );
            if window.label() == "main" && matches!(r, Ok(true)) {
                crate::idle::note_visible(window.app_handle());
            }
            r.map(|_| ())
        }
        "close" => window.close().map_err(|e| e.to_string()),
        "start-drag" => window.start_dragging().map_err(|e| e.to_string()),
        other => return Err(format!("unknown window action {other}")),
    };
    r
}

#[tauri::command]
pub fn rk_shell_open_window(spec: WindowSpec, app: AppHandle<Wry>) -> Result<String, String> {
    crate::windows::open(&app, &spec)
}

#[tauri::command]
pub fn rk_shell_set_tray(update: TrayUpdate, app: AppHandle<Wry>) -> Result<(), String> {
    crate::tray::update(&app, &update)
}

#[tauri::command]
pub fn rk_shell_set_menu_item_enabled(
    id: String,
    enabled: bool,
    state: State<'_, ShellState>,
) -> Result<(), String> {
    let items = state.menu_items.lock().unwrap_or_else(|e| e.into_inner());
    items
        .get(&id)
        .ok_or_else(|| format!("no menu item {id}"))?
        .set_enabled(enabled)
        .map_err(|e| e.to_string())
}

/// `enabled = None` reads; `Some(b)` sets and returns the new status.
#[tauri::command]
pub fn rk_shell_autostart(
    enabled: Option<bool>,
    state: State<'_, ShellState>,
) -> Result<crate::autostart::AutostartStatus, String> {
    match enabled {
        Some(on) => crate::autostart::set_enabled(&state.autostart, on),
        None => Ok(crate::autostart::status(&state.autostart)),
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClipboardPayload {
    pub text: Option<String>,
    pub html: Option<String>,
    /// PNG, base64.
    pub png: Option<String>,
    #[serde(default)]
    pub files: Vec<String>,
    /// format name -> base64.
    #[serde(default)]
    pub custom: BTreeMap<String, String>,
    /// Private pasteboard name (macOS); omit for the general clipboard.
    pub board: Option<String>,
}

fn board_of(p: &Option<String>) -> Board {
    p.clone().map(Board::Named).unwrap_or(Board::General)
}

#[tauri::command]
pub fn rk_shell_clipboard_read(
    board: Option<String>,
    state: State<'_, ShellState>,
) -> Result<ClipboardPayload, String> {
    require(&state, Module::Clipboard).map_err(|e| e.to_string())?;
    let c = crate::clipboard::read_with(&board_of(&board), &state.clipboard_options)?;
    Ok(ClipboardPayload {
        text: c.text,
        html: c.html,
        png: c.png.map(|p| b64::encode(&p)),
        files: c.files,
        custom: c
            .custom
            .into_iter()
            .map(|(k, v)| (k, b64::encode(&v)))
            .collect(),
        board,
    })
}

#[tauri::command]
pub fn rk_shell_clipboard_write(
    payload: ClipboardPayload,
    state: State<'_, ShellState>,
) -> Result<(), String> {
    require(&state, Module::Clipboard).map_err(|e| e.to_string())?;
    let mut custom = BTreeMap::new();
    for (k, v) in &payload.custom {
        custom.insert(
            k.clone(),
            b64::decode(v).ok_or_else(|| format!("custom format {k} is not base64"))?,
        );
    }
    let png = match &payload.png {
        Some(s) => Some(b64::decode(s).ok_or("png is not base64")?),
        None => None,
    };
    crate::clipboard::write(
        &board_of(&payload.board),
        &ClipboardContent {
            text: payload.text,
            html: payload.html,
            png,
            files: payload.files,
            custom,
        },
    )
}

/// The typed "open from clipboard" / paste result: files, then a bitmap (written to a granted temp
/// file), then text, then `{"kind":"none"}`. Blocking clipboard work runs off the UI thread.
#[tauri::command]
pub async fn rk_shell_clipboard_item(app: AppHandle<Wry>) -> Result<ClipboardItem, ShellError> {
    blocking(move || {
        let state = app.state::<ShellState>();
        require(&state, Module::Clipboard)?;
        require(&state, Module::Broker)?;
        crate::clipboard::take_item_with(
            &state.broker,
            &state.clipboard_dir,
            state.clipboard,
            &state.clipboard_options,
        )
    })
    .await
}

#[tauri::command]
pub async fn rk_shell_engine_call(
    method: String,
    params: Option<Value>,
    app: AppHandle<Wry>,
) -> Result<Value, String> {
    #[cfg(feature = "engine")]
    {
        // Engine calls block on the sidecar: keep them off the async executor threads.
        tauri::async_runtime::spawn_blocking(move || {
            let state = app.state::<ShellState>();
            let engine = state
                .engine
                .clone()
                .ok_or_else(|| "no engine configured".to_string())?;
            engine
                .call(&app, &method, params.unwrap_or(Value::Null))
                .map_err(|e| format!("{}: {}", e.code, e.message))
        })
        .await
        .map_err(|e| e.to_string())?
    }
    #[cfg(not(feature = "engine"))]
    {
        let _ = (method, params, app);
        Err("engine feature disabled".into())
    }
}

#[tauri::command]
pub fn rk_shell_traffic_lights(
    dx: f64,
    dy: f64,
    window: WebviewWindow<Wry>,
    state: State<'_, ShellState>,
) {
    state.traffic.set_offset(&window, dx, dy);
}

#[tauri::command]
pub fn rk_shell_quit(app: AppHandle<Wry>) {
    crate::lifecycle::quit(&app);
}

/// The renderer finished draining after `rightkit-shell://quit-requested`: mark the app exiting,
/// then exit. The `ExitRequested` this raises sees `exiting` and does not prompt again.
#[tauri::command]
pub fn rk_shell_finish_quit(app: AppHandle<Wry>) {
    crate::lifecycle::finish_quit(&app);
}

/// What the host supports, for the renderer to probe once. Read-only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShellCapabilities {
    /// `rightkit-shell://quit-requested` plus `rk_shell_finish_quit`: the host opted into the drain.
    pub quit_drain: bool,
    /// `rk_shell_notify` honours `bypassDoNotDisturb`.
    pub notify_bypass_dnd: bool,
}

/// The capabilities for a host whose quit drain is `quit_drain`.
pub fn capabilities_for(quit_drain: bool) -> ShellCapabilities {
    ShellCapabilities {
        quit_drain,
        notify_bypass_dnd: true,
    }
}

#[tauri::command]
pub fn rk_shell_capabilities(state: State<'_, ShellState>) -> ShellCapabilities {
    capabilities_for(state.quit.enabled())
}

/// Mirror the app theme into native chrome (window appearance; tray template icons follow it).
#[tauri::command]
pub fn rk_shell_set_theme(theme: String, window: WebviewWindow<Wry>) -> Result<(), String> {
    let t = match theme.as_str() {
        "light" => Some(tauri::Theme::Light),
        "dark" => Some(tauri::Theme::Dark),
        "system" => None,
        other => return Err(format!("unknown theme {other}")),
    };
    window.set_theme(t).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------------------------
// Notifications, presence / DnD, idle, path broker, recovery. These reject with the typed
// `ShellError` envelope (`{code, message}`), unlike the older string-rejecting commands above.
// ---------------------------------------------------------------------------------------------

use crate::error::ShellError;
use crate::notify::{NotificationRequest, NotifyOutcome, NotifyStatus};
use crate::presence::{AutoPrefs, Environment, PresenceState, Rect, WindowObservation};

async fn blocking<T: Send + 'static>(
    f: impl FnOnce() -> Result<T, ShellError> + Send + 'static,
) -> Result<T, ShellError> {
    tauri::async_runtime::spawn_blocking(f)
        .await
        .map_err(|e| ShellError::Other(e.to_string()))?
}

/// Post a native notification. Resolves `{delivered:false, suppressed:"dnd"}` while Do-Not-Disturb
/// (manual or an automatic meeting) is in effect. Runs off the UI thread: the first call may wait on
/// the OS permission prompt.
#[tauri::command]
pub async fn rk_shell_notify(
    request: NotificationRequest,
    app: AppHandle<Wry>,
) -> Result<NotifyOutcome, ShellError> {
    let handle = app.clone();
    let outcome = blocking(move || {
        let state = handle.state::<ShellState>();
        crate::notify::post(
            &request,
            &state.notifications,
            state.presence.effective_dnd(),
        )
    })
    .await?;
    // A frontmost app's banner is suppressed by the OS; ask for the gentler attention cue instead.
    if outcome.delivered {
        let main = app.state::<ShellState>().main_label.clone();
        if let Some(w) = app.get_webview_window(&main) {
            if w.is_focused().unwrap_or(false) {
                let _ = w.request_user_attention(Some(tauri::UserAttentionType::Informational));
            }
        }
    }
    Ok(outcome)
}

/// Authorization plus what the OS reports as delivered to this app (the QA read-back).
#[tauri::command]
pub async fn rk_shell_notify_status(app: AppHandle<Wry>) -> Result<NotifyStatus, ShellError> {
    blocking(move || {
        Ok(crate::notify::status(
            &app.state::<ShellState>().notifications,
        ))
    })
    .await
}

/// Remove delivered notifications by id; `None` or an empty list removes all of this app's.
#[tauri::command]
pub async fn rk_shell_notify_clear(ids: Option<Vec<String>>) -> Result<(), ShellError> {
    blocking(move || crate::notify::clear_delivered(&ids.unwrap_or_default())).await
}

#[tauri::command]
pub fn rk_shell_badge(
    count: i64,
    app: AppHandle<Wry>,
    state: State<'_, ShellState>,
) -> Result<u32, ShellError> {
    let n = state.notifications.set_badge(count);
    if let Some(w) = app.get_webview_window(&state.main_label) {
        w.set_badge_count((n > 0).then_some(i64::from(n)))
            .map_err(|e| ShellError::Other(format!("set badge count: {e}")))?;
    }
    Ok(n)
}

#[tauri::command]
pub fn rk_shell_set_dnd(
    enabled: bool,
    app: AppHandle<Wry>,
    state: State<'_, ShellState>,
) -> PresenceState {
    state.presence.set_manual_dnd(enabled);
    let s = state.presence.snapshot();
    let _ = tauri::Emitter::emit(&app, crate::EVENT_PRESENCE, s);
    s
}

#[tauri::command]
pub fn rk_shell_presence(state: State<'_, ShellState>) -> PresenceState {
    state.presence.snapshot()
}

/// Opt in or out of the automatic controls. Turning one off clears its stale automatic state.
#[tauri::command]
pub fn rk_shell_presence_prefs(prefs: AutoPrefs, state: State<'_, ShellState>) -> PresenceState {
    state.presence.set_prefs(prefs);
    if !prefs.auto_hide_fullscreen || !prefs.auto_dnd_meetings {
        let cur = state.presence.snapshot();
        state.presence.set_auto(crate::presence::AutoState {
            hidden_for_fullscreen: cur.auto_hidden && prefs.auto_hide_fullscreen,
            dnd_for_meeting: cur.auto_dnd && prefs.auto_dnd_meetings,
        });
    }
    state.presence.snapshot()
}

/// Sample the real OS now: `{environment, windows}` (count of visible windows seen).
#[tauri::command]
pub async fn rk_shell_presence_probe(app: AppHandle<Wry>) -> Result<Value, ShellError> {
    blocking(move || {
        let name = app.state::<ShellState>().app_name.clone();
        let (env, windows) = crate::presence::detect_live(&name).map_err(ShellError::Unsupported)?;
        Ok(json!({"environment": env, "windows": windows, "supported": crate::presence::controls_supported()}))
    })
    .await
}

/// Run the detection policy over an injected observation. With `apply`, the result is reconciled
/// with the current preferences and becomes the automatic state (what the poller would do), so a
/// meeting can be simulated without a real conferencing app.
#[tauri::command]
pub fn rk_shell_presence_evaluate(
    monitor: Rect,
    windows: Vec<WindowObservation>,
    apply: Option<bool>,
    state: State<'_, ShellState>,
) -> Value {
    let env: Environment = crate::presence::detect(monitor, &windows, &state.app_name);
    if apply.unwrap_or(false) {
        state
            .presence
            .apply_observation(crate::presence::reconcile(state.presence.prefs(), env));
    }
    json!({"environment": env, "state": state.presence.snapshot()})
}

#[tauri::command]
pub fn rk_shell_idle_status(app: AppHandle<Wry>) -> crate::idle::IdleStatus {
    crate::idle::status(&app)
}

/// App-driven hide/show of the main window for the idle machine.
#[tauri::command]
pub fn rk_shell_idle_note(hidden: bool, suspend_after_ms: Option<u64>, app: AppHandle<Wry>) {
    if hidden {
        crate::idle::note_hidden_after(
            &app,
            false,
            suspend_after_ms.map(std::time::Duration::from_millis),
        );
    } else {
        crate::idle::note_visible(&app);
    }
}

/// Canonicalise `path` and require a broker grant (`write: true` checks a save target).
#[tauri::command]
pub fn rk_shell_path_require(
    path: String,
    write: Option<bool>,
    state: State<'_, ShellState>,
) -> Result<String, ShellError> {
    require(&state, Module::Broker)?;
    if write.unwrap_or(false) {
        state.broker.require_write_target(&path)
    } else {
        state.broker.require_file(&path)
    }
}

#[tauri::command]
pub fn rk_shell_path_revoke(path: String, state: State<'_, ShellState>) -> Result<(), ShellError> {
    require(&state, Module::Broker)?;
    state.broker.revoke_path(&path)
}

/// Trade a one-shot recent-file id (minted in Rust) for a grant.
#[tauri::command]
pub fn rk_shell_path_grant_recent(
    id: String,
    state: State<'_, ShellState>,
) -> Result<String, ShellError> {
    require(&state, Module::Broker)?;
    state.broker.grant_known(&id)
}

/// Re-grant a save-as target the app just wrote.
#[tauri::command]
pub fn rk_shell_path_regrant_saved(
    path: String,
    state: State<'_, ShellState>,
) -> Result<String, ShellError> {
    require(&state, Module::Broker)?;
    state.broker.regrant_saved_target(&path)
}

/// Mint the stream URL for a granted file. `scheme` picks one of the registered stream schemes
/// (default: the first). Rejects `broker_denied` for anything not granted.
#[tauri::command]
pub fn rk_shell_stream_grant(
    path: String,
    scheme: Option<String>,
    state: State<'_, ShellState>,
) -> Result<Value, ShellError> {
    require(&state, Module::Broker)?;
    require(&state, Module::Stream)?;
    let scheme = match scheme {
        Some(requested) => {
            let requested = requested.to_ascii_lowercase();
            if state.stream_schemes.contains(&requested) {
                requested
            } else {
                return Err(ShellError::Invalid(format!(
                    "stream scheme {requested} is not registered"
                )));
            }
        }
        None => state
            .stream_scheme
            .clone()
            .ok_or_else(|| ShellError::Unsupported("no stream protocol configured".into()))?,
    };
    let id = state.broker.grant_stream(&path)?;
    let url = if cfg!(windows) {
        format!("http://{scheme}.localhost/{id}")
    } else {
        format!("{scheme}://localhost/{id}")
    };
    Ok(json!({"id": id, "url": url}))
}

/// Grant the site root of a document the person already opened, and return the base URL the
/// document's `<base href>` uses: `{token, root, baseUrl}`.
#[tauri::command]
pub fn rk_shell_site_grant(
    document: String,
    state: State<'_, ShellState>,
) -> Result<Value, ShellError> {
    require(&state, Module::Broker)?;
    require(&state, Module::Stream)?;
    let scheme = state
        .site_scheme
        .clone()
        .ok_or_else(|| ShellError::Unsupported("no site protocol configured".into()))?;
    let grant = crate::site::grant_document_site(&state.broker, &document, &state.site_policy)?;
    Ok(json!({
        "token": grant.token,
        "root": crate::broker::path_to_string(&grant.root),
        "baseUrl": crate::site::site_base_url(&scheme, &grant.token),
    }))
}

/// Revoke a site-root token when its tab closes. Its URLs stop serving at once and never revive.
#[tauri::command]
pub fn rk_shell_site_revoke(token: String, state: State<'_, ShellState>) -> Result<(), ShellError> {
    require(&state, Module::Broker)?;
    state.broker.revoke_site_root(&token)
}

fn recovery_of(state: &ShellState) -> Result<&crate::recovery::RecoveryStore, ShellError> {
    require(state, Module::Recovery)?;
    require(state, Module::Broker)?;
    state
        .recovery
        .as_ref()
        .ok_or_else(|| ShellError::Unsupported("setup recovery is not configured".into()))
}

#[tauri::command]
pub fn rk_shell_recovery_save(
    snapshot: String,
    state: State<'_, ShellState>,
) -> Result<(), ShellError> {
    recovery_of(&state)?.save(&snapshot, &state.broker)
}

#[tauri::command]
pub fn rk_shell_recovery_load(state: State<'_, ShellState>) -> Result<Option<String>, ShellError> {
    recovery_of(&state)?.load(&state.broker)
}

#[tauri::command]
pub fn rk_shell_recovery_clear(state: State<'_, ShellState>) -> Result<(), ShellError> {
    recovery_of(&state)?.clear()
}