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 <state>/grove-gui.log
- restart the tray service if its D-Bus connection ends

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 18:15:36 +01:00
1 parent 28e07aab56
commit ec6a3a04f3
10 files changed
+528 -25

No files matched your search

Generated
+1
View File
@@ -2096,6 +2096,7 @@ name = "grove-gui"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"grove-core",
"grove-daemon", "grove-daemon",
"ksni", "ksni",
"serde_json", "serde_json",
+7 -2
View File
@@ -515,9 +515,14 @@ mirror_to = ["gitea"]
#[test] #[test]
fn provider_protocol_defaults_to_https_and_is_validated() { fn provider_protocol_defaults_to_https_and_is_validated() {
let t = |p: &str| { 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(); let c = Config::parse(&t("protocol=\"ssh\"\n")).unwrap();
assert_eq!(c.providers["p"].protocol, Protocol::Ssh); assert_eq!(c.providers["p"].protocol, Protocol::Ssh);
assert!(toml::to_string(&c).unwrap().contains("protocol = \"ssh\"")); assert!(toml::to_string(&c).unwrap().contains("protocol = \"ssh\""));
+1
View File
@@ -11,6 +11,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
anyhow = "1.0.104" anyhow = "1.0.104"
grove-core = { version = "0.1.0", path = "../grove-core" }
grove-daemon = { version = "0.1.0", path = "../grove-daemon" } 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. # 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"] } ksni = { version = "0.3.7", default-features = false, features = ["async-io", "blocking"] }
+120 -1
View File
@@ -2,7 +2,7 @@
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::io::Write; use std::io::Write;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
/// `grove` subcommands the GUI may run. Everything else is refused. /// `grove` subcommands the GUI may run. Everything else is refused.
@@ -11,6 +11,7 @@ const ALLOWED: &[&str] = &[
"login", "login",
"new", "new",
"import", "import",
"add",
"config-repo-init", "config-repo-init",
"bootstrap", "bootstrap",
"resolve", "resolve",
@@ -44,6 +45,11 @@ impl Bridge {
if let Err(e) = validate(args) { if let Err(e) = validate(args) {
return json!({"ok": false, "output": format!("rejected: {e}")}); 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); let mut cmd = Command::new(&self.grove_bin);
if let Some(c) = &self.config { if let Some(c) = &self.config {
cmd.arg("--config").arg(c); cmd.arg("--config").arg(c);
@@ -79,6 +85,28 @@ impl Bridge {
} }
} }
fn loaded_config(&self) -> Option<grove_core::config::Config> {
let p = self
.config
.clone()
.or_else(grove_core::config::Config::default_path)?;
grove_core::config::Config::load(&p).ok()
}
/// `add <path>` only for an existing directory directly under `<root>/<group>/`.
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<PathBuf> {
grove_core::config::Config::state_dir().map(|d| d.join("backups"))
}
/// `config.toml` as JSON (it holds no secrets), or `None` before onboarding. /// `config.toml` as JSON (it holds no secrets), or `None` before onboarding.
pub fn config_json(&self) -> Option<Value> { pub fn config_json(&self) -> Option<Value> {
let p = self.config.clone().or_else(grove_core_default_config)?; let p = self.config.clone().or_else(grove_core_default_config)?;
@@ -135,6 +163,31 @@ pub fn validate(args: &[String]) -> Result<(), String> {
Ok(()) 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<PathBuf, String> {
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<PathBuf> { fn grove_core_default_config() -> Option<PathBuf> {
let base = std::env::var_os("XDG_CONFIG_HOME") let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from) .map(PathBuf::from)
@@ -160,6 +213,72 @@ mod tests {
assert!(v(&["secrets", "pull"]).is_ok()); 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 { fn bridge() -> Bridge {
Bridge { Bridge {
grove_bin: "/nonexistent/grove".into(), grove_bin: "/nonexistent/grove".into(),
+75
View File
@@ -0,0 +1,75 @@
//! A small log file (`<state dir>/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<std::path::PathBuf> = 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("<unnamed>")
));
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
)
}
+205 -8
View File
@@ -7,6 +7,7 @@
mod autostart; mod autostart;
mod bridge; mod bridge;
mod instance; mod instance;
mod log;
mod model; mod model;
mod tray; mod tray;
@@ -125,6 +126,10 @@ struct UiState {
detail_fp: String, detail_fp: String,
filter: String, filter: String,
pending: Option<Vec<String>>, pending: Option<Vec<String>>,
/// Clones waiting for the migration confirmation, and what happened to each so far.
mig_pending: Option<Vec<String>>,
mig: HashMap<String, (String, String)>,
migrating: bool,
picks: Rc<VecModel<Pick>>, picks: Rc<VecModel<Pick>>,
/// Last successful scan per import group, for the session (names still to import). /// Last successful scan per import group, for the session (names still to import).
import_cache: HashMap<String, Vec<String>>, import_cache: HashMap<String, Vec<String>>,
@@ -145,6 +150,9 @@ thread_local! {
detail_fp: String::new(), detail_fp: String::new(),
filter: String::new(), filter: String::new(),
pending: None, pending: None,
mig_pending: None,
mig: HashMap::new(),
migrating: false,
picks: Rc::new(VecModel::default()), picks: Rc::new(VecModel::default()),
import_cache: HashMap::new(), import_cache: HashMap::new(),
import_current: String::new(), import_current: String::new(),
@@ -224,16 +232,25 @@ fn render(ui: &MainWindow) {
ui.set_attention_count(agg.attention as i32); ui.set_attention_count(agg.attention as i32);
ui.set_has_config(snap.config.is_some()); ui.set_has_config(snap.config.is_some());
ui.set_autostart(autostart::config_home().is_some_and(|d| autostart::is_enabled(&d))); ui.set_autostart(autostart::config_home().is_some_and(|d| autostart::is_enabled(&d)));
let nm: Vec<SharedString> = snap let nm: Vec<MigRow> = snap
.status .status
.as_ref() .as_ref()
.and_then(|s| s["not_migrated"].as_array()) .and_then(|s| s["not_migrated"].as_array())
.map(|a| { .map(|a| {
a.iter() 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() .collect()
}) })
.unwrap_or_default(); .unwrap_or_default();
ui.set_migrating(st.migrating);
ui.set_not_migrated(ModelRc::from(Rc::new(VecModel::from(nm)))); ui.set_not_migrated(ModelRc::from(Rc::new(VecModel::from(nm))));
let empty = Vec::new(); let empty = Vec::new();
@@ -568,6 +585,91 @@ fn scan(ctx: &Ctx, ui: &MainWindow, group: String, force: bool, note: Option<Str
}); });
} }
/// Opens the confirmation dialog for migrating `paths` (nothing runs before the user accepts).
fn ask_migrate(ui: &MainWindow, paths: Vec<String>) {
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<String>) {
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<SharedString>) -> String { fn first_or(v: &str, list: &ModelRc<SharedString>) -> String {
if v.is_empty() { if v.is_empty() {
list.row_data(0).map(|x| x.to_string()).unwrap_or_default() 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.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<String> = 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({ ui.on_confirm_cancel({
let w = ui.as_weak(); let w = ui.as_weak();
move || { move || {
@@ -918,9 +1061,11 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
fn worker( fn worker(
core: Arc<Core>, core: Arc<Core>,
rx: Receiver<()>, rx: Receiver<()>,
tray: Option<tray::TrayHandle>, mut tray: Option<tray::TrayHandle>,
respawn_tray: impl Fn() -> Option<tray::TrayHandle>,
weak: Weak<MainWindow>, weak: Weak<MainWindow>,
) { ) {
let mut tray_lost = false;
let mut last_states: HashMap<String, String> = HashMap::new(); let mut last_states: HashMap<String, String> = HashMap::new();
let mut last_agg: Option<Aggregate> = None; let mut last_agg: Option<Aggregate> = None;
let mut last_run = Instant::now() - MIN_GAP_HIDDEN; 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 if let Some(t) = &tray
&& last_agg.as_ref() != Some(&agg) && 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); last_agg = Some(agg);
@@ -1034,17 +1194,27 @@ fn worker(
/// Wakes the worker whenever the daemon emits an activity event. /// Wakes the worker whenever the daemon emits an activity event.
fn subscriber(core: Arc<Core>) { fn subscriber(core: Arc<Core>) {
let mut connected = false;
loop { loop {
if let Ok(mut c) = UnixStream::connect(&core.bridge.socket) { 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() { if writeln!(c, r#"{{"v":1,"cmd":"subscribe"}}"#).is_ok() {
for line in BufReader::new(c).lines() { 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; break;
} }
core.wake(); core.wake();
} }
} }
core.wake(); // connection ended: the daemon went away core.wake(); // connection ended: the daemon went away
if connected {
log::line("daemon: event stream ended");
connected = false;
}
} }
std::thread::sleep(RECONNECT); std::thread::sleep(RECONNECT);
} }
@@ -1061,6 +1231,20 @@ fn default_grove_bin() -> PathBuf {
} }
fn main() -> Result<()> { fn main() -> Result<()> {
log::init();
log::line(&format!(
"start {}",
std::env::args().skip(1).collect::<Vec<_>>().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<String> = std::env::args().skip(1).collect(); let args: Vec<String> = std::env::args().skip(1).collect();
let arg = |name: &str| { let arg = |name: &str| {
args.iter() args.iter()
@@ -1154,18 +1338,21 @@ fn main() -> Result<()> {
Action::SyncNow => ctx.core.sync(None, ctx.weak.clone()), Action::SyncNow => ctx.core.sync(None, ctx.weak.clone()),
Action::TogglePause => ctx.core.toggle_pause(), Action::TogglePause => ctx.core.toggle_pause(),
Action::Quit => { Action::Quit => {
log::line("quit requested from the tray menu");
log::expected_exit();
let _ = slint::invoke_from_event_loop(|| { let _ = slint::invoke_from_event_loop(|| {
let _ = slint::quit_event_loop(); let _ = slint::quit_event_loop();
}); });
} }
}) })
}; };
let tray = match tray::spawn(on_action) { let tray = match tray::spawn(on_action.clone()) {
Ok(h) => { Ok(h) => {
core.tray_ok.store(true, Ordering::SeqCst); core.tray_ok.store(true, Ordering::SeqCst);
Some(h) Some(h)
} }
Err(e) => { Err(e) => {
log::line(&format!("no system tray: {e}"));
eprintln!("grove-gui: no system tray ({e}); closing the window will quit"); eprintln!("grove-gui: no system tray ({e}); closing the window will quit");
None None
} }
@@ -1176,6 +1363,8 @@ fn main() -> Result<()> {
move || { move || {
c.core.set_visible(false); c.core.set_visible(false);
if !c.core.tray_ok.load(Ordering::SeqCst) { if !c.core.tray_ok.load(Ordering::SeqCst) {
log::line("window closed and no tray: quitting");
log::expected_exit();
let _ = slint::quit_event_loop(); let _ = slint::quit_event_loop();
} }
slint::CloseRequestResponse::HideWindow slint::CloseRequestResponse::HideWindow
@@ -1184,7 +1373,10 @@ fn main() -> Result<()> {
{ {
let (c, w) = (core.clone(), ui.as_weak()); 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(); let c = core.clone();
@@ -1197,7 +1389,12 @@ fn main() -> Result<()> {
} else { } else {
core.wake(); 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); let _ = std::fs::remove_file(&inst_path);
Ok(()) Ok(())
} }
+9 -6
View File
@@ -31,13 +31,16 @@ pub fn spawn(on_action: Arc<dyn Fn(Action) + Send + Sync>) -> Result<TrayHandle,
.spawn() .spawn()
} }
pub fn set_state(handle: &TrayHandle, agg: &Aggregate) { /// Returns false when the tray service has ended (D-Bus connection lost).
pub fn set_state(handle: &TrayHandle, agg: &Aggregate) -> bool {
let agg = agg.clone(); let agg = agg.clone();
handle.update(move |t| { handle
if t.agg != agg { .update(move |t| {
t.agg = agg; if t.agg != agg {
} t.agg = agg;
}); }
})
.is_some()
} }
impl ksni::Tray for GroveTray { impl ksni::Tray for GroveTray {
+93 -5
View File
@@ -45,6 +45,13 @@ export struct Pick {
checked: bool, checked: bool,
} }
export struct MigRow {
path: string,
// "" (not started), "running", "ok", "failed"
state: string,
msg: string,
}
export struct Out { export struct Out {
text: string, text: string,
ok: bool, ok: bool,
@@ -180,7 +187,9 @@ export component MainWindow inherits Window {
in property <int> wt-count; in property <int> wt-count;
in property <int> attention-count; in property <int> attention-count;
in property <[Repo]> repos; in property <[Repo]> repos;
in property <[string]> not-migrated; in property <[MigRow]> not-migrated;
in property <bool> migrating;
in property <string> migrate-confirm-text;
in property <[LogRow]> log; in property <[LogRow]> log;
in property <[string]> groups; in property <[string]> groups;
in property <[string]> providers; in property <[string]> providers;
@@ -214,6 +223,10 @@ export component MainWindow inherits Window {
callback import-selected(string); callback import-selected(string);
callback pick-toggled(int, bool); callback pick-toggled(int, bool);
callback resolve(string, string, string); 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-accept();
callback confirm-cancel(); callback confirm-cancel();
callback run-settings(string); 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."; 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 { for p in root.not-migrated: VerticalLayout {
text: p; spacing: 2px;
font-size: 12px; HorizontalLayout {
overflow: elide; 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 { 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 ---- // ---- confirmation ----
if root.confirm-text != "": Rectangle { if root.confirm-text != "": Rectangle {
background: #00000088; background: #00000088;
+1 -3
View File
@@ -296,9 +296,7 @@ fn remote_key(url: &str) -> Option<String> {
_ => path, _ => path,
}; };
let path = path.trim_matches('/').trim_end_matches(".git"); let path = path.trim_matches('/').trim_end_matches(".git");
let mut parts = path.rsplitn(2, '/'); let (owner, name) = path.rsplit_once('/')?;
let name = parts.next()?;
let owner = parts.next()?;
Some(format!("{host}/{owner}/{name}").to_lowercase()) Some(format!("{host}/{owner}/{name}").to_lowercase())
} }
+16
View File
@@ -113,3 +113,19 @@ kind = "gitea"
url = "https://git.example.com" url = "https://git.example.com"
protocol = "ssh" # optional, default "https" 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, `<state dir>/backups`), then runs
`grove add <path>` 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 `<root>/<group>/` 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
`<state dir>/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.