From 2b0c70e96698c34e40d14eadc082ed2d29603de5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 09:04:30 +0000 Subject: [PATCH 1/5] feat(git): auto-fetch open repositories on a timer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → Git offers Off, 5, 10, or 30 minutes. Daniels chose 10 minutes as the default. Background fetch is fetch-only, staggered across open repositories, and fails quietly when credentials are missing. DAN-89. Co-authored-by: Daniels --- README.md | 4 +- ROADMAP.md | 16 ++ TASKS.md | 9 + crates/strand-core/Cargo.toml | 2 +- crates/strand-core/src/lib.rs | 59 ++++- crates/strand-core/src/network.rs | 358 ++++++++++++++++++++++++++- crates/strand-tauri/src/commands.rs | 12 +- crates/strand-tauri/src/main.rs | 1 + docs/learnings.md | 17 ++ ui/src/App.tsx | 29 ++- ui/src/lib/autoFetch.test.ts | 340 +++++++++++++++++++++++++ ui/src/lib/autoFetch.ts | 231 +++++++++++++++++ ui/src/lib/db.ts | 11 + ui/src/lib/i18n.ts | 9 + ui/src/lib/tauri.ts | 4 + ui/src/lib/types.ts | 14 +- ui/src/lib/useAutoFetch.ts | 89 +++++++ ui/src/stores/settings.test.ts | 1 + ui/src/stores/settings.ts | 8 + ui/src/views/MaintenanceDialog.tsx | 22 +- ui/src/views/settings/GitSection.tsx | 66 +++++ website/docs/everyday-git.md | 2 +- website/docs/settings.md | 1 + 23 files changed, 1276 insertions(+), 29 deletions(-) create mode 100644 ui/src/lib/autoFetch.test.ts create mode 100644 ui/src/lib/autoFetch.ts create mode 100644 ui/src/lib/useAutoFetch.ts diff --git a/README.md b/README.md index 9dd8e638..09a5b9c1 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 0b8f068c..52861070 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 a249c829..cc3c6b31 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 c3eb2865..e328d014 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 b3deec45..182fae03 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 == 0 { 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 != 0 { + 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 638a3958..ff461033 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,20 @@ 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 { let mut command = crate::git_command(); #[cfg(unix)] { @@ -798,14 +865,33 @@ 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"); + 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 - // 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 +} + +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 +1077,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 +1783,187 @@ 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"]); + } + + #[test] + fn background_fetch_command_uses_hidden_git_and_cannot_prompt() { + let quiet = prepare_git_command(Path::new("."), &background_fetch_args(false), &[], true, false); + 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 manual = prepare_git_command(Path::new("."), &["fetch", "--prune", "--progress"], &[], false, false); + assert!(manual.get_envs().all(|(key, _)| key != "GCM_INTERACTIVE")); + + 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 27c62cfa..e40c7a5b 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 6da22459..ae0a5704 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 f4a516ed..6a8d6758 100644 --- a/docs/learnings.md +++ b/docs/learnings.md @@ -3099,6 +3099,23 @@ 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`, `GIT_SSH_COMMAND=ssh -o BatchMode=yes`, +`SSH_ASKPASS_REQUIRE=never`, and removes `GIT_ASKPASS` / `SSH_ASKPASS`. +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. + +**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 ac4fcbc7..686064d1 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -60,7 +60,9 @@ import { stashApplyProgress, stashPopProgress, } from './lib/localGitOp'; +import { backgroundFetchInFlight } 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,13 @@ 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); + useAutoFetch({ + intervalMin: autoFetchIntervalMin, + manualBusy: syncing || pulling || pushing, + manualPath: activePath, + notify: showToast, + }); const networkBusyRef = useRef(false); networkBusyRef.current = syncing || pulling || pushing; @@ -982,7 +991,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 +1010,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 +1030,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 +1059,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 +1084,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 +1100,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 +1121,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 +1150,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 +1171,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 +2199,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 00000000..e8f8b92a --- /dev/null +++ b/ui/src/lib/autoFetch.test.ts @@ -0,0 +1,340 @@ +import { afterEach, describe, expect, it } from 'vitest'; + +import type { BackgroundFetchOutcome } from './types'; +import { + AUTO_FETCH_AUTH_BACKOFF_MS, + autoFetchActivity, + autoFetchNotice, + backgroundFetchInFlight, + 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('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('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 00000000..3e9cbef4 --- /dev/null +++ b/ui/src/lib/autoFetch.ts @@ -0,0 +1,231 @@ +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; +} + +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', + ); +} + +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 07fdf239..1e3c39d6 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 83e005db..3894ccef 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 b0be77ff..de61ed07 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 94a4d637..19f0f9ea 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 00000000..5325acb9 --- /dev/null +++ b/ui/src/lib/useAutoFetch.ts @@ -0,0 +1,89 @@ +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, + autoFetchNotice, + 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: !!manualPath && pathKey(manualPath) === pathKey(tab.path), + }; + })); + }, + fetch: (repo) => tauri.repoBackgroundFetch(repo.path, repo.prune), + onResult: (repo, result, startedAt, finishedAt) => { + const notice = autoFetchNotice(result); + if (notice) optionsRef.current.notify(notice); + const entry = autoFetchActivity(repo.path, result, startedAt, finishedAt); + void repoActivity.append(repo.path, entry).catch(() => {}); + if (!result.ok) return; + void refreshUpstream(repo.path); + }, + }); + return () => loop.stop(); + }, [intervalMin]); +} + +async function refreshUpstream(path: string): Promise { + try { + const [meta, refs] = await Promise.all([tauri.repoMeta(path), tauri.repoRefs(path)]); + useRepo.setState((state) => { + const key = pathKey(path); + const tabs = state.tabs.map((tab) => (pathKey(tab.path) === key ? { ...tab, meta } : tab)); + if (state.activePath && pathKey(state.activePath) === key) return { tabs, meta, refs }; + return { tabs }; + }); + } catch { + // The next manual refresh picks up the remote-tracking refs. + } +} diff --git a/ui/src/stores/settings.test.ts b/ui/src/stores/settings.test.ts index 5434b0d3..e233cc4c 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 dcadcba7..5538e675 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 32d2fe28..02d640c1 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 582499fe..e360d86a 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 428e600d..0e3bbca1 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 090d2567..aa4c3832 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. From 28a2111af9e7ebcdd0c1a81b4f899ed467d0f244 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 09:13:01 +0000 Subject: [PATCH 2/5] fix(windows): compare console HWND as a null pointer GetConsoleWindow returns *mut c_void on the current windows-sys, so the CREATE_NO_WINDOW probe compared a pointer with an integer and failed to compile on Windows CI. Co-authored-by: Daniels --- crates/strand-core/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/strand-core/src/lib.rs b/crates/strand-core/src/lib.rs index 182fae03..32581bdf 100644 --- a/crates/strand-core/src/lib.rs +++ b/crates/strand-core/src/lib.rs @@ -156,7 +156,7 @@ mod console_probe { 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 == 0 { 0 } else { 7 }); + std::process::exit(if hwnd.is_null() { 0 } else { 7 }); } let spawn = |hide: bool| { @@ -182,7 +182,7 @@ mod console_probe { // 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 != 0 { + if !parent.is_null() { let bare = spawn(false); assert!( !bare.success(), From c2682bfa959a4d165f9c6d80a507b5760132e022 Mon Sep 17 00:00:00 2001 From: Grok Bot Date: Mon, 19 Oct 2026 13:14:08 +0200 Subject: [PATCH 3/5] fix(fetch): keep core.sshCommand and clear core.askPass in background fetch (DAN-89) GIT_SSH_COMMAND outranks core.sshCommand, so forcing BatchMode unconditionally dropped a user's custom key or ssh. Only force it when no ssh command is configured. Pass -c core.askPass= so a configured askpass helper cannot prompt from a background tick. Co-authored-by: Daniels --- crates/strand-core/src/network.rs | 53 +++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/strand-core/src/network.rs b/crates/strand-core/src/network.rs index ff461033..adda5cc3 100644 --- a/crates/strand-core/src/network.rs +++ b/crates/strand-core/src/network.rs @@ -867,13 +867,23 @@ pub(crate) fn prepare_git_command( } if quiet_auth { command.env("GCM_INTERACTIVE", "never"); - command.env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes"); + // 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(cwd) { + 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 - .args(crate::GIT_SAFE_CONFIG) .args(args) .stdin(if piped_stdin { Stdio::piped() } else { Stdio::null() }) .stdout(Stdio::piped()) @@ -881,6 +891,22 @@ pub(crate) fn prepare_git_command( command } +/// The user picked an ssh command: `GIT_SSH_COMMAND` / `GIT_SSH` in the +/// environment, or `core.sshCommand` in the repo's effective config. +fn user_ssh_command(cwd: &Path) -> bool { + let set = |key: &str| std::env::var_os(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") + .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], @@ -1790,6 +1816,25 @@ mod tests { assert_eq!(background_fetch_args(false), ["fetch", "--no-prune"]); } + #[test] + fn background_fetch_keeps_the_users_core_ssh_command() { + let dir = std::env::temp_dir().join(format!("strand-ssh-cmd-{}", 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"]); + git(&["config", "core.sshCommand", "ssh -i ~/.ssh/work"]); + let quiet = prepare_git_command(&dir, &background_fetch_args(false), &[], true, false); + 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 quiet = prepare_git_command(Path::new("."), &background_fetch_args(false), &[], true, false); @@ -1809,9 +1854,13 @@ mod tests { 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(Path::new("."), &["fetch", "--prune", "--progress"], &[], false, false); assert!(manual.get_envs().all(|(key, _)| key != "GCM_INTERACTIVE")); + assert!(!manual.get_args().any(|arg| arg == "core.askPass=")); let src = include_str!("network.rs"); let start = src.find("pub(crate) fn prepare_git_command").expect("prepare_git_command"); From 25dc30ed67c1e26541c5e68f0b5855501aa542f1 Mon Sep 17 00:00:00 2001 From: Grok Bot Date: Mon, 19 Oct 2026 13:14:08 +0200 Subject: [PATCH 4/5] fix(fetch): key auto-fetch skips by the busy repo and drop no-op activity rows (DAN-89) - The manual-op skip now follows the repository the op started on, not whichever tab is active when the tick runs. - Refresh after a background fetch goes through the store's coalesced refreshUpstream (meta per tab, refs through refreshRefs when active). - A successful fetch that printed nothing and brought no commits writes no activity entry. Co-authored-by: Daniels --- docs/learnings.md | 11 ++++++++--- ui/src/App.tsx | 11 +++++++++-- ui/src/lib/autoFetch.test.ts | 11 +++++++++++ ui/src/lib/autoFetch.ts | 5 +++++ ui/src/lib/useAutoFetch.ts | 19 ++++--------------- ui/src/stores/repo.test.ts | 29 +++++++++++++++++++++++++++++ ui/src/stores/repo.ts | 22 ++++++++++++++++++++++ 7 files changed, 88 insertions(+), 20 deletions(-) diff --git a/docs/learnings.md b/docs/learnings.md index 6a8d6758..d4e887d6 100644 --- a/docs/learnings.md +++ b/docs/learnings.md @@ -3103,11 +3103,16 @@ lossy string conversion to fix a raw-libgit2 issue the Rust binding handles. **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`, `GIT_SSH_COMMAND=ssh -o BatchMode=yes`, -`SSH_ASKPASS_REQUIRE=never`, and removes `GIT_ASKPASS` / `SSH_ASKPASS`. +`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. +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 diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 686064d1..fb958159 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -558,10 +558,17 @@ export function App() { 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); + if (!manualBusy) manualBusyPath.current = null; + else if (manualBusyPath.current === null) manualBusyPath.current = activePath; useAutoFetch({ intervalMin: autoFetchIntervalMin, - manualBusy: syncing || pulling || pushing, - manualPath: activePath, + manualBusy, + manualPath: manualBusyPath.current, notify: showToast, }); diff --git a/ui/src/lib/autoFetch.test.ts b/ui/src/lib/autoFetch.test.ts index e8f8b92a..fd7e4c0a 100644 --- a/ui/src/lib/autoFetch.test.ts +++ b/ui/src/lib/autoFetch.test.ts @@ -4,6 +4,7 @@ import type { BackgroundFetchOutcome } from './types'; import { AUTO_FETCH_AUTH_BACKOFF_MS, autoFetchActivity, + autoFetchIsNoop, autoFetchNotice, backgroundFetchInFlight, normalizeAutoFetchInterval, @@ -330,6 +331,16 @@ describe('startAutoFetch', () => { }); }); +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); diff --git a/ui/src/lib/autoFetch.ts b/ui/src/lib/autoFetch.ts index 3e9cbef4..7221a81a 100644 --- a/ui/src/lib/autoFetch.ts +++ b/ui/src/lib/autoFetch.ts @@ -104,6 +104,11 @@ export function autoFetchNotice(result: Pick): boolean { + return result.ok && result.new_commits <= 0 && result.output.trim() === ''; +} + export function autoFetchActivity( path: string, result: BackgroundFetchOutcome, diff --git a/ui/src/lib/useAutoFetch.ts b/ui/src/lib/useAutoFetch.ts index 5325acb9..6dd78c58 100644 --- a/ui/src/lib/useAutoFetch.ts +++ b/ui/src/lib/useAutoFetch.ts @@ -6,6 +6,7 @@ import { isTauri, tauri } from './tauri'; import type { AutoFetchIntervalMin } from './autoFetch'; import { autoFetchActivity, + autoFetchIsNoop, autoFetchNotice, startAutoFetch, } from './autoFetch'; @@ -64,26 +65,14 @@ export function useAutoFetch(options: { 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 refreshUpstream(repo.path); + void useRepo.getState().refreshUpstream(repo.path); }, }); return () => loop.stop(); }, [intervalMin]); } - -async function refreshUpstream(path: string): Promise { - try { - const [meta, refs] = await Promise.all([tauri.repoMeta(path), tauri.repoRefs(path)]); - useRepo.setState((state) => { - const key = pathKey(path); - const tabs = state.tabs.map((tab) => (pathKey(tab.path) === key ? { ...tab, meta } : tab)); - if (state.activePath && pathKey(state.activePath) === key) return { tabs, meta, refs }; - return { tabs }; - }); - } catch { - // The next manual refresh picks up the remote-tracking refs. - } -} diff --git a/ui/src/stores/repo.test.ts b/ui/src/stores/repo.test.ts index 4f11e12d..6eef1b9e 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 d63ebb05..459679e7 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; From 7ab82c0658e0b1b200b454ca9628dd047f3b4d83 Mon Sep 17 00:00:00 2001 From: Grok Bot Date: Mon, 19 Oct 2026 15:58:05 +0200 Subject: [PATCH 5/5] test(fetch): cover the busy-repo skip and isolate the ssh probe (DAN-89) - Extract manualOpPath / isManualBusyRepo (no behaviour change) and test that a busy non-active repo is skipped while the active one fetches, that a tab switch mid-op keeps the skip, and that op end clears it. - The background-fetch command tests run in a fresh temp repo with the ssh probe blind to GIT_SSH_COMMAND, GIT_SSH and global/system config, so a developer's own ssh setup can't fail them. Co-authored-by: Daniels --- crates/strand-core/src/network.rs | 62 ++++++++++++++++++++++++++----- ui/src/App.tsx | 5 +-- ui/src/lib/autoFetch.test.ts | 53 ++++++++++++++++++++++++++ ui/src/lib/autoFetch.ts | 14 +++++++ ui/src/lib/useAutoFetch.ts | 3 +- 5 files changed, 123 insertions(+), 14 deletions(-) diff --git a/crates/strand-core/src/network.rs b/crates/strand-core/src/network.rs index adda5cc3..8647b88d 100644 --- a/crates/strand-core/src/network.rs +++ b/crates/strand-core/src/network.rs @@ -850,6 +850,21 @@ pub(crate) fn prepare_git_command( extra_env: &[(&str, &str)], 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)] @@ -870,7 +885,7 @@ pub(crate) fn prepare_git_command( // 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(cwd) { + if !user_ssh() { command.env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes"); } command.env("SSH_ASKPASS_REQUIRE", "never"); @@ -893,14 +908,20 @@ pub(crate) fn prepare_git_command( /// The user picked an ssh command: `GIT_SSH_COMMAND` / `GIT_SSH` in the /// environment, or `core.sshCommand` in the repo's effective config. -fn user_ssh_command(cwd: &Path) -> bool { - let set = |key: &str| std::env::var_os(key).is_some_and(|value| !value.is_empty()); +/// `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() @@ -1816,17 +1837,36 @@ mod tests { assert_eq!(background_fetch_args(false), ["fetch", "--no-prune"]); } - #[test] - fn background_fetch_keeps_the_users_core_ssh_command() { - let dir = std::env::temp_dir().join(format!("strand-ssh-cmd-{}", std::process::id())); + /// 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"]); - git(&["config", "core.sshCommand", "ssh -i ~/.ssh/work"]); - let quiet = prepare_git_command(&dir, &background_fetch_args(false), &[], true, false); + 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" @@ -1837,7 +1877,8 @@ mod tests { #[test] fn background_fetch_command_uses_hidden_git_and_cannot_prompt() { - let quiet = prepare_git_command(Path::new("."), &background_fetch_args(false), &[], true, false); + 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")); @@ -1858,9 +1899,10 @@ mod tests { assert_eq!(args[askpass - 1], "-c"); assert!(askpass < args.iter().position(|arg| arg == "fetch").unwrap()); - let manual = prepare_git_command(Path::new("."), &["fetch", "--prune", "--progress"], &[], false, false); + 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"); diff --git a/ui/src/App.tsx b/ui/src/App.tsx index fb958159..56dadb70 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -60,7 +60,7 @@ import { stashApplyProgress, stashPopProgress, } from './lib/localGitOp'; -import { backgroundFetchInFlight } from './lib/autoFetch'; +import { backgroundFetchInFlight, manualOpPath } from './lib/autoFetch'; import { errMessage, isCancelled, isTauri, tauri } from './lib/tauri'; import { useAutoFetch } from './lib/useAutoFetch'; import { useTheme } from './lib/theme'; @@ -563,8 +563,7 @@ export function App() { // auto-fetch skip onto a repository that is idle. const manualBusy = syncing || pulling || pushing; const manualBusyPath = useRef(null); - if (!manualBusy) manualBusyPath.current = null; - else if (manualBusyPath.current === null) manualBusyPath.current = activePath; + manualBusyPath.current = manualOpPath(manualBusy, manualBusyPath.current, activePath); useAutoFetch({ intervalMin: autoFetchIntervalMin, manualBusy, diff --git a/ui/src/lib/autoFetch.test.ts b/ui/src/lib/autoFetch.test.ts index fd7e4c0a..5255c2cc 100644 --- a/ui/src/lib/autoFetch.test.ts +++ b/ui/src/lib/autoFetch.test.ts @@ -7,6 +7,8 @@ import { autoFetchIsNoop, autoFetchNotice, backgroundFetchInFlight, + isManualBusyRepo, + manualOpPath, normalizeAutoFetchInterval, planAutoFetch, resetAutoFetchState, @@ -162,6 +164,57 @@ describe('planAutoFetch', () => { }); }); +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; diff --git a/ui/src/lib/autoFetch.ts b/ui/src/lib/autoFetch.ts index 7221a81a..5c454e47 100644 --- a/ui/src/lib/autoFetch.ts +++ b/ui/src/lib/autoFetch.ts @@ -31,6 +31,20 @@ export interface AutoFetchRepo { 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; diff --git a/ui/src/lib/useAutoFetch.ts b/ui/src/lib/useAutoFetch.ts index 6dd78c58..ba8ca7ed 100644 --- a/ui/src/lib/useAutoFetch.ts +++ b/ui/src/lib/useAutoFetch.ts @@ -8,6 +8,7 @@ import { autoFetchActivity, autoFetchIsNoop, autoFetchNotice, + isManualBusyRepo, startAutoFetch, } from './autoFetch'; import { useRepo } from '../stores/repo'; @@ -57,7 +58,7 @@ export function useAutoFetch(options: { active: !!activePath && pathKey(activePath) === pathKey(tab.path), optedOut, prune, - manualBusy: !!manualPath && pathKey(manualPath) === pathKey(tab.path), + manualBusy: isManualBusyRepo(tab.path, manualPath), }; })); },