From ec6a3a04f39451546e5ce3bebf26f495d2f13cce Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 18:15:36 +0100 Subject: [PATCH] feat(gui): migrate clones from the GUI; diagnostics log and tray restart - Migrate / Migrate all with confirmation, sequential runs, per-repo results - bridge: allow 'add' only for dirs directly under a group - log panics, exit reasons and daemon/tray events to /grove-gui.log - restart the tray service if its D-Bus connection ends Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/grove-core/src/config.rs | 9 +- crates/grove-gui/Cargo.toml | 1 + crates/grove-gui/src/bridge.rs | 121 +++++++++++++++++- crates/grove-gui/src/log.rs | 75 +++++++++++ crates/grove-gui/src/main.rs | 213 ++++++++++++++++++++++++++++++-- crates/grove-gui/src/tray.rs | 15 ++- crates/grove-gui/ui/app.slint | 98 ++++++++++++++- crates/grove/src/workflow.rs | 4 +- docs/phase7.md | 16 +++ 10 files changed, 528 insertions(+), 25 deletions(-) create mode 100644 crates/grove-gui/src/log.rs diff --git a/Cargo.lock b/Cargo.lock index f998eb5..849ddca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2096,6 +2096,7 @@ name = "grove-gui" version = "0.1.0" dependencies = [ "anyhow", + "grove-core", "grove-daemon", "ksni", "serde_json", diff --git a/crates/grove-core/src/config.rs b/crates/grove-core/src/config.rs index 4f7a58b..6178efd 100644 --- a/crates/grove-core/src/config.rs +++ b/crates/grove-core/src/config.rs @@ -515,9 +515,14 @@ mirror_to = ["gitea"] #[test] fn provider_protocol_defaults_to_https_and_is_validated() { let t = |p: &str| { - format!("[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitea\"\n{p}") + format!( + "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitea\"\n{p}" + ) }; - assert_eq!(Config::parse(&t("")).unwrap().providers["p"].protocol, Protocol::Https); + assert_eq!( + Config::parse(&t("")).unwrap().providers["p"].protocol, + Protocol::Https + ); let c = Config::parse(&t("protocol=\"ssh\"\n")).unwrap(); assert_eq!(c.providers["p"].protocol, Protocol::Ssh); assert!(toml::to_string(&c).unwrap().contains("protocol = \"ssh\"")); diff --git a/crates/grove-gui/Cargo.toml b/crates/grove-gui/Cargo.toml index af5d492..8c4d57f 100644 --- a/crates/grove-gui/Cargo.toml +++ b/crates/grove-gui/Cargo.toml @@ -11,6 +11,7 @@ path = "src/main.rs" [dependencies] anyhow = "1.0.104" +grove-core = { version = "0.1.0", path = "../grove-core" } grove-daemon = { version = "0.1.0", path = "../grove-daemon" } # async-io instead of the default tokio: no second async runtime in a small tray app. ksni = { version = "0.3.7", default-features = false, features = ["async-io", "blocking"] } diff --git a/crates/grove-gui/src/bridge.rs b/crates/grove-gui/src/bridge.rs index dc32f9b..8abd278 100644 --- a/crates/grove-gui/src/bridge.rs +++ b/crates/grove-gui/src/bridge.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use std::io::Write; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; /// `grove` subcommands the GUI may run. Everything else is refused. @@ -11,6 +11,7 @@ const ALLOWED: &[&str] = &[ "login", "new", "import", + "add", "config-repo-init", "bootstrap", "resolve", @@ -44,6 +45,11 @@ impl Bridge { if let Err(e) = validate(args) { return json!({"ok": false, "output": format!("rejected: {e}")}); } + if sub == "add" + && let Err(e) = self.check_migrate_args(args) + { + return json!({"ok": false, "output": format!("rejected: {e}")}); + } let mut cmd = Command::new(&self.grove_bin); if let Some(c) = &self.config { cmd.arg("--config").arg(c); @@ -79,6 +85,28 @@ impl Bridge { } } + fn loaded_config(&self) -> Option { + let p = self + .config + .clone() + .or_else(grove_core::config::Config::default_path)?; + grove_core::config::Config::load(&p).ok() + } + + /// `add ` only for an existing directory directly under `//`. + fn check_migrate_args(&self, args: &[String]) -> Result<(), String> { + let [_, path] = args else { + return Err("add takes exactly one path".into()); + }; + let cfg = self.loaded_config().ok_or("no readable configuration")?; + check_migrate_path(&cfg, Path::new(path)).map(|_| ()) + } + + /// Where `grove add` writes its safety backup. + pub fn backup_dir() -> Option { + grove_core::config::Config::state_dir().map(|d| d.join("backups")) + } + /// `config.toml` as JSON (it holds no secrets), or `None` before onboarding. pub fn config_json(&self) -> Option { let p = self.config.clone().or_else(grove_core_default_config)?; @@ -135,6 +163,31 @@ pub fn validate(args: &[String]) -> Result<(), String> { Ok(()) } +/// A clone the GUI may migrate: an existing directory (not a symlink) whose parent is one of the +/// configured group directories. Returns its canonical path. +pub fn check_migrate_path( + cfg: &grove_core::config::Config, + path: &Path, +) -> Result { + let meta = std::fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + if !meta.is_dir() { + return Err(format!("{} is not a directory", path.display())); + } + let canon = path.canonicalize().map_err(|e| e.to_string())?; + let parent = canon.parent().ok_or("path has no parent directory")?; + let root = cfg.root_path(); + let root = root.canonicalize().unwrap_or(root); + if cfg.groups.iter().any(|g| root.join(&g.name) == parent) { + Ok(canon) + } else { + Err(format!( + "{} is not directly inside a group directory under {}", + path.display(), + root.display() + )) + } +} + fn grove_core_default_config() -> Option { let base = std::env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) @@ -160,6 +213,72 @@ mod tests { assert!(v(&["secrets", "pull"]).is_ok()); } + #[test] + fn migrate_path_must_be_a_clone_directly_under_a_group() { + let base = std::env::temp_dir().join(format!("grove-mig-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("work/proj/sub")).unwrap(); + std::fs::create_dir_all(base.join("other/proj")).unwrap(); + std::fs::write(base.join("work/file"), "x").unwrap(); + std::os::unix::fs::symlink(base.join("other/proj"), base.join("work/link")).unwrap(); + let cfg = grove_core::config::Config::parse(&format!( + "[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n[[groups]]\nname=\"work\"\nprimary=\"p\"\n", + base.display() + )) + .unwrap(); + assert!(check_migrate_path(&cfg, &base.join("work/proj")).is_ok()); + for bad in [ + "work/proj/sub", + "other/proj", + "work/file", + "work/link", + "work/none", + "work", + "work/../other/proj", + ] { + assert!(check_migrate_path(&cfg, &base.join(bad)).is_err(), "{bad}"); + } + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn add_runs_only_for_valid_clone_paths() { + use std::os::unix::fs::PermissionsExt; + let base = std::env::temp_dir().join(format!("grove-add-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("work/proj")).unwrap(); + std::fs::create_dir_all(base.join("elsewhere")).unwrap(); + let cfg = base.join("config.toml"); + std::fs::write(&cfg, format!( + "[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n[[groups]]\nname=\"work\"\nprimary=\"p\"\n", + base.display() + )).unwrap(); + // A stand-in `grove` that reports what it was asked to do. + let fake = base.join("grove"); + std::fs::write(&fake, "#!/bin/sh\necho \"migrated: $3/wt\"\n").unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + let b = Bridge { + grove_bin: fake, + config: Some(cfg), + socket: "/nonexistent".into(), + }; + let ok = b.cli( + &["add".into(), base.join("work/proj").display().to_string()], + "", + ); + assert_eq!(ok["ok"], true, "{ok}"); + assert!(ok["output"].as_str().unwrap().starts_with("migrated:")); + let bad = b.cli( + &["add".into(), base.join("elsewhere").display().to_string()], + "", + ); + assert_eq!(bad["ok"], false); + assert!(bad["output"].as_str().unwrap().contains("rejected")); + let flag = b.cli(&["add".into(), "--backup-dir".into(), "/x".into()], ""); + assert_eq!(flag["ok"], false); + let _ = std::fs::remove_dir_all(&base); + } + fn bridge() -> Bridge { Bridge { grove_bin: "/nonexistent/grove".into(), diff --git a/crates/grove-gui/src/log.rs b/crates/grove-gui/src/log.rs new file mode 100644 index 0000000..6a40a73 --- /dev/null +++ b/crates/grove-gui/src/log.rs @@ -0,0 +1,75 @@ +//! A small log file (`/grove-gui.log`) for things that would otherwise vanish when the +//! GUI runs from autostart with stdout/stderr closed: panics, fatal errors and why it exited. + +use std::io::Write; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +static PATH: OnceLock = OnceLock::new(); +/// Set when the process leaves on purpose (tray "Quit", window closed without a tray). +pub static EXPECTED_EXIT: AtomicBool = AtomicBool::new(false); + +const MAX_BYTES: u64 = 256 * 1024; + +/// Opens the log (truncating a file past 256 KiB) and installs the panic hook. +pub fn init() { + let Some(dir) = grove_core::config::Config::state_dir() else { + return; + }; + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("grove-gui.log"); + if std::fs::metadata(&path).is_ok_and(|m| m.len() > MAX_BYTES) { + let _ = std::fs::rename(&path, dir.join("grove-gui.log.old")); + } + let _ = PATH.set(path); + let default = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let t = std::thread::current(); + let bt = std::backtrace::Backtrace::force_capture(); + line(&format!( + "PANIC in thread {:?}: {info}\n{bt}", + t.name().unwrap_or("") + )); + default(info); + })); +} + +/// Appends one timestamped line; never fails and never panics. +pub fn line(msg: &str) { + let Some(p) = PATH.get() else { return }; + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(p) + { + let _ = writeln!(f, "{} [{}] {msg}", stamp(), std::process::id()); + } +} + +pub fn expected_exit() { + EXPECTED_EXIT.store(true, Ordering::SeqCst); +} + +/// `YYYY-MM-DD HH:MM:SSZ` (UTC) from the system clock. +fn stamp() -> String { + let s = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let (days, rem) = (s / 86400, s % 86400); + // Civil-from-days (Howard Hinnant). + let z = days as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!( + "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} diff --git a/crates/grove-gui/src/main.rs b/crates/grove-gui/src/main.rs index e1e1e26..cf64fe0 100644 --- a/crates/grove-gui/src/main.rs +++ b/crates/grove-gui/src/main.rs @@ -7,6 +7,7 @@ mod autostart; mod bridge; mod instance; +mod log; mod model; mod tray; @@ -125,6 +126,10 @@ struct UiState { detail_fp: String, filter: String, pending: Option>, + /// Clones waiting for the migration confirmation, and what happened to each so far. + mig_pending: Option>, + mig: HashMap, + migrating: bool, picks: Rc>, /// Last successful scan per import group, for the session (names still to import). import_cache: HashMap>, @@ -145,6 +150,9 @@ thread_local! { detail_fp: String::new(), filter: String::new(), pending: None, + mig_pending: None, + mig: HashMap::new(), + migrating: false, picks: Rc::new(VecModel::default()), import_cache: HashMap::new(), import_current: String::new(), @@ -224,16 +232,25 @@ fn render(ui: &MainWindow) { ui.set_attention_count(agg.attention as i32); ui.set_has_config(snap.config.is_some()); ui.set_autostart(autostart::config_home().is_some_and(|d| autostart::is_enabled(&d))); - let nm: Vec = snap + let nm: Vec = snap .status .as_ref() .and_then(|s| s["not_migrated"].as_array()) .map(|a| { a.iter() - .filter_map(|p| p.as_str().map(SharedString::from)) + .filter_map(|p| p.as_str()) + .map(|p| { + let (state, msg) = st.mig.get(p).cloned().unwrap_or_default(); + MigRow { + path: p.into(), + state: state.into(), + msg: msg.into(), + } + }) .collect() }) .unwrap_or_default(); + ui.set_migrating(st.migrating); ui.set_not_migrated(ModelRc::from(Rc::new(VecModel::from(nm)))); let empty = Vec::new(); @@ -568,6 +585,91 @@ fn scan(ctx: &Ctx, ui: &MainWindow, group: String, force: bool, note: Option) { + if paths.is_empty() || ST.with(|st| st.borrow().migrating) { + return; + } + let backup = Bridge::backup_dir() + .map(|d| d.display().to_string()) + .unwrap_or_else(|| "grove's state directory".into()); + let what = match paths.as_slice() { + [one] => one.clone(), + many => format!("{} clones", many.len()), + }; + ST.with(|st| st.borrow_mut().mig_pending = Some(paths)); + ui.set_migrate_confirm_text( + format!( + "Migrate {what} to grove's bare + worktrees layout?\n\nA full backup of each clone (a tar archive and a git ref) is taken first, in {backup}. A clone grove cannot migrate safely (linked worktrees, submodules, detached HEAD...) is refused and left untouched." + ) + .into(), + ); +} + +/// Migrates the clones one after the other on a worker thread, reporting each result as it comes. +fn run_migrations(ctx: &Ctx, ui: &MainWindow, paths: Vec) { + ST.with(|st| { + let mut st = st.borrow_mut(); + st.migrating = true; + for p in &paths { + st.mig.remove(p); + } + }); + render(ui); + let (core, weak) = (ctx.core.clone(), ctx.weak.clone()); + std::thread::spawn(move || { + let total = paths.len(); + let (mut done, mut failed) = (0, 0); + for p in paths { + let (w, p1) = (weak.clone(), p.clone()); + let _ = slint::invoke_from_event_loop(move || { + ST.with(|st| { + st.borrow_mut() + .mig + .insert(p1, ("running".into(), String::new())) + }); + if let Some(ui) = w.upgrade() { + render(&ui); + } + }); + let r = core.bridge.cli(&["add".to_string(), p.clone()], ""); + let ok = r["ok"] == true; + let text = r["output"].as_str().unwrap_or("").to_string(); + let msg = if ok { + done += 1; + text.lines() + .find_map(|l| l.strip_prefix("migrated:")) + .map(|m| format!("Migrated to {}", m.trim())) + .unwrap_or_else(|| "Migrated".into()) + } else { + failed += 1; + text.lines().next().unwrap_or("failed").to_string() + }; + let (w, p2) = (weak.clone(), p); + let _ = slint::invoke_from_event_loop(move || { + let state = if ok { "ok" } else { "failed" }; + ST.with(|st| st.borrow_mut().mig.insert(p2, (state.into(), msg))); + if let Some(ui) = w.upgrade() { + render(&ui); + } + }); + } + let w = weak.clone(); + let _ = slint::invoke_from_event_loop(move || { + ST.with(|st| st.borrow_mut().migrating = false); + if let Some(ui) = w.upgrade() { + render(&ui); + toast( + &ui, + &format!("Migration finished: {done} of {total} migrated, {failed} failed"), + failed > 0, + ); + } + }); + core.wake(); // refresh the status + }); +} + fn first_or(v: &str, list: &ModelRc) -> String { if v.is_empty() { list.row_data(0).map(|x| x.to_string()).unwrap_or_default() @@ -736,6 +838,47 @@ fn wire(ui: &MainWindow, ctx: &Ctx) { ui.set_autostart(autostart::config_home().is_some_and(|d| autostart::is_enabled(&d))); } }); + ui.on_migrate_one({ + let w = ui.as_weak(); + move |path| { + if let Some(ui) = w.upgrade() { + ask_migrate(&ui, vec![path.to_string()]); + } + } + }); + ui.on_migrate_all({ + let w = ui.as_weak(); + move || { + let Some(ui) = w.upgrade() else { return }; + let todo: Vec = ui + .get_not_migrated() + .iter() + .filter(|r| r.state != "ok" && r.state != "running") + .map(|r| r.path.to_string()) + .collect(); + ask_migrate(&ui, todo); + } + }); + ui.on_migrate_confirm_cancel({ + let w = ui.as_weak(); + move || { + ST.with(|st| st.borrow_mut().mig_pending = None); + if let Some(ui) = w.upgrade() { + ui.set_migrate_confirm_text("".into()); + } + } + }); + ui.on_migrate_confirm_accept({ + let c = ctx.clone(); + move || { + let Some(ui) = c.weak.upgrade() else { return }; + ui.set_migrate_confirm_text("".into()); + let Some(paths) = ST.with(|st| st.borrow_mut().mig_pending.take()) else { + return; + }; + run_migrations(&c, &ui, paths); + } + }); ui.on_confirm_cancel({ let w = ui.as_weak(); move || { @@ -918,9 +1061,11 @@ fn wire(ui: &MainWindow, ctx: &Ctx) { fn worker( core: Arc, rx: Receiver<()>, - tray: Option, + mut tray: Option, + respawn_tray: impl Fn() -> Option, weak: Weak, ) { + let mut tray_lost = false; let mut last_states: HashMap = HashMap::new(); let mut last_agg: Option = None; let mut last_run = Instant::now() - MIN_GAP_HIDDEN; @@ -996,10 +1141,25 @@ fn worker( } } + // The tray service ends when its D-Bus connection is lost (e.g. the session bus or the + // desktop shell restarted): bring it back instead of leaving a running app with no icon. + if core.tray_ok.load(Ordering::SeqCst) && tray.as_ref().is_none_or(|t| t.is_closed()) { + if !tray_lost { + log::line("tray service ended; trying to restart it"); + tray_lost = true; + } + if let Some(h) = respawn_tray() { + log::line("tray service restarted"); + tray = Some(h); + tray_lost = false; + last_agg = None; + } + } if let Some(t) = &tray && last_agg.as_ref() != Some(&agg) + && !tray::set_state(t, &agg) { - tray::set_state(t, &agg); + log::line("tray update failed: service closed"); } last_agg = Some(agg); @@ -1034,17 +1194,27 @@ fn worker( /// Wakes the worker whenever the daemon emits an activity event. fn subscriber(core: Arc) { + let mut connected = false; loop { if let Ok(mut c) = UnixStream::connect(&core.bridge.socket) { + if !connected { + log::line("daemon: subscribed"); + connected = true; + } if writeln!(c, r#"{{"v":1,"cmd":"subscribe"}}"#).is_ok() { for line in BufReader::new(c).lines() { - if line.is_err() { + if let Err(e) = line { + log::line(&format!("daemon: event stream error: {e}")); break; } core.wake(); } } core.wake(); // connection ended: the daemon went away + if connected { + log::line("daemon: event stream ended"); + connected = false; + } } std::thread::sleep(RECONNECT); } @@ -1061,6 +1231,20 @@ fn default_grove_bin() -> PathBuf { } fn main() -> Result<()> { + log::init(); + log::line(&format!( + "start {}", + std::env::args().skip(1).collect::>().join(" ") + )); + let r = run(); + match &r { + Ok(()) => log::line("exit: ok"), + Err(e) => log::line(&format!("exit: error: {e:#}")), + } + r +} + +fn run() -> Result<()> { let args: Vec = std::env::args().skip(1).collect(); let arg = |name: &str| { args.iter() @@ -1154,18 +1338,21 @@ fn main() -> Result<()> { Action::SyncNow => ctx.core.sync(None, ctx.weak.clone()), Action::TogglePause => ctx.core.toggle_pause(), Action::Quit => { + log::line("quit requested from the tray menu"); + log::expected_exit(); let _ = slint::invoke_from_event_loop(|| { let _ = slint::quit_event_loop(); }); } }) }; - let tray = match tray::spawn(on_action) { + let tray = match tray::spawn(on_action.clone()) { Ok(h) => { core.tray_ok.store(true, Ordering::SeqCst); Some(h) } Err(e) => { + log::line(&format!("no system tray: {e}")); eprintln!("grove-gui: no system tray ({e}); closing the window will quit"); None } @@ -1176,6 +1363,8 @@ fn main() -> Result<()> { move || { c.core.set_visible(false); if !c.core.tray_ok.load(Ordering::SeqCst) { + log::line("window closed and no tray: quitting"); + log::expected_exit(); let _ = slint::quit_event_loop(); } slint::CloseRequestResponse::HideWindow @@ -1184,7 +1373,10 @@ fn main() -> Result<()> { { let (c, w) = (core.clone(), ui.as_weak()); - std::thread::spawn(move || worker(c, rx, tray, w)); + let respawn = on_action.clone(); + std::thread::spawn(move || { + worker(c, rx, tray, move || tray::spawn(respawn.clone()).ok(), w) + }); } { let c = core.clone(); @@ -1197,7 +1389,12 @@ fn main() -> Result<()> { } else { core.wake(); } - slint::run_event_loop_until_quit().context("event loop")?; + let r = slint::run_event_loop_until_quit(); + log::line(&format!( + "event loop ended: {r:?} (expected: {})", + log::EXPECTED_EXIT.load(Ordering::SeqCst) + )); + r.context("event loop")?; let _ = std::fs::remove_file(&inst_path); Ok(()) } diff --git a/crates/grove-gui/src/tray.rs b/crates/grove-gui/src/tray.rs index e300dd8..51752fa 100644 --- a/crates/grove-gui/src/tray.rs +++ b/crates/grove-gui/src/tray.rs @@ -31,13 +31,16 @@ pub fn spawn(on_action: Arc) -> Result bool { let agg = agg.clone(); - handle.update(move |t| { - if t.agg != agg { - t.agg = agg; - } - }); + handle + .update(move |t| { + if t.agg != agg { + t.agg = agg; + } + }) + .is_some() } impl ksni::Tray for GroveTray { diff --git a/crates/grove-gui/ui/app.slint b/crates/grove-gui/ui/app.slint index 1ba09d2..292dd3b 100644 --- a/crates/grove-gui/ui/app.slint +++ b/crates/grove-gui/ui/app.slint @@ -45,6 +45,13 @@ export struct Pick { checked: bool, } +export struct MigRow { + path: string, + // "" (not started), "running", "ok", "failed" + state: string, + msg: string, +} + export struct Out { text: string, ok: bool, @@ -180,7 +187,9 @@ export component MainWindow inherits Window { in property wt-count; in property attention-count; in property <[Repo]> repos; - in property <[string]> not-migrated; + in property <[MigRow]> not-migrated; + in property migrating; + in property migrate-confirm-text; in property <[LogRow]> log; in property <[string]> groups; in property <[string]> providers; @@ -214,6 +223,10 @@ export component MainWindow inherits Window { callback import-selected(string); callback pick-toggled(int, bool); callback resolve(string, string, string); + callback migrate-one(string); + callback migrate-all(); + callback migrate-confirm-accept(); + callback migrate-confirm-cancel(); callback confirm-accept(); callback confirm-cancel(); callback run-settings(string); @@ -376,10 +389,48 @@ export component MainWindow inherits Window { text: "These clones are in your workspace but not managed by grove yet: run `grove add` for each one to bring it into a group."; } - for p in root.not-migrated: Muted { - text: p; - font-size: 12px; - overflow: elide; + for p in root.not-migrated: VerticalLayout { + spacing: 2px; + HorizontalLayout { + spacing: 8px; + Muted { + text: p.path; + font-size: 12px; + overflow: elide; + horizontal-stretch: 1; + } + + if p.state == "running": Muted { + text: "Migrating…"; + } + if p.state == "ok": Muted { + text: "Migrated"; + } + if p.state == "" || p.state == "failed": Button { + text: p.state == "failed" ? "Retry" : "Migrate"; + enabled: !root.migrating; + clicked => { + root.migrate-one(p.path); + } + } + } + + if p.msg != "": Muted { + text: p.msg; + font-size: 12px; + overflow: elide; + } + } + + HorizontalLayout { + alignment: start; + Button { + text: root.migrating ? "Migrating…" : "Migrate all"; + enabled: !root.migrating; + clicked => { + root.migrate-all(); + } + } } } if !root.offline && root.loading: Muted { @@ -1110,6 +1161,43 @@ export component MainWindow inherits Window { } } + // ---- migration confirmation ---- + if root.migrate-confirm-text != "": Rectangle { + background: #00000088; + TouchArea { } + + Card { + width: min(500px, parent.width - 40px); + height: self.preferred-height; + x: (parent.width - self.width) / 2; + y: (parent.height - self.height) / 2; + background: Palette.background; + Text { + text: root.migrate-confirm-text; + wrap: word-wrap; + } + + HorizontalLayout { + spacing: 8px; + alignment: end; + Button { + text: "Cancel"; + clicked => { + root.migrate-confirm-cancel(); + } + } + + Button { + text: "Migrate"; + primary: true; + clicked => { + root.migrate-confirm-accept(); + } + } + } + } + } + // ---- confirmation ---- if root.confirm-text != "": Rectangle { background: #00000088; diff --git a/crates/grove/src/workflow.rs b/crates/grove/src/workflow.rs index f729077..c8d75bc 100644 --- a/crates/grove/src/workflow.rs +++ b/crates/grove/src/workflow.rs @@ -296,9 +296,7 @@ fn remote_key(url: &str) -> Option { _ => path, }; let path = path.trim_matches('/').trim_end_matches(".git"); - let mut parts = path.rsplitn(2, '/'); - let name = parts.next()?; - let owner = parts.next()?; + let (owner, name) = path.rsplit_once('/')?; Some(format!("{host}/{owner}/{name}").to_lowercase()) } diff --git a/docs/phase7.md b/docs/phase7.md index 82f6559..b20a8d7 100644 --- a/docs/phase7.md +++ b/docs/phase7.md @@ -113,3 +113,19 @@ kind = "gitea" url = "https://git.example.com" protocol = "ssh" # optional, default "https" ``` + +## Migrating clones from the GUI + +The "Not migrated clones" card has a Migrate button per row and a Migrate all button. Each asks +for confirmation first (the dialog names the backup directory, `/backups`), then runs +`grove add ` one clone at a time off the UI thread, showing "Migrating…", then the migrated +path or the refusal message (linked worktrees, submodules, detached HEAD...). The bridge only runs +`add` for an existing, non-symlink directory directly under `//` and passes no flags +(so no custom backup directory). Afterwards the status is refreshed; the daemon computes its +not-migrated list at start (a daemon-side fix is separate), so finished rows stay on screen with +their result until the daemon list changes. + +## Diagnostics log + +`/grove-gui.log` (rotated at 256 KiB) records start-up, daemon subscribe/disconnect, +tray errors and restarts, panics with a backtrace (from any thread) and why the event loop ended.