agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
use std::process::Command;
use std::sync::Arc;
#[cfg(target_os = "macos")]
use tauri::Manager;
use tauri::State;

use crate::core::{central_repo, error::AppError, log_sanitize, skill_store::SkillStore};

#[tauri::command]
pub async fn get_settings(
    key: String,
    store: State<'_, Arc<SkillStore>>,
) -> Result<Option<String>, AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || store.get_setting(&key).map_err(AppError::db))
        .await?
}

/// Diagnostic-only: let the frontend write a named startup event with elapsed
/// milliseconds into the backend log file. Used to correlate WebView2 boot,
/// first paint, and refreshAppData timing with Rust-side startup logs when
/// debugging slow launches (see issue #153).
///
/// `label` is sanitized (control chars stripped, capped at 64 chars) so a
/// buggy or malicious caller cannot inject newlines that would corrupt the
/// log file layout.
#[tauri::command]
pub fn log_startup_event(label: String, elapsed_ms: u64) {
    let sanitized: String = label.chars().filter(|c| !c.is_control()).take(64).collect();
    let display = if sanitized.is_empty() {
        "(empty)".to_string()
    } else {
        sanitized
    };
    log::info!("frontend startup: {display} {elapsed_ms} ms");
}

#[tauri::command]
pub async fn set_settings(
    app: tauri::AppHandle,
    key: String,
    value: String,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    if key == crate::core::deployment_preferences::SETTING
        && !matches!(value.as_str(), "symlink" | "copy")
    {
        return Err(AppError::invalid_input("Invalid deployment mode"));
    }
    let store = store.inner().clone();
    let key_for_store = key.clone();
    let value_for_store = value.clone();
    tauri::async_runtime::spawn_blocking(move || {
        store
            .set_setting(&key_for_store, &value_for_store)
            .map_err(AppError::db)?;
        if key_for_store == "backup_auto_enabled" {
            // A disabled startup round may have consumed the pending flag.
            // Re-arm when the preference changes so enabling needs no file edit.
            crate::core::cloud_sync::notify_central_change();
        }
        if key_for_store == crate::core::git_auth_source::SETTING_USE_GH {
            crate::core::git_auth_source::set_preference(Some(&value_for_store));
        }
        Ok::<(), AppError>(())
    })
    .await??;

    if key == "show_tray_icon" {
        let enabled = matches!(
            value.trim().to_ascii_lowercase().as_str(),
            "true" | "1" | "yes" | "on"
        );
        crate::set_tray_icon_enabled(&app, enabled).map_err(AppError::io)?;
    } else if key == "language" {
        // The tray menu is built by Rust and reads the persisted language;
        // rebuild it immediately after the frontend changes locale.
        crate::refresh_tray_menu(&app).map_err(AppError::io)?;
    }
    Ok(())
}

#[cfg(feature = "cloud-sync")]
#[tauri::command]
pub fn get_backup_directory() -> String {
    crate::core::backup_workspace::repo_dir()
        .to_string_lossy()
        .to_string()
}

#[tauri::command]
pub fn get_skills_directory() -> String {
    central_repo::skills_dir().to_string_lossy().to_string()
}

#[tauri::command]
pub fn get_central_repo_path() -> String {
    central_repo::base_dir().to_string_lossy().to_string()
}

#[tauri::command]
pub fn get_central_repo_path_override() -> Option<String> {
    central_repo::configured_base_dir().map(|path| path.to_string_lossy().to_string())
}

/// Where a saved path change will move the library at the next launch.
#[tauri::command]
pub fn get_central_repo_pending_path() -> Option<String> {
    central_repo::pending_base_dir().map(|path| path.to_string_lossy().to_string())
}

/// Warning codes recorded while resolving the central repository at startup
/// (e.g. unreadable config, invalid configured path). Non-empty means the app
/// fell back to the default location and the user should be told (#228).
#[tauri::command]
pub fn get_central_repo_warnings() -> Vec<String> {
    central_repo::startup_warnings()
}

#[tauri::command]
pub async fn set_central_repo_path(path: Option<String>) -> Result<String, AppError> {
    tauri::async_runtime::spawn_blocking(move || {
        central_repo::set_base_dir_override(path)
            .map(|resolved| resolved.to_string_lossy().to_string())
            .map_err(AppError::io)
    })
    .await?
}

#[tauri::command]
pub async fn open_central_repo_folder() -> Result<(), AppError> {
    tauri::async_runtime::spawn_blocking(|| {
        let repo_path = central_repo::base_dir();

        #[cfg(target_os = "macos")]
        let mut cmd = Command::new("open");
        #[cfg(target_os = "windows")]
        let mut cmd = {
            let mut c = Command::new("explorer");
            use std::os::windows::process::CommandExt;
            c.creation_flags(0x08000000); // CREATE_NO_WINDOW
            c
        };
        #[cfg(target_os = "linux")]
        let mut cmd = Command::new("xdg-open");

        let status = cmd
            .arg(&repo_path)
            .status()
            .map_err(|e| AppError::io(format!("Failed to open folder: {e}")))?;

        // Windows explorer.exe returns exit code 1 even on success
        #[cfg(not(target_os = "windows"))]
        if !status.success() {
            return Err(AppError::io(format!(
                "File manager exited with status: {status}"
            )));
        }

        let _ = status;
        Ok(())
    })
    .await?
}

#[derive(serde::Serialize)]
pub struct DiagnosticInfo {
    pub app_version: String,
    pub os: String,
    pub os_version: String,
    pub arch: String,
    pub central_repo_path: String,
    pub central_repo_path_overridden: bool,
}

#[tauri::command]
pub async fn get_diagnostic_info(app: tauri::AppHandle) -> Result<DiagnosticInfo, AppError> {
    let app_version = app.config().version.clone().unwrap_or_default();
    tauri::async_runtime::spawn_blocking(move || {
        let os = std::env::consts::OS.to_string();
        let arch = std::env::consts::ARCH.to_string();
        let os_version = detect_os_version();
        let configured = central_repo::configured_base_dir();
        let central_repo_path = central_repo::base_dir().to_string_lossy().to_string();
        Ok(DiagnosticInfo {
            app_version,
            os,
            os_version,
            arch,
            central_repo_path,
            central_repo_path_overridden: configured.is_some(),
        })
    })
    .await?
}

fn detect_os_version() -> String {
    #[cfg(target_os = "macos")]
    {
        Command::new("sw_vers")
            .arg("-productVersion")
            .output()
            .ok()
            .and_then(|out| {
                if out.status.success() {
                    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
                } else {
                    None
                }
            })
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "unknown".to_string())
    }
    #[cfg(target_os = "windows")]
    {
        use std::os::windows::process::CommandExt;
        let mut cmd = Command::new("cmd");
        cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
        cmd.args(["/C", "ver"])
            .output()
            .ok()
            .and_then(|out| {
                if out.status.success() {
                    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
                } else {
                    None
                }
            })
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "unknown".to_string())
    }
    #[cfg(target_os = "linux")]
    {
        std::fs::read_to_string("/etc/os-release")
            .ok()
            .and_then(|content| {
                for line in content.lines() {
                    if let Some(rest) = line.strip_prefix("PRETTY_NAME=") {
                        return Some(rest.trim().trim_matches('"').to_string());
                    }
                }
                None
            })
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "unknown".to_string())
    }
    #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
    {
        "unknown".to_string()
    }
}

#[derive(serde::Serialize)]
pub struct PanicInfo {
    pub timestamp: String,
    pub message: String,
}

#[tauri::command]
pub async fn check_last_panic() -> Result<Option<PanicInfo>, AppError> {
    let log_dir = central_repo::log_dir();
    let panic_path = log_dir.join("last_panic.log");
    if !panic_path.exists() {
        return Ok(None);
    }
    tauri::async_runtime::spawn_blocking(move || {
        let metadata = std::fs::metadata(&panic_path).map_err(AppError::io)?;
        let modified = metadata
            .modified()
            .map_err(AppError::io)
            .unwrap_or(std::time::SystemTime::now());
        let datetime: chrono::DateTime<chrono::Local> = modified.into();
        let timestamp = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
        let content = std::fs::read_to_string(&panic_path).unwrap_or_default();
        let first_lines: Vec<&str> = content.lines().take(3).collect();
        let message = log_sanitize::sanitize(&first_lines.join("\n"));
        Ok(Some(PanicInfo { timestamp, message }))
    })
    .await?
}

#[tauri::command]
pub async fn clear_last_panic() -> Result<(), AppError> {
    let log_dir = central_repo::log_dir();
    let panic_path = log_dir.join("last_panic.log");
    if panic_path.exists() {
        std::fs::remove_file(&panic_path).map_err(AppError::io)?;
    }
    Ok(())
}

#[derive(serde::Serialize)]
pub struct LogExcerpt {
    pub log_path: String,
    pub excerpt: String,
    pub line_count: usize,
    pub has_warnings: bool,
}

#[tauri::command]
pub async fn get_recent_log_excerpt() -> Result<LogExcerpt, AppError> {
    let log_dir = central_repo::log_dir();
    tauri::async_runtime::spawn_blocking(move || read_recent_log_excerpt(&log_dir)).await?
}

fn read_recent_log_excerpt(log_dir: &std::path::Path) -> Result<LogExcerpt, AppError> {
    let log_path = log_dir.join(format!("{}.log", central_repo::APP_LOG_FILE_STEM));
    let display_path = log_sanitize::sanitize(&log_path.to_string_lossy());
    let raw = match std::fs::read(&log_path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
        Err(error) => return Err(AppError::io(error)),
    };
    let raw = String::from_utf8_lossy(&raw);

    let lines: Vec<&str> = raw.lines().collect();
    let scan_window = 200usize.min(lines.len());
    let start = lines.len().saturating_sub(scan_window);
    let window = &lines[start..];

    let alerts: Vec<usize> = window
        .iter()
        .enumerate()
        .filter_map(|(i, line)| {
            if line.contains(" ERROR ") || line.contains(" WARN ") {
                Some(i)
            } else {
                None
            }
        })
        .collect();

    let excerpt_raw = if alerts.is_empty() {
        let tail_n = 80usize.min(window.len());
        window[window.len() - tail_n..].join("\n")
    } else {
        let context = 10usize;
        let mut keep = vec![false; window.len()];
        for &idx in &alerts {
            let lo = idx.saturating_sub(context);
            let hi = (idx + context + 1).min(window.len());
            keep[lo..hi].fill(true);
        }
        let mut out = String::new();
        let mut last_kept: Option<usize> = None;
        for (i, line) in window.iter().enumerate() {
            if keep[i] {
                if let Some(prev) = last_kept {
                    if i > prev + 1 {
                        out.push_str("... (gap)\n");
                    }
                }
                out.push_str(line);
                out.push('\n');
                last_kept = Some(i);
            }
        }
        out.trim_end().to_string()
    };

    let collapsed = collapse_consecutive_repeats(&excerpt_raw);
    let excerpt = log_sanitize::sanitize(&collapsed);
    let line_count = excerpt.lines().count();

    Ok(LogExcerpt {
        log_path: display_path,
        excerpt,
        line_count,
        has_warnings: !alerts.is_empty(),
    })
}

/// Strip the leading timestamp so two log lines that differ only in time
/// produce identical fingerprints (used to detect repeated noise).
fn line_fingerprint(line: &str) -> &str {
    // New format: `2026-05-17T17:56:13.845+10:00 INFO  [app_lib] msg`
    //   → take everything starting at `INFO`/`WARN`/... (after the first space)
    // Old format: `[2026-03-22][04:20:02][app_lib][INFO] msg`
    //   → take everything after the second `]` (skips date+time, keeps module+level+msg)
    if line.starts_with('[') {
        // skip first two bracketed groups (date, time)
        let mut count = 0;
        for (i, ch) in line.char_indices() {
            if ch == ']' {
                count += 1;
                if count == 2 {
                    return line[i + 1..].trim_start();
                }
            }
        }
        line
    } else if let Some(idx) = line.find(' ') {
        line[idx + 1..].trim_start()
    } else {
        line
    }
}

fn collapse_consecutive_repeats(text: &str) -> String {
    let lines: Vec<&str> = text.lines().collect();
    if lines.is_empty() {
        return String::new();
    }
    let mut out: Vec<String> = Vec::with_capacity(lines.len());
    let mut i = 0;
    while i < lines.len() {
        let key = line_fingerprint(lines[i]);
        let mut j = i + 1;
        while j < lines.len() && line_fingerprint(lines[j]) == key {
            j += 1;
        }
        let count = j - i;
        out.push(lines[i].to_string());
        if count >= 3 {
            out.push(format!(
                "... (line above repeated {} more times)",
                count - 1
            ));
        } else if count == 2 {
            out.push(lines[i + 1].to_string());
        }
        i = j;
    }
    out.join("\n")
}

#[derive(serde::Serialize)]
pub struct LogExportResult {
    pub zip_path: String,
    pub file_count: usize,
}

#[tauri::command]
pub async fn export_logs_zip(
    app: tauri::AppHandle,
    store: State<'_, Arc<SkillStore>>,
) -> Result<LogExportResult, AppError> {
    use std::io::{Read, Write};

    let log_dir = central_repo::log_dir();
    let app_name = app.package_info().name.clone();
    let app_version = app.config().version.clone().unwrap_or_default();
    let central_path = central_repo::base_dir().to_string_lossy().to_string();
    let central_overridden = central_repo::configured_base_dir().is_some();
    let os = std::env::consts::OS.to_string();
    let arch = std::env::consts::ARCH.to_string();
    let os_version = detect_os_version();
    let store = store.inner().clone();

    tauri::async_runtime::spawn_blocking(move || {
        let downloads = dirs::download_dir()
            .or_else(dirs::home_dir)
            .ok_or_else(|| AppError::io("Failed to resolve Downloads directory"))?;
        std::fs::create_dir_all(&downloads).map_err(AppError::io)?;

        let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
        let zip_path = downloads.join(format!("{app_name}-log-{timestamp}.zip"));

        let mut log_files: Vec<std::path::PathBuf> = Vec::new();
        if log_dir.exists() {
            if let Ok(entries) = std::fs::read_dir(&log_dir) {
                let mut all: Vec<(std::path::PathBuf, std::time::SystemTime)> = entries
                    .filter_map(|e| e.ok())
                    .filter(|e| e.path().extension().map(|x| x == "log").unwrap_or(false))
                    .filter(|e| e.file_name().to_string_lossy() != "last_panic.log")
                    .filter_map(|e| {
                        e.metadata()
                            .and_then(|m| m.modified())
                            .ok()
                            .map(|t| (e.path(), t))
                    })
                    .collect();
                all.sort_by_key(|a| std::cmp::Reverse(a.1));
                for (path, _) in all.into_iter().take(3) {
                    log_files.push(path);
                }
            }
        }
        let panic_path = log_dir.join("last_panic.log");

        // Serialize the audit log to JSONL ahead of writing the zip so we can
        // report the entry count in diagnostics.md. String fields go through
        // log_sanitize so credentialed URLs / home paths captured in failure
        // details do not leak when the user attaches the zip to a public issue.
        let audit_entries = store.list_audit(None).unwrap_or_default();
        let mut audit_jsonl = String::with_capacity(audit_entries.len() * 96);
        for entry in &audit_entries {
            let mut sanitized = entry.clone();
            sanitized.skill_name = sanitized.skill_name.as_deref().map(log_sanitize::sanitize);
            sanitized.detail = sanitized.detail.as_deref().map(log_sanitize::sanitize);
            if let Ok(line) = serde_json::to_string(&sanitized) {
                audit_jsonl.push_str(&line);
                audit_jsonl.push('\n');
            }
        }

        let diagnostics = format!(
            "# Diagnostics\n\nExported: {ts}\n\n- App version: `{ver}`\n- OS: `{os} {osver} ({arch})`\n- Central repo: `{repo}`{custom}\n- Log files included: {count}\n- Audit entries included: {audit}\n",
            ts = chrono::Local::now().to_rfc3339(),
            ver = app_version,
            os = os,
            osver = os_version,
            arch = arch,
            repo = log_sanitize::sanitize(&central_path),
            custom = if central_overridden { " (custom path)" } else { "" },
            count = log_files.len() + if panic_path.exists() { 1 } else { 0 },
            audit = audit_entries.len(),
        );

        let file = std::fs::File::create(&zip_path).map_err(AppError::io)?;
        let mut zip = zip::ZipWriter::new(file);
        let opts: zip::write::FileOptions<()> = zip::write::FileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated)
            .unix_permissions(0o644);

        zip.start_file("diagnostics.md", opts)
            .map_err(|e| AppError::io(e.to_string()))?;
        zip.write_all(diagnostics.as_bytes()).map_err(AppError::io)?;

        let mut included = 0usize;
        for path in &log_files {
            if let Ok(mut f) = std::fs::File::open(path) {
                let mut content = String::new();
                if f.read_to_string(&mut content).is_ok() {
                    let collapsed = collapse_consecutive_repeats(&content);
                    let sanitized = log_sanitize::sanitize(&collapsed);
                    let name = path
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| "log.txt".into());
                    zip.start_file(name, opts)
                        .map_err(|e| AppError::io(e.to_string()))?;
                    zip.write_all(sanitized.as_bytes()).map_err(AppError::io)?;
                    included += 1;
                }
            }
        }

        if panic_path.exists() {
            if let Ok(content) = std::fs::read_to_string(&panic_path) {
                let sanitized = log_sanitize::sanitize(&content);
                zip.start_file("last_panic.log", opts)
                    .map_err(|e| AppError::io(e.to_string()))?;
                zip.write_all(sanitized.as_bytes()).map_err(AppError::io)?;
                included += 1;
            }
        }

        if !audit_jsonl.is_empty() {
            zip.start_file("audit.jsonl", opts)
                .map_err(|e| AppError::io(e.to_string()))?;
            zip.write_all(audit_jsonl.as_bytes())
                .map_err(AppError::io)?;
        }

        zip.finish().map_err(|e| AppError::io(e.to_string()))?;

        reveal_in_file_manager(&zip_path);

        Ok(LogExportResult {
            zip_path: zip_path.to_string_lossy().to_string(),
            file_count: included,
        })
    })
    .await?
}

fn reveal_in_file_manager(path: &std::path::Path) {
    #[cfg(target_os = "macos")]
    {
        let _ = Command::new("open").arg("-R").arg(path).status();
    }
    #[cfg(target_os = "windows")]
    {
        use std::os::windows::process::CommandExt;
        let mut cmd = Command::new("explorer");
        cmd.creation_flags(0x08000000);
        let arg = format!("/select,{}", path.display());
        let _ = cmd.arg(arg).status();
    }
    #[cfg(target_os = "linux")]
    {
        if let Some(parent) = path.parent() {
            let _ = Command::new("xdg-open").arg(parent).status();
        }
    }
}

#[cfg(test)]
mod tests;

#[tauri::command]
pub async fn app_exit(app: tauri::AppHandle) -> Result<(), AppError> {
    crate::desktop::workspaces::request_quit(&app)
}

/// Relaunch the app so a freshly installed update takes effect. Only ever
/// invoked from an explicit user confirmation — the updater never restarts on
/// its own.
///
/// Scheduled onto the main thread for the same reason `app_exit` is: the
/// teardown destroys the main window before the process goes away.
#[tauri::command]
pub async fn restart_app(app: tauri::AppHandle) {
    let app_for_main = app.clone();
    if let Err(err) = app.run_on_main_thread(move || crate::restart_app(&app_for_main)) {
        log::error!("Failed to schedule restart_app on main thread: {err}");
        crate::restart_app(&app);
    }
}

/// Report why an in-app update cannot be installed from where the app is
/// running right now, or `None` to let the updater proceed.
///
/// Deliberately narrow. A general "is the bundle's parent writable" test would
/// be wrong: a `/Applications` copy owned by a different admin account is not
/// writable by this process either, and there the updater's own privileged
/// prompt succeeds. Only the two states below are beyond its reach, because it
/// replaces the `.app` in place.
#[tauri::command]
pub async fn update_install_blocker() -> Result<Option<String>, AppError> {
    // macOS-specific: elsewhere the updater runs an installer from a temp
    // directory instead of swapping the running bundle.
    if !cfg!(target_os = "macos") {
        return Ok(None);
    }
    tauri::async_runtime::spawn_blocking(|| {
        let exe = std::env::current_exe().map_err(|e| AppError::io(e.to_string()))?;
        // Gatekeeper runs a quarantined copy from a randomized read-only mount
        // that is discarded on quit, so an update written there would vanish
        // rather than apply.
        if exe
            .components()
            .any(|c| c.as_os_str() == "AppTranslocation")
        {
            return Ok(Some("relocate".to_string()));
        }
        // …/Foo.app/Contents/MacOS/foo — the updater swaps the bundle inside
        // its parent directory, so that is what has to accept a write.
        let Some(parent) = exe.ancestors().nth(4) else {
            return Ok(None);
        };
        match tempfile::Builder::new()
            .prefix(".agent-hub-update-probe")
            .tempfile_in(parent)
        {
            Ok(_) => Ok(None),
            // EROFS: still running from a mounted .dmg or another read-only
            // image, which no amount of privilege makes writable.
            Err(e) if e.raw_os_error() == Some(30) => Ok(Some("relocate".to_string())),
            // EACCES and friends: the updater escalates on its own, so let it.
            Err(_) => Ok(None),
        }
    })
    .await?
}

#[tauri::command]
pub async fn hide_to_tray(
    app: tauri::AppHandle,
    window: tauri::Window,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let show_tray_icon = {
        let store = store.inner().clone();
        tauri::async_runtime::spawn_blocking(move || {
            let value = store.get_setting("show_tray_icon").map_err(AppError::db)?;
            Ok::<bool, AppError>(!matches!(
                value.as_deref().map(str::trim).map(str::to_ascii_lowercase),
                Some(v) if matches!(v.as_str(), "false" | "0" | "no" | "off")
            ))
        })
        .await??
    };

    if !show_tray_icon {
        return Err(AppError::io(
            "Enable the tray icon before hiding the window",
        ));
    }

    window.hide().map_err(|e| AppError::io(e.to_string()))?;
    // On macOS, avoid app.hide() (app-level hidden state can block restore in tray flow).
    // Keep app running and hide only the window + Dock icon.
    #[cfg(target_os = "macos")]
    if !app
        .windows()
        .values()
        .any(|candidate| candidate.is_visible().unwrap_or(false))
    {
        app.set_dock_visibility(false)
            .map_err(|e| AppError::io(format!("Failed to hide Dock icon on macOS: {e}")))?;
        app.set_activation_policy(tauri::ActivationPolicy::Accessory)
            .map_err(|e| {
                AppError::io(format!("Failed to set activation policy to Accessory: {e}"))
            })?;
    }
    #[cfg(not(target_os = "macos"))]
    let _ = app;
    Ok(())
}