agent_hub_runtime/commands/
settings.rs1use std::process::Command;
2use std::sync::Arc;
3#[cfg(target_os = "macos")]
4use tauri::Manager;
5use tauri::State;
6
7use crate::core::{central_repo, error::AppError, log_sanitize, skill_store::SkillStore};
8
9#[tauri::command]
10pub async fn get_settings(
11 key: String,
12 store: State<'_, Arc<SkillStore>>,
13) -> Result<Option<String>, AppError> {
14 let store = store.inner().clone();
15 tauri::async_runtime::spawn_blocking(move || store.get_setting(&key).map_err(AppError::db))
16 .await?
17}
18
19#[tauri::command]
28pub fn log_startup_event(label: String, elapsed_ms: u64) {
29 let sanitized: String = label.chars().filter(|c| !c.is_control()).take(64).collect();
30 let display = if sanitized.is_empty() {
31 "(empty)".to_string()
32 } else {
33 sanitized
34 };
35 log::info!("frontend startup: {display} {elapsed_ms} ms");
36}
37
38#[tauri::command]
39pub async fn set_settings(
40 app: tauri::AppHandle,
41 key: String,
42 value: String,
43 store: State<'_, Arc<SkillStore>>,
44) -> Result<(), AppError> {
45 if key == crate::core::deployment_preferences::SETTING
46 && !matches!(value.as_str(), "symlink" | "copy")
47 {
48 return Err(AppError::invalid_input("Invalid deployment mode"));
49 }
50 let store = store.inner().clone();
51 let key_for_store = key.clone();
52 let value_for_store = value.clone();
53 tauri::async_runtime::spawn_blocking(move || {
54 store
55 .set_setting(&key_for_store, &value_for_store)
56 .map_err(AppError::db)?;
57 if key_for_store == "backup_auto_enabled" {
58 crate::core::cloud_sync::notify_central_change();
61 }
62 if key_for_store == crate::core::git_auth_source::SETTING_USE_GH {
63 crate::core::git_auth_source::set_preference(Some(&value_for_store));
64 }
65 Ok::<(), AppError>(())
66 })
67 .await??;
68
69 if key == "show_tray_icon" {
70 let enabled = matches!(
71 value.trim().to_ascii_lowercase().as_str(),
72 "true" | "1" | "yes" | "on"
73 );
74 crate::set_tray_icon_enabled(&app, enabled).map_err(AppError::io)?;
75 } else if key == "language" {
76 crate::refresh_tray_menu(&app).map_err(AppError::io)?;
79 }
80 Ok(())
81}
82
83#[cfg(feature = "cloud-sync")]
84#[tauri::command]
85pub fn get_backup_directory() -> String {
86 crate::core::backup_workspace::repo_dir()
87 .to_string_lossy()
88 .to_string()
89}
90
91#[tauri::command]
92pub fn get_skills_directory() -> String {
93 central_repo::skills_dir().to_string_lossy().to_string()
94}
95
96#[tauri::command]
97pub fn get_central_repo_path() -> String {
98 central_repo::base_dir().to_string_lossy().to_string()
99}
100
101#[tauri::command]
102pub fn get_central_repo_path_override() -> Option<String> {
103 central_repo::configured_base_dir().map(|path| path.to_string_lossy().to_string())
104}
105
106#[tauri::command]
108pub fn get_central_repo_pending_path() -> Option<String> {
109 central_repo::pending_base_dir().map(|path| path.to_string_lossy().to_string())
110}
111
112#[tauri::command]
116pub fn get_central_repo_warnings() -> Vec<String> {
117 central_repo::startup_warnings()
118}
119
120#[tauri::command]
121pub async fn set_central_repo_path(path: Option<String>) -> Result<String, AppError> {
122 tauri::async_runtime::spawn_blocking(move || {
123 central_repo::set_base_dir_override(path)
124 .map(|resolved| resolved.to_string_lossy().to_string())
125 .map_err(AppError::io)
126 })
127 .await?
128}
129
130#[tauri::command]
131pub async fn open_central_repo_folder() -> Result<(), AppError> {
132 tauri::async_runtime::spawn_blocking(|| {
133 let repo_path = central_repo::base_dir();
134
135 #[cfg(target_os = "macos")]
136 let mut cmd = Command::new("open");
137 #[cfg(target_os = "windows")]
138 let mut cmd = {
139 let mut c = Command::new("explorer");
140 use std::os::windows::process::CommandExt;
141 c.creation_flags(0x08000000); c
143 };
144 #[cfg(target_os = "linux")]
145 let mut cmd = Command::new("xdg-open");
146
147 let status = cmd
148 .arg(&repo_path)
149 .status()
150 .map_err(|e| AppError::io(format!("Failed to open folder: {e}")))?;
151
152 #[cfg(not(target_os = "windows"))]
154 if !status.success() {
155 return Err(AppError::io(format!(
156 "File manager exited with status: {status}"
157 )));
158 }
159
160 let _ = status;
161 Ok(())
162 })
163 .await?
164}
165
166#[derive(serde::Serialize)]
167pub struct DiagnosticInfo {
168 pub app_version: String,
169 pub os: String,
170 pub os_version: String,
171 pub arch: String,
172 pub central_repo_path: String,
173 pub central_repo_path_overridden: bool,
174}
175
176#[tauri::command]
177pub async fn get_diagnostic_info(app: tauri::AppHandle) -> Result<DiagnosticInfo, AppError> {
178 let app_version = app.config().version.clone().unwrap_or_default();
179 tauri::async_runtime::spawn_blocking(move || {
180 let os = std::env::consts::OS.to_string();
181 let arch = std::env::consts::ARCH.to_string();
182 let os_version = detect_os_version();
183 let configured = central_repo::configured_base_dir();
184 let central_repo_path = central_repo::base_dir().to_string_lossy().to_string();
185 Ok(DiagnosticInfo {
186 app_version,
187 os,
188 os_version,
189 arch,
190 central_repo_path,
191 central_repo_path_overridden: configured.is_some(),
192 })
193 })
194 .await?
195}
196
197fn detect_os_version() -> String {
198 #[cfg(target_os = "macos")]
199 {
200 Command::new("sw_vers")
201 .arg("-productVersion")
202 .output()
203 .ok()
204 .and_then(|out| {
205 if out.status.success() {
206 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
207 } else {
208 None
209 }
210 })
211 .filter(|s| !s.is_empty())
212 .unwrap_or_else(|| "unknown".to_string())
213 }
214 #[cfg(target_os = "windows")]
215 {
216 use std::os::windows::process::CommandExt;
217 let mut cmd = Command::new("cmd");
218 cmd.creation_flags(0x08000000); cmd.args(["/C", "ver"])
220 .output()
221 .ok()
222 .and_then(|out| {
223 if out.status.success() {
224 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
225 } else {
226 None
227 }
228 })
229 .filter(|s| !s.is_empty())
230 .unwrap_or_else(|| "unknown".to_string())
231 }
232 #[cfg(target_os = "linux")]
233 {
234 std::fs::read_to_string("/etc/os-release")
235 .ok()
236 .and_then(|content| {
237 for line in content.lines() {
238 if let Some(rest) = line.strip_prefix("PRETTY_NAME=") {
239 return Some(rest.trim().trim_matches('"').to_string());
240 }
241 }
242 None
243 })
244 .filter(|s| !s.is_empty())
245 .unwrap_or_else(|| "unknown".to_string())
246 }
247 #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
248 {
249 "unknown".to_string()
250 }
251}
252
253#[derive(serde::Serialize)]
254pub struct PanicInfo {
255 pub timestamp: String,
256 pub message: String,
257}
258
259#[tauri::command]
260pub async fn check_last_panic() -> Result<Option<PanicInfo>, AppError> {
261 let log_dir = central_repo::log_dir();
262 let panic_path = log_dir.join("last_panic.log");
263 if !panic_path.exists() {
264 return Ok(None);
265 }
266 tauri::async_runtime::spawn_blocking(move || {
267 let metadata = std::fs::metadata(&panic_path).map_err(AppError::io)?;
268 let modified = metadata
269 .modified()
270 .map_err(AppError::io)
271 .unwrap_or(std::time::SystemTime::now());
272 let datetime: chrono::DateTime<chrono::Local> = modified.into();
273 let timestamp = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
274 let content = std::fs::read_to_string(&panic_path).unwrap_or_default();
275 let first_lines: Vec<&str> = content.lines().take(3).collect();
276 let message = log_sanitize::sanitize(&first_lines.join("\n"));
277 Ok(Some(PanicInfo { timestamp, message }))
278 })
279 .await?
280}
281
282#[tauri::command]
283pub async fn clear_last_panic() -> Result<(), AppError> {
284 let log_dir = central_repo::log_dir();
285 let panic_path = log_dir.join("last_panic.log");
286 if panic_path.exists() {
287 std::fs::remove_file(&panic_path).map_err(AppError::io)?;
288 }
289 Ok(())
290}
291
292#[derive(serde::Serialize)]
293pub struct LogExcerpt {
294 pub log_path: String,
295 pub excerpt: String,
296 pub line_count: usize,
297 pub has_warnings: bool,
298}
299
300#[tauri::command]
301pub async fn get_recent_log_excerpt() -> Result<LogExcerpt, AppError> {
302 let log_dir = central_repo::log_dir();
303 tauri::async_runtime::spawn_blocking(move || read_recent_log_excerpt(&log_dir)).await?
304}
305
306fn read_recent_log_excerpt(log_dir: &std::path::Path) -> Result<LogExcerpt, AppError> {
307 let log_path = log_dir.join(format!("{}.log", central_repo::APP_LOG_FILE_STEM));
308 let display_path = log_sanitize::sanitize(&log_path.to_string_lossy());
309 let raw = match std::fs::read(&log_path) {
310 Ok(bytes) => bytes,
311 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
312 Err(error) => return Err(AppError::io(error)),
313 };
314 let raw = String::from_utf8_lossy(&raw);
315
316 let lines: Vec<&str> = raw.lines().collect();
317 let scan_window = 200usize.min(lines.len());
318 let start = lines.len().saturating_sub(scan_window);
319 let window = &lines[start..];
320
321 let alerts: Vec<usize> = window
322 .iter()
323 .enumerate()
324 .filter_map(|(i, line)| {
325 if line.contains(" ERROR ") || line.contains(" WARN ") {
326 Some(i)
327 } else {
328 None
329 }
330 })
331 .collect();
332
333 let excerpt_raw = if alerts.is_empty() {
334 let tail_n = 80usize.min(window.len());
335 window[window.len() - tail_n..].join("\n")
336 } else {
337 let context = 10usize;
338 let mut keep = vec![false; window.len()];
339 for &idx in &alerts {
340 let lo = idx.saturating_sub(context);
341 let hi = (idx + context + 1).min(window.len());
342 keep[lo..hi].fill(true);
343 }
344 let mut out = String::new();
345 let mut last_kept: Option<usize> = None;
346 for (i, line) in window.iter().enumerate() {
347 if keep[i] {
348 if let Some(prev) = last_kept {
349 if i > prev + 1 {
350 out.push_str("... (gap)\n");
351 }
352 }
353 out.push_str(line);
354 out.push('\n');
355 last_kept = Some(i);
356 }
357 }
358 out.trim_end().to_string()
359 };
360
361 let collapsed = collapse_consecutive_repeats(&excerpt_raw);
362 let excerpt = log_sanitize::sanitize(&collapsed);
363 let line_count = excerpt.lines().count();
364
365 Ok(LogExcerpt {
366 log_path: display_path,
367 excerpt,
368 line_count,
369 has_warnings: !alerts.is_empty(),
370 })
371}
372
373fn line_fingerprint(line: &str) -> &str {
376 if line.starts_with('[') {
381 let mut count = 0;
383 for (i, ch) in line.char_indices() {
384 if ch == ']' {
385 count += 1;
386 if count == 2 {
387 return line[i + 1..].trim_start();
388 }
389 }
390 }
391 line
392 } else if let Some(idx) = line.find(' ') {
393 line[idx + 1..].trim_start()
394 } else {
395 line
396 }
397}
398
399fn collapse_consecutive_repeats(text: &str) -> String {
400 let lines: Vec<&str> = text.lines().collect();
401 if lines.is_empty() {
402 return String::new();
403 }
404 let mut out: Vec<String> = Vec::with_capacity(lines.len());
405 let mut i = 0;
406 while i < lines.len() {
407 let key = line_fingerprint(lines[i]);
408 let mut j = i + 1;
409 while j < lines.len() && line_fingerprint(lines[j]) == key {
410 j += 1;
411 }
412 let count = j - i;
413 out.push(lines[i].to_string());
414 if count >= 3 {
415 out.push(format!(
416 "... (line above repeated {} more times)",
417 count - 1
418 ));
419 } else if count == 2 {
420 out.push(lines[i + 1].to_string());
421 }
422 i = j;
423 }
424 out.join("\n")
425}
426
427#[derive(serde::Serialize)]
428pub struct LogExportResult {
429 pub zip_path: String,
430 pub file_count: usize,
431}
432
433#[tauri::command]
434pub async fn export_logs_zip(
435 app: tauri::AppHandle,
436 store: State<'_, Arc<SkillStore>>,
437) -> Result<LogExportResult, AppError> {
438 use std::io::{Read, Write};
439
440 let log_dir = central_repo::log_dir();
441 let app_name = app.package_info().name.clone();
442 let app_version = app.config().version.clone().unwrap_or_default();
443 let central_path = central_repo::base_dir().to_string_lossy().to_string();
444 let central_overridden = central_repo::configured_base_dir().is_some();
445 let os = std::env::consts::OS.to_string();
446 let arch = std::env::consts::ARCH.to_string();
447 let os_version = detect_os_version();
448 let store = store.inner().clone();
449
450 tauri::async_runtime::spawn_blocking(move || {
451 let downloads = dirs::download_dir()
452 .or_else(dirs::home_dir)
453 .ok_or_else(|| AppError::io("Failed to resolve Downloads directory"))?;
454 std::fs::create_dir_all(&downloads).map_err(AppError::io)?;
455
456 let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
457 let zip_path = downloads.join(format!("{app_name}-log-{timestamp}.zip"));
458
459 let mut log_files: Vec<std::path::PathBuf> = Vec::new();
460 if log_dir.exists() {
461 if let Ok(entries) = std::fs::read_dir(&log_dir) {
462 let mut all: Vec<(std::path::PathBuf, std::time::SystemTime)> = entries
463 .filter_map(|e| e.ok())
464 .filter(|e| e.path().extension().map(|x| x == "log").unwrap_or(false))
465 .filter(|e| e.file_name().to_string_lossy() != "last_panic.log")
466 .filter_map(|e| {
467 e.metadata()
468 .and_then(|m| m.modified())
469 .ok()
470 .map(|t| (e.path(), t))
471 })
472 .collect();
473 all.sort_by_key(|a| std::cmp::Reverse(a.1));
474 for (path, _) in all.into_iter().take(3) {
475 log_files.push(path);
476 }
477 }
478 }
479 let panic_path = log_dir.join("last_panic.log");
480
481 let audit_entries = store.list_audit(None).unwrap_or_default();
486 let mut audit_jsonl = String::with_capacity(audit_entries.len() * 96);
487 for entry in &audit_entries {
488 let mut sanitized = entry.clone();
489 sanitized.skill_name = sanitized.skill_name.as_deref().map(log_sanitize::sanitize);
490 sanitized.detail = sanitized.detail.as_deref().map(log_sanitize::sanitize);
491 if let Ok(line) = serde_json::to_string(&sanitized) {
492 audit_jsonl.push_str(&line);
493 audit_jsonl.push('\n');
494 }
495 }
496
497 let diagnostics = format!(
498 "# 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",
499 ts = chrono::Local::now().to_rfc3339(),
500 ver = app_version,
501 os = os,
502 osver = os_version,
503 arch = arch,
504 repo = log_sanitize::sanitize(¢ral_path),
505 custom = if central_overridden { " (custom path)" } else { "" },
506 count = log_files.len() + if panic_path.exists() { 1 } else { 0 },
507 audit = audit_entries.len(),
508 );
509
510 let file = std::fs::File::create(&zip_path).map_err(AppError::io)?;
511 let mut zip = zip::ZipWriter::new(file);
512 let opts: zip::write::FileOptions<()> = zip::write::FileOptions::default()
513 .compression_method(zip::CompressionMethod::Deflated)
514 .unix_permissions(0o644);
515
516 zip.start_file("diagnostics.md", opts)
517 .map_err(|e| AppError::io(e.to_string()))?;
518 zip.write_all(diagnostics.as_bytes()).map_err(AppError::io)?;
519
520 let mut included = 0usize;
521 for path in &log_files {
522 if let Ok(mut f) = std::fs::File::open(path) {
523 let mut content = String::new();
524 if f.read_to_string(&mut content).is_ok() {
525 let collapsed = collapse_consecutive_repeats(&content);
526 let sanitized = log_sanitize::sanitize(&collapsed);
527 let name = path
528 .file_name()
529 .map(|n| n.to_string_lossy().into_owned())
530 .unwrap_or_else(|| "log.txt".into());
531 zip.start_file(name, opts)
532 .map_err(|e| AppError::io(e.to_string()))?;
533 zip.write_all(sanitized.as_bytes()).map_err(AppError::io)?;
534 included += 1;
535 }
536 }
537 }
538
539 if panic_path.exists() {
540 if let Ok(content) = std::fs::read_to_string(&panic_path) {
541 let sanitized = log_sanitize::sanitize(&content);
542 zip.start_file("last_panic.log", opts)
543 .map_err(|e| AppError::io(e.to_string()))?;
544 zip.write_all(sanitized.as_bytes()).map_err(AppError::io)?;
545 included += 1;
546 }
547 }
548
549 if !audit_jsonl.is_empty() {
550 zip.start_file("audit.jsonl", opts)
551 .map_err(|e| AppError::io(e.to_string()))?;
552 zip.write_all(audit_jsonl.as_bytes())
553 .map_err(AppError::io)?;
554 }
555
556 zip.finish().map_err(|e| AppError::io(e.to_string()))?;
557
558 reveal_in_file_manager(&zip_path);
559
560 Ok(LogExportResult {
561 zip_path: zip_path.to_string_lossy().to_string(),
562 file_count: included,
563 })
564 })
565 .await?
566}
567
568fn reveal_in_file_manager(path: &std::path::Path) {
569 #[cfg(target_os = "macos")]
570 {
571 let _ = Command::new("open").arg("-R").arg(path).status();
572 }
573 #[cfg(target_os = "windows")]
574 {
575 use std::os::windows::process::CommandExt;
576 let mut cmd = Command::new("explorer");
577 cmd.creation_flags(0x08000000);
578 let arg = format!("/select,{}", path.display());
579 let _ = cmd.arg(arg).status();
580 }
581 #[cfg(target_os = "linux")]
582 {
583 if let Some(parent) = path.parent() {
584 let _ = Command::new("xdg-open").arg(parent).status();
585 }
586 }
587}
588
589#[cfg(test)]
590mod tests;
591
592#[tauri::command]
593pub async fn app_exit(app: tauri::AppHandle) -> Result<(), AppError> {
594 crate::desktop::workspaces::request_quit(&app)
595}
596
597#[tauri::command]
604pub async fn restart_app(app: tauri::AppHandle) {
605 let app_for_main = app.clone();
606 if let Err(err) = app.run_on_main_thread(move || crate::restart_app(&app_for_main)) {
607 log::error!("Failed to schedule restart_app on main thread: {err}");
608 crate::restart_app(&app);
609 }
610}
611
612#[tauri::command]
621pub async fn update_install_blocker() -> Result<Option<String>, AppError> {
622 if !cfg!(target_os = "macos") {
625 return Ok(None);
626 }
627 tauri::async_runtime::spawn_blocking(|| {
628 let exe = std::env::current_exe().map_err(|e| AppError::io(e.to_string()))?;
629 if exe
633 .components()
634 .any(|c| c.as_os_str() == "AppTranslocation")
635 {
636 return Ok(Some("relocate".to_string()));
637 }
638 let Some(parent) = exe.ancestors().nth(4) else {
641 return Ok(None);
642 };
643 match tempfile::Builder::new()
644 .prefix(".agent-hub-update-probe")
645 .tempfile_in(parent)
646 {
647 Ok(_) => Ok(None),
648 Err(e) if e.raw_os_error() == Some(30) => Ok(Some("relocate".to_string())),
651 Err(_) => Ok(None),
653 }
654 })
655 .await?
656}
657
658#[tauri::command]
659pub async fn hide_to_tray(
660 app: tauri::AppHandle,
661 window: tauri::Window,
662 store: State<'_, Arc<SkillStore>>,
663) -> Result<(), AppError> {
664 let show_tray_icon = {
665 let store = store.inner().clone();
666 tauri::async_runtime::spawn_blocking(move || {
667 let value = store.get_setting("show_tray_icon").map_err(AppError::db)?;
668 Ok::<bool, AppError>(!matches!(
669 value.as_deref().map(str::trim).map(str::to_ascii_lowercase),
670 Some(v) if matches!(v.as_str(), "false" | "0" | "no" | "off")
671 ))
672 })
673 .await??
674 };
675
676 if !show_tray_icon {
677 return Err(AppError::io(
678 "Enable the tray icon before hiding the window",
679 ));
680 }
681
682 window.hide().map_err(|e| AppError::io(e.to_string()))?;
683 #[cfg(target_os = "macos")]
686 if !app
687 .windows()
688 .values()
689 .any(|candidate| candidate.is_visible().unwrap_or(false))
690 {
691 app.set_dock_visibility(false)
692 .map_err(|e| AppError::io(format!("Failed to hide Dock icon on macOS: {e}")))?;
693 app.set_activation_policy(tauri::ActivationPolicy::Accessory)
694 .map_err(|e| {
695 AppError::io(format!("Failed to set activation policy to Accessory: {e}"))
696 })?;
697 }
698 #[cfg(not(target_os = "macos"))]
699 let _ = app;
700 Ok(())
701}