From 5a534d7b5d2ebbbfe05701bf92590392cf0a0448 Mon Sep 17 00:00:00 2001 From: Andriy Massimilla Date: Thu, 29 Oct 2026 10:48:05 +0000 Subject: [PATCH] git: Add git auto fetch (#53089) ## Summary Adds an opt-in periodic background `git fetch --all` for local repositories, so remote-tracking branches and ahead/behind counts stay current without a manual fetch. Because the fetch runs unattended, it behaves differently from a user-initiated fetch: - **Trusted repositories only.** Re-checked on every tick, since a worktree can be trusted or restricted at any point in a session. - **Never prompts.** Credentials that need no interaction (e.g. an SSH agent, or a credential helper answering from a keychain) still work. Anything that would need input fails instead of blocking on a prompt nothing will answer. - **Silent.** No activity indicator in the status bar, since a spinner every minute is noise. Failures are logged at debug level. - **Stays out of the user's way.** It runs off the repository's serial job queue, so status refreshes and staging aren't stalled behind the network. A user-initiated fetch, pull, or push preempts an in-flight background fetch rather than waiting for it. - **Leaves the repository clean when stopped.** Stopping a fetch (a settings change, preemption, closing the project) asks git to terminate so it can remove its ref lockfiles, rather than killing it and leaving a stale `.lock` behind that breaks every later fetch. It also never triggers auto-maintenance on the user's behalf. ## Configuration ```json [settings] { "git": { "auto_fetch": { "enabled": false, "interval_secs": 60 } } } ``` - `enabled` (default `false`): whether to fetch from all remotes in the background. - `interval_secs` (default `60`, clamped to a minimum of `15`): how often to fetch. Both are exposed in the settings UI under **Version Control > Git Integration**, where the interval is only shown while auto-fetch is enabled, and documented in `docs/src/reference/all-settings.md`. Unrelated settings changes don't restart the timer. ## Implementation design ### `GitCaller` The remote-capable `GitRepository` methods (`fetch`, `pull`, `push`, `commit`) take a `GitCaller` instead of a bare `AskPassDelegate`: ```rust pub enum GitCaller { /// A user started this and is waiting on it. Prompts route to the UI. User(AskPassDelegate), /// No user attached. Never prompts, and stops when the receiver resolves. Background(Option>), } ``` Every such command goes through `GitBinary::run_remote_command`, which applies everything the caller implies. git, credential helpers, and ssh each prompt through a different mechanism, so keeping the list in one place means no call site can miss one. For `Background`: | Prompt channel | Mitigation | | --- | --- | | git's own terminal prompt | `GIT_TERMINAL_PROMPT=0` | | Credential helpers | `credential.interactive=false`, which is narrower than clearing `credential.helper` so helpers that answer without prompting keep working | | askpass | `core.askPass=`, and `GIT_ASKPASS`/`SSH_ASKPASS` unset | | ssh (key passphrases, host key confirmation) | `-o BatchMode=yes` composed onto the ssh command git would otherwise use (`GIT_SSH_COMMAND`, then `core.sshCommand`, then `ssh`), so custom ssh commands keep working. Setups that only set the deprecated `GIT_SSH` are left alone, since setting `GIT_SSH_COMMAND` would silently replace them. | `gc.auto=0` is also set, since auto-maintenance can repack the whole repository. gpg's pinentry when signing isn't covered, as no background caller signs. ### Cancellation A background command is spawned with `kill_on_drop` and raced against its cancel receiver, where a dropped sender counts as cancellation: 1. If already cancelled before spawning, git is never started. 2. On cancellation, git is sent `SIGTERM` (`util::process::request_termination`), which runs its handlers that remove lockfiles. 3. If it hasn't exited within a 2s grace period, it's killed. Windows has no equivalent signal, so cancellation there is a kill. ### Scheduling - Each repository has a timer task, restarted only when `enabled` or `interval_secs` change. - On each tick, the timer checks trust, then tries to acquire the repository's `fetch_lock` semaphore and skips the tick if it's held. It spawns a **detached** fetch task that holds the permit until the fetch settles. - `AutoFetchState.cancel` holds the sender, and is the only thing bounding the fetch's lifetime. It's dropped on a settings change, on preemption, and when the repository is dropped, so every way of stopping a fetch goes through graceful cancellation. - Running off the serial job queue is safe because auto-fetch mutates no `Repository` state. It only updates remote-tracking refs, which git guards with its own lockfiles, and the results reach the UI via the resulting git directory rescan. Manual fetch stays on the queue, since it also writes snapshot state via `refresh_branch_list`. - `fetch`, `pull`, and `push` call `preempt_auto_fetch()`, which drops the cancel sender, then wait on `fetch_lock` inside their job. That wait is bounded by a cancelled fetch shutting down rather than by the network, and stops them failing with "cannot lock ref" against a background fetch. ## Test plan `test_auto_fetch` covers: - [x] An untrusted repository is never auto-fetched, and fetching begins once its worktree is trusted - [x] Timer fires on schedule, and again on the following interval - [x] Unrelated settings change mid-interval doesn't reset the timer - [x] Disabling `auto_fetch` stops all fetches - [x] Re-enabling with a longer interval respects the new cadence ## Review Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments - [x] The content is consistent with the [UI/UX checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Addresses #24611(https://github.com/zed-industries/zed/discussions/24611) Release Notes: - git: Added option (off-by-default) to automatically fetch upstream of the current branch and default upstream of the project. Enable it with: ``` { "git": { "auto_fetch": { "enabled": false, "interval_secs": 60 } } } ```. --------- Co-authored-by: Claude Opus 5 Co-authored-by: Codex (GPT-6) Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> --- assets/settings/default.json | 8 + crates/fs/src/fake_git_repo.rs | 40 +- crates/git/src/repository.rs | 335 ++++++++++----- crates/git_ui/src/git_panel.rs | 190 ++++++++- crates/git_ui_core/src/worktree_service.rs | 2 +- crates/project/src/git_store.rs | 380 ++++++++++++++++-- crates/project/src/project_settings.rs | 22 + .../remote_server/src/remote_editing_tests.rs | 194 +++++++++ crates/settings_content/src/project.rs | 17 + crates/settings_ui/src/page_data.rs | 72 +++- docs/src/reference/all-settings.md | 29 ++ docs/src/remote-development.md | 9 +- 12 files changed, 1148 insertions(+), 150 deletions(-) diff --git a/assets/settings/default.json b/assets/settings/default.json index 8172ebde474..aec35d8bd8a 100644 --- a/assets/settings/default.json +++ b/assets/settings/default.json @@ -1906,6 +1906,14 @@ // // Trailing slashes are ignored. "worktree_directory": "../worktrees", + // Settings for automatically fetching the default branch's remote and the current branch's upstream remote. + "auto_fetch": { + // Whether to automatically fetch in the background. + "enabled": false, + // How long to wait between automatic fetches, in seconds. + // Only applies when auto fetch is enabled. (min: 15) + "interval_secs": 60, + }, }, // The list of custom Git hosting providers. "git_hosting_providers": [ diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rs index 58daa4ef368..914f07b9271 100644 --- a/crates/fs/src/fake_git_repo.rs +++ b/crates/fs/src/fake_git_repo.rs @@ -68,7 +68,9 @@ pub struct FakeGitRepositoryState { pub blames: HashMap, pub blames_at_revision: HashMap<(RepoPath, Oid), Blame>, pub current_branch_name: Option, + pub default_branch_ref: Option, pub branches: HashSet, + pub branch_upstreams: HashMap, /// List of remotes, keys are names and values are URLs pub remotes: HashMap, pub simulated_index_write_error_message: Option, @@ -80,6 +82,7 @@ pub struct FakeGitRepositoryState { pub graph_commits: Vec>, pub commit_data: HashMap, pub stash_entries: GitStash, + pub fetches: Arc>>, pub commit_template: Option, pub blob_read_gate: Option, } @@ -95,7 +98,9 @@ impl FakeGitRepositoryState { blames: Default::default(), blames_at_revision: Default::default(), current_branch_name: Default::default(), + default_branch_ref: Some("refs/remotes/origin/main".into()), branches: Default::default(), + branch_upstreams: Default::default(), simulated_index_write_error_message: Default::default(), simulated_create_worktree_error: Default::default(), simulated_graph_error: None, @@ -109,6 +114,7 @@ impl FakeGitRepositoryState { commit_data: Default::default(), commit_history: Vec::new(), stash_entries: Default::default(), + fetches: Arc::default(), commit_template: None, } } @@ -688,7 +694,7 @@ impl GitRepository for FakeGitRepository { is_head: Some(branch_name) == current_branch.as_ref(), ref_name, most_recent_commit: None, - upstream: None, + upstream: state.branch_upstreams.get(branch_name).cloned(), } }) .collect::>(); @@ -1320,12 +1326,18 @@ impl GitRepository for FakeGitRepository { fn fetch( &self, - _fetch_options: FetchOptions, - _askpass: AskPassDelegate, + fetch_options: FetchOptions, + _askpass: Option, _env: Arc>, _cx: AsyncApp, ) -> BoxFuture<'_, Result> { - unimplemented!() + self.with_state_async(true, move |state| { + state.fetches.lock().push(fetch_options); + Ok(git::repository::RemoteCommandOutput { + stdout: String::new(), + stderr: String::new(), + }) + }) } fn get_all_remotes(&self) -> BoxFuture<'_, Result>> { @@ -1525,14 +1537,20 @@ impl GitRepository for FakeGitRepository { &self, include_remote_name: bool, ) -> BoxFuture<'_, Result>> { - async move { - Ok(Some(if include_remote_name { - "origin/main".into() - } else { - "main".into() + self.with_state_async(false, move |state| { + Ok(state.default_branch_ref.as_ref().map(|branch| { + let name = if let Some(name) = branch.strip_prefix("refs/remotes/") { + if include_remote_name { + name + } else { + name.split_once('/').map_or(name, |(_, name)| name) + } + } else { + branch.strip_prefix("refs/heads/").unwrap_or(branch) + }; + name.to_owned().into() })) - } - .boxed() + }) } fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> { diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rs index 507e282a29d..e08c0019a69 100644 --- a/crates/git/src/repository.rs +++ b/crates/git/src/repository.rs @@ -1043,7 +1043,7 @@ pub trait GitRepository: Send + Sync { fn fetch( &self, fetch_options: FetchOptions, - askpass: AskPassDelegate, + askpass: Option, env: Arc>, // This method takes an AsyncApp to ensure it's invoked on the main thread, // otherwise git-credentials-manager won't work. @@ -2777,43 +2777,41 @@ impl GitRepository for RealGitRepository { message: SharedString, name_and_email: Option<(SharedString, SharedString)>, options: CommitOptions, - ask_pass: AskPassDelegate, + askpass: AskPassDelegate, env: Arc>, ) -> BoxFuture<'_, Result<()>> { let git = self.git_binary_in_worktree(); - let executor = self.executor.clone(); // Note: Do not spawn this command on the background thread, it might pop open the credential helper // which we want to block on. async move { let git = git?; - let mut cmd = git.build_command(&["commit", "--quiet", "-m"]); - cmd.envs(env.iter()) - .arg(&message.to_string()) - .arg("--cleanup=strip") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + git.run_remote_command(Some(askpass), &env, &["commit", "--quiet", "-m"], |cmd| { + cmd.arg(&message.to_string()) + .arg("--cleanup=strip") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); - if options.amend { - cmd.arg("--amend"); - } + if options.amend { + cmd.arg("--amend"); + } - if options.signoff { - cmd.arg("--signoff"); - } + if options.signoff { + cmd.arg("--signoff"); + } - if options.allow_empty { - cmd.arg("--allow-empty"); - } + if options.allow_empty { + cmd.arg("--allow-empty"); + } - if options.no_verify { - cmd.arg("--no-verify"); - } + if options.no_verify { + cmd.arg("--no-verify"); + } - if let Some((name, email)) = name_and_email { - cmd.arg("--author").arg(&format!("{name} <{email}>")); - } - - run_git_command(env, ask_pass, cmd, executor).await?; + if let Some((name, email)) = name_and_email { + cmd.arg("--author").arg(&format!("{name} <{email}>")); + } + }) + .await?; Ok(()) } @@ -2849,7 +2847,7 @@ impl GitRepository for RealGitRepository { remote_branch_name: String, remote_name: String, options: Option, - ask_pass: AskPassDelegate, + askpass: AskPassDelegate, env: Arc>, cx: AsyncApp, ) -> BoxFuture<'_, Result> { @@ -2866,23 +2864,22 @@ impl GitRepository for RealGitRepository { git_binary_path, working_directory, git_directory, - executor.clone(), + executor, is_trusted, ); - let mut command = git.build_command(&["push"]); - command - .envs(env.iter()) - .args(options.map(|option| match option { - PushOptions::SetUpstream => "--set-upstream", - PushOptions::Force => "--force-with-lease", - })) - .arg(remote_name) - .arg(format!("{}:{}", branch_name, remote_branch_name)) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - - run_git_command(env, ask_pass, command, executor).await + git.run_remote_command(Some(askpass), &env, &["push"], |command| { + command + .args(options.map(|option| match option { + PushOptions::SetUpstream => "--set-upstream", + PushOptions::Force => "--force-with-lease", + })) + .arg(remote_name) + .arg(format!("{}:{}", branch_name, remote_branch_name)) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + }) + .await } .boxed() } @@ -2892,7 +2889,7 @@ impl GitRepository for RealGitRepository { branch_name: Option, remote_name: String, rebase: bool, - ask_pass: AskPassDelegate, + askpass: AskPassDelegate, env: Arc>, cx: AsyncApp, ) -> BoxFuture<'_, Result> { @@ -2909,23 +2906,21 @@ impl GitRepository for RealGitRepository { git_binary_path, working_directory, git_directory, - executor.clone(), + executor, is_trusted, ); - let mut command = git.build_command(&["pull"]); - command.envs(env.iter()); + git.run_remote_command(Some(askpass), &env, &["pull"], |command| { + if rebase { + command.arg("--rebase"); + } - if rebase { - command.arg("--rebase"); - } - - command - .arg(remote_name) - .args(branch_name) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - - run_git_command(env, ask_pass, command, executor).await + command + .arg(remote_name) + .args(branch_name) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + }) + .await } .boxed() } @@ -2933,7 +2928,7 @@ impl GitRepository for RealGitRepository { fn fetch( &self, fetch_options: FetchOptions, - ask_pass: AskPassDelegate, + askpass: Option, env: Arc>, cx: AsyncApp, ) -> BoxFuture<'_, Result> { @@ -2951,16 +2946,13 @@ impl GitRepository for RealGitRepository { git_binary_path, working_directory, git_directory, - executor.clone(), + executor, is_trusted, ); - let mut command = git.build_command(&["fetch", &remote_name]); - command - .envs(env.iter()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - - run_git_command(env, ask_pass, command, executor).await + git.run_remote_command(askpass, &env, &["fetch", &remote_name], |command| { + command.stdout(Stdio::piped()).stderr(Stdio::piped()); + }) + .await } .boxed() } @@ -3790,6 +3782,18 @@ impl GitBinary { #[allow(clippy::disallowed_methods)] pub(crate) fn build_command(&self, args: &[S]) -> util::command::Command + where + S: AsRef, + { + self.build_command_with_config(&[], args) + } + + #[allow(clippy::disallowed_methods)] + fn build_command_with_config( + &self, + config: &[(&str, &str)], + args: &[S], + ) -> util::command::Command where S: AsRef, { @@ -3810,6 +3814,9 @@ impl GitBinary { command.args(["-c", "protocol.ext.allow=never"]); command.args(["-c", "diff.external="]); } + for (key, value) in config { + command.args(["-c", &format!("{key}={value}")]); + } // If the `diff` command is being used, we'll want to add the // `--no-ext-diff` flag when working on an untrusted repository, // preventing any external diff programs from being invoked. It goes @@ -3832,36 +3839,103 @@ impl GitBinary { command.envs(&self.envs); command } -} -#[derive(Error, Debug)] -#[error("Git command failed:\n{stdout}{stderr}\n")] -struct GitBinaryCommandError { - stdout: String, - stderr: String, - status: ExitStatus, -} + /// Git, credential helpers, and SSH have separate prompting mechanisms, so + /// omitting an askpass delegate must configure more than Zed's prompt path. + async fn run_remote_command( + &self, + askpass: Option, + env: &HashMap, + args: &[S], + configure: impl FnOnce(&mut util::command::Command), + ) -> Result + where + S: AsRef, + { + let mut config = Vec::new(); + if askpass.is_none() { + // Narrower than clearing `credential.helper`, which would also disable + // helpers that answer from a keychain without prompting — exactly what + // makes an unattended fetch useful. Only prompting is forbidden, and + // this covers git's own prompt as well as helpers that honor it. + config.push(("credential.interactive", "false")); + // Auto-maintenance can repack the entire repository, far outweighing + // the fetch that triggered it. A background caller should not start + // that work on the user's behalf. + config.push(("gc.auto", "0")); + config.push(("core.askPass", "")); + } -async fn run_git_command( - env: Arc>, - ask_pass: AskPassDelegate, - mut command: util::command::Command, - executor: BackgroundExecutor, -) -> Result { - if env.contains_key("GIT_ASKPASS") { - let git_process = command.spawn()?; - let output = git_process.output().await?; - anyhow::ensure!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - Ok(RemoteCommandOutput { - stdout: String::from_utf8_lossy(&output.stdout).to_string(), - stderr: String::from_utf8_lossy(&output.stderr).to_string(), - }) - } else { - let ask_pass = AskPassSession::new(executor, ask_pass).await?; + let mut command = self.build_command_with_config(&config, args); + command.envs(env.iter()); + configure(&mut command); + + match askpass { + Some(delegate) => self.run_with_askpass(delegate, env, command).await, + None => { + // These are set after the project environment has been applied + // above, so that environment cannot override them. + command.env("GIT_TERMINAL_PROMPT", "0"); + // `credential.interactive` says nothing about ssh, which prompts + // for key passphrases and host key confirmation on its own. Batch + // mode is composed onto the ssh command git would use anyway + // rather than replacing it, so a custom `core.sshCommand` keeps + // working. + if let Some(ssh_command) = self.batch_mode_ssh_command(env).await { + command.env("GIT_SSH_COMMAND", ssh_command); + } + // Neither of these should be able to route back to a prompt via a + // value inherited from the environment Zed was launched with. + command.env_remove("GIT_ASKPASS"); + command.env_remove("SSH_ASKPASS"); + remote_command_output(command.output().await?) + } + } + } + + /// The ssh command git should use for background work, if one can be + /// composed. See [`compose_batch_mode_ssh_command`]. + async fn batch_mode_ssh_command(&self, env: &HashMap) -> Option { + // Same precedence the spawned command ends up with: the project + // environment is applied over `self.envs`, and both over the environment + // Zed itself was launched with, which the child inherits. + let inherited = |key: &str| { + env.get(key) + .or_else(|| self.envs.get(key)) + .cloned() + .or_else(|| std::env::var(key).ok()) + }; + let ssh_command_env = inherited("GIT_SSH_COMMAND"); + let core_ssh_command = if ssh_command_env.is_some() { + None + } else if self.is_trusted { + // Absent from config, git exits non-zero rather than printing nothing. + self.run(&["config", "--get", "core.sshCommand"]).await.ok() + } else { + // Pinned by `build_command`. Reading the repository's own value back + // here would hand it to git through an environment variable that + // outranks the pin. + Some("ssh".to_string()) + }; + compose_batch_mode_ssh_command( + ssh_command_env.as_deref(), + core_ssh_command.as_deref(), + inherited("GIT_SSH").as_deref(), + ) + } + + async fn run_with_askpass( + &self, + delegate: AskPassDelegate, + env: &HashMap, + mut command: util::command::Command, + ) -> Result { + if env.contains_key("GIT_ASKPASS") { + let git_process = command.spawn()?; + return remote_command_output(git_process.output().await?); + } + + let ask_pass = AskPassSession::new(self.executor.clone(), delegate).await?; command .env("GIT_ASKPASS", ask_pass.script_path()) .env("SSH_ASKPASS", ask_pass.script_path()) @@ -3884,6 +3958,51 @@ async fn run_git_command( } } +/// Composes batch mode onto the ssh command git would otherwise pick, or returns +/// `None` when the only thing configured is the deprecated `GIT_SSH`. +/// +/// git resolves its ssh command as `GIT_SSH_COMMAND`, then `core.sshCommand`, +/// then `GIT_SSH`, then plain `ssh`. Setting `GIT_SSH_COMMAND` therefore silently +/// replaces a `GIT_SSH` program (e.g. plink on Windows), and since `GIT_SSH` names +/// a bare program rather than a shell command there is nothing to compose onto. +/// Those setups are left alone and keep whatever prompting behavior they have. +fn compose_batch_mode_ssh_command( + ssh_command_env: Option<&str>, + core_ssh_command: Option<&str>, + git_ssh_env: Option<&str>, +) -> Option { + let configured = ssh_command_env + .or(core_ssh_command) + .map(str::trim) + .filter(|command| !command.is_empty()); + let base = match configured { + Some(configured) => configured, + None if git_ssh_env.is_some_and(|program| !program.trim().is_empty()) => return None, + None => "ssh", + }; + Some(format!("{base} -o BatchMode=yes")) +} + +fn remote_command_output(output: Output) -> Result { + anyhow::ensure!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + Ok(RemoteCommandOutput { + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + }) +} + +#[derive(Error, Debug)] +#[error("Git command failed:\n{stdout}{stderr}\n")] +struct GitBinaryCommandError { + stdout: String, + stderr: String, + status: ExitStatus, +} + async fn run_askpass_command( mut ask_pass: AskPassSession, git_process: util::command::Child, @@ -6759,4 +6878,32 @@ mod tests { "/Users/user/My Projects/upstream.git" ); } + + #[test] + fn test_compose_batch_mode_ssh_command() { + assert_eq!( + compose_batch_mode_ssh_command(None, None, None).as_deref(), + Some("ssh -o BatchMode=yes") + ); + assert_eq!( + compose_batch_mode_ssh_command(Some("ssh -i key "), Some("ssh -F config"), None) + .as_deref(), + Some("ssh -i key -o BatchMode=yes"), + "GIT_SSH_COMMAND outranks core.sshCommand" + ); + assert_eq!( + compose_batch_mode_ssh_command(None, Some("ssh -F config"), Some("plink")).as_deref(), + Some("ssh -F config -o BatchMode=yes"), + "core.sshCommand outranks GIT_SSH, so it is still composed onto" + ); + assert_eq!( + compose_batch_mode_ssh_command(Some(""), None, None).as_deref(), + Some("ssh -o BatchMode=yes") + ); + assert_eq!( + compose_batch_mode_ssh_command(None, None, Some("plink")), + None, + "setting GIT_SSH_COMMAND would silently replace the GIT_SSH program" + ); + } } diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs index 33ca210eb8a..2fa9bd1fd72 100644 --- a/crates/git_ui/src/git_panel.rs +++ b/crates/git_ui/src/git_panel.rs @@ -4748,7 +4748,7 @@ impl GitPanel { return Ok(()); }; let fetch = repo.update(cx, |repo, cx| { - repo.fetch(fetch_options.clone(), askpass, cx) + repo.fetch(fetch_options.clone(), Some(askpass), cx) }); let remote_message = fetch.await?; @@ -14392,6 +14392,194 @@ mod tests { assert!(!commit_title_exceeds_limit("", 72)); } + #[gpui::test] + async fn test_auto_fetch(cx: &mut TestAppContext) { + use collections::HashSet; + use project::trusted_worktrees::{DbTrustedPaths, PathTrust, TrustedWorktrees}; + + init_test(cx); + + let fs = FakeFs::new(cx.background_executor.clone()); + fs.insert_tree( + "/root", + json!({ + "repo": { + ".git": {}, + "file.rs": "fn main() {}" + } + }), + ) + .await; + fs.set_status_for_repo( + Path::new(path!("/root/repo/.git")), + &[("file.rs", StatusCode::Modified.worktree())], + ); + fs.insert_branches(Path::new(path!("/root/repo/.git")), &["origin/main"]); + fs.set_remote_for_repo( + Path::new(path!("/root/repo/.git")), + "origin", + "https://example.com/repo.git", + ); + + // Use 20s interval (above the 15s minimum clamp) + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_user_settings( + r#"{"git": {"auto_fetch": {"enabled": true, "interval_secs": 20}}}"#, + cx, + ) + .unwrap(); + }); + project::trusted_worktrees::init(DbTrustedPaths::default(), cx); + }); + + let project = + Project::test_with_worktree_trust(fs.clone(), [path!("/root/repo").as_ref()], cx).await; + + cx.run_until_parked(); + + let repo = project + .update(cx, |project, cx| project.active_repository(cx)) + .expect("should have an active repository"); + repo.read_with(cx, |repo, _| { + assert!(!repo.is_trusted(), "repository should start untrusted"); + }); + + let fetch_count = |fs: &FakeFs| { + fs.with_git_state(Path::new(path!("/root/repo/.git")), false, |state| { + state.fetches.lock().len() + }) + .unwrap() + }; + + assert_eq!(fetch_count(&fs), 0, "no fetch before timer fires"); + + cx.background_executor + .advance_clock(std::time::Duration::from_secs(40)); + cx.run_until_parked(); + assert_eq!( + fetch_count(&fs), + 0, + "untrusted repository should never be auto-fetched" + ); + + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_id = worktree_store.read_with(cx, |store, cx| { + store.worktrees().next().unwrap().read(cx).id() + }); + let trusted_worktrees = cx + .update(|cx| TrustedWorktrees::try_get_global(cx).expect("trust global should be set")); + trusted_worktrees.update(cx, |store, cx| { + store.trust( + &worktree_store, + HashSet::from_iter([PathTrust::Worktree(worktree_id)]), + cx, + ); + }); + cx.run_until_parked(); + repo.read_with(cx, |repo, _| { + assert!( + repo.is_trusted(), + "repository should be trusted after trusting its worktree" + ); + }); + + // Change an unrelated setting mid-wait — should not reset the timer + cx.background_executor + .advance_clock(std::time::Duration::from_secs(10)); + cx.run_until_parked(); + assert_eq!(fetch_count(&fs), 0, "no fetch at 10s"); + + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_user_settings( + r#"{"git": {"auto_fetch": {"enabled": true, "interval_secs": 20}, "inline_blame": {"enabled": false}}}"#, + cx, + ) + .unwrap(); + }); + }); + + // Advance the remaining 10s — fetch should fire on the original schedule + cx.background_executor + .advance_clock(std::time::Duration::from_secs(10)); + cx.run_until_parked(); + + assert!( + fetch_count(&fs) >= 1, + "unrelated settings change should not reset auto-fetch timer" + ); + + // Second fetch fires on schedule + let count_after_first = fetch_count(&fs); + cx.background_executor + .advance_clock(std::time::Duration::from_secs(20)); + cx.run_until_parked(); + + assert!( + fetch_count(&fs) > count_after_first, + "auto-fetch should trigger again on next interval" + ); + + // Disable auto-fetch via settings change + let count_before_disable = fetch_count(&fs); + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_user_settings( + r#"{"git": {"auto_fetch": {"enabled": false, "interval_secs": 20}}}"#, + cx, + ) + .unwrap(); + }); + }); + cx.background_executor + .advance_clock(std::time::Duration::from_secs(30)); + cx.run_until_parked(); + + assert_eq!( + fetch_count(&fs), + count_before_disable, + "no fetches should occur after disabling auto-fetch" + ); + + // Re-enable with a longer interval + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_user_settings( + r#"{"git": {"auto_fetch": {"enabled": true, "interval_secs": 30}}}"#, + cx, + ) + .unwrap(); + }); + }); + let count_before_re_enable = fetch_count(&fs); + + // Advance less than the new interval — should not fetch + cx.background_executor + .advance_clock(std::time::Duration::from_secs(20)); + cx.run_until_parked(); + + assert_eq!( + fetch_count(&fs), + count_before_re_enable, + "should not fetch before new interval elapses" + ); + + // Advance past the new interval — should fetch + cx.background_executor + .advance_clock(std::time::Duration::from_secs(10)); + cx.run_until_parked(); + + assert!( + fetch_count(&fs) > count_before_re_enable, + "should fetch after new interval elapses" + ); + } + #[gpui::test] async fn test_dispatch_context_with_focus_states(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/git_ui_core/src/worktree_service.rs b/crates/git_ui_core/src/worktree_service.rs index cc01351243a..bb10e74bcf9 100644 --- a/crates/git_ui_core/src/worktree_service.rs +++ b/crates/git_ui_core/src/worktree_service.rs @@ -433,7 +433,7 @@ async fn fetch_remote_for_worktree_base( FetchOptions::Remote(Remote { name: remote_name.clone().into(), }), - askpass, + Some(askpass), cx, ) }) diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs index 66b50de981d..7bcddc83080 100644 --- a/crates/project/src/git_store.rs +++ b/crates/project/src/git_store.rs @@ -703,6 +703,23 @@ pub struct Repository { initial_graph_data: HashMap<(LogSource, LogOrder), InitialGitGraphData>, commit_data_handler: CommitDataHandlerState, commit_data: HashMap, + auto_fetch: AutoFetchState, +} + +struct AutoFetchState { + enabled: bool, + interval_secs: u64, + task: Option>, +} + +impl Default for AutoFetchState { + fn default() -> Self { + Self { + enabled: false, + interval_secs: 60, + task: None, + } + } } type RemoteAskPassDelegates = Arc>>; @@ -3437,7 +3454,7 @@ impl GitStore { let remote_output = repository_handle .update(&mut cx, |repository_handle, cx| { - repository_handle.fetch(fetch_options, askpass, cx) + repository_handle.fetch(fetch_options, Some(askpass), cx) }) .await??; @@ -6346,7 +6363,9 @@ impl MergeDetails { impl Repository { pub fn is_trusted(&self) -> bool { - match self.repository_state.peek() { + // The worker awaits its own shared state. Poll this wrapper too, so + // auto-fetch does not depend on a manual operation initializing it first. + match self.repository_state.clone().now_or_never() { Some(Ok(RepositoryState::Local(state))) => state.backend.is_trusted(), _ => false, } @@ -6452,6 +6471,19 @@ impl Repository { PathStyle::local(), ); + cx.observe_global::(|this: &mut Self, cx| { + this.restart_auto_fetch_timer(cx); + }) + .detach(); + + let weak = cx.weak_entity(); + cx.defer(move |cx| { + weak.update(cx, |this, cx| { + this.restart_auto_fetch_timer(cx); + }) + .ok(); + }); + let mut repo = Repository { this: cx.weak_entity(), git_store, @@ -6472,6 +6504,7 @@ impl Repository { initial_graph_data: Default::default(), commit_data: Default::default(), commit_data_handler: CommitDataHandlerState::Closed, + auto_fetch: AutoFetchState::default(), }; repo.respawn_local_worker(project_environment, fs, is_trusted, cx); cx.subscribe_self(Self::handle_subscribe_self).detach(); @@ -6524,6 +6557,7 @@ impl Repository { initial_graph_data: Default::default(), commit_data: Default::default(), commit_data_handler: CommitDataHandlerState::Closed, + auto_fetch: AutoFetchState::default(), } } @@ -8580,6 +8614,99 @@ impl Repository { Ok(()) } + fn restart_auto_fetch_timer(&mut self, cx: &mut Context) { + let git_settings = &ProjectSettings::get_global(cx).git; + let enabled = git_settings.auto_fetch.enabled; + let interval_secs = git_settings.auto_fetch.interval_secs; + + if self.auto_fetch.enabled == enabled && self.auto_fetch.interval_secs == interval_secs { + return; + } + + self.auto_fetch.enabled = enabled; + self.auto_fetch.interval_secs = interval_secs; + + if !enabled { + self.auto_fetch.task = None; + return; + } + + let interval = Duration::from_secs(interval_secs); + + self.auto_fetch.task = Some(cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(interval).await; + // Re-checked every tick rather than once up front, because a + // repository can be trusted (or restricted) at any point in the + // session. + let fetch = this.update(cx, |this, cx| { + this.is_trusted().then(|| this.auto_fetch(cx)) + }); + match fetch { + Ok(Some(fetch)) => { + if let Err(error) = fetch.await { + log::debug!("auto-fetch failed: {error:#}"); + } + } + Ok(None) => {} + Err(_) => break, + } + } + })); + } + + fn auto_fetch(&mut self, cx: &mut Context) -> Task> { + let default_branch = self.default_branch(true); + let remotes = self.get_remotes(None, false); + cx.spawn(async move |this, cx| { + let default_branch = default_branch.await??; + let remotes = remotes.await??; + let (default_remote, branch_remote) = this.read_with(cx, |this, _| { + let default_remote = default_branch + .and_then(|name| { + this.branch_list + .iter() + .find(|branch| branch.is_remote() && branch.name() == name.as_ref()) + .or_else(|| { + this.branch_list.iter().find(|branch| { + !branch.is_remote() && branch.name() == name.as_ref() + }) + }) + }) + .and_then(|branch| { + branch.remote_name().or_else(|| { + branch + .upstream + .as_ref() + .and_then(|upstream| upstream.remote_name()) + }) + }) + .map(str::to_owned); + let branch_remote = this + .branch + .as_ref() + .and_then(|branch| branch.upstream.as_ref()) + .and_then(|upstream| upstream.remote_name()) + .map(str::to_owned); + (default_remote, branch_remote) + })?; + for remote in remotes { + if Some(remote.name.as_ref()) != default_remote.as_deref() + && Some(remote.name.as_ref()) != branch_remote.as_deref() + { + continue; + } + let fetch = this.update(cx, |this, cx| { + this.fetch(FetchOptions::Remote(remote), None, cx) + })?; + if let Err(error) = fetch.await? { + log::debug!("auto-fetch failed: {error:#}"); + } + } + Ok(()) + }) + } + pub fn unshallow_state(&self) -> UnshallowState { self.unshallow_state } @@ -8589,7 +8716,7 @@ impl Repository { askpass: AskPassDelegate, cx: &mut Context, ) -> oneshot::Receiver> { - let receiver = self.fetch(FetchOptions::Unshallow, askpass, cx); + let receiver = self.fetch(FetchOptions::Unshallow, Some(askpass), cx); self.unshallow_state = UnshallowState::InProgress; cx.notify(); let (tx, rx) = oneshot::channel(); @@ -8616,7 +8743,7 @@ impl Repository { pub fn fetch( &mut self, fetch_options: FetchOptions, - askpass: AskPassDelegate, + askpass: Option, cx: &mut Context, ) -> oneshot::Receiver> { let askpass_delegates = self.askpass_delegates.clone(); @@ -8633,46 +8760,49 @@ impl Repository { }); let this = cx.weak_entity(); - self.send_job( - "fetch", - Some("git fetch".into()), - move |git_repo, mut cx| async move { - match git_repo { - RepositoryState::Local(LocalRepositoryState { - backend, - environment, - .. - }) => { - let result = backend - .fetch(fetch_options, askpass, environment, cx.clone()) - .await; - if result.is_ok() { - Self::refresh_branch_list(&this, backend, updates_tx, &mut cx).await?; - } - result + let status = askpass.is_some().then(|| "git fetch".into()); + self.send_job("fetch", status, move |git_repo, mut cx| async move { + match git_repo { + RepositoryState::Local(LocalRepositoryState { + backend, + environment, + .. + }) => { + if askpass.is_none() && !backend.is_trusted() { + bail!("auto-fetch requires a trusted repository"); } - RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => { - let _askpass_operation = - RemoteAskPassOperation::new(askpass_id, askpass, askpass_delegates); - - let response = client - .request(proto::Fetch { - project_id: project_id.0, - repository_id: id.to_proto(), - askpass_id, - remote: fetch_options.to_proto(), - unshallow: fetch_options == FetchOptions::Unshallow, - }) - .await?; - - Ok(RemoteCommandOutput { - stdout: response.stdout, - stderr: response.stderr, - }) + let result = backend + .fetch(fetch_options, askpass, environment, cx.clone()) + .await; + if result.is_ok() { + Self::refresh_branch_list(&this, backend, updates_tx, &mut cx).await?; } + result } - }, - ) + RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => { + let Some(askpass) = askpass else { + bail!("auto-fetch must run on the repository host"); + }; + let _askpass_operation = + RemoteAskPassOperation::new(askpass_id, askpass, askpass_delegates); + + let response = client + .request(proto::Fetch { + project_id: project_id.0, + repository_id: id.to_proto(), + askpass_id, + remote: fetch_options.to_proto(), + unshallow: fetch_options == FetchOptions::Unshallow, + }) + .await?; + + Ok(RemoteCommandOutput { + stdout: response.stdout, + stderr: response.stderr, + }) + } + } + }) } pub fn push( @@ -11222,6 +11352,174 @@ mod tests { }); } + #[gpui::test] + async fn test_auto_fetch_without_manual_git_operation(cx: &mut TestAppContext) { + use git::repository::{Upstream, UpstreamTracking}; + use util::path; + + init_test(cx); + cx.update(|cx| { + crate::trusted_worktrees::init(Default::default(), cx); + SettingsStore::update_global(cx, |store, cx| { + store.set_user_settings( + r#"{"session":{"trust_all_worktrees":true},"git":{"auto_fetch":{"enabled":true,"interval_secs":15}}}"#, + cx, + ).expect("valid settings"); + }); + }); + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/project"), + json!({".git": {}, "README.md": "project"}), + ) + .await; + let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await; + project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + cx.run_until_parked(); + let fetches = fs + .with_git_state(Path::new(path!("/project/.git")), false, |state| { + state.fetches.clone() + }) + .expect("repository exists"); + assert!(fetches.lock().is_empty()); + cx.executor().advance_clock(Duration::from_secs(15)); + cx.run_until_parked(); + assert!(fetches.lock().is_empty(), "no remotes to fetch"); + + for (default_branch, branch, upstream, expected) in [ + ( + Some("refs/remotes/upstream/main"), + Some("refs/heads/feature"), + Some("refs/remotes/fork/topic"), + vec!["fork", "upstream"], + ), + ( + Some("refs/remotes/upstream/main"), + Some("refs/heads/feature"), + Some("refs/remotes/upstream/topic"), + vec!["upstream"], + ), + ( + Some("refs/remotes/origin/main"), + Some("refs/heads/feature"), + Some("refs/remotes/fork/topic"), + vec!["fork", "origin"], + ), + ( + Some("refs/heads/main"), + Some("refs/heads/feature"), + Some("refs/remotes/fork/topic"), + vec!["central", "fork"], + ), + ( + Some("refs/heads/release/stable"), + Some("refs/heads/feature"), + Some("refs/remotes/central/topic"), + vec!["central"], + ), + ( + Some("refs/heads/untracked"), + Some("refs/heads/feature"), + Some("refs/remotes/fork/topic"), + vec!["fork"], + ), + ( + Some("refs/remotes/upstream/main"), + Some("refs/heads/feature"), + None, + vec!["upstream"], + ), + ( + Some("refs/remotes/upstream/main"), + None, + None, + vec!["upstream"], + ), + ( + None, + Some("refs/heads/feature"), + Some("refs/remotes/fork/topic"), + vec!["fork"], + ), + ( + None, + Some("refs/heads/feature"), + Some("refs/heads/other"), + vec![], + ), + (None, None, None, vec![]), + ] { + fs.with_git_state(Path::new(path!("/project/.git")), true, |state| { + state.branches = [ + "refs/heads/main", + "refs/heads/release/stable", + "refs/heads/untracked", + "refs/heads/feature", + "refs/remotes/origin/main", + "refs/remotes/upstream/main", + ] + .into_iter() + .map(str::to_owned) + .collect(); + state.default_branch_ref = default_branch.map(str::to_owned); + state.current_branch_name = branch.map(str::to_owned); + state.branch_upstreams.clear(); + for (branch, upstream) in [ + ("refs/heads/main", Some("refs/remotes/central/main")), + ( + "refs/heads/release/stable", + Some("refs/remotes/central/stable"), + ), + ("refs/heads/feature", upstream), + ] { + let Some(upstream) = upstream else { + continue; + }; + state.branch_upstreams.insert( + branch.into(), + Upstream { + ref_name: upstream.into(), + tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { + ahead: 0, + behind: 0, + }), + }, + ); + } + state.remotes = ["origin", "upstream", "central", "fork", "unrelated"] + .into_iter() + .map(|remote| { + ( + remote.to_owned(), + format!("https://example.com/{remote}.git"), + ) + }) + .collect(); + state.fetches.lock().clear(); + }) + .expect("repository exists"); + project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + cx.run_until_parked(); + cx.executor().advance_clock(Duration::from_secs(15)); + cx.run_until_parked(); + + let mut fetched_remotes = fetches + .lock() + .iter() + .map(|options| options.name().to_string()) + .collect::>(); + fetched_remotes.sort(); + assert_eq!( + fetched_remotes, expected, + "default_branch={default_branch:?}, branch={branch:?}, upstream={upstream:?}" + ); + } + } + type TestPasswordPrompt = ( String, oneshot::Sender, diff --git a/crates/project/src/project_settings.rs b/crates/project/src/project_settings.rs index 078711c8641..189ac52bbd7 100644 --- a/crates/project/src/project_settings.rs +++ b/crates/project/src/project_settings.rs @@ -503,6 +503,21 @@ pub struct GitSettings { /// /// Default: ../worktrees pub worktree_directory: String, + /// Settings for automatically fetching the default branch's remote and the current branch's upstream remote. + pub auto_fetch: AutoFetchSettings, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AutoFetchSettings { + /// Whether to automatically fetch in the background. + /// + /// Default: false + pub enabled: bool, + /// How long to wait between automatic fetches, in seconds. + /// Only applies when `enabled` is true. (min: 15) + /// + /// Default: 60 + pub interval_secs: u64, } #[derive(Clone, Copy, Debug)] @@ -719,6 +734,13 @@ impl Settings for ProjectSettings { .worktree_directory .clone() .unwrap_or_else(|| DEFAULT_WORKTREE_DIRECTORY.to_string()), + auto_fetch: { + let auto_fetch = git.auto_fetch.unwrap_or_default(); + AutoFetchSettings { + enabled: auto_fetch.enabled.unwrap_or(false), + interval_secs: auto_fetch.interval_secs.unwrap_or(60).max(15), + } + }, }; Self { context_servers: project diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rs index 2bbe0d5cc6f..5f9137aecec 100644 --- a/crates/remote_server/src/remote_editing_tests.rs +++ b/crates/remote_server/src/remote_editing_tests.rs @@ -83,6 +83,200 @@ use util::{ rel_path::rel_path, }; +#[gpui::test] +async fn test_remote_auto_fetch(cx: &mut TestAppContext, server_cx: &mut TestAppContext) { + use project::{ + project_settings::ProjectSettings, + trusted_worktrees::{self, PathTrust, TrustedWorktrees}, + }; + use std::time::Duration; + + cx.update(|cx| { + let mut store = SettingsStore::test(cx); + store + .set_user_settings( + r#"{"git":{"auto_fetch":{"enabled":true,"interval_secs":15}}}"#, + cx, + ) + .expect("valid client settings"); + cx.set_global(store); + }); + server_cx.update(|cx| { + trusted_worktrees::init(Default::default(), cx); + }); + let fs = FakeFs::new(server_cx.executor()); + let dot_git = Path::new(path!("/project/.git")); + fs.insert_tree( + path!("/project"), + json!({".git": {}, "README.md": "project"}), + ) + .await; + fs.insert_branches(dot_git, &["main", "origin/main"]); + fs.set_remote_for_repo(dot_git, "origin", "https://example.com/repo.git"); + let fetches = fs + .with_git_state(dot_git, false, |state| state.fetches.clone()) + .expect("repository exists"); + let (project, headless) = init_test(&fs, cx, server_cx).await; + server_cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_server_settings(r#"{"git":{"auto_fetch":{"interval_secs":45}}}"#, cx) + .expect("valid server settings"); + }); + }); + project + .update(cx, |project, cx| { + project.find_or_create_worktree(path!("/project"), true, cx) + }) + .await + .expect("open remote project"); + cx.run_until_parked(); + server_cx.update(|cx| { + let settings = ProjectSettings::get_global(cx).git.auto_fetch; + assert!( + settings.enabled, + "forward existing user settings on connection" + ); + assert_eq!(settings.interval_secs, 45); + }); + server_cx.executor().advance_clock(Duration::from_secs(45)); + cx.run_until_parked(); + assert_eq!( + fetches.lock().len(), + 0, + "untrusted repositories must not fetch" + ); + + let (worktree_store, worktree_id) = headless.read_with(server_cx, |headless, cx| { + let store = headless.worktree_store.clone(); + let id = store + .read(cx) + .worktrees() + .next() + .expect("host worktree exists") + .read(cx) + .id(); + (store, id) + }); + let trusted = + server_cx.update(|cx| TrustedWorktrees::try_get_global(cx).expect("trust store exists")); + trusted.update(server_cx, |trusted, cx| { + trusted.trust( + &worktree_store, + [PathTrust::Worktree(worktree_id)].into_iter().collect(), + cx, + ); + }); + cx.run_until_parked(); + let repository = project + .read_with(cx, |project, cx| project.active_repository(cx)) + .expect("client repository exists"); + // Leave the client unaware of the new branch until fetch emits a Git event. + fs.with_git_state(dot_git, false, |state| { + state.branches.insert("fetched-branch".into()); + }) + .expect("repository exists"); + cx.run_until_parked(); + assert!(!repository.read_with(cx, |repository, _| { + repository + .branch_list + .iter() + .any(|branch| branch.name() == "fetched-branch") + })); + server_cx.executor().advance_clock(Duration::from_secs(15)); + cx.run_until_parked(); + assert_eq!( + fetches.lock().len(), + 0, + "server interval overrides client interval" + ); + server_cx.executor().advance_clock(Duration::from_secs(30)); + cx.run_until_parked(); + assert_eq!(fetches.lock().len(), 1); + assert!(repository.read_with(cx, |repository, _| { + repository + .branch_list + .iter() + .any(|branch| branch.name() == "fetched-branch") + })); + + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_user_settings( + r#"{"git":{"auto_fetch":{"enabled":false,"interval_secs":15}}}"#, + cx, + ) + .expect("disable auto-fetch on client"); + }); + }); + cx.run_until_parked(); + server_cx.executor().advance_clock(Duration::from_secs(60)); + cx.run_until_parked(); + assert_eq!(fetches.lock().len(), 1); + + server_cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_server_settings( + r#"{"git":{"auto_fetch":{"enabled":true,"interval_secs":30}}}"#, + cx, + ) + .expect("enable server override"); + }); + }); + cx.run_until_parked(); + server_cx.executor().advance_clock(Duration::from_secs(30)); + cx.run_until_parked(); + assert_eq!(fetches.lock().len(), 2); + + server_cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_server_settings("{}", cx) + .expect("clear server override"); + }); + }); + cx.run_until_parked(); + server_cx.executor().advance_clock(Duration::from_secs(60)); + cx.run_until_parked(); + assert_eq!( + fetches.lock().len(), + 2, + "fall back to disabled client setting" + ); + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store + .set_user_settings( + r#"{"git":{"auto_fetch":{"enabled":true,"interval_secs":15}}}"#, + cx, + ) + .expect("enable auto-fetch on client"); + }); + }); + cx.run_until_parked(); + server_cx.executor().advance_clock(Duration::from_secs(15)); + cx.run_until_parked(); + assert_eq!(fetches.lock().len(), 3); + + trusted.update(server_cx, |trusted, cx| { + trusted.restrict( + worktree_store.downgrade(), + [PathTrust::Worktree(worktree_id)].into_iter().collect(), + cx, + ); + }); + cx.run_until_parked(); + server_cx.executor().advance_clock(Duration::from_secs(45)); + cx.run_until_parked(); + assert_eq!( + fetches.lock().len(), + 3, + "revoking trust stops subsequent fetches" + ); +} + #[gpui::test] async fn test_basic_remote_editing(cx: &mut TestAppContext, server_cx: &mut TestAppContext) { let fs = FakeFs::new(server_cx.executor()); diff --git a/crates/settings_content/src/project.rs b/crates/settings_content/src/project.rs index 787849a75f6..582cb7219a6 100644 --- a/crates/settings_content/src/project.rs +++ b/crates/settings_content/src/project.rs @@ -694,6 +694,23 @@ pub struct GitSettings { /// /// Default: ../worktrees pub worktree_directory: Option, + /// Settings for automatically fetching the default branch's remote and the current branch's upstream remote. + pub auto_fetch: Option, +} + +#[with_fallible_options] +#[derive(Clone, Copy, PartialEq, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom)] +#[serde(rename_all = "snake_case")] +pub struct AutoFetchSettingsContent { + /// Whether to automatically fetch in the background. + /// + /// Default: false + pub enabled: Option, + /// How long to wait between automatic fetches, in seconds. + /// Only used when `enabled` is true. (min: 15) + /// + /// Default: 60 + pub interval_secs: Option, } #[with_fallible_options] diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs index eefb373eb85..f50548be2f1 100644 --- a/crates/settings_ui/src/page_data.rs +++ b/crates/settings_ui/src/page_data.rs @@ -8128,7 +8128,7 @@ fn terminal_page() -> SettingsPage { } fn version_control_page() -> SettingsPage { - fn git_integration_section() -> [SettingsPageItem; 2] { + fn git_integration_section() -> [SettingsPageItem; 3] { [ SettingsPageItem::SectionHeader("Git Integration"), SettingsPageItem::DynamicItem(DynamicItem { @@ -8229,6 +8229,76 @@ fn version_control_page() -> SettingsPage { ], ], }), + SettingsPageItem::DynamicItem(DynamicItem { + discriminant: SettingItem { + files: USER, + title: "Auto Fetch", + description: "Automatically fetch the default branch's remote and the current branch's upstream remote.", + field: Box::new(SettingField:: { + organization_override: None, + json_path: Some("git.auto_fetch.enabled"), + pick: |settings_content| { + settings_content + .git + .as_ref()? + .auto_fetch + .as_ref()? + .enabled + .as_ref() + }, + write: |settings_content, value, _| { + settings_content + .git + .get_or_insert_default() + .auto_fetch + .get_or_insert_default() + .enabled = value; + }, + }), + metadata: None, + }, + pick_discriminant: |settings_content| { + Some( + *settings_content + .git + .as_ref()? + .auto_fetch + .as_ref()? + .enabled + .as_ref()? as usize, + ) + }, + fields: vec![ + vec![], + vec![SettingItem { + files: USER, + title: "Auto Fetch Interval", + description: "How long to wait between automatic fetches, in seconds. (min: 15)", + field: Box::new(SettingField:: { + organization_override: None, + json_path: Some("git.auto_fetch.interval_secs"), + pick: |settings_content| { + settings_content + .git + .as_ref()? + .auto_fetch + .as_ref()? + .interval_secs + .as_ref() + }, + write: |settings_content, value, _| { + settings_content + .git + .get_or_insert_default() + .auto_fetch + .get_or_insert_default() + .interval_secs = value; + }, + }), + metadata: None, + }], + ], + }), ] } diff --git a/docs/src/reference/all-settings.md b/docs/src/reference/all-settings.md index 0b80faf6036..22881530e6a 100644 --- a/docs/src/reference/all-settings.md +++ b/docs/src/reference/all-settings.md @@ -2898,6 +2898,35 @@ Example: } ``` +### Auto Fetch + +- Description: Whether and how often to automatically fetch the default branch's remote and the current branch's upstream remote in the background. If the default branch is local, its upstream remote is used. If both refer to the same remote, it is fetched only once. Other remotes are not fetched. Auto-fetch never prompts for credentials, so it relies on credentials that can be supplied without interaction, such as an SSH agent or a credential helper answering from a keychain. It is also disabled for repositories in worktrees you have not trusted. +- Setting: `auto_fetch` +- Default: + +```json [settings] +{ + "git": { + "auto_fetch": { + "enabled": false, + "interval_secs": 60 + } + } +} +``` + +**Options** + +- `enabled`: Whether to automatically fetch in the background. Disabling it stops future fetches without interrupting a fetch already queued or running. +- `interval_secs`: How long to wait between automatic fetches, in seconds, starting after the previous fetch completes. Only applies when `enabled` is `true`. Values below 15 are clamped to 15. + +In remote development, auto-fetch runs on the host that owns the checkout and +sends repository updates to your local Zed window. Your user settings are forwarded +to the SSH server; server settings override them. In a shared project, the host's +settings control auto-fetch for all collaborators. Configure `git.auto_fetch` in +user or server settings; Git settings are not read from project `.zed/settings.json` +files. + ## Go to Definition Fallback - Description: What to do when the {#action editor::GoToDefinition} action fails to find a definition diff --git a/docs/src/remote-development.md b/docs/src/remote-development.md index f2e1ab36b9f..b633a6b5656 100644 --- a/docs/src/remote-development.md +++ b/docs/src/remote-development.md @@ -180,7 +180,14 @@ When opening a remote project there are three relevant settings locations: - The server Zed settings (in the same place) on the remote server. - The project settings (in `.zed/settings.json` or `.editorconfig` of your project) -Both the local Zed and the server Zed read the project settings, but they are not aware of the other's main settings file. +Both the local Zed and the server Zed read supported project settings. Zed forwards +your local user settings to the server, where server settings override them. + +Git auto-fetch runs on the server and sends updated branch information to your +local Zed window. Enable `git.auto_fetch` in your user settings or the server's +settings. Git settings are not read from project `.zed/settings.json` files. See +[Auto Fetch](./reference/all-settings.md#auto-fetch) for configuration and credential +requirements. Which settings file you should use depends on the kind of setting you want to make: