Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): stop scanning whole repo for workspace snapshots
Akarshan Biswas60e6585c975f
diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rsindex e861daa04..697f8a2a3 100644--- a/src-tauri/src/core/agent/git.rs+++ b/src-tauri/src/core/agent/git.rs@@ -1,6 +1,15 @@//! Git-backed workspace snapshots (ticket #164). The agent edits files in place//! in the user's working directory; to make a run revertible we snapshot the-//! whole working tree per turn and can restore it, Claude-Code style.+//! state after each turn and can restore it, Claude-Code style.+//!+//! Snapshots never scan the working tree. Each checkpoint stages only the exact+//! paths the caller reports as touched this turn (`edit`/`write` tool calls);+//! the base snapshot seeds from the current `HEAD` tree plus a `git diff+//! --name-only HEAD` (tracked files only -- no untracked-file walk). This keeps+//! cost bounded by what actually changed instead of the size of the repo, which+//! matters on large trees or ones with big non-ignored build/model directories.+//! A known trade-off: changes made by other means (a `bash` tool call, an+//! external editor) are not captured unless also reported via `changed`.//!//! Snapshots are kept OUT of the user's branch, HEAD, and index: we stage into a//! throwaway index file (`GIT_INDEX_FILE`) and build commit objects with@@ -59,12 +68,22 @@ fn run(repo: &Path, index: Option<&Path>, args: &[&str]) -> Result<String, Strinstatic IDX_COUNTER: AtomicU64 = AtomicU64::new(0);-/// A unique throwaway index path so snapshotting never disturbs the real index.+/// A unique throwaway index path so one-off git operations (restore) never+/// disturb the real index.fn temp_index() -> PathBuf {let n = IDX_COUNTER.fetch_add(1, Ordering::SeqCst);std::env::temp_dir().join(format!("jan-agent-idx-{}-{n}", std::process::id()))}+/// A stable index path for a thread's snapshot chain, kept across calls (not+/// deleted after use). Reusing it lets `git add -A` compare against its own+/// prior stat cache instead of a fresh empty one, so unchanged files are only+/// stat'd (cheap) rather than re-hashed and re-inserted like every other file+/// touched this turn.+fn snapshot_index(thread_id: &str) -> PathBuf {+ std::env::temp_dir().join(format!("jan-agent-snap-idx-{thread_id}"))+}+/// Hidden ref that keeps a thread's snapshot chain reachable across GC. One ref/// per thread; each snapshot parents the previous, so the whole chain is live.pub(crate) fn snapshot_ref(thread_id: &str) -> String {@@ -82,27 +101,74 @@ pub(crate) fn repo_root(path: &Path) -> Option<PathBuf> {.map(PathBuf::from)}-/// Snapshot the entire working tree as a commit object, without touching the-/// user's branch/HEAD/index. `.gitignore` is respected (build/deps dirs are not-/// captured). `parent` chains onto the previous snapshot; `None` for the base.-/// Returns the snapshot commit sha.-pub(crate) fn snapshot(repo: &Path, parent: Option<&str>, msg: &str) -> Result<String, String> {- let idx = temp_index();- let result = (|| {- run(repo, Some(&idx), &["read-tree", "--empty"])?;- run(repo, Some(&idx), &["add", "-A"])?;- let tree = run(repo, Some(&idx), &["write-tree"])?;- let mut args = vec!["commit-tree", &tree];- if let Some(p) = parent {- args.push("-p");- args.push(p);+/// The canonical empty tree object every git repo has, without needing a+/// commit to hash it from -- used as the base tree when `HEAD` is unborn.+const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";++/// Stage a single relative path into `idx`: `add` if it still exists on disk,+/// `rm --cached` (ignoring paths not currently tracked) if it was deleted.+/// Never touches any other path, so cost is O(1) per call, not O(repo size).+fn stage_path(repo: &Path, idx: &Path, rel: &Path) -> Result<(), String> {+ let rel_str = rel.to_string_lossy();+ if repo.join(rel).exists() {+ run(repo, Some(idx), &["add", "--", &rel_str])?;+ } else {+ run(repo, Some(idx), &["rm", "--cached", "--ignore-unmatch", "--", &rel_str])?;+ }+ Ok(())+}++/// Snapshot the current state as a commit object, without touching the user's+/// branch/HEAD/index, and without ever scanning the whole working tree.+/// `parent` chains onto the previous snapshot; `None` for the base. `changed`+/// lists paths (relative to `repo`) touched since the previous snapshot in+/// this thread's chain -- only these are staged. Returns the snapshot sha.+///+/// `thread_id` keys a persistent throwaway index reused across a thread's+/// whole snapshot chain, seeded once (base) from `HEAD`'s tree (or the empty+/// tree for an unborn `HEAD`) plus any already-dirty tracked files (via `git+/// diff --name-only HEAD`, which compares only tracked paths -- no untracked+/// scan). Every later checkpoint reuses that same index and stages only+/// `changed`.+pub(crate) fn snapshot(+ repo: &Path,+ parent: Option<&str>,+ msg: &str,+ thread_id: &str,+ changed: &[PathBuf],+) -> Result<String, String> {+ let idx = snapshot_index(thread_id);+ if !idx.exists() {+ let base_tree = run(repo, None, &["rev-parse", "--verify", "-q", "HEAD^{tree}"])+ .ok()+ .filter(|s| !s.is_empty())+ .unwrap_or_else(|| EMPTY_TREE.to_string());+ run(repo, Some(&idx), &["read-tree", &base_tree])?;+ if let Ok(dirty) = run(repo, None, &["diff", "--name-only", "HEAD"]) {+ for rel in dirty.lines().filter(|l| !l.is_empty()) {+ stage_path(repo, &idx, Path::new(rel))?;+ }}- args.push("-m");- args.push(msg);- run(repo, None, &args)- })();- let _ = std::fs::remove_file(&idx);- result+ }+ for rel in changed {+ stage_path(repo, &idx, rel)?;+ }+ let tree = run(repo, Some(&idx), &["write-tree"])?;+ let mut args = vec!["commit-tree", &tree];+ if let Some(p) = parent {+ args.push("-p");+ args.push(p);+ }+ args.push("-m");+ args.push(msg);+ run(repo, None, &args)+}++/// Drop a thread's persistent snapshot index (e.g. once the thread is done or+/// after a workspace restore invalidates it). Safe to call even if it was+/// never created.+pub(crate) fn cleanup_snapshot_index(thread_id: &str) {+ let _ = std::fs::remove_file(snapshot_index(thread_id));}/// Point the thread's snapshot ref at `sha` (create or update).@@ -161,7 +227,8 @@ mod tests {fn snapshot_restore_roundtrip() {let Some(root) = init_repo() else { return };- let base = snapshot(&root, None, "base").expect("base snapshot");+ let thread_id = "test-thread";+ let base = snapshot(&root, None, "base", thread_id, &[]).expect("base snapshot");// Mutate: edit a file, add a new one, and drop something into an ignored dir.std::fs::write(root.join("a.txt"), "two\n").unwrap();@@ -169,7 +236,9 @@ mod tests {std::fs::create_dir_all(root.join("ignored")).unwrap();std::fs::write(root.join("ignored/keep.txt"), "keep\n").unwrap();- let turn = snapshot(&root, Some(&base), "turn 1").expect("turn snapshot");+ let changed = [PathBuf::from("a.txt"), PathBuf::from("b.txt")];+ let turn =+ snapshot(&root, Some(&base), "turn 1", thread_id, &changed).expect("turn snapshot");assert_ne!(turn, base);// Restore to base: a.txt reverts, b.txt (added) is removed, ignored file stays.@@ -180,6 +249,7 @@ mod tests {root.join("ignored/keep.txt").exists(),"gitignored file must be left alone");+ cleanup_snapshot_index(thread_id);let _ = std::fs::remove_dir_all(&root);}@@ -187,12 +257,62 @@ mod tests {#[test]fn snapshot_is_invisible_to_user_state() {let Some(root) = init_repo() else { return };+ let thread_id = "test-thread-2";std::fs::write(root.join("a.txt"), "dirty\n").unwrap();- let _ = snapshot(&root, None, "s").expect("snapshot");+ let _ = snapshot(&root, None, "s", thread_id, &[]).expect("snapshot");// The user's index/branch are untouched: HEAD still the init commit and the// working change is still unstaged.let staged = run(&root, None, &["diff", "--cached", "--name-only"]).unwrap();assert!(staged.is_empty(), "snapshot must not stage anything");+ cleanup_snapshot_index(thread_id);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn base_snapshot_picks_up_preexisting_dirty_tracked_file() {+ let Some(root) = init_repo() else { return };+ let thread_id = "test-thread-dirty-base";++ // Dirty *before* the agent starts -- no tool call reported it, so the+ // base must still capture it via the tracked-only diff, not `changed`.+ std::fs::write(root.join("a.txt"), "dirty-at-start\n").unwrap();+ let base = snapshot(&root, None, "base", thread_id, &[]).expect("base snapshot");++ let head_tree = run(&root, None, &["rev-parse", "HEAD^{tree}"]).unwrap();+ let base_tree = run(&root, None, &["rev-parse", &format!("{base}^{{tree}}")]).unwrap();+ assert_ne!(base_tree, head_tree, "base tree must include the pre-existing dirty edit");++ cleanup_snapshot_index(thread_id);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn checkpoint_only_stages_reported_paths() {+ let Some(root) = init_repo() else { return };+ let thread_id = "test-thread-3";++ let base = snapshot(&root, None, "base", thread_id, &[]).expect("base snapshot");+ let idx = snapshot_index(thread_id);+ assert!(idx.exists(), "base snapshot should persist its index");++ // Two files change on disk, but only one is reported as touched; the+ // checkpoint must reflect just that one.+ std::fs::write(root.join("a.txt"), "two\n").unwrap();+ std::fs::write(root.join("untouched.txt"), "not reported\n").unwrap();+ let changed = [PathBuf::from("a.txt")];+ let turn =+ snapshot(&root, Some(&base), "turn 1", thread_id, &changed).expect("turn snapshot");+ assert_ne!(turn, base);++ let listed = run(&root, None, &["ls-tree", "-r", "--name-only", &turn]).unwrap();+ assert!(listed.lines().any(|l| l == "a.txt"));+ assert!(+ !listed.lines().any(|l| l == "untouched.txt"),+ "unreported path must not be staged even though it changed on disk"+ );++ cleanup_snapshot_index(thread_id);+ assert!(!idx.exists());let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 56dafa566..a2cb79f30 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -99,6 +99,7 @@ pub fn cli_delete_thread(thread_id: &str) -> Result<(), String> {if thread_dir.exists() {fs::remove_dir_all(thread_dir).map_err(|e| e.to_string())?;}+ crate::core::agent::git::cleanup_snapshot_index(thread_id);Ok(())}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 5cf151e04..3deb44ef4 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -230,6 +230,12 @@ struct App {/// Repo top-level when the project is a git repo; enables workspace snapshots./// Cleared if git setup fails, permanently disabling snapshots this session.repo_root: Option<PathBuf>,+ /// Directory tool paths (`edit`/`write` "path" args) are resolved against.+ project_root: PathBuf,+ /// Absolute paths touched by `edit`/`write` tool calls so far this turn;+ /// drained into the next checkpoint's snapshot and reset per turn. Only+ /// these exact paths are staged -- checkpoints never scan the repo.+ turn_touched: Vec<PathBuf>,/// Base snapshot (working-tree state before the first turn) for the active/// thread. `Some` once snapshotting is armed; `None` = no workspace restore.base_snapshot: Option<String>,@@ -335,29 +341,42 @@ struct SubagentBlock {/// Rolling window size for a subagent's live tool-call list.const SUBAGENT_WINDOW: usize = 5;-/// A queued git workspace snapshot. The `git` subprocess re-hashes the whole-/// working tree and is slow on a large repo, so snapshots run off the render-/// loop (via `spawn_blocking`) and serialized (each checkpoint parents the-/// previous), driven from the main loop rather than inline in `submit_user`/-/// `on_done`.+/// A queued git workspace snapshot. Snapshots only stage the paths the agent+/// actually touched this turn (see `App::turn_touched`), never the whole+/// working tree, so this stays cheap on a large repo. Still run off the+/// render loop (via `spawn_blocking`) and serialized (each checkpoint parents+/// the previous), driven from the main loop rather than inline in+/// `submit_user`/`on_done`.enum SnapshotJob {/// Base state captured before the first turn; gates the first run.Base,- /// Per-turn checkpoint keyed to the driving user message.- Checkpoint { user_index: usize, preview: String },+ /// Per-turn checkpoint keyed to the driving user message, carrying the+ /// paths touched by `edit`/`write` tool calls since the previous one.+ Checkpoint {+ user_index: usize,+ preview: String,+ changed: Vec<PathBuf>,+ },}+/// `(repo, parent sha, commit message, thread id, changed paths)` resolved+/// from a queued [`SnapshotJob`], ready to hand to `git::snapshot`.+type SnapshotInputs = (PathBuf, Option<String>, String, String, Vec<PathBuf>);+impl App {fn new(model: String,max_turns: u32,agent_dir: std::path::PathBuf,+ project_root: PathBuf,repo_root: Option<PathBuf>,) -> Self {Self {model,max_turns,repo_root,+ project_root,+ turn_touched: Vec::new(),base_snapshot: None,checkpoints: Vec::new(),snap_queue: std::collections::VecDeque::new(),@@ -764,25 +783,32 @@ impl App {self.snap_queue.push_back(SnapshotJob::Checkpoint {user_index,preview,+ changed: std::mem::take(&mut self.turn_touched),});}/// Resolve the git inputs for the next queued snapshot from current state:- /// `(repo, parent, message, thread_id)`. `None` when snapshotting is- /// unavailable (not a git repo, or no thread id yet), so the job is dropped.- fn resolve_snapshot(&self, job: &SnapshotJob) -> Option<(PathBuf, Option<String>, String, String)> {+ /// `(repo, parent, message, thread_id, changed paths)`. `None` when+ /// snapshotting is unavailable (not a git repo, or no thread id yet), so the+ /// job is dropped. Changed paths are made relative to `repo`; anything+ /// outside it is dropped rather than passed to `git`.+ fn resolve_snapshot(&self, job: &SnapshotJob) -> Option<SnapshotInputs> {let repo = self.repo_root.clone()?;let id = self.thread_id.clone()?;match job {- SnapshotJob::Base => Some((repo, None, "jan agent base".to_string(), id)),- SnapshotJob::Checkpoint { .. } => {+ SnapshotJob::Base => Some((repo, None, "jan agent base".to_string(), id, Vec::new())),+ SnapshotJob::Checkpoint { changed, .. } => {let parent = self.checkpoints.last().map(|c| c.sha.clone()).or_else(|| self.base_snapshot.clone());let n = self.checkpoints.len() + 1;- Some((repo, parent, format!("jan agent turn {n}"), id))+ let changed = changed+ .iter()+ .filter_map(|p| p.strip_prefix(&repo).ok().map(|p| p.to_path_buf()))+ .collect();+ Some((repo, parent, format!("jan agent turn {n}"), id, changed))}}}@@ -853,7 +879,12 @@ impl App {let label = truncate(&tool_activity(&name, &args), max);let done = truncate(&tool_finished(&name, &args), max);if matches!(name.as_str(), "edit" | "write") {- // Diff-producing tools render standalone (call row + panel).+ // Record the touched path so the next checkpoint snapshots+ // exactly this file instead of scanning the whole repo.+ if let Some(p) = args.get("path").and_then(|v| v.as_str()) {+ self.turn_touched.push(self.project_root.join(p));+ }+ // Diff-producing tools render standalone (call row & panel).self.finalize_tool_group();self.flush_assistant();self.gap(Kind::Tool);@@ -1731,16 +1762,18 @@ async fn await_mcp(task: &mut Option<tokio::task::JoinHandle<Vec<String>>>) -> V}/// Run one git snapshot (and ref update) off the render loop. Returns the-/// snapshot sha. Blocking `git` work is confined to a blocking thread so the UI-/// stays responsive on large repos.+/// snapshot sha. Only `changed` (the paths touched this turn) are staged, so+/// this stays fast regardless of repo size; the blocking `git` work still runs+/// on a blocking thread so the UI stays responsive.fn spawn_snapshot(repo: PathBuf,parent: Option<String>,msg: String,thread_id: String,+ changed: Vec<PathBuf>,) -> tokio::task::JoinHandle<Result<String, String>> {tokio::task::spawn_blocking(move || {- let sha = git::snapshot(&repo, parent.as_deref(), &msg)?;+ let sha = git::snapshot(&repo, parent.as_deref(), &msg, &thread_id, &changed)?;git::update_ref(&repo, &thread_id, &sha)?;Ok(sha)})@@ -1788,7 +1821,7 @@ pub async fn run(// A git repo enables workspace snapshots (rewind can restore files); a// non-repo runs exactly as before with conversation-only rewind.let repo_root = git::repo_root(&project_root);- let mut app = App::new(model, max_turns, agent_dir, repo_root);+ let mut app = App::new(model, max_turns, agent_dir, project_root, repo_root);let res = chat_loop(&mut terminal,&args,@@ -1842,8 +1875,8 @@ async fn chat_loop<B: Backend>(// inputs no longer resolve (snapshots disabled) is dropped.if snap_task.is_none() {while let Some(job) = app.snap_queue.pop_front() {- if let Some((repo, parent, msg, id)) = app.resolve_snapshot(&job) {- snap_task = Some(spawn_snapshot(repo, parent, msg, id));+ if let Some((repo, parent, msg, id, changed)) = app.resolve_snapshot(&job) {+ snap_task = Some(spawn_snapshot(repo, parent, msg, id, changed));snap_inflight = Some(job);break;}@@ -1905,7 +1938,7 @@ async fn chat_loop<B: Backend>(app.base_snapshot = Some(sha);app.persist();}- (Some(SnapshotJob::Checkpoint { user_index, preview }), Ok(sha)) => {+ (Some(SnapshotJob::Checkpoint { user_index, preview, .. }), Ok(sha)) => {app.checkpoints.push(Checkpoint { user_index, preview, sha });app.persist();}@@ -3248,7 +3281,7 @@ mod tests {std::process::id(),uuid::Uuid::new_v4()));- App::new("m".into(), 8, agent_dir, None)+ App::new("m".into(), 8, agent_dir, std::path::PathBuf::from("/tmp/repo"), None)}fn pending(offers_always: bool) -> Pending {@@ -3676,7 +3709,7 @@ mod tests {app.base_requested = true;app.checkpoint_turn();match app.snap_queue.front() {- Some(SnapshotJob::Checkpoint { user_index, preview }) => {+ Some(SnapshotJob::Checkpoint { user_index, preview, .. }) => {assert_eq!(*user_index, 0);assert_eq!(preview, "do it");}@@ -3689,16 +3722,22 @@ mod tests {let mut app = test_app();app.repo_root = Some(std::path::PathBuf::from("/tmp/repo"));app.thread_id = Some("t1".into());- let (_, parent, msg, id) = app.resolve_snapshot(&SnapshotJob::Base).unwrap();+ let (_, parent, msg, id, changed) = app.resolve_snapshot(&SnapshotJob::Base).unwrap();assert!(parent.is_none());assert_eq!(msg, "jan agent base");assert_eq!(id, "t1");+ assert!(changed.is_empty());app.base_snapshot = Some("basesha".into());- let job = SnapshotJob::Checkpoint { user_index: 0, preview: "x".into() };- let (_, parent, msg, _) = app.resolve_snapshot(&job).unwrap();+ let job = SnapshotJob::Checkpoint {+ user_index: 0,+ preview: "x".into(),+ changed: vec![std::path::PathBuf::from("/tmp/repo/src/a.rs")],+ };+ let (_, parent, msg, _, changed) = app.resolve_snapshot(&job).unwrap();assert_eq!(parent.as_deref(), Some("basesha"), "first checkpoint parents the base");assert_eq!(msg, "jan agent turn 1");+ assert_eq!(changed, vec![std::path::PathBuf::from("src/a.rs")]);// Disabled (no repo) -> job dropped.app.repo_root = None;