diff --git a/README.md b/README.md index 9dd8e63..09a5b9c 100644 --- a/README.md +++ b/README.md @@ -302,7 +302,9 @@ the resolved app appearance automatically. track, tag/commit detach, graph and reflog detached checkout, and stash apply/pop/drop show a transient progress pill; fetch / pull / - push with streaming progress and explicit + push with streaming progress; background auto-fetch of open repositories + (Settings → Git, default 10 minutes, per-repository opt-out) that updates + the behind-count and notices new upstream commits without merging; explicit pull modes (merge, rebase, fast-forward only) plus a per-repo default; normal, annotated-tag, all-tag, and guarded force-with-lease pushes; explicit push of any local branch to a chosen remote destination; upstream set/change/unset; diff --git a/ROADMAP.md b/ROADMAP.md index 0b8f068..5286107 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2184,6 +2184,9 @@ the audit does not mark these fixes or proposals shipped. `Repo::lfs_action`); real Git fixtures and native dialog verification pass. - ☑ GPG / SSH commit signing UI (repository/worktree settings and per-operation choices; signed-tag creation and verification, 2026-09-06). +- ☑ **Auto-fetch** (DAN-89, 2026-10-19) — open repositories fetch on a timer + (Off / 5 / 10 / 30 min, default 10). Behind-count updates and a short toast + reports new upstream commits. Fetch only; no pull, merge, or credential prompt. - ☑ **What's New dialog** (DAN-86, 2026-10-15) — Strand menu **What's New…** lists `vX.Y.Z` app releases; What's Changed PRs expand in-app to the cleaned PR description; Settings → Updates is unchanged @@ -3259,6 +3262,19 @@ reason plus a Pull retry hint. `error_summary` keeps LFS explanation lines. Fixtures in `clone_lfs.rs`. Live check against private Azure DevOps `portal-setup` remains on Daniels' machine. +**Auto-fetch (2026-10-19, DAN-89):** Open repositories fetch in the background +on the Settings → Git interval. Daniels chose 10 minutes as the default +(Off, 5, and 30 remain available, and each open repository can opt out). +The active repository goes first and the others are staggered. A tick is +skipped when that repository already has a manual fetch, pull, or push, when +Strand is offline, or when a fetch is already running. The fetch honors the +repository's fetch-prune setting and never pulls, merges, rebases, or touches +the worktree or index. A remote with no cached credential fails once, quietly, +and backs off instead of opening a prompt. New commits on the current branch's +upstream update the behind-count and show a toast. Background fetches are +quiet activity-log entries. Git is spawned through `git_command` +(`CREATE_NO_WINDOW`), the same hidden-console path as DAN-83. + **Worktrees UI revision (2026-09-04):** Reworked PR 113's cramped table into readable two-line rows: branch and directory together, working changes and latest commit in separate columns, explicit current/locked indicators, and diff --git a/TASKS.md b/TASKS.md index a249c82..cc3c6b3 100644 --- a/TASKS.md +++ b/TASKS.md @@ -448,6 +448,15 @@ community plugins, performance and platform certification from Git feature gaps. - ☑ Persist fetch-prune, pull-strategy, and pull-autostash defaults per repository, with explicit one-operation overrides (`repoNetworkPreferences`, `Repo::{fetch,pull,pull_branch}` explicit flags, topbar/palette actions). +- ☑ Auto-fetch open repositories on a timer (DAN-89). Settings → Git interval + Off / 5 / 10 / 30 min, default 10 (Daniels's choice), per-repo opt-out + (`repoAutoFetch`). Active repo first, others staggered. Skips a manual + fetch/pull/push, offline, and in-flight work. Fetch only, honoring + fetch-prune. Missing credentials fail quietly and back off + (`Repo::fetch_background`, `useAutoFetch`). New upstream commits update the + behind-count and toast “N new commits on origin/”. Quiet activity + log entries (`background-fetch`). Windows spawn stays on `git_command` + (`CREATE_NO_WINDOW`). - ☑ Edit a remote's fetch and push URLs independently (`RemoteDialog`, `repo_remote_set_urls`, native Git remote config). - ☑ Credentials: inherit user's `git` config (helper, SSH agent) via diff --git a/crates/strand-core/Cargo.toml b/crates/strand-core/Cargo.toml index c3eb286..e328d01 100644 --- a/crates/strand-core/Cargo.toml +++ b/crates/strand-core/Cargo.toml @@ -27,6 +27,6 @@ libc = "0.2" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = [ - "Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", + "Win32_Foundation", "Win32_Security", "Win32_System_Console", "Win32_System_JobObjects", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Threading", ] } diff --git a/crates/strand-core/src/lib.rs b/crates/strand-core/src/lib.rs index b3deec4..32581bd 100644 --- a/crates/strand-core/src/lib.rs +++ b/crates/strand-core/src/lib.rs @@ -126,13 +126,68 @@ pub fn init() { /// Exception: `mergetool` keeps default flags — a console-based merge tool /// needs a real console window to be usable. pub(crate) fn git_command() -> std::process::Command { - #[cfg_attr(not(windows), allow(unused_mut))] let mut cmd = std::process::Command::new("git"); + hide_console(&mut cmd); + cmd +} + +/// Apply `CREATE_NO_WINDOW` on Windows so a child of the GUI-subsystem build +/// does not flash a console. No-op elsewhere. Background fetch and every +/// other `git_command` spawn go through here — do not set the flag ad hoc. +pub(crate) fn hide_console(cmd: &mut std::process::Command) { #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; cmd.creation_flags(CREATE_NO_WINDOW); } - cmd + #[cfg(not(windows))] + { + let _ = cmd; + } +} + +#[cfg(all(test, windows))] +mod console_probe { + use super::hide_console; + + /// Child side exits 0 when this process has no console window, 7 when it does. + #[test] + fn hidden_console_child_has_no_window() { + if std::env::var_os("STRAND_CONSOLE_PROBE").is_some() { + let hwnd = unsafe { windows_sys::Win32::System::Console::GetConsoleWindow() }; + std::process::exit(if hwnd.is_null() { 0 } else { 7 }); + } + + let spawn = |hide: bool| { + let mut command = std::process::Command::new(std::env::current_exe().unwrap()); + command + .args(["--exact", "console_probe::hidden_console_child_has_no_window", "--nocapture"]) + .env("STRAND_CONSOLE_PROBE", "1") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + if hide { + hide_console(&mut command); + } + command.status().expect("spawn console probe") + }; + + let hidden = spawn(true); + assert!( + hidden.success(), + "CREATE_NO_WINDOW child still had a console window: {hidden}" + ); + // A console parent (the usual Windows test host) would show a window + // for a bare spawn. Service sessions have no console at all; only + // assert the differential when the parent itself has one. + let parent = unsafe { windows_sys::Win32::System::Console::GetConsoleWindow() }; + if !parent.is_null() { + let bare = spawn(false); + assert!( + !bare.success(), + "bare Command::new unexpectedly hid its console; the probe cannot tell CREATE_NO_WINDOW apart" + ); + } + } } diff --git a/crates/strand-core/src/network.rs b/crates/strand-core/src/network.rs index 638a395..8647b88 100644 --- a/crates/strand-core/src/network.rs +++ b/crates/strand-core/src/network.rs @@ -102,6 +102,26 @@ pub struct NetworkOutcome { pub output: String, } +/// Result of one background `git fetch`. Failures stay in this struct so the +/// scheduler can record a quiet entry and back off; they are not raised as +/// command errors. The fetch never pulls, merges, or rebases. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BackgroundFetchOutcome { + pub ok: bool, + /// Credential fill would have prompted. The caller should record one + /// quiet failure and skip later ticks until its backoff elapses. + pub auth_required: bool, + pub output: String, + /// Short command line for the activity log (`git fetch --prune`). + pub command: String, + /// Commits that arrived on the current branch's upstream during this fetch. + pub new_commits: u32, + /// Upstream short name, e.g. `origin/main`, when the branch tracks one. + pub upstream: Option, + /// Behind-count of the current branch after the fetch. + pub behind: u32, +} + /// Full subprocess transcript used by callers that need to retain both /// successful and failed Git output instead of mapping a non-zero exit to an /// error immediately. @@ -288,6 +308,51 @@ impl Repo { run_git_streaming(&self.path, &args, on_progress, cancel) } + /// Fetch remotes without merging, without touching the index or worktree, + /// and without opening a credential or console prompt. Uses the same + /// spawn path as [`Repo::fetch`] (`git_command` / `CREATE_NO_WINDOW`) + /// with non-interactive auth env. `prune` is the repo's fetch-prune + /// setting. Auth failures return `ok: false` rather than hanging. + pub fn fetch_background(&self, prune: bool) -> Result { + let before = read_head_upstream(&self.path); + let quiet_auth = true; + let args = background_fetch_args(prune); + let command = format!("git {}", args.join(" ")); + let transcript = run_git_input_transcript_env( + &self.path, + &args, + None, + &[], + quiet_auth, + |_| {}, + None, + )?; + if !transcript.success { + let output = error_summary(&transcript.output, &args); + let auth_required = is_auth_failure(&output) || is_auth_failure(&transcript.output); + return Ok(BackgroundFetchOutcome { + ok: false, + auth_required, + output, + command, + new_commits: 0, + upstream: before.as_ref().map(|u| u.name.clone()), + behind: before.as_ref().map(|u| u.behind).unwrap_or(0), + }); + } + let after = read_head_upstream(&self.path); + let new_commits = new_upstream_commits(&self.path, before.as_ref(), after.as_ref()); + Ok(BackgroundFetchOutcome { + ok: true, + auth_required: false, + output: transcript.output, + command, + new_commits, + upstream: after.as_ref().map(|u| u.name.clone()), + behind: after.as_ref().map(|u| u.behind).unwrap_or(0), + }) + } + pub fn pull( &self, mode: PullMode, @@ -656,7 +721,7 @@ pub fn clone_with_options( let args = owned_args.iter().map(String::as_str).collect::>(); let lfs_skip = [("GIT_LFS_SKIP_SMUDGE", "1")]; let parent = cwd.unwrap_or_else(|| Path::new(".")); - let transcript = run_git_input_transcript_env(parent, &args, None, &lfs_skip, &mut on_progress, cancel)?; + let transcript = run_git_input_transcript_env(parent, &args, None, &lfs_skip, false, &mut on_progress, cancel)?; if !transcript.success { return Err(Error::Other(error_summary(&transcript.output, &args))); } @@ -772,18 +837,35 @@ pub(crate) fn run_git_input_transcript( on_progress: impl FnMut(Progress), cancel: Option<&CancelHandle>, ) -> Result { - run_git_input_transcript_env(cwd, args, input, &[], on_progress, cancel) + run_git_input_transcript_env(cwd, args, input, &[], false, on_progress, cancel) } -pub(crate) fn run_git_input_transcript_env( +/// Build the `git` command shared by manual and background network ops. +/// Always starts from [`crate::git_command`] so Windows gets `CREATE_NO_WINDOW`. +/// `quiet_auth` is the background-fetch path: cached credentials may still be +/// used, but a missing credential must fail instead of opening a prompt. +pub(crate) fn prepare_git_command( cwd: &Path, args: &[&str], - input: Option>, extra_env: &[(&str, &str)], - mut on_progress: impl FnMut(Progress), - cancel: Option<&CancelHandle>, -) -> Result { - if cancel.is_some_and(CancelHandle::is_cancelled) { return Err(Error::Cancelled); } + quiet_auth: bool, + piped_stdin: bool, +) -> std::process::Command { + prepare_git_command_probed(cwd, args, extra_env, quiet_auth, piped_stdin, || { + user_ssh_command(cwd, |key| std::env::var_os(key), &[]) + }) +} + +/// [`prepare_git_command`] with the "did the user pick an ssh?" probe passed +/// in, so tests can run it against an isolated environment and config. +fn prepare_git_command_probed( + cwd: &Path, + args: &[&str], + extra_env: &[(&str, &str)], + quiet_auth: bool, + piped_stdin: bool, + user_ssh: impl FnOnce() -> bool, +) -> std::process::Command { let mut command = crate::git_command(); #[cfg(unix)] { @@ -798,14 +880,65 @@ pub(crate) fn run_git_input_transcript_env( for &(key, value) in extra_env { command.env(key, value); } + if quiet_auth { + command.env("GCM_INTERACTIVE", "never"); + // GIT_SSH_COMMAND outranks core.sshCommand and GIT_SSH, so only + // force BatchMode when the user hasn't chosen their own ssh. Theirs + // still gets null stdin and SSH_ASKPASS_REQUIRE=never. + if !user_ssh() { + command.env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes"); + } + command.env("SSH_ASKPASS_REQUIRE", "never"); + command.env_remove("GIT_ASKPASS"); + command.env_remove("SSH_ASKPASS"); + } + command.args(crate::GIT_SAFE_CONFIG); + if quiet_auth { + // git runs a configured core.askPass before it checks + // GIT_TERMINAL_PROMPT; an empty value disables it. + command.args(["-c", "core.askPass="]); + } command - // Neutralize repo-local config that would run code as a side effect. - .args(crate::GIT_SAFE_CONFIG) - // Force progress reporting even though stderr isn't a TTY. .args(args) - .stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() }) + .stdin(if piped_stdin { Stdio::piped() } else { Stdio::null() }) .stdout(Stdio::piped()) .stderr(Stdio::piped()); + command +} + +/// The user picked an ssh command: `GIT_SSH_COMMAND` / `GIT_SSH` in the +/// environment, or `core.sshCommand` in the repo's effective config. +/// `env` reads the environment; `config_env` is added to the config probe. +fn user_ssh_command( + cwd: &Path, + env: impl Fn(&str) -> Option, + config_env: &[(&str, &str)], +) -> bool { + let set = |key: &str| env(key).is_some_and(|value| !value.is_empty()); + if set("GIT_SSH_COMMAND") || set("GIT_SSH") { + return true; + } + crate::git_command() + .current_dir(cwd) + .env("GIT_TERMINAL_PROMPT", "0") + .envs(config_env.iter().copied()) + .stdin(Stdio::null()) + .args(["config", "--get", "core.sshCommand"]) + .output() + .is_ok_and(|out| out.status.success() && !out.stdout.trim_ascii().is_empty()) +} + +pub(crate) fn run_git_input_transcript_env( + cwd: &Path, + args: &[&str], + input: Option>, + extra_env: &[(&str, &str)], + quiet_auth: bool, + mut on_progress: impl FnMut(Progress), + cancel: Option<&CancelHandle>, +) -> Result { + if cancel.is_some_and(CancelHandle::is_cancelled) { return Err(Error::Cancelled); } + let mut command = prepare_git_command(cwd, args, extra_env, quiet_auth, input.is_some()); #[cfg(windows)] let (mut child, job) = crate::windows_job::WindowsJob::spawn(&mut command).map_err(Error::Other)?; #[cfg(not(windows))] @@ -991,6 +1124,73 @@ mod bounded_process_tests { } } +fn background_fetch_args(prune: bool) -> [&'static str; 2] { + ["fetch", if prune { "--prune" } else { "--no-prune" }] +} + +struct HeadUpstream { + name: String, + oid: Option, + behind: u32, +} + +/// Fresh git2 open so a fetch that just updated refs is visible. The cached +/// handle on `Repo` can keep the pre-fetch ref snapshot. +fn read_head_upstream(path: &Path) -> Option { + let repo = git2::Repository::open(path).ok()?; + let head = repo.head().ok()?; + if !head.is_branch() { + return None; + } + let short = head.shorthand()?.to_string(); + let branch = repo.find_branch(&short, git2::BranchType::Local).ok()?; + let upstream = branch.upstream().ok()?; + let name = upstream.name().ok().flatten()?.to_string(); + if name.is_empty() { + return None; + } + let oid = upstream.get().target(); + let behind = match (head.target(), oid) { + (Some(local), Some(remote)) => repo + .graph_ahead_behind(local, remote) + .map(|(_, behind)| behind as u32) + .unwrap_or(0), + _ => 0, + }; + Some(HeadUpstream { name, oid, behind }) +} + +fn new_upstream_commits(path: &Path, before: Option<&HeadUpstream>, after: Option<&HeadUpstream>) -> u32 { + let Some(after) = after else { return 0 }; + match (before.and_then(|prior| prior.oid), after.oid) { + (Some(old), Some(new)) if old != new => git2::Repository::open(path) + .ok() + .and_then(|repo| repo.graph_ahead_behind(new, old).ok()) + .map(|(ahead, _)| ahead as u32) + .unwrap_or(0), + (None, Some(_)) => after.behind, + _ => 0, + } +} + +fn is_auth_failure(text: &str) -> bool { + let lower = text.to_ascii_lowercase(); + const MARKERS: &[&str] = &[ + "terminal prompts disabled", + "could not read username", + "could not read password", + "authentication failed", + "authentication required", + "authorization failed", + "invalid username or password", + "permission denied (publickey)", + "401 unauthorized", + "returned error: 401", + "returned error: 403", + ]; + MARKERS.iter().any(|marker| lower.contains(marker)) +} + /// Pull the meaningful failure out of a git transcript. git streams progress to /// stderr too, so the full combined output is mostly "Resolving deltas: NN%" /// noise with the actual `fatal:` / `error:` line buried at the very end — @@ -1630,4 +1830,231 @@ mod tests { assert!(validate_branch_ref("../escape", "branch").is_err()); assert!(validate_tracking_ref("origin", "bad..name").is_err()); } + + #[test] + fn background_fetch_args_follow_the_prune_setting() { + assert_eq!(background_fetch_args(true), ["fetch", "--prune"]); + assert_eq!(background_fetch_args(false), ["fetch", "--no-prune"]); + } + + /// A fresh `git init` repo in a temp dir, optionally with repo-local config. + fn ssh_probe_repo(name: &str, config: &[(&str, &str)]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let git = |args: &[&str]| { + assert!(std::process::Command::new("git").current_dir(&dir).args(args).status().unwrap().success()); + }; + git(&["init", "-q"]); + for (key, value) in config { + git(&["config", key, value]); + } + std::fs::write(dir.join(".git").join("empty-global-config"), "").unwrap(); + dir + } + + /// The quiet background-fetch command, with the ssh probe blind to the + /// developer's GIT_SSH_COMMAND / GIT_SSH and global/system config. + fn isolated_quiet_fetch(dir: &Path) -> Command { + let global = dir.join(".git").join("empty-global-config"); + let global = global.to_str().unwrap(); + prepare_git_command_probed(dir, &background_fetch_args(false), &[], true, false, || { + user_ssh_command(dir, |_| None, &[("GIT_CONFIG_GLOBAL", global), ("GIT_CONFIG_NOSYSTEM", "1")]) + }) + } + + #[test] + fn background_fetch_keeps_the_users_core_ssh_command() { + let dir = ssh_probe_repo("strand-ssh-cmd", &[("core.sshCommand", "ssh -i ~/.ssh/work")]); + let quiet = isolated_quiet_fetch(&dir); + assert!( + quiet.get_envs().all(|(key, _)| key != "GIT_SSH_COMMAND"), + "core.sshCommand must not be overridden" + ); + assert!(quiet.get_envs().any(|(key, value)| key == "SSH_ASKPASS_REQUIRE" && value == Some("never".as_ref()))); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn background_fetch_command_uses_hidden_git_and_cannot_prompt() { + let dir = ssh_probe_repo("strand-ssh-batch", &[]); + let quiet = isolated_quiet_fetch(&dir); + assert_eq!(quiet.get_program(), "git"); + let args: Vec<_> = quiet.get_args().map(|arg| arg.to_string_lossy().into_owned()).collect(); + assert!(args.iter().any(|arg| arg == "fetch")); + assert!(args.iter().any(|arg| arg == "--no-prune")); + assert!(!args.iter().any(|arg| arg == "pull" || arg == "merge" || arg == "rebase")); + let env = |key: &str| { + quiet.get_envs().find(|(name, _)| *name == key).map(|(_, value)| { + value.map(|value| value.to_string_lossy().into_owned()) + }) + }; + assert_eq!(env("GIT_TERMINAL_PROMPT"), Some(Some("0".into()))); + assert_eq!(env("GCM_INTERACTIVE"), Some(Some("never".into()))); + assert_eq!(env("GIT_SSH_COMMAND"), Some(Some("ssh -o BatchMode=yes".into()))); + assert_eq!(env("SSH_ASKPASS_REQUIRE"), Some(Some("never".into()))); + assert_eq!(env("GIT_ASKPASS"), Some(None)); + assert_eq!(env("SSH_ASKPASS"), Some(None)); + let askpass = args.iter().position(|arg| arg == "core.askPass=").expect("core.askPass cleared"); + assert_eq!(args[askpass - 1], "-c"); + assert!(askpass < args.iter().position(|arg| arg == "fetch").unwrap()); + + let manual = prepare_git_command(&dir, &["fetch", "--prune", "--progress"], &[], false, false); + assert!(manual.get_envs().all(|(key, _)| key != "GCM_INTERACTIVE")); + assert!(!manual.get_args().any(|arg| arg == "core.askPass=")); + let _ = std::fs::remove_dir_all(&dir); + + let src = include_str!("network.rs"); + let start = src.find("pub(crate) fn prepare_git_command").expect("prepare_git_command"); + let body = &src[start..]; + let end = body.find("pub(crate) fn run_git_input_transcript_env").expect("runner"); + let body = &body[..end]; + assert!(body.contains("crate::git_command()")); + assert!(!body.contains("Command::new"), "bare Command::new flashes a console on Windows"); + + let fetch_start = src.find("pub fn fetch_background").expect("fetch_background"); + let fetch_body = &src[fetch_start..]; + let fetch_end = fetch_body.find("\n pub fn pull(").expect("pull"); + let fetch_body = &fetch_body[..fetch_end]; + assert!(fetch_body.contains("let quiet_auth = true;")); + assert!(fetch_body.contains("run_git_input_transcript_env")); + assert!(!fetch_body.contains("Command::new")); + assert!(!fetch_body.contains("\"pull\"")); + assert!(!fetch_body.contains("\"merge\"")); + assert!(!fetch_body.contains("\"rebase\"")); + } + + #[test] + fn auth_failure_text_is_classified_without_treating_network_blips_as_auth() { + assert!(is_auth_failure("fatal: could not read Username for 'https://example': terminal prompts disabled")); + assert!(is_auth_failure("fatal: Authentication failed for 'https://example/repo.git'")); + assert!(!is_auth_failure("fatal: unable to access 'https://example/': Could not resolve host")); + } + + #[test] + fn background_fetch_one_tick_reports_new_commits_without_touching_worktree() { + let (publisher, publisher_path, base) = push_fixture(); + publisher.push(PushMode::Default, |_| {}, None).unwrap(); + + let remote = base.join("remote.git"); + git(&remote, &["symbolic-ref", "HEAD", "refs/heads/topic"]); + let consumer_path = base.join("consumer"); + git(&base, &["clone", "-q", remote.to_str().unwrap(), consumer_path.to_str().unwrap()]); + std::fs::write(consumer_path.join("a.txt"), "dirty worktree\n").unwrap(); + std::fs::write(consumer_path.join("staged.txt"), "staged\n").unwrap(); + git(&consumer_path, &["add", "staged.txt"]); + + let head_before = git(&consumer_path, &["rev-parse", "HEAD"]); + let status_before = git(&consumer_path, &["status", "--porcelain=v1", "-uall"]); + // Staged content, not the raw index file. `git fetch` may refresh the + // untracked-cache extension without staging or unstaging anything. + let index_entries_before = git(&consumer_path, &["ls-files", "-s"]); + let worktree_before = std::fs::read(consumer_path.join("a.txt")).unwrap(); + let staged_before = std::fs::read(consumer_path.join("staged.txt")).unwrap(); + let index_tree_before = git(&consumer_path, &["write-tree"]); + + std::fs::write(publisher_path.join("a.txt"), "two\n").unwrap(); + git(&publisher_path, &["add", "a.txt"]); + git(&publisher_path, &["commit", "-q", "-m", "second"]); + publisher.push(PushMode::Default, |_| {}, None).unwrap(); + + let consumer = Repo::discover(&consumer_path).unwrap(); + let outcome = consumer.fetch_background(false).unwrap(); + assert!(outcome.ok, "{}", outcome.output); + assert!(!outcome.auth_required); + assert_eq!(outcome.new_commits, 1); + assert_eq!(outcome.behind, 1); + assert_eq!(outcome.upstream.as_deref(), Some("origin/topic")); + assert_eq!(outcome.command, "git fetch --no-prune"); + assert_eq!(git(&consumer_path, &["rev-parse", "HEAD"]), head_before); + assert_eq!(git(&consumer_path, &["status", "--porcelain=v1", "-uall"]), status_before); + assert_eq!(git(&consumer_path, &["ls-files", "-s"]), index_entries_before); + assert_eq!(std::fs::read(consumer_path.join("a.txt")).unwrap(), worktree_before); + assert_eq!(std::fs::read(consumer_path.join("staged.txt")).unwrap(), staged_before); + assert_eq!(git(&consumer_path, &["write-tree"]), index_tree_before); + + drop(consumer); + drop(publisher); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn background_fetch_auth_failure_does_not_prompt() { + let base = std::env::temp_dir().join(format!( + "strand-auth-fetch-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&base); + let local = base.join("local"); + std::fs::create_dir_all(&local).unwrap(); + git(&local, &["init", "-q", "-b", "main"]); + git(&local, &["config", "user.name", "Test"]); + git(&local, &["config", "user.email", "test@example.com"]); + git(&local, &["config", "commit.gpgsign", "false"]); + std::fs::write(local.join("a.txt"), "one\n").unwrap(); + git(&local, &["add", "a.txt"]); + git(&local, &["commit", "-q", "-m", "first"]); + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + let _ = listener.set_nonblocking(false); + for _ in 0..8 { + let Ok((mut sock, _)) = listener.accept() else { break }; + let _ = sock.set_read_timeout(Some(std::time::Duration::from_secs(2))); + let mut buf = [0u8; 2048]; + let _ = std::io::Read::read(&mut sock, &mut buf); + let _ = std::io::Write::write_all( + &mut sock, + b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"strand\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ); + } + }); + + let marker = base.join("prompted"); + let script = base.join("helper.sh"); + let marker_arg = marker.to_string_lossy().replace('\\', "/"); + std::fs::write( + &script, + "#!/bin/sh\nmarker=$1\nif [ \"$GCM_INTERACTIVE\" = \"never\" ] && [ \"$GIT_TERMINAL_PROMPT\" = \"0\" ]; then\n exit 1\nfi\necho prompted > \"$marker\"\nsleep 60\nexit 1\n", + ).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let script_arg = script.to_string_lossy().replace('\\', "/"); + git(&local, &["config", "--local", "credential.helper", ""]); + git(&local, &[ + "config", + "--local", + "--add", + "credential.helper", + &format!("!sh \"{script_arg}\" \"{marker_arg}\""), + ]); + git(&local, &[ + "remote", + "add", + "origin", + &format!("http://127.0.0.1:{port}/repo.git"), + ]); + + let repo = Repo::discover(&local).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(repo.fetch_background(true)); + }); + let outcome = rx.recv_timeout(std::time::Duration::from_secs(20)) + .expect("background fetch blocked on a credential prompt") + .unwrap(); + assert!(!outcome.ok, "expected a quiet auth failure, got {outcome:?}"); + assert!(outcome.auth_required, "output was not classified as auth: {}", outcome.output); + assert!(!marker.exists(), "credential helper opened a prompt"); + assert_eq!(outcome.new_commits, 0); + assert_eq!(git(&local, &["status", "--porcelain"]), ""); + + drop(rx); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/crates/strand-tauri/src/commands.rs b/crates/strand-tauri/src/commands.rs index 27c62cf..e40c7a5 100644 --- a/crates/strand-tauri/src/commands.rs +++ b/crates/strand-tauri/src/commands.rs @@ -27,7 +27,7 @@ use strand_core::{ maintenance::{MaintenanceOutcome, MaintenanceTask}, lfs::LfsAction, history::{MergeMode, RebaseEntry, RebaseStep}, log::{Commit, SearchMode}, - network::{clone_with_options as core_clone, CancelHandle, CloneOptions, CloneOutcome, CloneScope, HistoryExpansion, NetworkOutcome, Progress, PullMode, PushMode}, + network::{clone_with_options as core_clone, BackgroundFetchOutcome, CancelHandle, CloneOptions, CloneOutcome, CloneScope, HistoryExpansion, NetworkOutcome, Progress, PullMode, PushMode}, reflog::ReflogEntry, refs::{BaseBranch, Refs}, repo::RepoMeta, reset::{ResetMode, ResetOutcome}, snapshot::Snapshot, stash::{Stash, StashOutcome}, @@ -1193,6 +1193,16 @@ pub async fn repo_fetch( result } +/// Background auto-fetch. Same git spawn as `repo_fetch` (`CREATE_NO_WINDOW`, +/// non-interactive auth) and no progress channel — the scheduler stays quiet. +#[tauri::command(async)] +pub async fn repo_background_fetch(path: String, prune: bool) -> CmdResult { + run_blocking("background fetch", move || { + Ok(Repo::discover(&path)?.fetch_background(prune)?) + }) + .await +} + #[tauri::command(async)] pub async fn repo_pull( path: String, diff --git a/crates/strand-tauri/src/main.rs b/crates/strand-tauri/src/main.rs index 6da2245..ae0a570 100644 --- a/crates/strand-tauri/src/main.rs +++ b/crates/strand-tauri/src/main.rs @@ -270,6 +270,7 @@ fn main() { commands::repo_apply_patch, commands::repo_commit, commands::repo_fetch, + commands::repo_background_fetch, commands::repo_pull, commands::repo_push, commands::repo_branch_push, diff --git a/docs/learnings.md b/docs/learnings.md index f4a516e..d4e887d 100644 --- a/docs/learnings.md +++ b/docs/learnings.md @@ -3099,6 +3099,28 @@ sparse expansion through its existing reader. git2 0.19 `Index::get_path` already normalizes Windows separators through `path_to_repo_path`; do not add lossy string conversion to fix a raw-libgit2 issue the Rust binding handles. +## Background fetch stays on `git_command` and never prompts (DAN-89) + +**Rule.** Auto-fetch spawns git only through `prepare_git_command` → +`git_command` / `hide_console` (`CREATE_NO_WINDOW`). The background call sets +`quiet_auth`: `GCM_INTERACTIVE=never`, `-c core.askPass=` (git consults it +before `GIT_TERMINAL_PROMPT`), `SSH_ASKPASS_REQUIRE=never`, and removes +`GIT_ASKPASS` / `SSH_ASKPASS`. It sets `GIT_SSH_COMMAND=ssh -o BatchMode=yes` +only when the user has no `core.sshCommand` / `GIT_SSH_COMMAND` / `GIT_SSH`; +the env var outranks config, so setting it unconditionally drops their key. +Manual fetch must keep the user's credential helper and askpass. An auth +failure is one quiet activity entry plus backoff — do not retry every tick, +and do not pull, merge, or touch the index. A fetch that printed nothing and +brought no commits writes no activity entry. Refresh the repo afterwards +through the store's `refreshUpstream` (coalesced queue), not a direct setState. + +**Why.** The release build is GUI-subsystem. A bare `Command::new("git")` +flashes a console on Windows (DAN-83). A background tick that opens Git +Credential Manager or an SSH prompt steals focus and can hang the interval. + +**How to apply.** Add new network spawns to `prepare_git_command`. Lock the +path with the source test in `network.rs` and, on Windows, `console_probe`. + ## Agent Session Recap is a Strand builtin, not static markdown (2026-10-01) **Rule.** Community plugins stay data-only (`markdown` / `status`, diff --git a/ui/src/App.tsx b/ui/src/App.tsx index ac4fcbc..56dadb7 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -60,7 +60,9 @@ import { stashApplyProgress, stashPopProgress, } from './lib/localGitOp'; +import { backgroundFetchInFlight, manualOpPath } from './lib/autoFetch'; import { errMessage, isCancelled, isTauri, tauri } from './lib/tauri'; +import { useAutoFetch } from './lib/useAutoFetch'; import { useTheme } from './lib/theme'; import type { InitRepoRequest } from './views/InitRepoDialog'; import type { SettingsSectionId } from './views/SettingsDialog'; @@ -555,6 +557,19 @@ export function App() { // latest showToast through this ref instead of re-subscribing. const showToastRef = useRef(showToast); showToastRef.current = showToast; + const autoFetchIntervalMin = useSettings((s) => s.autoFetchIntervalMin); + // Manual network ops run against the repository that was active when they + // started. Remember that one, so switching tabs mid-op doesn't move the + // auto-fetch skip onto a repository that is idle. + const manualBusy = syncing || pulling || pushing; + const manualBusyPath = useRef(null); + manualBusyPath.current = manualOpPath(manualBusy, manualBusyPath.current, activePath); + useAutoFetch({ + intervalMin: autoFetchIntervalMin, + manualBusy, + manualPath: manualBusyPath.current, + notify: showToast, + }); const networkBusyRef = useRef(false); networkBusyRef.current = syncing || pulling || pushing; @@ -982,7 +997,7 @@ export function App() { }, []); const onExpandHistory = useCallback(async (path: string, remote: string, expansion: HistoryExpansion) => { - if (syncing || pulling || pushing) throw new Error('Another network operation is running.'); + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) throw new Error('Another network operation is running.'); setSyncing(true); setNetProgress('Downloading history…'); const opId = nextOpId(); @@ -1001,7 +1016,7 @@ export function App() { }, [syncing, pulling, pushing, nextOpId, showToast]); const onFetch = useCallback(async (prune?: boolean) => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; setSyncing(true); setNetProgress('Fetching…'); const opId = nextOpId(); @@ -1021,7 +1036,7 @@ export function App() { }, [fetchRepo, showToast, flashDone, syncing, pulling, pushing, nextOpId]); const onPull = useCallback(async (mode?: PullMode, autostash?: boolean) => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; const effectiveMode = mode ?? pullMode; const effectiveAutostash = autostash ?? pullAutostash; const label = effectiveMode === 'rebase' @@ -1050,7 +1065,7 @@ export function App() { }, [pullRepo, showToast, flashDone, syncing, pulling, pushing, pullAutostash, pullMode, nextOpId]); const onPush = useCallback(async (mode: PushMode = 'default') => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; const label = mode === 'force-with-lease' ? 'Force push with lease' : mode === 'follow-tags' @@ -1075,7 +1090,7 @@ export function App() { }, [pushRepo, showToast, flashDone, syncing, pulling, pushing, nextOpId]); const onPushAllTags = useCallback(async () => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; setPushing(true); setNetProgress('Pushing all tags…'); await waitForPaint(); @@ -1091,7 +1106,7 @@ export function App() { }, [pushAllTags, showToast, flashDone, syncing, pulling, pushing]); const onFetchBranch = useCallback(async (remoteBranch: RemoteBranch) => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; setSyncing(true); setNetProgress(`Fetching ${remoteBranch.name}…`); const opId = nextOpId(); @@ -1112,7 +1127,7 @@ export function App() { }, [fetchBranch, flashDone, nextOpId, pulling, pushing, showToast, syncing]); const onPullBranch = useCallback(async (remoteBranch: RemoteBranch, mode?: PullMode) => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; const effectiveMode = mode ?? pullMode; setPulling(true); setNetProgress(`Pulling ${remoteBranch.name}…`); @@ -1141,7 +1156,7 @@ export function App() { }, [flashDone, nextOpId, pullAutostash, pullBranch, pullMode, pulling, pushing, showToast, syncing]); const onPushBranch = useCallback(async (request: BranchPushRequest) => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; setPushing(true); setNetProgress(`Pushing ${request.branch} to ${request.remote}/${request.remoteBranch}…`); const opId = nextOpId(); @@ -1162,7 +1177,7 @@ export function App() { }, [flashDone, nextOpId, pulling, pushBranch, pushing, showToast, syncing]); const onSync = useCallback(async () => { - if (syncing || pulling || pushing) return; + if (syncing || pulling || pushing || backgroundFetchInFlight(useRepo.getState().activePath)) return; setSyncing(true); const opId = nextOpId(); setNetOpId(opId); @@ -2190,7 +2205,7 @@ export function App() { { id: 'settings', label: 'Settings…', group: 'Actions', shortcut: keyHint('settings'), keywords: 'preferences shortcuts keyboard config options', run: () => openSettingsAt('appearance') }, { id: 'whats-new', label: t('whatsNew.menu'), group: 'Actions', keywords: 'whats new changelog release notes versions history', run: () => setWhatsNewOpen(true) }, { id: 'keybindings', label: 'Settings: Keyboard shortcuts', group: 'Actions', keywords: 'keyboard shortcuts keybindings rebind configure customize', run: () => openSettingsAt('keyboard') }, - { id: 'settings-git-global', label: 'Settings: Git', group: 'Actions', keywords: 'global identity name email', run: () => openSettingsAt('git') }, + { id: 'settings-git-global', label: 'Settings: Git', group: 'Actions', keywords: 'global identity name email auto-fetch interval background', run: () => openSettingsAt('git') }, ...(meta ? [{ id: 'settings-git', label: 'Repository settings: Identity and signing', group: 'Actions', keywords: 'author committer name email local override config gpg ssh key sign tags', run: () => setRepositorySettingsPath(meta.path) } satisfies PaletteAction] : []), { id: 'settings-ai', label: 'Settings: AI', group: 'Actions', keywords: 'ai chatgpt codex claude commit message suggest login', run: () => openSettingsAt('ai') }, { id: 'settings-hosting', label: 'Settings: Hosting', group: 'Actions', keywords: 'github enterprise custom host gitlab bitbucket azure provider authentication account', run: () => openSettingsAt('hosting') }, diff --git a/ui/src/lib/autoFetch.test.ts b/ui/src/lib/autoFetch.test.ts new file mode 100644 index 0000000..5255c2c --- /dev/null +++ b/ui/src/lib/autoFetch.test.ts @@ -0,0 +1,404 @@ +import { afterEach, describe, expect, it } from 'vitest'; + +import type { BackgroundFetchOutcome } from './types'; +import { + AUTO_FETCH_AUTH_BACKOFF_MS, + autoFetchActivity, + autoFetchIsNoop, + autoFetchNotice, + backgroundFetchInFlight, + isManualBusyRepo, + manualOpPath, + normalizeAutoFetchInterval, + planAutoFetch, + resetAutoFetchState, + startAutoFetch, + type AutoFetchRepo, +} from './autoFetch'; + +const unchanged: BackgroundFetchOutcome = { + ok: true, + auth_required: false, + output: '', + command: 'git fetch --no-prune', + new_commits: 0, + upstream: 'origin/main', + behind: 0, +}; + +function repo(overrides: Partial = {}): AutoFetchRepo { + return { + path: '/repo', + active: true, + optedOut: false, + prune: true, + manualBusy: false, + ...overrides, + }; +} + +afterEach(() => { + resetAutoFetchState(); +}); + +async function settle(): Promise { + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); +} + +describe('planAutoFetch', () => { + it('fires at the interval and starts the active repository before the others', () => { + const repos = [ + repo({ path: '/other', active: false }), + repo({ path: '/active', active: true }), + ]; + const idle = planAutoFetch({ + now: 0, + intervalMin: 10, + offline: false, + repos, + armedAt: 0, + lastStarted: new Map(), + backoffUntil: new Map(), + inFlight: new Set(), + staggerMs: 1_000, + }); + expect(idle.start).toEqual([]); + expect(idle.wakeAt).toBe(10 * 60_000); + + const first = planAutoFetch({ + now: 10 * 60_000, + intervalMin: 10, + offline: false, + repos, + armedAt: 0, + lastStarted: new Map(), + backoffUntil: new Map(), + inFlight: new Set(), + staggerMs: 1_000, + }); + expect(first.start.map((item) => item.path)).toEqual(['/active']); + expect(first.wakeAt).toBe(10 * 60_000 + 1_000); + + const second = planAutoFetch({ + now: 10 * 60_000 + 1_000, + intervalMin: 10, + offline: false, + repos, + armedAt: 0, + lastStarted: new Map([['/active', 10 * 60_000]]), + backoffUntil: new Map(), + inFlight: new Set(), + staggerMs: 1_000, + }); + expect(second.start.map((item) => item.path)).toEqual(['/other']); + }); + + it('does not start a second fetch while one is in flight and skips a manual fetch', () => { + const base = { + now: 10 * 60_000, + intervalMin: 10, + offline: false, + armedAt: 0, + lastStarted: new Map(), + backoffUntil: new Map(), + staggerMs: 1_000, + }; + const busy = planAutoFetch({ + ...base, + repos: [repo()], + inFlight: new Set(['/repo']), + }); + expect(busy.start).toEqual([]); + + const manual = planAutoFetch({ + ...base, + repos: [repo({ manualBusy: true })], + inFlight: new Set(), + }); + expect(manual.start).toEqual([]); + }); + + it('spawns nothing when the interval is off, the repo opted out, or the app is offline', () => { + const shared = { + now: 10 * 60_000, + offline: false, + repos: [repo()], + armedAt: 0, + lastStarted: new Map(), + backoffUntil: new Map(), + inFlight: new Set(), + }; + expect(planAutoFetch({ ...shared, intervalMin: 0 }).start).toEqual([]); + expect(planAutoFetch({ ...shared, intervalMin: 0 }).wakeAt).toBeNull(); + expect(planAutoFetch({ ...shared, intervalMin: 10, repos: [repo({ optedOut: true })] }).start).toEqual([]); + expect(planAutoFetch({ ...shared, intervalMin: 10, offline: true }).start).toEqual([]); + }); + + it('backs off after an auth failure instead of retrying the next tick', () => { + const failedAt = 10 * 60_000; + const during = planAutoFetch({ + now: failedAt + 10 * 60_000, + intervalMin: 10, + offline: false, + repos: [repo()], + armedAt: 0, + lastStarted: new Map([['/repo', failedAt]]), + backoffUntil: new Map([['/repo', failedAt + AUTO_FETCH_AUTH_BACKOFF_MS]]), + inFlight: new Set(), + }); + expect(during.start).toEqual([]); + + const after = planAutoFetch({ + now: failedAt + AUTO_FETCH_AUTH_BACKOFF_MS, + intervalMin: 10, + offline: false, + repos: [repo()], + armedAt: 0, + lastStarted: new Map([['/repo', failedAt]]), + backoffUntil: new Map([['/repo', failedAt + AUTO_FETCH_AUTH_BACKOFF_MS]]), + inFlight: new Set(), + }); + expect(after.start.map((item) => item.path)).toEqual(['/repo']); + }); +}); + +describe('manual op skip', () => { + const tabs = ['/a', '/b']; + // Mirrors useAutoFetch's repos callback: the busy flag follows the op's repo. + function plan(activePath: string, manualPath: string | null, lastStarted = new Map()) { + return planAutoFetch({ + now: 10 * 60_000, + intervalMin: 10, + offline: false, + repos: tabs.map((path) => repo({ + path, + active: path === activePath, + manualBusy: isManualBusyRepo(path, manualPath), + })), + armedAt: 0, + lastStarted, + backoffUntil: new Map(), + inFlight: new Set(), + staggerMs: 1_000, + }).start.map((item) => item.path); + } + + it('skips the busy non-active repo and still fetches the active one', () => { + expect(plan('/a', '/b')).toEqual(['/a']); + }); + + it('skips the busy active repo and still fetches the other one', () => { + expect(plan('/a', '/a')).toEqual(['/b']); + }); + + it('keeps the skip on the original repo when tabs switch mid-op, and clears it when the op ends', () => { + // Op starts on /b, then the user switches to /a while it runs. + let remembered = manualOpPath(true, null, '/b'); + expect(remembered).toBe('/b'); + remembered = manualOpPath(true, remembered, '/a'); + expect(remembered).toBe('/b'); + expect(plan('/a', remembered)).toEqual(['/a']); + expect(plan('/a', remembered, new Map([['/a', 10 * 60_000]]))).toEqual([]); + + // Op ends: nothing is skipped, and the next op picks up the new active repo. + remembered = manualOpPath(false, remembered, '/a'); + expect(remembered).toBeNull(); + expect(plan('/a', remembered, new Map([['/a', 10 * 60_000]]))).toEqual(['/b']); + expect(manualOpPath(true, remembered, '/a')).toBe('/a'); + }); + + it('matches the busy repo by path identity', () => { + expect(isManualBusyRepo('C:\\repo', 'C:/repo/')).toBe(true); + expect(isManualBusyRepo('/repo', null)).toBe(false); + }); +}); + +describe('startAutoFetch', () => { + it('does not spawn a fetch until the interval, then surfaces a new-commit notice once', async () => { + let now = 5_000; + const queued: Array<{ at: number; run: () => void | Promise }> = []; + const fetched: Array<{ path: string; prune: boolean }> = []; + const notices: string[] = []; + const loop = startAutoFetch({ + now: () => now, + schedule(fn, ms) { + queued.push({ at: now + ms, run: fn }); + return queued.length; + }, + clear() {}, + intervalMin: () => 10, + offline: () => false, + staggerMs: 1_000, + repos: () => [ + repo({ path: '/active', active: true, prune: false }), + repo({ path: '/other', active: false, prune: true }), + ], + fetch: async (item) => { + fetched.push({ path: item.path, prune: item.prune }); + if (item.path === '/active') { + return { ...unchanged, command: 'git fetch --no-prune', new_commits: 2, upstream: 'origin/main', behind: 2 }; + } + return unchanged; + }, + onResult: (_item, result) => { + const notice = autoFetchNotice(result); + if (notice) notices.push(notice); + }, + }); + await loop.whenIdle(); + expect(fetched).toEqual([]); + expect(queued[0].at - 5_000).toBe(10 * 60_000); + + now = queued[0].at; + queued[0].run(); + await loop.whenIdle(); + await settle(); + expect(fetched).toEqual([{ path: '/active', prune: false }]); + expect(notices).toEqual(['2 new commits on origin/main']); + expect(autoFetchNotice({ new_commits: 1, upstream: 'origin/main' })).toBe('1 new commit on origin/main'); + expect(autoFetchNotice({ new_commits: 0, upstream: 'origin/main' })).toBeNull(); + loop.stop(); + }); + + it('never runs two fetches for the same repo and skips a manual fetch or pull', async () => { + let now = 0; + const queued: Array<{ at: number; run: () => void | Promise }> = []; + const gate: { release: (() => void) | null } = { release: null }; + let calls = 0; + let manual = false; + const loop = startAutoFetch({ + now: () => now, + schedule(fn, ms) { + queued.push({ at: now + ms, run: fn }); + return queued.length; + }, + clear() {}, + intervalMin: () => 10, + offline: () => false, + staggerMs: 1_000, + repos: () => [repo({ manualBusy: manual })], + fetch: () => new Promise((resolve) => { + calls += 1; + gate.release = () => resolve(unchanged); + }), + onResult() {}, + }); + await loop.whenIdle(); + now = 10 * 60_000; + queued.at(-1)?.run(); + await loop.whenIdle(); + expect(calls).toBe(1); + expect(backgroundFetchInFlight('/repo')).toBe(true); + + now = 20 * 60_000; + const before = queued.length; + queued.at(-1)?.run(); + await loop.whenIdle(); + expect(calls).toBe(1); + expect(queued.length).toBeGreaterThan(before); + + gate.release?.(); + await Promise.resolve(); + manual = true; + now = 30 * 60_000; + queued.at(-1)?.run(); + await loop.whenIdle(); + expect(calls).toBe(1); + loop.stop(); + }); + + it('records one quiet auth failure and does not spawn again until backoff ends', async () => { + let now = 0; + const queued: Array<{ at: number; run: () => void | Promise }> = []; + const calls: number[] = []; + const activities: string[] = []; + const loop = startAutoFetch({ + now: () => now, + schedule(fn, ms) { + queued.push({ at: now + ms, run: fn }); + return queued.length; + }, + clear() {}, + intervalMin: () => 10, + offline: () => false, + repos: () => [repo()], + fetch: async () => { + calls.push(now); + return { + ...unchanged, + ok: false, + auth_required: true, + output: 'fatal: could not read Username: terminal prompts disabled', + }; + }, + onResult: (item, result, startedAt, finishedAt) => { + activities.push(autoFetchActivity(item.path, result, startedAt, finishedAt).output); + }, + }); + await loop.whenIdle(); + now = 10 * 60_000; + queued.at(-1)?.run(); + await loop.whenIdle(); + await settle(); + expect(calls).toEqual([10 * 60_000]); + expect(activities).toEqual(['fatal: could not read Username: terminal prompts disabled']); + + now = 20 * 60_000; + queued.at(-1)?.run(); + await loop.whenIdle(); + expect(calls).toEqual([10 * 60_000]); + + now = 10 * 60_000 + AUTO_FETCH_AUTH_BACKOFF_MS; + queued.at(-1)?.run(); + await loop.whenIdle(); + await settle(); + expect(calls).toEqual([10 * 60_000, now]); + loop.stop(); + }); + + it('spawns no background fetch when the setting is off', async () => { + const queued: unknown[] = []; + let fetched = 0; + const loop = startAutoFetch({ + now: () => 0, + schedule(fn) { + queued.push(fn); + return queued.length; + }, + clear() {}, + intervalMin: () => 0, + offline: () => false, + repos: () => [repo()], + fetch: async () => { + fetched += 1; + return unchanged; + }, + onResult() {}, + }); + await loop.whenIdle(); + expect(fetched).toBe(0); + expect(queued).toEqual([]); + loop.stop(); + }); +}); + +describe('autoFetchIsNoop', () => { + it('treats a silent successful fetch as a no-op and anything else as worth logging', () => { + expect(autoFetchIsNoop(unchanged)).toBe(true); + expect(autoFetchIsNoop({ ...unchanged, output: ' \n' })).toBe(true); + expect(autoFetchIsNoop({ ...unchanged, output: ' - [deleted] (none) -> origin/old' })).toBe(false); + expect(autoFetchIsNoop({ ...unchanged, new_commits: 2, output: '' })).toBe(false); + expect(autoFetchIsNoop({ ...unchanged, ok: false })).toBe(false); + }); +}); + +describe('normalizeAutoFetchInterval', () => { + it('keeps the chosen 10 minute default and rejects unknown values', () => { + expect(normalizeAutoFetchInterval(undefined)).toBe(10); + expect(normalizeAutoFetchInterval(10)).toBe(10); + expect(normalizeAutoFetchInterval(7)).toBe(10); + expect(normalizeAutoFetchInterval(0)).toBe(0); + }); +}); diff --git a/ui/src/lib/autoFetch.ts b/ui/src/lib/autoFetch.ts new file mode 100644 index 0000000..5c454e4 --- /dev/null +++ b/ui/src/lib/autoFetch.ts @@ -0,0 +1,250 @@ +import { plural } from './i18n'; +import { pathKey } from './repoIdentity'; +import type { BackgroundFetchOutcome, RepoActivityEntry } from './types'; + +/** + * Background fetch interval. Daniels chose 10 minutes. + * Change this one constant to change the default. + */ +export const DEFAULT_AUTO_FETCH_INTERVAL_MIN = 10; + +export const AUTO_FETCH_INTERVALS = [0, 5, 10, 30] as const; +export type AutoFetchIntervalMin = (typeof AUTO_FETCH_INTERVALS)[number]; + +/** Gap between open repositories so one tick does not fetch them together. */ +export const AUTO_FETCH_STAGGER_MS = 15_000; + +/** After an auth failure, skip this repository instead of prompting every tick. */ +export const AUTO_FETCH_AUTH_BACKOFF_MS = 60 * 60 * 1000; + +export function normalizeAutoFetchInterval(value: unknown): AutoFetchIntervalMin { + if (value === 0 || value === 5 || value === 10 || value === 30) return value; + return DEFAULT_AUTO_FETCH_INTERVAL_MIN; +} + +export interface AutoFetchRepo { + path: string; + active: boolean; + optedOut: boolean; + prune: boolean; + /** A manual fetch, pull, or push is already running for this repository. */ + manualBusy: boolean; +} + +/** + * The repository a manual network op runs against: the one active when it + * started. Switching tabs mid-op keeps it; the op ending clears it. + */ +export function manualOpPath(busy: boolean, remembered: string | null, activePath: string | null): string | null { + if (!busy) return null; + return remembered ?? activePath; +} + +/** Whether `path` is the repository a running manual network op targets. */ +export function isManualBusyRepo(path: string, manualPath: string | null): boolean { + return !!manualPath && pathKey(manualPath) === pathKey(path); +} + +export interface AutoFetchPlanInput { + now: number; + intervalMin: number; + offline: boolean; + repos: readonly AutoFetchRepo[]; + /** When the loop started. A repo with no prior fetch becomes due one interval later. */ + armedAt: number; + lastStarted: ReadonlyMap; + backoffUntil: ReadonlyMap; + inFlight: ReadonlySet; + staggerMs?: number; +} + +export interface AutoFetchPlan { + /** At most one repository — the active one first, then the others. */ + start: AutoFetchRepo[]; + /** Absolute time of the next wake, or null when auto-fetch is off. */ + wakeAt: number | null; +} + +export function planAutoFetch(input: AutoFetchPlanInput): AutoFetchPlan { + const intervalMin = normalizeAutoFetchInterval(input.intervalMin); + if (intervalMin === 0) return { start: [], wakeAt: null }; + + const intervalMs = intervalMin * 60_000; + const stagger = input.staggerMs ?? AUTO_FETCH_STAGGER_MS; + if (input.offline) return { start: [], wakeAt: input.now + intervalMs }; + + const ordered = [...input.repos].sort((a, b) => Number(b.active) - Number(a.active)); + const ready: AutoFetchRepo[] = []; + let nextDue = Number.POSITIVE_INFINITY; + let recheck = Number.POSITIVE_INFINITY; + + for (const repo of ordered) { + if (repo.optedOut) continue; + const dueAt = (input.lastStarted.get(repo.path) ?? input.armedAt) + intervalMs; + if (input.now < dueAt) { + nextDue = Math.min(nextDue, dueAt); + continue; + } + const backoff = input.backoffUntil.get(repo.path) ?? 0; + if (input.now < backoff) { + recheck = Math.min(recheck, backoff); + continue; + } + if (repo.manualBusy || input.inFlight.has(repo.path)) { + recheck = Math.min(recheck, input.now + stagger); + continue; + } + ready.push(repo); + } + + const start: AutoFetchRepo[] = []; + if (ready.length > 0) { + start.push(ready[0]); + if (ready.length > 1) recheck = Math.min(recheck, input.now + stagger); + } + + const candidates = [nextDue, recheck].filter((at) => Number.isFinite(at)); + const wakeAt = candidates.length > 0 ? Math.min(...candidates) : input.now + intervalMs; + return { start, wakeAt }; +} + +export function autoFetchNotice(result: Pick): string | null { + if (!result.upstream || result.new_commits <= 0) return null; + return plural( + result.new_commits, + { one: 'git.notice.one', other: 'git.notice.other' }, + { upstream: result.upstream }, + 'en-US', + ); +} + +/** A successful fetch that git reported nothing for: no ref moved or was pruned. */ +export function autoFetchIsNoop(result: Pick): boolean { + return result.ok && result.new_commits <= 0 && result.output.trim() === ''; +} + +export function autoFetchActivity( + path: string, + result: BackgroundFetchOutcome, + startedAt: number, + finishedAt: number, +): RepoActivityEntry { + return { + id: `background-fetch-${path}-${startedAt}`, + task: 'background-fetch', + started_at: startedAt, + command: result.command, + output: result.ok ? (autoFetchNotice(result) ?? '') : result.output, + success: result.ok, + duration_ms: Math.max(0, finishedAt - startedAt), + }; +} + +const inFlight = new Set(); +const lastStarted = new Map(); +const backoffUntil = new Map(); + +export function resetAutoFetchState(): void { + inFlight.clear(); + lastStarted.clear(); + backoffUntil.clear(); +} + +export function backgroundFetchInFlight(path: string | null): boolean { + if (!path) return false; + const key = pathKey(path); + for (const running of inFlight) { + if (pathKey(running) === key) return true; + } + return false; +} + +export interface AutoFetchLoopDeps { + now: () => number; + schedule: (fn: () => void | Promise, ms: number) => number; + clear: (id: number) => void; + intervalMin: () => number; + offline: () => boolean; + repos: () => AutoFetchRepo[] | Promise; + fetch: (repo: AutoFetchRepo) => Promise; + onResult: (repo: AutoFetchRepo, result: BackgroundFetchOutcome, startedAt: number, finishedAt: number) => void; + staggerMs?: number; +} + +export function startAutoFetch(deps: AutoFetchLoopDeps): { stop: () => void; whenIdle: () => Promise } { + let stopped = false; + let timer: number | null = null; + let idle: Promise = Promise.resolve(); + const armedAt = deps.now(); + + async function run(): Promise { + if (stopped) return; + const now = deps.now(); + const repos = await deps.repos(); + if (stopped) return; + const plan = planAutoFetch({ + now, + intervalMin: deps.intervalMin(), + offline: deps.offline(), + repos, + armedAt, + lastStarted, + backoffUntil, + inFlight, + staggerMs: deps.staggerMs, + }); + for (const repo of plan.start) { + inFlight.add(repo.path); + lastStarted.set(repo.path, now); + const startedAt = now; + void deps.fetch(repo).then( + (result) => { + const finishedAt = deps.now(); + if (result.auth_required) backoffUntil.set(repo.path, finishedAt + AUTO_FETCH_AUTH_BACKOFF_MS); + if (!stopped) deps.onResult(repo, result, startedAt, finishedAt); + }, + (error: unknown) => { + const finishedAt = deps.now(); + if (stopped) return; + const message = error instanceof Error ? error.message : String(error); + deps.onResult(repo, { + ok: false, + auth_required: false, + output: message, + command: repo.prune ? 'git fetch --prune' : 'git fetch --no-prune', + new_commits: 0, + upstream: null, + behind: 0, + }, startedAt, finishedAt); + }, + ).finally(() => { + inFlight.delete(repo.path); + }); + } + arm(plan.wakeAt); + } + + function kick(): Promise { + const job = run(); + idle = job; + return job; + } + + function arm(wakeAt: number | null) { + if (timer != null) deps.clear(timer); + timer = null; + if (wakeAt == null || stopped) return; + const delay = Math.max(0, wakeAt - deps.now()); + timer = deps.schedule(() => { void kick(); }, delay); + } + + void kick(); + return { + stop() { + stopped = true; + if (timer != null) deps.clear(timer); + timer = null; + }, + whenIdle: () => idle, + }; +} diff --git a/ui/src/lib/db.ts b/ui/src/lib/db.ts index 07fdf23..1e3c39d 100644 --- a/ui/src/lib/db.ts +++ b/ui/src/lib/db.ts @@ -332,6 +332,17 @@ export const repoNetworkPreferences = { }, }; +/** Per-repository auto-fetch opt-out. Missing or `true` means the global + * interval applies; `false` skips this repository. */ +export const repoAutoFetch = { + get(repoPath: string): Promise { + return settings.get(`auto-fetch:${repoPath}`); + }, + set(repoPath: string, enabled: boolean): Promise { + return settings.set(`auto-fetch:${repoPath}`, enabled); + }, +}; + /** Durable, bounded transcript of explicit repository housekeeping runs. */ export const repoActivity = { async list(repoPath: string): Promise { diff --git a/ui/src/lib/i18n.ts b/ui/src/lib/i18n.ts index 83e005d..3894cce 100644 --- a/ui/src/lib/i18n.ts +++ b/ui/src/lib/i18n.ts @@ -369,6 +369,15 @@ export const en = { 'merge.ai.retry': 'Retry with {provider}', 'merge.ai.signIn': 'Sign-in started — complete it in the browser or CLI window, then suggest again.', 'merge.ai.signInFailed': 'Sign-in failed: {message}', + 'git.autoFetch': 'Auto-fetch', + 'git.autoFetchHint': 'Fetch open repositories on a timer. Fetch only — Strand does not pull, merge, or change your files.', + 'git.autoFetch.off': 'Off', + 'git.autoFetch.minutes': '{count} min', + 'git.autoFetchRepoHint': 'Uncheck a repository to skip its background fetch.', + 'git.autoFetchNone': 'Open a repository to choose a per-repository exception.', + 'git.activity.fetch': 'Background fetch', + 'git.notice.one': '1 new commit on {upstream}', + 'git.notice.other': '{count} new commits on {upstream}', } as const; export type MessageKey = keyof typeof en; diff --git a/ui/src/lib/tauri.ts b/ui/src/lib/tauri.ts index b0be77f..de61ed0 100644 --- a/ui/src/lib/tauri.ts +++ b/ui/src/lib/tauri.ts @@ -62,6 +62,7 @@ import type { SubmoduleAction, SubmodulePage, MergeMode, + BackgroundFetchOutcome, NetworkOutcome, Progress, PullMode, @@ -478,6 +479,9 @@ export const tauri = { opId, onEvent: progressChannel(onProgress), }), + /** Background auto-fetch. No progress channel and no credential prompt. */ + repoBackgroundFetch: (path: string, prune: boolean) => + invoke('repo_background_fetch', { path, prune }), repoPull: (path: string, mode: PullMode, autostash: boolean, onProgress?: (p: Progress) => void, opId?: string) => invoke('repo_pull', { path, diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 94a4d63..19f0f9e 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -527,6 +527,18 @@ export interface NetworkOutcome { output: string; } +/** One background `git fetch`. Auth failures stay here so the scheduler can + * record a single quiet entry and back off instead of prompting. */ +export interface BackgroundFetchOutcome { + ok: boolean; + auth_required: boolean; + output: string; + command: string; + new_commits: number; + upstream: string | null; + behind: number; +} + export type MaintenanceTask = 'maintenance' | 'garbage-collect' | 'integrity-check'; export interface MaintenanceOutcome { @@ -538,7 +550,7 @@ export interface MaintenanceOutcome { export interface RepoActivityEntry extends MaintenanceOutcome { id: string; - task: MaintenanceTask | 'commit' | 'amend'; + task: MaintenanceTask | 'commit' | 'amend' | 'background-fetch'; started_at: number; } diff --git a/ui/src/lib/useAutoFetch.ts b/ui/src/lib/useAutoFetch.ts new file mode 100644 index 0000000..ba8ca7e --- /dev/null +++ b/ui/src/lib/useAutoFetch.ts @@ -0,0 +1,79 @@ +import { useEffect, useRef } from 'react'; + +import { repoActivity, repoAutoFetch, repoNetworkPreferences } from './db'; +import { pathKey } from './repoIdentity'; +import { isTauri, tauri } from './tauri'; +import type { AutoFetchIntervalMin } from './autoFetch'; +import { + autoFetchActivity, + autoFetchIsNoop, + autoFetchNotice, + isManualBusyRepo, + startAutoFetch, +} from './autoFetch'; +import { useRepo } from '../stores/repo'; + +/** + * Fetch open repositories on the Settings → Git interval. Active repo first, + * others one stagger later. Manual network ops and in-flight fetches skip + * that repository. Auth failures are one quiet activity entry plus a backoff. + */ +export function useAutoFetch(options: { + intervalMin: AutoFetchIntervalMin; + manualBusy: boolean; + manualPath: string | null; + notify: (message: string) => void; +}): void { + const optionsRef = useRef(options); + optionsRef.current = options; + const intervalMin = options.intervalMin; + + useEffect(() => { + if (!isTauri()) return; + const loop = startAutoFetch({ + now: () => Date.now(), + schedule: (fn, ms) => window.setTimeout(() => { void fn(); }, ms), + clear: (id) => window.clearTimeout(id), + intervalMin: () => optionsRef.current.intervalMin, + offline: () => typeof navigator !== 'undefined' && navigator.onLine === false, + staggerMs: undefined, + repos: async () => { + const { tabs, activePath } = useRepo.getState(); + const manualPath = optionsRef.current.manualBusy ? optionsRef.current.manualPath : null; + return Promise.all(tabs.map(async (tab) => { + let prune = true; + let optedOut = false; + try { + const [prefs, enabled] = await Promise.all([ + repoNetworkPreferences.get(tab.path), + repoAutoFetch.get(tab.path), + ]); + if (typeof prefs?.fetchPrune === 'boolean') prune = prefs.fetchPrune; + optedOut = enabled === false; + } catch { + // A settings read failure must not turn into a fetch storm. + } + return { + path: tab.path, + active: !!activePath && pathKey(activePath) === pathKey(tab.path), + optedOut, + prune, + manualBusy: isManualBusyRepo(tab.path, manualPath), + }; + })); + }, + fetch: (repo) => tauri.repoBackgroundFetch(repo.path, repo.prune), + onResult: (repo, result, startedAt, finishedAt) => { + const notice = autoFetchNotice(result); + if (notice) optionsRef.current.notify(notice); + // A fetch that changed nothing is not worth an activity row every tick. + if (autoFetchIsNoop(result)) return; + const entry = autoFetchActivity(repo.path, result, startedAt, finishedAt); + void repoActivity.append(repo.path, entry).catch(() => {}); + if (!result.ok) return; + void useRepo.getState().refreshUpstream(repo.path); + }, + }); + return () => loop.stop(); + }, [intervalMin]); +} diff --git a/ui/src/stores/repo.test.ts b/ui/src/stores/repo.test.ts index 4f11e12..6eef1b9 100644 --- a/ui/src/stores/repo.test.ts +++ b/ui/src/stores/repo.test.ts @@ -120,6 +120,35 @@ describe('repository navigation state', () => { }); }); +describe('background fetch refresh', () => { + it('coalesces upstream refreshes and only reloads refs for the active repository', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + const meta = { branch: 'main', ahead: 0, behind: 3 } as unknown as RepoMeta; + const repoMeta = vi.spyOn(tauri, 'repoMeta').mockImplementation(async () => { await gate; return meta; }); + const refreshRefs = vi.fn(async () => {}); + useRepo.setState({ + activePath: '/active', + tabs: [{ path: '/active' }, { path: '/other' }] as never, + refreshRefs, + }); + + const first = useRepo.getState().refreshUpstream('/other'); + const second = useRepo.getState().refreshUpstream('/other'); + release(); + await Promise.all([first, second]); + + expect(repoMeta).toHaveBeenCalledTimes(1); + expect(refreshRefs).not.toHaveBeenCalled(); + expect(useRepo.getState().tabs.find((t) => t.path === '/other')?.meta).toBe(meta); + expect(useRepo.getState().meta).not.toBe(meta); + + await useRepo.getState().refreshUpstream('/active'); + expect(refreshRefs).toHaveBeenCalledOnce(); + expect(useRepo.getState().meta).toBe(meta); + }); +}); + describe('AI review notes', () => { it('adds accepted AI findings without touching existing feedback', () => { const next = addAiReviewNoteSet( diff --git a/ui/src/stores/repo.ts b/ui/src/stores/repo.ts index d63ebb0..459679e 100644 --- a/ui/src/stores/repo.ts +++ b/ui/src/stores/repo.ts @@ -445,6 +445,11 @@ export interface RepoState { /** Re-read RepoMeta (branch, ahead/behind) for the active tab. */ refreshMeta(): Promise; + /** + * After a background fetch: re-read `path`'s meta (ahead/behind) through the + * coalesced refresh queue, and its refs when it is the active repository. + */ + refreshUpstream(path: string): Promise; /** Default strategy used by the primary Pull action for this repository. */ pullMode: PullMode; setPullMode(mode: PullMode): void; @@ -1930,6 +1935,23 @@ export const useRepo = create((set, get) => ({ tabs: s.tabs.map((t) => (t.path === path ? { ...t, meta } : t)), })); }, + async refreshUpstream(path) { + const key = pathKey(path); + await refreshes.run(`${key}:upstream`, async (current) => { + try { + const meta = await tauri.repoMeta(path); + if (!current()) return; + set((s) => { + const tabs = s.tabs.map((t) => (pathKey(t.path) === key ? { ...t, meta } : t)); + return s.activePath && pathKey(s.activePath) === key ? { tabs, meta } : { tabs }; + }); + } catch (e) { + console.warn('repoMeta failed', e); + } + }); + const active = get().activePath; + if (active && pathKey(active) === key) await get().refreshRefs(); + }, setPullMode(mode) { set({ pullMode: mode }); const path = get().activePath; diff --git a/ui/src/stores/settings.test.ts b/ui/src/stores/settings.test.ts index 5434b0d..e233cc4 100644 --- a/ui/src/stores/settings.test.ts +++ b/ui/src/stores/settings.test.ts @@ -21,6 +21,7 @@ test('persists startup settings and seeds the configured initial space', async ( const { useSettings } = await import('./settings'); expect(useSettings.getState().startupSpace).toBe('work'); + expect(useSettings.getState().autoFetchIntervalMin).toBe(10); expect(useSettings.getState().keybindings).toEqual({ 'customize-workbench': 'Mod+9' }); useSettings.getState().set('aiConnectionStatus', { openai: { installed: true, loggedIn: true, checkedAt: 123 }, diff --git a/ui/src/stores/settings.ts b/ui/src/stores/settings.ts index dcadcba..5538e67 100644 --- a/ui/src/stores/settings.ts +++ b/ui/src/stores/settings.ts @@ -2,6 +2,7 @@ import { create } from 'zustand'; import type { UserAction } from '../lib/userActions'; import { persist } from 'zustand/middleware'; +import { DEFAULT_AUTO_FETCH_INTERVAL_MIN, normalizeAutoFetchInterval, type AutoFetchIntervalMin } from '../lib/autoFetch'; import { t } from '../lib/i18n'; import type { KeyOverrides } from '../lib/keys'; import type { AiProvider, EmbeddedShellChoice } from '../lib/types'; @@ -135,6 +136,11 @@ export interface SettingsState { fileOpenTab: FileOpenTab; /** Directory the clone dialog and open-repo picker start in. */ defaultCloneDir: string | null; + /** + * Background fetch interval in minutes. `0` is off. + * Default is {@link DEFAULT_AUTO_FETCH_INTERVAL_MIN} (Daniels chose 10). + */ + autoFetchIntervalMin: AutoFetchIntervalMin; editorTool: ExternalTool; terminalTool: ExternalTool; userActions: UserAction[]; @@ -279,6 +285,7 @@ export const useSettings = create()( diffWordHighlight: true, fileOpenTab: 'preview', defaultCloneDir: null, + autoFetchIntervalMin: DEFAULT_AUTO_FETCH_INTERVAL_MIN, editorTool: null, terminalTool: null, userActions: [], @@ -348,6 +355,7 @@ export const useSettings = create()( platform: detectPlatform(), terminalFont, diffSyntaxTheme, + autoFetchIntervalMin: normalizeAutoFetchInterval(next.autoFetchIntervalMin), terminalFontSize: Number.isFinite(storedSize) ? Math.min(32, Math.max(10, Math.round(storedSize))) : current.terminalFontSize, diff --git a/ui/src/views/MaintenanceDialog.tsx b/ui/src/views/MaintenanceDialog.tsx index 32d2fe2..02d640c 100644 --- a/ui/src/views/MaintenanceDialog.tsx +++ b/ui/src/views/MaintenanceDialog.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { Dialog } from '../components/Dialog'; import { repoActivity } from '../lib/db'; +import { t } from '../lib/i18n'; import { errMessage, isCancelled, tauri } from '../lib/tauri'; import type { MaintenanceOutcome, MaintenanceTask, RepoActivityEntry } from '../lib/types'; @@ -35,6 +36,25 @@ function taskDefinition(task: MaintenanceTask) { return TASKS.find((candidate) => candidate.task === task) as (typeof TASKS)[number]; } +function activityLabel(task: RepoActivityEntry['task']): string { + switch (task) { + case 'commit': + return 'Commit'; + case 'amend': + return 'Amend commit'; + case 'background-fetch': + return t('git.activity.fetch'); + case 'maintenance': + case 'garbage-collect': + case 'integrity-check': + return taskDefinition(task).label; + default: { + const exhaustive: never = task; + return exhaustive; + } + } +} + function duration(ms: number): string { if (ms < 1_000) return `${ms} ms`; return `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)} s`; @@ -161,7 +181,7 @@ export function MaintenanceDialog({ ) : entries.map((entry) => (
- {entry.task === 'commit' ? 'Commit' : entry.task === 'amend' ? 'Amend commit' : taskDefinition(entry.task).label} + {activityLabel(entry.task)} {entry.success ? 'Completed' : 'Failed'} · {duration(entry.duration_ms)} · {new Date(entry.started_at).toLocaleString()} {entry.command} diff --git a/ui/src/views/settings/GitSection.tsx b/ui/src/views/settings/GitSection.tsx index 582499f..e360d86 100644 --- a/ui/src/views/settings/GitSection.tsx +++ b/ui/src/views/settings/GitSection.tsx @@ -1,8 +1,20 @@ import { useEffect, useState } from 'react'; +import { type AutoFetchIntervalMin } from '../../lib/autoFetch'; +import { repoAutoFetch } from '../../lib/db'; import { pickDirectory } from '../../lib/dialog'; +import { t } from '../../lib/i18n'; import { errMessage, isTauri, tauri } from '../../lib/tauri'; +import { useRepo } from '../../stores/repo'; import { useSettings } from '../../stores/settings'; +import { CheckRow, SegRow } from './shared'; + +const AUTO_FETCH_OPTIONS: { id: `${AutoFetchIntervalMin}`; label: string }[] = [ + { id: '0', label: t('git.autoFetch.off') }, + { id: '5', label: t('git.autoFetch.minutes', { count: 5 }) }, + { id: '10', label: t('git.autoFetch.minutes', { count: 10 }) }, + { id: '30', label: t('git.autoFetch.minutes', { count: 30 }) }, +]; /** * Git — the global identity (`user.name` / `user.email`, written to @@ -12,7 +24,11 @@ import { useSettings } from '../../stores/settings'; */ export function GitSection() { const defaultCloneDir = useSettings((s) => s.defaultCloneDir); + const autoFetchIntervalMin = useSettings((s) => s.autoFetchIntervalMin); const set = useSettings((s) => s.set); + const tabs = useRepo((s) => s.tabs); + const tabKey = tabs.map((tab) => tab.path).join('\n'); + const [autoFetchOff, setAutoFetchOff] = useState>({}); const [name, setName] = useState(''); const [email, setEmail] = useState(''); @@ -20,6 +36,20 @@ export function GitSection() { const [dirty, setDirty] = useState(false); const [status, setStatus] = useState(null); + useEffect(() => { + if (!isTauri()) return; + let cancelled = false; + const paths = tabKey ? tabKey.split('\n') : []; + void Promise.all(paths.map(async (path) => [path, (await repoAutoFetch.get(path)) === false] as const)) + .then((rows) => { + if (!cancelled) setAutoFetchOff(Object.fromEntries(rows)); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [tabKey]); + useEffect(() => { if (!isTauri()) return; let cancelled = false; @@ -101,6 +131,42 @@ export function GitSection() { +
+ {t('git.autoFetch')} +

{t('git.autoFetchHint')}

+
+ { + const minutes = Number(id); + if (minutes === 0 || minutes === 5 || minutes === 10 || minutes === 30) { + set('autoFetchIntervalMin', minutes); + } + }} + /> +
+

{t('git.autoFetchRepoHint')}

+ {tabs.length === 0 ? ( +

{t('git.autoFetchNone')}

+ ) : ( +
+ {tabs.map((tab) => ( + { + setAutoFetchOff((current) => ({ ...current, [tab.path]: !enabled })); + void repoAutoFetch.set(tab.path, enabled); + }} + /> + ))} +
+ )} +
+
Default clone & open folder

diff --git a/website/docs/everyday-git.md b/website/docs/everyday-git.md index 428e600..0e3bbca 100644 --- a/website/docs/everyday-git.md +++ b/website/docs/everyday-git.md @@ -113,7 +113,7 @@ the other provider without changing the default in Settings. ## Fetch, pull, push -The topbar Fetch / Pull / Push buttons show real ahead/behind counts. The adjacent chevron opens the full network menu: fetch with or without pruning stale remote-tracking branches; pull using Git's configured behavior, an explicit merge, rebase, or fast-forward-only, with or without autostash; and push the current branch, follow annotated tags, push every tag, or force-push with a lease. Fetch-prune, pull-strategy, and pull-autostash choices can each be saved as this repository's default. Network operations stream progress (phase and percent) into a live topbar toast, are cancellable, and surface git's own stderr in a toast on failure. Sync runs fetch, then the repository's default pull, then push, and stops at the first failed stage. +Open repositories also fetch on their own. Settings → Git → **Auto-fetch** is 10 minutes by default (or 5, 30, or off), and any open repository can opt out. Strand fetches only — it does not pull or change your files — then updates the behind-count. When new commits arrive on the current branch's upstream, a short notice names the count and the upstream (`2 new commits on origin/main`). Nothing is shown when the fetch finds no new commits. A missing credential does not open a prompt; that repository waits before the next try. The topbar Fetch / Pull / Push buttons show real ahead/behind counts. The adjacent chevron opens the full network menu: fetch with or without pruning stale remote-tracking branches; pull using Git's configured behavior, an explicit merge, rebase, or fast-forward-only, with or without autostash; and push the current branch, follow annotated tags, push every tag, or force-push with a lease. Fetch-prune, pull-strategy, and pull-autostash choices can each be saved as this repository's default. Network operations stream progress (phase and percent) into a live topbar toast, are cancellable, and surface git's own stderr in a toast on failure. Sync runs fetch, then the repository's default pull, then push, and stops at the first failed stage. Force-push is deliberately guarded: Strand only exposes `--force-with-lease`, names the branch and upstream in a confirmation dialog, and refuses the update if the remote branch moved since the last fetch. Plain `--force` is not available. The same strategy actions are keyboard-reachable from the command palette; the current branch's context menu also exposes the pull and push variants. diff --git a/website/docs/settings.md b/website/docs/settings.md index 090d256..aa4c383 100644 --- a/website/docs/settings.md +++ b/website/docs/settings.md @@ -120,6 +120,7 @@ and key details expand when needed. ## Git - **Global identity** — Name and Email inputs written to your global git config (`~/.gitconfig`) with an explicit **Save identity** button. These defaults apply to Git outside Strand too; repository, worktree, conditional and environment overrides can take precedence. +- **Auto-fetch** — Off, 5 min, 10 min, or 30 min. The default is 10 min. Strand fetches each open repository on that interval, the active one first and the others a few seconds apart. It only fetches: nothing is pulled, merged, or checked out. A repository can opt out with its checkbox. Turn the interval off to stop background fetches entirely. New commits on the current branch's upstream update the behind-count and show a short notice. A remote that needs a credential you have not saved fails once, without a prompt, and waits before trying again. Successful and failed background fetches are listed in **Activity history…**. - **Default clone & open folder** — a path with **Choose…** and **Clear** buttons. This is where the clone dialog and the open-repository picker start. Network operations, commit/amend and tag creation use your system Git.