Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cli): fork a session into a new thread, and run it in its own git worktree (#8970)

Akarshan Biswas8fe0d2692c71
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 48991c20d..fa50acfa9 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -41,6 +41,9 @@ jan <COMMAND>
| `--no-sandbox` | Run shell commands unconfined, overriding a persistent `sandbox` setting |
| `--resume [ID]` | Resume the most recent session, or one whose id starts with `ID` |
| `-c`, `--continue` | Resume the most recent session |
+| `--fork-session` | Open the resumed session as a new thread, leaving the original resumable |
+| `--worktree` | Work in a dedicated git worktree instead of the project directory. Off by default |
+| `--no-worktree` | Work in the project directory, overriding a persistent `worktree` setting |
| `--provider <ID>` | Target a specific provider for this run |
| `--api-key <KEY>` | API key for that provider |
@@ -53,6 +56,8 @@ jan --resume 3f7a91c2 # resume by id prefix
jan --plan # read-only
jan --safe # ask before writes and shell commands
jan --sandbox # confine shell commands to the project
+jan -c --fork-session # branch the latest session into a new one
+jan --worktree # work in a dedicated checkout, not yours
```
<Callout type="warning">
@@ -88,6 +93,9 @@ jan cli agent run --safe "run the migration" # approve each step
| `--no-sandbox` | Run shell commands unconfined, overriding a persistent `sandbox` setting |
| `--resume[=ID]` | Resume the most recent session, or one by id |
| `-c`, `--continue` | Resume the most recent session |
+| `--fork-session` | Open the resumed session as a new thread, leaving the original resumable |
+| `--worktree` | Work in a dedicated git worktree instead of the project directory. Off by default |
+| `--no-worktree` | Work in the project directory, overriding a persistent `worktree` setting |
| `--provider`, `--api-key` | Credential overrides for this run |
| `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object; `stream-json` prints one JSON event per line |
| `--input-format <FORMAT>` | `text` (default) ignores stdin; `stream-json` reads client messages while the run is in flight. Requires `--output-format stream-json` |
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index c27138b26..f1cb89d8d 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -64,6 +64,7 @@ Point at a different file with `instructions_file` if you already keep conventio
# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO
# show_reasoning = false # unfold thinking blocks in the transcript (Ctrl-O still toggles)
# send_reasoning = true # resend prior reasoning to the model; false drops it from the request
+# worktree = true # give each session its own git checkout instead of editing this one
instructions_file = "AGENT.md"
# [provider]
@@ -104,6 +105,7 @@ inject = "always"
| `max_parallel_subagents` | `10` | Subagents that may run at once (min 1); extra dispatches queue FIFO |
| `show_reasoning` | `false` | Unfold model reasoning (`<thinking>`) blocks in the transcript instead of folding them to a summary row. <kbd>Ctrl</kbd>+<kbd>O</kbd> still toggles a folded block |
| `send_reasoning` | `true` | Resend a prior turn's reasoning to the model with the conversation. Set `false` for an upstream that rejects the field (e.g. Groq), or to keep chains of thought out of the context budget |
+| `worktree` | `false` | Run each session in its own git worktree under `~/.jan/worktrees`, on a `jan/agent/` branch, instead of editing this checkout. Overridden by `--worktree` / `--no-worktree`. See [Sessions](/docs/agent/sessions) |
| `instructions_file` | `AGENT.md` | Markdown injected into the system prompt |
### `[provider]`
diff --git a/docs/src/pages/docs/agent/sessions.mdx b/docs/src/pages/docs/agent/sessions.mdx
index 6d670aba3..7e13876c1 100644
--- a/docs/src/pages/docs/agent/sessions.mdx
+++ b/docs/src/pages/docs/agent/sessions.mdx
@@ -1,7 +1,7 @@
---
title: Sessions
description: Saved conversations, resuming, rewinding, and queueing messages while the agent works.
-keywords: [Jan, Jan Agent, sessions, threads, resume, rewind, checkpoints, queue]
+keywords: [Jan, Jan Agent, sessions, threads, resume, fork, worktree, rewind, checkpoints, queue]
---
import { Callout } from 'nextra/components'
@@ -61,6 +61,93 @@ is the same behaviour minus the file restore.
This is the escape hatch when the agent goes down a wrong path: rather than arguing it back, rewind
to before the turn that started it and rephrase.
+## Forking
+
+A rewind is destructive: the turns after the point you roll back to are gone. Forking is the same
+cut without losing them - the prefix is copied into a **new** session and the original stays exactly
+as it was.
+
+```
+/fork # pick a past message; the branch opens with that message back in the input
+/tree # saved sessions as a tree, Enter resumes one
+```
+
+At startup, to branch instead of continuing:
+
+```bash
+jan -c --fork-session
+jan --resume 3f7a91c2 --fork-session
+jan cli agent run --resume=3f7a91c2 --fork-session "try it the other way"
+```
+
+The branch keeps the transcript, tool calls and diffs of the turns it inherited, and records the
+session it came from - which is what `/tree` draws. Sessions with no forks render as the flat list
+`/resume` shows.
+
+This is what to reach for when a long session has built up context worth keeping and you want to try
+a second approach from the middle of it without destroying the first.
+
+## Working in a git worktree
+
+By default the agent edits your checkout in place. With a worktree it gets its own, on its own
+branch, so a run you don't like costs a `git branch -D` instead of a revert:
+
+```bash
+jan --worktree # this session only
+jan --no-worktree # override a persistent setting
+```
+
+Persistently:
+
+```toml
+# .jan/agent/agent.toml - for everyone who checks this project out
+[agent]
+worktree = true
+```
+
+```toml
+# ~/.jan/config.toml - for every project you work on
+worktree = true
+```
+
+A flag beats the project file, which beats the global setting, which beats the default - the same
+order as [`sandbox`](/docs/agent/permissions), and the reason `--no-worktree` exists.
+
+The checkout lives under `~/.jan/worktrees/`, outside your repository, on a `jan/agent/<id>` branch.
+`/worktree` in the console names the path, the branch, and what's changed there.
+
+```
+worktree:
+ path ~/.jan/worktrees/app-a1b2c3d4/3f7a91c2
+ branch jan/agent/3f7a91c2
+ changes 2 file(s)
+ src/parser.rs
+ tests/parser.rs
+ review with: git -C ~/.jan/worktrees/app-a1b2c3d4/3f7a91c2 diff
+```
+
+Getting the work back out is your own git - nothing here writes to the branch you left. A session
+remembers its worktree, so resuming returns to it; a fork gets one of its own, branched from where
+the source left off. A `/fork` taken mid-session is the exception: the checkout can't change under a
+running session, so the branch borrows it until you reopen the fork with `--worktree`, which is when
+it gets its own.
+
+Nothing prunes these. When you're done with a session's work, the checkout and its branch go the
+usual way:
+
+```bash
+git worktree remove ~/.jan/worktrees/app-a1b2c3d4/3f7a91c2
+git branch -D jan/agent/3f7a91c2
+```
+
+Delete the directory by hand instead and the next resume of that session quietly starts over from
+`HEAD`, saying so in the banner.
+
+<Callout type="info">
+Rewinding still restores files, and now restores them in the worktree - the snapshots follow the
+agent into whichever checkout it's working in.
+</Callout>
+
## Queueing
Type while the agent is working and your message is queued instead of dropped. It's sent as soon as
@@ -94,7 +181,7 @@ Under `<project>/.jan/agent/`:
| Path | Contents |
| --- | --- |
-| `threads/` | Saved sessions and their messages |
+| `threads/` | Saved sessions and their messages, including which worktree each used |
| `memory/` | Durable facts, see [Memory](/docs/agent/memory) |
| `skills/` | Reusable procedures, see [Skills](/docs/agent/skills) |
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index a259e1ba2..de38ed8e9 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -34,6 +34,9 @@ Either form loads the skill's full instructions into the conversation (no separa
| `/clear` | Clear the conversation |
| `/threads` | List saved threads for this project |
| `/resume [id]` | Resume a thread. Bare: pick interactively |
+| `/fork` | Branch this session at a past message into a new thread, keeping this one |
+| `/tree` | Saved threads as a fork tree. Enter resumes one |
+| `/worktree` | The dedicated checkout this session works in, and what changed there |
| `/quit` | Exit |
See [Sessions](/docs/agent/sessions).
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index dd696a6f6..65b15b64b 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -18,7 +18,7 @@ use app_lib::core::cli::{
cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,
cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,
cli_get_thread, cli_list_messages, cli_list_threads, cli_plugin_install, cli_plugin_list,
- cli_plugin_remove, cli_plugin_search, ResumeTarget, SessionFlags,
+ cli_plugin_remove, cli_plugin_search, ResumeRequest, SessionFlags,
};
use std::fmt::Write as _;
@@ -43,6 +43,8 @@ to opt out of both.",
jan --task \"fix the failing test\" # seed the TUI with a first message\n \
jan -c # resume the most recent session\n \
jan --resume 3f7a91c2 # resume a session by id (or id prefix)\n \
+ jan -c --fork-session # branch the most recent session into a new one\n \
+ jan --worktree # work in a dedicated git worktree, not your checkout\n \
jan cli agent run \"fix the failing test\" # run the agent non-interactively\n \
jan cli models list # show every configured provider model\n \
jan cli threads list # list saved conversation threads\n \
@@ -79,6 +81,8 @@ struct Cli {
plan: bool,
#[command(flatten)]
sandbox: SandboxArgs,
+ #[command(flatten)]
+ worktree: WorktreeArgs,
}
/// Whether this invocation confines the shell, shared by every surface that
@@ -98,6 +102,32 @@ struct SandboxArgs {
no_sandbox: bool,
}
+/// Whether this invocation works in its own git worktree.
+///
+/// Two flags for the same reason `SandboxArgs` has two: the setting is also
+/// persistent (`[agent].worktree` in agent.toml, `worktree` in
+/// `~/.jan/config.toml`), so there has to be a way out of it for one run.
+#[derive(Args, Clone, Copy)]
+struct WorktreeArgs {
+ /// Work in a dedicated git worktree instead of the project directory
+ #[arg(long)]
+ worktree: bool,
+ /// Work in the project directory, overriding a persistent worktree setting
+ #[arg(long, conflicts_with = "worktree")]
+ no_worktree: bool,
+}
+
+impl WorktreeArgs {
+ /// `None` when neither flag was passed, so the config files decide.
+ fn into_flag(self) -> Option<bool> {
+ match (self.worktree, self.no_worktree) {
+ (true, _) => Some(true),
+ (_, true) => Some(false),
+ _ => None,
+ }
+ }
+}
+
impl SandboxArgs {
/// `None` when neither flag was passed, so the config files decide.
fn into_flag(self) -> Option<bool> {
@@ -120,11 +150,14 @@ struct ResumeArgs {
/// Resume the most recent session (alias for a bare --resume)
#[arg(long = "continue", short = 'c', conflicts_with = "resume")]
continue_session: bool,
+ /// Open the resumed session as a new thread, leaving the original resumable
+ #[arg(long)]
+ fork_session: bool,
}
impl ResumeArgs {
- fn into_target(self) -> Option<ResumeTarget> {
- ResumeTarget::from_flags(self.resume, self.continue_session)
+ fn into_request(self) -> Option<ResumeRequest> {
+ ResumeRequest::from_flags(self.resume, self.continue_session, self.fork_session)
}
}
@@ -139,11 +172,14 @@ struct ResumeRunArgs {
/// Resume the most recent session (alias for a bare --resume)
#[arg(long = "continue", short = 'c', conflicts_with = "resume")]
continue_session: bool,
+ /// Open the resumed session as a new thread, leaving the original resumable
+ #[arg(long)]
+ fork_session: bool,
}
impl ResumeRunArgs {
- fn into_target(self) -> Option<ResumeTarget> {
- ResumeTarget::from_flags(self.resume, self.continue_session)
+ fn into_request(self) -> Option<ResumeRequest> {
+ ResumeRequest::from_flags(self.resume, self.continue_session, self.fork_session)
}
}
@@ -312,6 +348,8 @@ enum AgentCommands {
#[command(flatten)]
sandbox: SandboxArgs,
#[command(flatten)]
+ worktree: WorktreeArgs,
+ #[command(flatten)]
resume: ResumeRunArgs,
/// `text` streams the answer as it arrives; `json` prints one result
/// object on stdout when the run finishes; `stream-json` prints one
@@ -544,9 +582,10 @@ async fn main() {
auto_approve: !cli.safe,
plan: cli.plan,
sandbox: cli.sandbox.into_flag(),
+ worktree: cli.worktree.into_flag(),
..Default::default()
},
- cli.resume.into_target(),
+ cli.resume.into_request(),
)
.await
{
@@ -738,6 +777,7 @@ async fn handle_agent(cmd: AgentCommands) {
safe,
providers,
sandbox,
+ worktree,
resume,
output_format,
input_format,
@@ -750,9 +790,10 @@ async fn handle_agent(cmd: AgentCommands) {
SessionFlags {
auto_approve: !safe,
sandbox: sandbox.into_flag(),
+ worktree: worktree.into_flag(),
..Default::default()
},
- resume.into_target(),
+ resume.into_request(),
output_format,
input_format,
)
diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rs
index c4856548f..0bb3cb238 100644
--- a/src-tauri/src/core/agent/git.rs
+++ b/src-tauri/src/core/agent/git.rs
@@ -1,6 +1,12 @@
-//! 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
-//! state after each turn and can restore it, Claude-Code style.
+//! Git-backed workspace snapshots. The agent edits files in place in the
+//! directory it works in; to make a run revertible we snapshot the state after
+//! each turn and can restore it, Claude-Code style.
+//!
+//! That directory is the user's own checkout by default, and a dedicated
+//! worktree when the session asked for one (`core::cli::worktree`), which the
+//! snapshots follow: the worktree isolates the files, these snapshots make the
+//! turns inside it revertible. The worktree primitives below are the git side
+//! of that, kept here because this module owns every `git` invocation.
//!
//! Snapshots never scan the working tree. Each checkpoint stages only the exact
//! paths the caller reports as touched this turn (`edit`/`write` tool calls);
@@ -232,6 +238,103 @@ pub(crate) fn restore(repo: &Path, target: &str, latest: &str) -> Result<(), Str
result
}
+/// `HEAD`'s commit sha, or `None` on an unborn branch (or no git).
+#[cfg(feature = "cli")]
+pub(crate) fn head_sha(repo: &Path) -> Option<String> {
+ run(repo, None, &["rev-parse", "HEAD"])
+ .ok()
+ .filter(|s| !s.is_empty())
+}
+
+/// Create a worktree at `path`, checking out a new branch `branch` starting at
+/// `base` (any commit-ish). The parent directory is created first: `git
+/// worktree add` requires the path's parent to exist but refuses the path
+/// itself to.
+#[cfg(feature = "cli")]
+pub(crate) fn worktree_add(
+ repo: &Path,
+ path: &Path,
+ branch: &str,
+ base: &str,
+) -> Result<(), String> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ }
+ run(
+ repo,
+ None,
+ &[
+ "worktree",
+ "add",
+ "-b",
+ branch,
+ &path.to_string_lossy(),
+ base,
+ ],
+ )
+ .map(|_| ())
+}
+
+/// The worktree checkouts registered with `repo`, main worktree included.
+///
+/// Parsed from `--porcelain`, whose `worktree <path>` lines are the stable
+/// machine-readable form; the human listing pads the path with the sha and
+/// branch, which a path containing spaces makes ambiguous.
+#[cfg(feature = "cli")]
+pub(crate) fn worktree_paths(repo: &Path) -> Vec<PathBuf> {
+ run(repo, None, &["worktree", "list", "--porcelain"])
+ .unwrap_or_default()
+ .lines()
+ .filter_map(|l| l.strip_prefix("worktree "))
+ .map(PathBuf::from)
+ .collect()
+}
+
+/// Whether `path` is a checkout `repo` still knows about. Compared after
+/// canonicalization, because git reports the resolved path and the caller's
+/// copy came from a config file or a thread record.
+#[cfg(feature = "cli")]
+pub(crate) fn worktree_registered(repo: &Path, path: &Path) -> bool {
+ let Ok(want) = path.canonicalize() else {
+ return false;
+ };
+ worktree_paths(repo)
+ .iter()
+ .filter_map(|p| p.canonicalize().ok())
+ .any(|p| p == want)
+}
+
+/// Forget worktree registrations whose directory the user has deleted. Without
+/// this, `worktree add` refuses a path that a stale registration still claims.
+#[cfg(feature = "cli")]
+pub(crate) fn worktree_prune(repo: &Path) {
+ let _ = run(repo, None, &["worktree", "prune"]);
+}
+
+/// Paths changed in a worktree relative to its own `HEAD`, staged, unstaged and
+/// untracked alike (`status --porcelain`, whose status letters are stripped).
+/// This is the "what has the agent done in there" summary, not a diff.
+///
+/// The status field is split off at its first space rather than by a fixed
+/// width: `run` trims the output, so the leading space of an unstaged-only
+/// line (` M a.txt`) is gone by the time this sees it and a fixed offset would
+/// eat the first character of that one path.
+#[cfg(feature = "cli")]
+pub(crate) fn changed_paths(worktree: &Path) -> Vec<String> {
+ run(worktree, None, &["status", "--porcelain"])
+ .unwrap_or_default()
+ .lines()
+ .filter_map(|l| l.trim_start().split_once(' '))
+ // A rename reads `R old -> new`; the new name is the path on disk, and
+ // the old one no longer exists, so staging it would be a delete.
+ .map(|(_, path)| match path.trim().split_once(" -> ") {
+ Some((_, to)) => to.to_string(),
+ None => path.trim().to_string(),
+ })
+ .filter(|s| !s.is_empty())
+ .collect()
+}
+
#[cfg(all(test, feature = "cli"))]
mod tests {
use super::*;
@@ -259,6 +362,75 @@ mod tests {
repo_root(&root)
}
+ #[test]
+ fn a_worktree_is_added_registered_and_reports_its_changes() {
+ let Some(root) = init_repo() else { return };
+ let wt = root.parent().unwrap().join(format!(
+ "{}-wt",
+ root.file_name().unwrap().to_string_lossy()
+ ));
+ let _ = std::fs::remove_dir_all(&wt);
+
+ let head = head_sha(&root).expect("a repo with one commit has a HEAD");
+ worktree_add(&root, &wt, "jan/agent/test1", &head).expect("worktree add");
+
+ assert!(wt.join("a.txt").is_file(), "the tree was checked out");
+ assert!(worktree_registered(&root, &wt));
+ assert!(
+ worktree_paths(&root).len() >= 2,
+ "the main checkout and the new one"
+ );
+ assert_eq!(
+ current_branch(&wt).as_deref(),
+ Some("jan/agent/test1"),
+ "the worktree is on its own branch"
+ );
+ // The main checkout is untouched by work done in the worktree.
+ assert!(changed_paths(&wt).is_empty());
+ std::fs::write(wt.join("a.txt"), "edited\n").unwrap();
+ std::fs::write(wt.join("new.txt"), "added\n").unwrap();
+ let mut changed = changed_paths(&wt);
+ changed.sort();
+ assert_eq!(changed, vec!["a.txt".to_string(), "new.txt".to_string()]);
+ assert!(
+ changed_paths(&root).is_empty(),
+ "the user's checkout is clean"
+ );
+ assert_eq!(
+ std::fs::read_to_string(root.join("a.txt")).unwrap(),
+ "one\n"
+ );
+
+ // A worktree the user deleted is forgotten, so its path is reusable.
+ std::fs::remove_dir_all(&wt).unwrap();
+ worktree_prune(&root);
+ assert!(!worktree_registered(&root, &wt));
+ }
+
+ /// A worktree can start from any commit, which is how a fork of a session
+ /// picks up where that conversation left off instead of at `HEAD`.
+ #[test]
+ fn a_worktree_can_branch_from_a_snapshot_commit() {
+ let Some(root) = init_repo() else { return };
+ std::fs::write(root.join("a.txt"), "two\n").unwrap();
+ let snap =
+ snapshot(&root, None, "turn 1", "t1", &[PathBuf::from("a.txt")]).expect("snapshot");
+ std::fs::write(root.join("a.txt"), "three\n").unwrap();
+
+ let wt = root.parent().unwrap().join(format!(
+ "{}-snapwt",
+ root.file_name().unwrap().to_string_lossy()
+ ));
+ let _ = std::fs::remove_dir_all(&wt);
+ worktree_add(&root, &wt, "jan/agent/test2", &snap).expect("worktree add at a snapshot");
+ assert_eq!(
+ std::fs::read_to_string(wt.join("a.txt")).unwrap(),
+ "two\n",
+ "the branch starts from the snapshot, not HEAD and not the live tree"
+ );
+ let _ = std::fs::remove_dir_all(&wt);
+ }
+
#[test]
fn snapshot_restore_roundtrip() {
let Some(root) = init_repo() else { return };
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 1ea90a402..8f8b0d16b 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -23,6 +23,9 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# sandbox = true # run `bash` under OS confinement (same as
# # passing --sandbox); off by default, so
# # shell commands run with your own access
+# worktree = true # run each session in its own git worktree
+# # (same as passing --worktree); off by
+# # default, so the agent edits your checkout
# think_tags = false # stop treating <think> tags in model
# # content as reasoning; they render and
# # are resent as ordinary prose. On by
@@ -75,6 +78,10 @@ struct GlobalConfigToml {
/// `--sandbox` flag.
#[serde(default, skip_serializing_if = "Option::is_none")]
sandbox: Option<bool>,
+ /// Give each session its own git worktree to work in. `None` = the
+ /// default, off. The "permanently on" answer to `--worktree`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ worktree: Option<bool>,
/// Parse `<think>` tags in model *content* as reasoning. `None` = the
/// default, on. Native `reasoning_content` streaming is a separate
/// mechanism and is unaffected.
@@ -296,6 +303,14 @@ pub(crate) fn sandbox_setting() -> Option<bool> {
load_raw().ok().and_then(|config| config.sandbox)
}
+/// Whether a session gets its own git worktree by default (`worktree` in
+/// `~/.jan/config.toml`). `None` when unset, so a project's `agent.toml` or the
+/// `--worktree` flag decides first. Unreadable config yields `None`, like
+/// [`sandbox_setting`]: a preference must not block a session from starting.
+pub(crate) fn worktree_setting() -> Option<bool> {
+ load_raw().ok().and_then(|config| config.worktree)
+}
+
/// Host env-var names the sandboxed `bash` may inherit beyond the base
/// allowlist (`env_passthrough` in `~/.jan/config.toml`), merged under a
/// project's `[tools].env_passthrough`. Empty on an unreadable or malformed
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index d876ba227..9edc339e6 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -121,6 +121,11 @@ pub(crate) struct AgentSection {
/// out of the context budget.
#[serde(default)]
pub send_reasoning: Option<bool>,
+ /// Give each session in this project its own git worktree, so the agent's
+ /// edits land in a separate checkout instead of the user's. `None` = defer
+ /// to the global `worktree` setting, then the default, off.
+ #[serde(default)]
+ pub worktree: Option<bool>,
}
// `default`/`allow`/`deny`/`allow_write` are consumed by `permissions_from`,
@@ -269,6 +274,11 @@ pub(crate) struct RunSettings {
pub env_passthrough: Vec<String>,
/// `[tools].env_set`: explicit shell-env overrides, sorted by key.
pub env_set: Vec<(String, String)>,
+ /// `[agent].worktree`: give each session its own git checkout. Merged with
+ /// the global setting and the `--worktree` flag by the caller. CLI-only,
+ /// like the `[agent]` section it comes from.
+ #[cfg(feature = "cli")]
+ pub worktree: Option<bool>,
}
/// A missing or malformed config yields defaults rather than an error: a project
@@ -284,6 +294,8 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {
sandbox: cfg.tools.sandbox,
env_passthrough: cfg.tools.env_passthrough,
env_set: cfg.tools.env_set.into_iter().collect(),
+ #[cfg(feature = "cli")]
+ worktree: cfg.agent.worktree,
}
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 836f272af..356f16c69 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -21,6 +21,7 @@ pub mod terminal_setup;
pub mod tokamak;
mod tui;
pub mod updater;
+pub mod worktree;
use std::path::PathBuf;
use std::sync::Arc;
@@ -91,6 +92,41 @@ impl ResumeTarget {
}
}
+/// A resume request: which thread, and whether to branch it instead of
+/// continuing it. `fork` writes the resolved thread's prefix into a fresh id and
+/// opens that, so the source stays on disk exactly as it was.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ResumeRequest {
+ pub target: ResumeTarget,
+ pub fork: bool,
+}
+
+impl ResumeRequest {
+ /// Continue the resolved thread in place.
+ pub fn resume(target: ResumeTarget) -> Self {
+ Self {
+ target,
+ fork: false,
+ }
+ }
+
+ /// Branch the resolved thread into a new one.
+ pub fn fork(target: ResumeTarget) -> Self {
+ Self { target, fork: true }
+ }
+
+ /// Build a request from the CLI flags. `--fork-session` alone means "branch
+ /// the most recent session", so it implies a target of its own.
+ pub fn from_flags(
+ resume: Option<Option<String>>,
+ continue_session: bool,
+ fork: bool,
+ ) -> Option<Self> {
+ let target = ResumeTarget::from_flags(resume, continue_session)
+ .or_else(|| fork.then_some(ResumeTarget::Latest))?;
+ Some(Self { target, fork })
+ }
+}
/// Recency sort key for a saved thread (`updated`, falling back to `created`).
pub fn thread_recency(t: &serde_json::Value) -> f64 {
t.get("updated")
@@ -145,6 +181,24 @@ pub fn find_resume_thread(
}
}
+/// Resolve a resume request to the thread the session should open: the matched
+/// thread, or a fresh fork of it that leaves the match untouched.
+pub fn resolve_resume(
+ base: &std::path::Path,
+ request: &ResumeRequest,
+) -> Result<serde_json::Value, String> {
+ let thread = find_resume_thread(base, &request.target)?;
+ if !request.fork {
+ return Ok(thread);
+ }
+ let source = thread
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "saved thread has no id".to_string())?;
+ let id = fork_thread(base, source, None)?;
+ cli_get_thread_in(base, &id)
+}
+
/// Read a thread's messages, tolerating a truncated or malformed line (a crash
/// mid-append leaves one). Returns the parsed records and the skipped count, so
/// a resume degrades to "lost the tail" instead of failing outright.
@@ -201,10 +255,12 @@ pub fn cli_delete_thread(thread_id: &str) -> Result<(), String> {
Ok(())
}
-/// Get thread metadata by ID.
-pub fn cli_get_thread(thread_id: &str) -> Result<serde_json::Value, String> {
- let data_folder = resolve_jan_data_folder();
- let path = get_thread_metadata_path(&data_folder, thread_id);
+/// Get thread metadata by ID from a given store (`<base>/threads/<id>`).
+pub fn cli_get_thread_in(
+ base: &std::path::Path,
+ thread_id: &str,
+) -> Result<serde_json::Value, String> {
+ let path = get_thread_metadata_path(base, thread_id);
if !path.exists() {
return Err(format!("Thread '{thread_id}' not found"));
}
@@ -212,6 +268,11 @@ pub fn cli_get_thread(thread_id: &str) -> Result<serde_json::Value, String> {
serde_json::from_str(&data).map_err(|e| e.to_string())
}
+/// Get thread metadata by ID from the desktop store.
+pub fn cli_get_thread(thread_id: &str) -> Result<serde_json::Value, String> {
+ cli_get_thread_in(&resolve_jan_data_folder(), thread_id)
+}
+
/// Persist a TUI conversation as a desktop-compatible thread so it appears in
/// `/resume` and the desktop app. `history` is OpenAI-shaped (`{role, content}`);
/// it is written as `thread.message` records plus `thread.json` metadata. Pass
@@ -385,6 +446,199 @@ pub(crate) fn rebuild_wire_history(messages: &[serde_json::Value]) -> Vec<serde_
out
}
+// ── Thread forking ─────────────────────────────────────────────────────────
+
+/// Key in a thread's `metadata` naming the thread it was branched from. A
+/// free-form metadata entry rather than a field on the thread record, so the
+/// desktop reader and the mobile store need no migration and an existing store
+/// (where every thread is a root) renders as today's flat list.
+pub const FORKED_FROM_KEY: &str = "forked_from";
+
+/// True for a `user` message the user actually authored. Hidden reminders ride
+/// in on the `user` role but are not turns: a rewind target, a fork point, a
+/// recall entry or a checkpoint key built from one would be a row the user never
+/// typed, and would shift every later index out of step with the display
+/// journal, which holds no reminder at all.
+pub(crate) fn is_user_turn(m: &serde_json::Value) -> bool {
+ m.get("role").and_then(|v| v.as_str()) == Some("user")
+ && !crate::core::agent::reminder::is_reminder_only(
+ m.get("content").unwrap_or(&serde_json::Value::Null),
+ )
+}
+
+/// Index of the `target`-th (0-based) user turn in a wire conversation, i.e.
+/// where a rewind or fork to that turn cuts. `None` when there are fewer turns.
+pub(crate) fn user_turn_index(history: &[serde_json::Value], target: usize) -> Option<usize> {
+ history
+ .iter()
+ .enumerate()
+ .filter(|(_, m)| is_user_turn(m))
+ .nth(target)
+ .map(|(i, _)| i)
+}
+
+/// How many user turns a wire conversation holds.
+pub(crate) fn user_turn_count(history: &[serde_json::Value]) -> usize {
+ history.iter().filter(|m| is_user_turn(m)).count()
+}
+
+/// The thread a fork came from, when this one is a fork.
+pub fn forked_parent(thread: &serde_json::Value) -> Option<&str> {
+ thread
+ .get("metadata")?
+ .get(FORKED_FROM_KEY)?
+ .get("thread_id")?
+ .as_str()
+}
+
+/// Metadata for a fork: the source's, minus the bookkeeping that describes turns
+/// the branch does not have, plus the parent pointer. Forking a fork overwrites
+/// the pointer, so it always names the immediate parent.
+fn fork_metadata(
+ source_metadata: Option<&serde_json::Value>,
+ source_id: &str,
+ user_turn: usize,
+) -> serde_json::Value {
+ let mut meta = source_metadata
+ .and_then(|m| m.as_object().cloned())
+ .unwrap_or_default();
+ if let Some(checkpoints) = meta.get_mut("checkpoints").and_then(|v| v.as_array_mut()) {
+ checkpoints.retain(|c| {
+ c.get("user_index")
+ .and_then(serde_json::Value::as_u64)
+ .is_some_and(|i| (i as usize) < user_turn)
+ });
+ }
+ // Two conversations must not edit one checkout: the branch records no
+ // worktree, so opening it with worktrees on gets it one of its own, based on
+ // where the source left off (see `resolve_workspace`).
+ meta.remove(worktree::WORKTREE_KEY);
+ meta.insert(
+ FORKED_FROM_KEY.to_string(),
+ serde_json::json!({ "thread_id": source_id, "user_turn": user_turn }),
+ );
+ serde_json::Value::Object(meta)
+}
+
+/// Branch a saved thread into a new one holding its prefix up to `at_user_turn`
+/// (that turn and everything after it are left behind, the same cut a rewind
+/// makes), or the whole conversation when `None`. Both the wire history and the
+/// display journal are carried, so the fork replays with its tool rows.
+///
+/// The source is only read, never written: that is the whole point of a fork
+/// over a rewind.
+///
+/// A fork never inherits the source's worktree (see `fork_metadata`): the two
+/// conversations diverge from here, and one checkout cannot hold both.
+pub fn fork_thread(
+ base: &std::path::Path,
+ source_id: &str,
+ at_user_turn: Option<usize>,
+) -> Result<String, String> {
+ let source = std::fs::read_to_string(get_thread_metadata_path(base, source_id))
+ .map_err(|e| format!("thread '{source_id}' not found: {e}"))?;
+ let source: serde_json::Value = serde_json::from_str(&source).map_err(|e| e.to_string())?;
+
+ let (messages, _) = cli_read_messages_lenient(base, source_id)?;
+ // Cut the rebuilt conversation, not the raw records: `rebuild_wire_history`
+ // is what enforces tool_call/tool_result pairing, and cutting immediately
+ // before a user turn leaves that pairing intact because it closes every open
+ // call at each turn boundary.
+ let mut history = rebuild_wire_history(&messages);
+ let mut journal = journal::read_journal(&journal::journal_path(base, source_id));
+ if let Some(turn) = at_user_turn {
+ let cut = user_turn_index(&history, turn)
+ .ok_or_else(|| format!("no message #{} to fork at", turn + 1))?;
+ history.truncate(cut);
+ // The journal is keyed by its own user entries, not by history indices:
+ // it holds rows (tool calls, reasoning) history never had.
+ journal.truncate(journal::truncate_at_user(&journal, turn));
+ }
+ if history.is_empty() {
+ return Err("nothing before that message to fork".to_string());
+ }
+
+ let model = source
+ .get("model")
+ .and_then(|m| m.get("id"))
+ .and_then(|v| v.as_str())
+ .unwrap_or_default();
+ // Cutting at user turn N keeps exactly N turns, so the recorded turn is the
+ // same number whether the cut was asked for or the whole thread was taken.
+ let metadata = fork_metadata(source.get("metadata"), source_id, user_turn_count(&history));
+ let id = cli_save_thread(base, None, model, &history, Some(metadata))?;
+ journal::write_journal(&journal::journal_path(base, &id), &journal)?;
+ Ok(id)
+}
+
+/// One row of the fork forest: a thread plus how deep it sits under its root.
+pub struct ThreadNode {
+ pub thread: serde_json::Value,
+ pub depth: usize,
+ /// Last among its siblings, so a renderer can pick the corner glyph.
+ pub last: bool,
+}
+
+fn push_children(stack: &mut Vec<(usize, usize, bool)>, kids: &[usize], depth: usize) {
+ // Reversed, so popping yields the children in order.
+ for (n, &child) in kids.iter().enumerate().rev() {
+ stack.push((child, depth, n + 1 == kids.len()));
+ }
+}
+
+/// Arrange saved threads into the forest their `forked_from` pointers describe,
+/// depth-first, siblings most-recent-first. A thread whose parent is gone is a
+/// root, so deleting a session never hides the forks taken from it.
+pub fn thread_forest(mut threads: Vec<serde_json::Value>) -> Vec<ThreadNode> {
+ use std::collections::HashMap;
+
+ sort_threads_recent(&mut threads);
+ let index_of: HashMap<&str, usize> = threads
+ .iter()
+ .enumerate()
+ .filter_map(|(i, t)| Some((t.get("id")?.as_str()?, i)))
+ .collect();
+ let mut children: Vec<Vec<usize>> = vec![Vec::new(); threads.len()];
+ let mut roots: Vec<usize> = Vec::new();
+ for (i, t) in threads.iter().enumerate() {
+ match forked_parent(t)
+ .and_then(|p| index_of.get(p))
+ .copied()
+ .filter(|&p| p != i)
+ {
+ Some(parent) => children[parent].push(i),
+ None => roots.push(i),
+ }
+ }
+
+ let mut out = Vec::new();
+ let mut seen = vec![false; threads.len()];
+ let mut stack: Vec<(usize, usize, bool)> = Vec::new();
+ push_children(&mut stack, &roots, 0);
+ while let Some((i, depth, last)) = stack.pop() {
+ if std::mem::replace(&mut seen[i], true) {
+ continue;
+ }
+ push_children(&mut stack, &children[i], depth + 1);
+ out.push(ThreadNode {
+ thread: threads[i].clone(),
+ depth,
+ last,
+ });
+ }
+ // A cycle of forks is reachable from no root and would otherwise vanish from
+ // the list; show those threads flat rather than lose a session.
+ for (i, t) in threads.iter().enumerate() {
+ if !seen[i] {
+ out.push(ThreadNode {
+ thread: t.clone(),
+ depth: 0,
+ last: true,
+ });
+ }
+ }
+ out
+}
/// Text of a persisted `thread.message` (content parts carry `text.value`) or of
/// an OpenAI-shaped message (`content` is a plain string or `text` parts), so
/// the same reader works on both sides of a save/resume round trip.
@@ -657,7 +911,7 @@ pub async fn cli_agent_run(
model: Option<String>,
overrides: ProviderOverrides,
flags: SessionFlags,
- resume: Option<ResumeTarget>,
+ resume: Option<ResumeRequest>,
format: OutputFormat,
input_format: InputFormat,
) -> Result<(), String> {
@@ -765,6 +1019,9 @@ struct PersistTarget {
thread_id: Option<String>,
model: String,
history: Vec<serde_json::Value>,
+ /// The checkout this run worked in, recorded on the thread so a later
+ /// `--resume` reattaches to it.
+ workspace: Option<worktree::Worktree>,
}
/// Per-run limits resolved from agent.toml. Grouped rather than passed as a
@@ -815,6 +1072,13 @@ pub(crate) struct AgentSession {
/// Background connect of `active` MCP servers, awaited before the first turn.
/// `None` when no server is active. Resolves to the connected server names.
pub mcp_task: Option<tokio::task::JoinHandle<mcp::ConnectOutcome>>,
+ /// The git worktree this session's tools work in, when it has one. `None`
+ /// is the default: the agent edits the project directory itself.
+ pub workspace: Option<worktree::Worktree>,
+ /// Why a requested worktree could not be set up, for the surface to report.
+ /// `Some` only when one was asked for and the session fell back to the
+ /// project directory.
+ pub workspace_note: Option<String>,
}
impl AgentSession {
@@ -856,6 +1120,10 @@ pub struct SessionFlags {
/// to `[tools].sandbox`, then the global `sandbox`, then the CLI default of
/// off.
pub sandbox: Option<bool>,
+ /// `--worktree`: work in a dedicated git checkout. `None` (not passed)
+ /// defers to `[agent].worktree`, then the global `worktree`, then the CLI
+ /// default of off.
+ pub worktree: Option<bool>,
}
/// The desktop app's currently-selected model, adopted only when signed in to
@@ -869,6 +1137,125 @@ fn inherit_desktop_model(
signed_in.then_some(selection.model).flatten()
}
+/// The newest workspace snapshot a thread recorded, which is where a fork of it
+/// should start its own checkout: the files as that conversation last left them,
+/// rather than a `HEAD` its whole transcript predates.
+fn latest_snapshot(thread: Option<&serde_json::Value>) -> Option<String> {
+ let metadata = thread?.get("metadata")?;
+ metadata
+ .get("checkpoints")
+ .and_then(|c| c.as_array())
+ .and_then(|c| c.last())
+ .and_then(|c| c.get("sha"))
+ .or_else(|| metadata.get("base_snapshot"))
+ .and_then(|v| v.as_str())
+ .map(str::to_string)
+}
+
+/// The metadata to save a thread with so it names the checkout the run worked
+/// in, merged into whatever that thread already recorded rather than replacing
+/// it. `None` when there is no worktree, which is `cli_save_thread`'s "keep the
+/// existing metadata" case.
+///
+/// Without this a resumed session branches a *fresh* worktree and the model
+/// reads a pristine tree, silently losing everything the run it is continuing
+/// did in there.
+fn worktree_metadata(
+ agent_dir: &std::path::Path,
+ thread_id: Option<&str>,
+ workspace: Option<&worktree::Worktree>,
+) -> Option<serde_json::Value> {
+ let workspace = workspace?;
+ let mut meta = thread_id
+ .and_then(|id| cli_get_thread_in(agent_dir, id).ok())
+ .and_then(|thread| thread.get("metadata")?.as_object().cloned())
+ .unwrap_or_default();
+ meta.insert(
+ worktree::WORKTREE_KEY.to_string(),
+ worktree::to_metadata(workspace),
+ );
+ Some(serde_json::Value::Object(meta))
+}
+
+/// The commit a fork's checkout starts from.
+///
+/// The newest snapshot the source thread recorded is the best answer: it is the
+/// tree that conversation last left. A headless run takes no snapshots (they are
+/// the TUI's per-turn checkpoints), so fall back to capturing the source's
+/// worktree as it stands -- otherwise the branch opens on a pristine `HEAD`
+/// while the transcript it inherited describes work that is not in it, and the
+/// model's first act is to re-read files that disagree with what it just said.
+///
+/// `None` leaves the choice to `HEAD`, which is right when the source never had
+/// a checkout of its own.
+fn fork_base(source: Option<&serde_json::Value>) -> Option<String> {
+ use crate::core::agent::git;
+
+ if let Some(sha) = latest_snapshot(source) {
+ return Some(sha);
+ }
+ let source = source?;
+ let workspace = worktree::from_metadata(source.get("metadata"))?;
+ if !workspace.path.is_dir() {
+ return None;
+ }
+ // Keyed per source thread and cleaned up: this index is a one-shot, unlike
+ // the per-thread one a session keeps warm across its turns.
+ let key = format!("fork-base-{}", source.get("id")?.as_str()?);
+ let changed: Vec<PathBuf> = git::changed_paths(&workspace.path)
+ .into_iter()
+ .map(PathBuf::from)
+ .collect();
+ let sha = git::snapshot(&workspace.path, None, "jan agent fork base", &key, &changed).ok();
+ git::cleanup_snapshot_index(&key);
+ sha
+}
+
+/// Decide the checkout this session's tools work in.
+///
+/// A plain resume reattaches to the worktree its thread recorded. A fork is a
+/// *different* thread, so it branches its own from where the source left off --
+/// two conversations editing one checkout is the thing a worktree exists to
+/// prevent. A session that cannot get the worktree it asked for runs in the
+/// project directory and says why, because that fallback is exactly how every
+/// session behaved before worktrees existed.
+fn resolve_workspace(
+ project_root: &std::path::Path,
+ flag: Option<bool>,
+ resume: Option<&ResumeRequest>,
+) -> (Option<worktree::Worktree>, Option<String>) {
+ let configured = crate::core::agent::project::run_settings(project_root).worktree;
+ if !worktree::resolve_enabled(flag, configured) {
+ return (None, None);
+ }
+ let forking = resume.is_some_and(|request| request.fork);
+ let source = resume
+ .and_then(|request| find_resume_thread(&agent_dir_for(project_root), &request.target).ok());
+ let recorded = if forking {
+ None
+ } else {
+ worktree::from_metadata(source.as_ref().and_then(|t| t.get("metadata")))
+ };
+ let base = forking.then(|| fork_base(source.as_ref())).flatten();
+ match worktree::for_session(project_root, recorded.as_ref(), base.as_deref()) {
+ // A different path than the one recorded means the checkout was gone and
+ // a fresh one was branched from HEAD: nothing was committed there, so the
+ // resumed conversation now describes edits this tree does not have.
+ Ok(workspace) => {
+ let note = recorded
+ .filter(|old| old.path != workspace.path)
+ .map(|old| {
+ format!(
+ "the checkout this thread recorded ({}) is gone; starting fresh from HEAD",
+ old.path.display()
+ )
+ });
+ (Some(workspace), note)
+ }
+ Err(e) => (None, Some(format!("no worktree for this session: {e}"))),
+ }
+}
+
/// Resolve project config + credentials into a ready-to-run engine handle.
/// Shared by `run_agent_loop` (plain CLI) and `cli_agent_ui` (TUI).
fn prepare_agent_session(
@@ -876,6 +1263,7 @@ fn prepare_agent_session(
model_override: Option<String>,
overrides: ProviderOverrides,
flags: SessionFlags,
+ resume: Option<&ResumeRequest>,
) -> Result<AgentSession, String> {
let project_root = resolve_project_root(project);
ensure_project(&project_root)?;
@@ -980,8 +1368,16 @@ fn prepare_agent_session(
.agent
.max_parallel_subagents
.unwrap_or(crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS);
+ // The tools work in the worktree when there is one; everything else about
+ // the session (agent.toml, credentials, the thread store) stays keyed to the
+ // project, which is where the user configured it.
+ let (workspace, workspace_note) = resolve_workspace(&project_root, flags.worktree, resume);
+ let tool_root = workspace
+ .as_ref()
+ .map(|w| w.path.clone())
+ .unwrap_or_else(|| project_root.clone());
let args = build_cli_orchestration_args(
- project_root,
+ tool_root,
permissions,
provider_configs,
mcp_servers.clone(),
@@ -1015,6 +1411,8 @@ fn prepare_agent_session(
send_reasoning: cfg.agent.send_reasoning.unwrap_or(true),
mcp_servers,
mcp_task,
+ workspace,
+ workspace_note,
})
}
@@ -1030,9 +1428,9 @@ struct ResumedSession {
/// describe why nothing could be resumed; the caller starts fresh.
fn load_resume_history(
agent_dir: &std::path::Path,
- target: &ResumeTarget,
+ request: &ResumeRequest,
) -> Result<ResumedSession, String> {
- let thread = find_resume_thread(agent_dir, target)?;
+ let thread = resolve_resume(agent_dir, request)?;
let thread_id = thread
.get("id")
.and_then(|v| v.as_str())
@@ -1053,7 +1451,7 @@ fn prepare_agent_run(
single_turn: bool,
overrides: ProviderOverrides,
flags: SessionFlags,
- resume: Option<ResumeTarget>,
+ resume: Option<ResumeRequest>,
) -> Result<PreparedRun, String> {
// Non-interactive runs (`agent run`/`step`) have no plan-review handoff, so
// plan mode stays a TUI-only startup option, and a run with no model has no
@@ -1067,9 +1465,27 @@ fn prepare_agent_run(
require_model: true,
..flags
},
+ resume.as_ref(),
)?;
let project_root = resolve_project_root(project);
- let (clean_task, injected) = path_refs::resolve_references(task, &project_root);
+ if let Some(note) = session.workspace_note.as_deref() {
+ eprintln!("({note})");
+ }
+ if let Some(workspace) = session.workspace.as_ref() {
+ eprintln!(
+ "(working in {} on {})",
+ workspace.path.display(),
+ workspace.branch
+ );
+ }
+ // `@path` names a file the agent is about to work on, so it resolves against
+ // the checkout the tools see rather than the project directory.
+ let read_root = session
+ .workspace
+ .as_ref()
+ .map(|w| w.path.clone())
+ .unwrap_or_else(|| project_root.clone());
+ let (clean_task, injected) = path_refs::resolve_references(task, &read_root);
let final_task = if injected.is_empty() {
clean_task
} else {
@@ -1077,10 +1493,19 @@ fn prepare_agent_run(
};
// A failed resume is not fatal: report it and run the prompt in a new session.
- let resumed = resume.and_then(|target| {
- match load_resume_history(&agent_dir_for(&project_root), &target) {
+ let resumed = resume.and_then(|request| {
+ let verb = if request.fork {
+ "forked into"
+ } else {
+ "resumed"
+ };
+ match load_resume_history(&agent_dir_for(&project_root), &request) {
Ok(r) => {
- eprintln!("(resumed session {} with {} message(s))", short_id(&r.thread_id), r.history.len());
+ eprintln!(
+ "({verb} session {} with {} message(s))",
+ short_id(&r.thread_id),
+ r.history.len()
+ );
Some(r)
}
Err(e) => {
@@ -1112,6 +1537,7 @@ fn prepare_agent_run(
thread_id: resumed.map(|r| r.thread_id),
model: session.model,
history,
+ workspace: session.workspace,
},
})
}
@@ -1129,7 +1555,7 @@ async fn run_agent_loop(
single_turn: bool,
overrides: ProviderOverrides,
flags: SessionFlags,
- resume: Option<ResumeTarget>,
+ resume: Option<ResumeRequest>,
format: OutputFormat,
input_format: InputFormat,
) -> Result<(), String> {
@@ -1271,6 +1697,7 @@ async fn run_agent_loop(
thread_id,
model,
mut history,
+ workspace,
} = persist;
let mut session_id = thread_id.clone();
let mut final_text = None;
@@ -1279,7 +1706,8 @@ async fn run_agent_loop(
if let Some(text) = final_text.as_ref() {
history.push(serde_json::json!({ "role": "assistant", "content": text.clone() }));
}
- match cli_save_thread(&agent_dir, thread_id.as_deref(), &model, &history, None) {
+ let metadata = worktree_metadata(&agent_dir, thread_id.as_deref(), workspace.as_ref());
+ match cli_save_thread(&agent_dir, thread_id.as_deref(), &model, &history, metadata) {
Ok(id) => {
if !format.is_machine() {
eprintln!(
@@ -1588,7 +2016,7 @@ pub async fn cli_agent_ui(
images: Vec<String>,
overrides: ProviderOverrides,
flags: SessionFlags,
- resume: Option<ResumeTarget>,
+ resume: Option<ResumeRequest>,
) -> Result<(), String> {
let project_root = resolve_project_root(project);
// A non-interactive invocation with nothing configured has no terminal to
@@ -1608,6 +2036,7 @@ pub async fn cli_agent_ui(
require_model: false,
..flags
},
+ resume.as_ref(),
)?;
// TUI threads persist under the project's .jan/agent dir, separate from the
// desktop store, so continuing here never mutates desktop threads.
@@ -2090,7 +2519,8 @@ mod tests {
];
let id = cli_save_thread(base, None, "m", &history, None).unwrap();
- let resumed = load_resume_history(base, &ResumeTarget::Latest).unwrap();
+ let resumed =
+ load_resume_history(base, &ResumeRequest::resume(ResumeTarget::Latest)).unwrap();
assert_eq!(resumed.thread_id, id);
assert_eq!(resumed.history, history);
@@ -2101,9 +2531,12 @@ mod tests {
assert_eq!(same, id);
assert_eq!(list_threads_in(base).unwrap().len(), 1);
assert_eq!(
- load_resume_history(base, &ResumeTarget::Id(id[..8].to_string()))
- .unwrap()
- .history,
+ load_resume_history(
+ base,
+ &ResumeRequest::resume(ResumeTarget::Id(id[..8].to_string())),
+ )
+ .unwrap()
+ .history,
extended
);
}
@@ -2128,7 +2561,8 @@ mod tests {
];
let id = cli_save_thread(base, None, "m", &history, None).unwrap();
- let resumed = load_resume_history(base, &ResumeTarget::Latest).unwrap();
+ let resumed =
+ load_resume_history(base, &ResumeRequest::resume(ResumeTarget::Latest)).unwrap();
assert_eq!(resumed.thread_id, id);
assert_eq!(
resumed.history, history,
@@ -2347,6 +2781,7 @@ mod tests {
None,
ProviderOverrides::default(),
SessionFlags::default(),
+ None,
)
.expect("TUI session prep must not fail with nothing configured");
assert_eq!(session.model, "");
@@ -2395,6 +2830,7 @@ mod tests {
None,
ProviderOverrides::default(),
SessionFlags::default(),
+ None,
)
.expect("session prep");
std::env::remove_var("JAN_DATA_FOLDER");
@@ -2435,9 +2871,496 @@ mod tests {
None,
ProviderOverrides::default(),
SessionFlags::default(),
+ None,
)
.expect("session prep");
assert_eq!(session.model, "tokamak-1-preview");
});
}
+
+ // ── fork ───────────────────────────────────────────────────────────────
+
+ /// Three user turns, each with a tool call and its result, plus the journal
+ /// the TUI would have written for them.
+ fn seed_forkable(base: &std::path::Path) -> String {
+ let mut history = Vec::new();
+ for n in 0..3 {
+ history.push(serde_json::json!({ "role": "user", "content": format!("turn {n}") }));
+ history.push(serde_json::json!({
+ "role": "assistant", "content": "", "tool_calls": [call(&format!("c{n}"), "write")]
+ }));
+ history.push(serde_json::json!({
+ "role": "tool", "tool_call_id": format!("c{n}"), "content": "ok"
+ }));
+ history
+ .push(serde_json::json!({ "role": "assistant", "content": format!("done {n}") }));
+ }
+ let id = cli_save_thread(base, None, "m", &history, None).unwrap();
+ let entries: Vec<journal::DisplayEntry> = (0..3)
+ .flat_map(|n| {
+ vec![
+ journal::DisplayEntry::User {
+ text: format!("turn {n}"),
+ images: Vec::new(),
+ },
+ journal::DisplayEntry::ToolCall {
+ id: format!("c{n}"),
+ name: "write".into(),
+ args: serde_json::json!({ "path": "a.txt" }),
+ },
+ journal::DisplayEntry::ToolResult {
+ id: format!("c{n}"),
+ content: "ok".into(),
+ is_error: false,
+ diff: None,
+ },
+ journal::DisplayEntry::Assistant {
+ text: format!("done {n}"),
+ reasoning: Vec::new(),
+ reasoning_ms: None,
+ },
+ ]
+ })
+ .collect();
+ journal::write_journal(&journal::journal_path(base, &id), &entries).unwrap();
+ id
+ }
+
+ #[test]
+ fn fork_carries_the_prefix_of_both_files_and_leaves_the_source_alone() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+ let before_messages = std::fs::read(get_messages_path(base, &source)).unwrap();
+ let before_journal = std::fs::read(journal::journal_path(base, &source)).unwrap();
+
+ let forked = fork_thread(base, &source, Some(2)).unwrap();
+ assert_ne!(forked, source);
+
+ // Two user turns, each still holding its call/result pair.
+ let history = load_resume_history(
+ base,
+ &ResumeRequest::resume(ResumeTarget::Id(forked.clone())),
+ )
+ .unwrap()
+ .history;
+ assert_eq!(user_turn_count(&history), 2);
+ assert_eq!(history.len(), 8);
+ assert!(history
+ .iter()
+ .all(|m| !thread_message_text(m).contains("turn 2")));
+ assert_eq!(
+ history
+ .iter()
+ .filter(|m| m.get("role").and_then(|v| v.as_str()) == Some("tool"))
+ .count(),
+ 2,
+ "every carried call keeps its result"
+ );
+
+ let journal = journal::read_journal(&journal::journal_path(base, &forked));
+ assert_eq!(
+ journal.len(),
+ 8,
+ "tool rows were carried, not just the wire history"
+ );
+ assert!(
+ matches!(journal.last(), Some(journal::DisplayEntry::Assistant { text, .. }) if text == "done 1")
+ );
+
+ assert_eq!(
+ std::fs::read(get_messages_path(base, &source)).unwrap(),
+ before_messages,
+ "a fork must not touch the thread it came from"
+ );
+ assert_eq!(
+ std::fs::read(journal::journal_path(base, &source)).unwrap(),
+ before_journal
+ );
+ }
+
+ #[test]
+ fn fork_records_its_immediate_parent() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+
+ let child = fork_thread(base, &source, Some(2)).unwrap();
+ let grandchild = fork_thread(base, &child, Some(1)).unwrap();
+
+ let meta =
+ |id: &str| cli_get_thread_in(base, id).unwrap()["metadata"][FORKED_FROM_KEY].clone();
+ assert_eq!(
+ meta(&child),
+ serde_json::json!({ "thread_id": source, "user_turn": 2 })
+ );
+ assert_eq!(
+ meta(&grandchild),
+ serde_json::json!({ "thread_id": child, "user_turn": 1 }),
+ "forking a fork names the fork, not the root"
+ );
+ }
+
+ #[test]
+ fn a_whole_thread_fork_records_every_turn_and_keeps_them() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+
+ let forked = fork_thread(base, &source, None).unwrap();
+ let thread = cli_get_thread_in(base, &forked).unwrap();
+ assert_eq!(thread["metadata"][FORKED_FROM_KEY]["user_turn"], 3);
+ assert_eq!(
+ journal::read_journal(&journal::journal_path(base, &forked)).len(),
+ 12
+ );
+ }
+
+ #[test]
+ fn fork_refuses_a_cut_that_would_keep_nothing() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+ assert!(fork_thread(base, &source, Some(0)).is_err());
+ assert!(fork_thread(base, &source, Some(9)).is_err());
+ assert!(fork_thread(base, "nope", None).is_err());
+ assert_eq!(
+ list_threads_in(base).unwrap().len(),
+ 1,
+ "a refused fork leaves no half-built thread behind"
+ );
+ }
+
+ /// A fork drops the checkpoints for turns it does not have: restoring the
+ /// workspace to one of them would put the branch in a state it never saw.
+ #[test]
+ fn fork_drops_checkpoints_past_the_cut() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+ let history = cli_read_messages_lenient(base, &source).unwrap().0;
+ cli_save_thread(
+ base,
+ Some(&source),
+ "m",
+ &rebuild_wire_history(&history),
+ Some(serde_json::json!({
+ "base_snapshot": "aaa",
+ "checkpoints": [
+ { "user_index": 0, "preview": "turn 0", "sha": "s0" },
+ { "user_index": 2, "preview": "turn 2", "sha": "s2" },
+ ],
+ })),
+ )
+ .unwrap();
+
+ let forked = fork_thread(base, &source, Some(2)).unwrap();
+ let meta = cli_get_thread_in(base, &forked).unwrap()["metadata"].clone();
+ assert_eq!(
+ meta["base_snapshot"], "aaa",
+ "the branch shares the base commit"
+ );
+ assert_eq!(meta["checkpoints"].as_array().unwrap().len(), 1);
+ assert_eq!(meta["checkpoints"][0]["sha"], "s0");
+ }
+
+ #[test]
+ fn resume_request_from_flags() {
+ assert_eq!(ResumeRequest::from_flags(None, false, false), None);
+ assert_eq!(
+ ResumeRequest::from_flags(None, false, true),
+ Some(ResumeRequest::fork(ResumeTarget::Latest)),
+ "--fork-session alone branches the most recent session"
+ );
+ assert_eq!(
+ ResumeRequest::from_flags(Some(Some("3f7a".into())), false, true),
+ Some(ResumeRequest::fork(ResumeTarget::Id("3f7a".into())))
+ );
+ assert_eq!(
+ ResumeRequest::from_flags(None, true, false),
+ Some(ResumeRequest::resume(ResumeTarget::Latest))
+ );
+ }
+
+ #[test]
+ fn resolve_resume_forks_into_a_new_id_and_leaves_the_source_resumable() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+
+ let opened = resolve_resume(base, &ResumeRequest::fork(ResumeTarget::Latest)).unwrap();
+ let forked = opened["id"].as_str().unwrap().to_string();
+ assert_ne!(forked, source);
+ assert_eq!(opened["metadata"][FORKED_FROM_KEY]["thread_id"], source);
+ assert_eq!(
+ load_resume_history(
+ base,
+ &ResumeRequest::resume(ResumeTarget::Id(source.clone()))
+ )
+ .unwrap()
+ .thread_id,
+ source,
+ "the source is still there to resume"
+ );
+ }
+
+ #[test]
+ fn thread_forest_nests_forks_and_keeps_orphans_as_roots() {
+ let node = |id: &str, updated: f64, parent: Option<&str>| {
+ let mut t = serde_json::json!({ "id": id, "updated": updated, "metadata": {} });
+ if let Some(p) = parent {
+ t["metadata"][FORKED_FROM_KEY] =
+ serde_json::json!({ "thread_id": p, "user_turn": 1 });
+ }
+ t
+ };
+ let rows = thread_forest(vec![
+ node("root", 1.0, None),
+ node("child-old", 2.0, Some("root")),
+ node("child-new", 3.0, Some("root")),
+ node("grandchild", 4.0, Some("child-new")),
+ node("orphan", 5.0, Some("deleted")),
+ ]);
+ let shape: Vec<(String, usize)> = rows
+ .iter()
+ .map(|n| (n.thread["id"].as_str().unwrap().to_string(), n.depth))
+ .collect();
+ assert_eq!(
+ shape,
+ vec![
+ ("orphan".into(), 0),
+ ("root".into(), 0),
+ ("child-new".into(), 1),
+ ("grandchild".into(), 2),
+ ("child-old".into(), 1),
+ ]
+ );
+ assert!(
+ rows.iter()
+ .find(|n| n.thread["id"] == "child-old")
+ .unwrap()
+ .last
+ );
+ }
+
+ /// A store with no forks is today's flat, most-recent-first list.
+ #[test]
+ fn thread_forest_of_unforked_threads_is_the_flat_list() {
+ let threads = vec![
+ serde_json::json!({ "id": "a", "updated": 1.0 }),
+ serde_json::json!({ "id": "b", "updated": 2.0 }),
+ ];
+ let rows = thread_forest(threads);
+ assert!(rows.iter().all(|n| n.depth == 0));
+ assert_eq!(rows[0].thread["id"], "b");
+ }
+
+ /// A fork cycle is reachable from no root; listing it flat beats dropping
+ /// the sessions from `/tree` entirely.
+ #[test]
+ fn thread_forest_survives_a_cycle() {
+ let rows = thread_forest(vec![
+ serde_json::json!({ "id": "a", "updated": 1.0, "metadata": { FORKED_FROM_KEY: { "thread_id": "b" } } }),
+ serde_json::json!({ "id": "b", "updated": 2.0, "metadata": { FORKED_FROM_KEY: { "thread_id": "a" } } }),
+ ]);
+ assert_eq!(rows.len(), 2);
+ }
+
+ // ── worktree ───────────────────────────────────────────────────────────
+
+ #[test]
+ fn a_fork_never_inherits_the_parent_checkout() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let source = seed_forkable(base);
+ let history = cli_read_messages_lenient(base, &source).unwrap().0;
+ cli_save_thread(
+ base,
+ Some(&source),
+ "m",
+ &rebuild_wire_history(&history),
+ Some(serde_json::json!({
+ "base_snapshot": "aaa",
+ worktree::WORKTREE_KEY: {
+ "path": "/home/u/.jan/worktrees/jan-abc/deadbeef",
+ "branch": "jan/agent/deadbeef",
+ },
+ })),
+ )
+ .unwrap();
+
+ let forked = fork_thread(base, &source, Some(2)).unwrap();
+ let meta = cli_get_thread_in(base, &forked).unwrap()["metadata"].clone();
+ assert_eq!(
+ worktree::from_metadata(Some(&meta)),
+ None,
+ "two conversations must not edit one checkout"
+ );
+ assert_eq!(
+ meta["base_snapshot"], "aaa",
+ "the rest of the bookkeeping is kept"
+ );
+ // The source still names its own.
+ let source_meta = cli_get_thread_in(base, &source).unwrap()["metadata"].clone();
+ assert!(worktree::from_metadata(Some(&source_meta)).is_some());
+ }
+
+ /// A fork branches from where the source conversation left off, so the
+ /// files match the transcript it inherited.
+ #[test]
+ fn latest_snapshot_prefers_the_newest_checkpoint() {
+ let thread = serde_json::json!({ "metadata": {
+ "base_snapshot": "base",
+ "checkpoints": [
+ { "user_index": 0, "preview": "one", "sha": "s0" },
+ { "user_index": 1, "preview": "two", "sha": "s1" },
+ ],
+ }});
+ assert_eq!(latest_snapshot(Some(&thread)).as_deref(), Some("s1"));
+
+ // No checkpoints yet: the base snapshot is still better than HEAD.
+ let fresh = serde_json::json!({ "metadata": { "base_snapshot": "base" } });
+ assert_eq!(latest_snapshot(Some(&fresh)).as_deref(), Some("base"));
+ // Nothing recorded at all leaves the choice to the caller (HEAD).
+ assert_eq!(latest_snapshot(None), None);
+ assert_eq!(
+ latest_snapshot(Some(&serde_json::json!({ "metadata": {} }))),
+ None
+ );
+ }
+
+ /// Off by default, and off costs nothing: no git call, no directory.
+ #[test]
+ fn no_worktree_is_resolved_when_nothing_asks_for_one() {
+ let dir = tempfile::tempdir().unwrap();
+ let (workspace, note) = resolve_workspace(dir.path(), None, None);
+ assert_eq!(workspace, None);
+ assert_eq!(note, None);
+ }
+
+ /// Asking for a worktree outside a repository is not fatal: the session runs
+ /// in the project directory and is told why.
+ #[test]
+ fn a_worktree_outside_a_repository_falls_back_with_a_reason() {
+ let dir = tempfile::tempdir().unwrap();
+ let (workspace, note) = resolve_workspace(dir.path(), Some(true), None);
+ assert_eq!(workspace, None);
+ assert!(
+ note.is_some_and(|n| n.contains("not a git repository")),
+ "the fallback has to say why"
+ );
+ }
+
+ /// The regression behind a real failure: a headless run recorded no
+ /// checkout, so the next `--resume` branched a fresh worktree and the model
+ /// read a pristine tree, losing everything the run it continued had done.
+ #[test]
+ fn a_saved_thread_names_the_checkout_the_run_worked_in() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = dir.path();
+ let workspace = worktree::Worktree {
+ path: std::path::PathBuf::from("/home/u/.jan/worktrees/p-abc/deadbeef"),
+ branch: "jan/agent/deadbeef".to_string(),
+ };
+ let history = vec![serde_json::json!({ "role": "user", "content": "do it" })];
+
+ let meta = worktree_metadata(base, None, Some(&workspace));
+ let id = cli_save_thread(base, None, "m", &history, meta).unwrap();
+ let saved = cli_get_thread_in(base, &id).unwrap();
+ assert_eq!(
+ worktree::from_metadata(saved.get("metadata")),
+ Some(workspace.clone()),
+ "a resume has to be able to find the checkout again"
+ );
+
+ // A second turn merges into what is already there rather than replacing
+ // it, so the snapshot bookkeeping beside it survives.
+ cli_save_thread(
+ base,
+ Some(&id),
+ "m",
+ &history,
+ Some(serde_json::json!({
+ "base_snapshot": "aaa",
+ worktree::WORKTREE_KEY: worktree::to_metadata(&workspace),
+ })),
+ )
+ .unwrap();
+ let meta = worktree_metadata(base, Some(&id), Some(&workspace)).expect("some");
+ assert_eq!(meta["base_snapshot"], "aaa");
+ assert_eq!(
+ worktree::from_metadata(Some(&meta)),
+ Some(workspace),
+ "and the pointer is still the one this run used"
+ );
+
+ // No worktree: `None` keeps `cli_save_thread`'s preserve-existing path.
+ assert_eq!(worktree_metadata(base, Some(&id), None), None);
+ }
+
+ /// A headless run takes no snapshots, so without capturing the source's
+ /// checkout a fork opens on a pristine `HEAD` while the transcript it
+ /// inherited describes work that is not in it. Caught against a live model:
+ /// the fork's first `wc -l` disagreed with the answer it had just read.
+ #[test]
+ fn a_fork_base_captures_the_source_checkout_when_there_is_no_snapshot() {
+ fn git(args: &[&str]) -> Option<String> {
+ let out = std::process::Command::new("git").args(args).output().ok()?;
+ out.status
+ .success()
+ .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
+ }
+
+ let dir = tempfile::tempdir().unwrap();
+ let repo = dir.path().join("repo");
+ std::fs::create_dir_all(&repo).unwrap();
+ let r = repo.to_string_lossy().to_string();
+ // Skip on a box without git rather than failing the suite.
+ if git(&["-C", &r, "init", "-q"]).is_none() {
+ return;
+ }
+ git(&["-C", &r, "config", "user.email", "[email protected]"]);
+ git(&["-C", &r, "config", "user.name", "t"]);
+ std::fs::write(repo.join("notes.txt"), "one\n").unwrap();
+ git(&["-C", &r, "add", "-A"]);
+ git(&["-C", &r, "commit", "-q", "-m", "init", "--no-gpg-sign"]).expect("commit");
+
+ // A session worked in its own checkout: one tracked edit, one new file.
+ let wt = dir.path().join("wt");
+ let head = crate::core::agent::git::head_sha(&repo).expect("HEAD");
+ crate::core::agent::git::worktree_add(&repo, &wt, "jan/agent/testfb", &head).unwrap();
+ std::fs::write(wt.join("notes.txt"), "one\ntwo\n").unwrap();
+ std::fs::write(wt.join("added.txt"), "new\n").unwrap();
+
+ let source = serde_json::json!({
+ "id": "src-thread",
+ "metadata": { worktree::WORKTREE_KEY: {
+ "path": wt.to_string_lossy(), "branch": "jan/agent/testfb",
+ }},
+ });
+ let base = fork_base(Some(&source)).expect("the source checkout is captured");
+ assert_ne!(
+ base, head,
+ "a fork must not start at a HEAD the work predates"
+ );
+
+ let show = |path: &str| git(&["-C", &r, "show", &format!("{base}:{path}")]);
+ assert_eq!(
+ show("notes.txt").as_deref(),
+ Some("one\ntwo"),
+ "the branch starts from the work the conversation did"
+ );
+ assert_eq!(
+ show("added.txt").as_deref(),
+ Some("new"),
+ "untracked files the agent created are carried too"
+ );
+
+ // A recorded checkout the user deleted leaves the choice to HEAD.
+ std::fs::remove_dir_all(&wt).unwrap();
+ assert_eq!(fork_base(Some(&source)), None);
+ // A source that recorded a snapshot uses it, no capture needed.
+ let snapped = serde_json::json!({ "id": "s", "metadata": { "base_snapshot": "cafe" } });
+ assert_eq!(fork_base(Some(&snapped)).as_deref(), Some("cafe"));
+ }
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 0f3bec203..4fa84b940 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -47,7 +47,10 @@ use super::agent_status::AgentStatusReporter;
use super::brand;
use super::journal::{self, DisplayEntry, ReasoningSeg};
use super::mcp::McpServerEntry;
-use super::{sort_threads_recent, AgentSession, ResumeTarget, SessionLimits};
+use super::worktree::Worktree;
+use super::{
+ is_user_turn, sort_threads_recent, AgentSession, ResumeRequest, ResumeTarget, SessionLimits,
+};
use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};
use crate::core::agent::git;
use crate::core::agent::r#loop::{
@@ -415,6 +418,12 @@ enum PickerKind {
ToggleMcp,
/// Double-Esc rewind: pick a past user message to roll back to.
RewindMessage,
+ /// `/fork`: pick the past user message to branch before. Same list as
+ /// `RewindMessage`; the cut is written to a new thread instead of this one.
+ ForkMessage,
+ /// `/tree`: the fork forest of this project's saved threads. Enter resumes
+ /// the selected node.
+ ThreadTree,
/// Second step of a rewind: restore conversation only, or + workspace.
RewindScope,
/// Read-only view of `~/.jan/config.toml` providers (`/config`). Enter closes.
@@ -464,6 +473,8 @@ impl Picker {
PickerKind::LoginProvider => " sign in ",
PickerKind::ToggleMcp => " mcp servers ",
PickerKind::RewindMessage => " rewind to message ",
+ PickerKind::ForkMessage => " fork before message ",
+ PickerKind::ThreadTree => " thread tree ",
PickerKind::RewindScope => " restore ",
PickerKind::ViewConfig => " provider config ",
PickerKind::AgentSettings => " agent settings ",
@@ -485,6 +496,8 @@ impl Picker {
" ↑/↓ select Enter open Space toggle a add e edit d delete Esc close"
}
PickerKind::RewindMessage => " ↑/↓ select Enter choose Esc cancel",
+ PickerKind::ForkMessage => " ↑/↓ select Enter fork Esc cancel",
+ PickerKind::ThreadTree => " ↑/↓ select Enter resume Esc cancel",
PickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",
PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",
PickerKind::AgentSettings => " ↑/↓ select Enter edit x unset Esc close",
@@ -1079,6 +1092,11 @@ struct Banner {
branch: Option<String>,
/// How tool calls are approved this session (sandboxed, or `--safe`).
tools: String,
+ /// The dedicated checkout the tools work in, when the session has one. The
+ /// splash names it because with a worktree the edits do *not* land in the
+ /// directory the user started `jan` in, which is the one thing about this
+ /// mode that must never be a surprise.
+ workspace: Option<String>,
/// False when `--task` already seeded the first message, so the splash does
/// not invite one.
awaiting_first_message: bool,
@@ -1139,6 +1157,9 @@ fn banner_lines(banner: &Banner, width: u16) -> Vec<Line<'static>> {
None => banner.project.clone(),
};
field("project", location);
+ if let Some(workspace) = banner.workspace.as_ref() {
+ field("worktree", workspace.clone());
+ }
field("tools", banner.tools.clone());
out.push(Line::raw(""));
@@ -1781,6 +1802,21 @@ struct App {
base_snapshot: Option<String>,
/// Per-turn workspace checkpoints for the active thread, oldest first.
checkpoints: Vec<Checkpoint>,
+ /// The git worktree this session's tools work in, when it has one. Fixed for
+ /// the session: it is baked into the frozen `OrchestrationArgs` the runs
+ /// share, so `/resume` onto a thread that used a different one reports the
+ /// mismatch rather than switching under a run.
+ workspace: Option<Worktree>,
+ /// The worktree pointer the *active thread* saves, which is not always the
+ /// one the session works in: a fork shares the live checkout without
+ /// claiming it (its own branch is minted when it is reopened), and a resumed
+ /// thread that recorded another checkout keeps that pointer rather than
+ /// having this session's written over it.
+ workspace_record: Option<Worktree>,
+ /// `metadata.forked_from` of the active thread, carried so a later save does
+ /// not drop the parent pointer `fork_thread` wrote (`thread_metadata` owns
+ /// the whole metadata object, not a merge into it).
+ forked_from: Option<serde_json::Value>,
/// Pending git snapshots, run off the render loop (see `SnapshotJob`).
snap_queue: std::collections::VecDeque<SnapshotJob>,
/// Whether a base snapshot has been requested for the active thread (queued,
@@ -2439,6 +2475,9 @@ impl App {
bg_shells: Vec::new(),
base_snapshot: None,
checkpoints: Vec::new(),
+ workspace: None,
+ workspace_record: None,
+ forked_from: None,
snap_queue: std::collections::VecDeque::new(),
base_requested: false,
last_esc: None,
@@ -2595,6 +2634,14 @@ impl App {
self.last_kind = next;
}
+ /// Put the session in a checkout and let the active thread claim it. The two
+ /// fields are separate only where a thread must not claim what it works in
+ /// (a fork, a resume from elsewhere); everywhere else they move together.
+ fn set_workspace(&mut self, workspace: Option<Worktree>) {
+ self.workspace_record = workspace.clone();
+ self.workspace = workspace;
+ }
+
/// Drop the current conversation and all transient turn state, detaching from
/// the saved thread so the next message starts a fresh one. Backs `/clear` and
/// `/new`; the model/MCP setup and picker state are untouched.
@@ -2607,6 +2654,10 @@ impl App {
// Detach snapshots; the next submit arms a fresh base + thread id.
self.base_snapshot = None;
self.checkpoints.clear();
+ // A fresh session is a root, whatever the one it replaced was, and it
+ // owns the checkout this session is working in.
+ self.forked_from = None;
+ self.workspace_record = self.workspace.clone();
self.snap_queue.clear();
self.base_requested = false;
self.last_esc = None;
@@ -2702,6 +2753,10 @@ impl App {
project: tilde_path(&self.project_root),
branch: self.git_branch.clone(),
tools: tools.to_string(),
+ workspace: self
+ .workspace
+ .as_ref()
+ .map(|w| format!("{} ⎇ {}", tilde_path(&w.path), w.branch)),
awaiting_first_message,
};
self.gap(Kind::Meta);
@@ -4431,11 +4486,25 @@ impl App {
// Persist metadata when snapshots, a goal, or plan mode are present; each
// must survive restart/resume even in a non-git project (no snapshots).
let planning = self.run_mode == crate::core::agent::plan::RunMode::Plan;
- if self.base_snapshot.is_none() && self.goal.is_none() && !planning && self.todos.is_empty()
+ if self.base_snapshot.is_none()
+ && self.goal.is_none()
+ && !planning
+ && self.todos.is_empty()
+ && self.forked_from.is_none()
+ && self.workspace_record.is_none()
{
return None;
}
let mut meta = serde_json::Map::new();
+ if let Some(workspace) = self.workspace_record.as_ref() {
+ meta.insert(
+ super::worktree::WORKTREE_KEY.to_string(),
+ super::worktree::to_metadata(workspace),
+ );
+ }
+ if let Some(parent) = self.forked_from.as_ref() {
+ meta.insert(super::FORKED_FROM_KEY.to_string(), parent.clone());
+ }
if let Some(base) = self.base_snapshot.as_ref() {
meta.insert("base_snapshot".to_string(), serde_json::json!(base));
meta.insert(
@@ -8288,7 +8357,7 @@ pub async fn run(
project_root: PathBuf,
initial_task: Option<String>,
initial_images: Vec<String>,
- resume: Option<ResumeTarget>,
+ resume: Option<ResumeRequest>,
) -> Result<(), String> {
let AgentSession {
mut args,
@@ -8301,6 +8370,8 @@ pub async fn run(
send_reasoning,
mcp_servers,
mcp_task,
+ workspace,
+ workspace_note,
} = session;
let ask_requests = crate::core::agent::interaction::new_registry();
args.ask_requests = Some(ask_requests.clone());
@@ -8347,8 +8418,14 @@ pub async fn run(
let mut terminal = Terminal::new(backend).map_err(|e| e.to_string())?;
// 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);
+ // non-repo runs exactly as before with conversation-only rewind. With a
+ // worktree the snapshots follow the tools into it, so a rewind restores the
+ // checkout the edits actually landed in.
+ let repo_root = git::repo_root(
+ workspace
+ .as_ref()
+ .map_or(project_root.as_path(), |w| w.path.as_path()),
+ );
let mut app = App::new(
model,
limits,
@@ -8357,6 +8434,7 @@ pub async fn run(
project_root,
repo_root,
);
+ app.set_workspace(workspace);
app.smol_model = smol_model;
app.stream_reasoning = stream_reasoning;
app.send_reasoning = send_reasoning;
@@ -8382,6 +8460,9 @@ pub async fn run(
(false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)".to_string(),
};
app.push_session_banner(!seeded);
+ if let Some(note) = workspace_note {
+ app.note(&note);
+ }
if app.model.is_empty() {
app.note("not signed in - run /login to choose a provider");
} else if let Some(warning) = super::tokamak::expiry_warning() {
@@ -8411,8 +8492,15 @@ pub async fn run(
}
// A failed resume is not fatal: the note explains why and the blank session
// the user already has stays usable.
- if let Some(target) = &resume {
- apply_resume(&mut app, target).await;
+ if let Some(request) = &resume {
+ apply_resume(&mut app, request).await;
+ // `resolve_workspace` resolved the checkout for *this* thread, so it owns
+ // it even when it had none recorded before (`--worktree` on a thread that
+ // ran in the project directory).
+ app.workspace_record = app
+ .workspace_record
+ .take()
+ .or_else(|| app.workspace.clone());
if app.thread_id.is_none() {
app.note("starting a new session");
}
@@ -10238,7 +10326,9 @@ async fn handle_key(
let value = picker.items[picker.selected].value.clone();
app.picker = None;
match kind {
- PickerKind::ResumeThread => resume_thread(app, &value).await,
+ PickerKind::ResumeThread | PickerKind::ThreadTree => {
+ resume_thread(app, &value).await
+ }
PickerKind::LoginProvider => {
if crate::core::cli::auth::account::AccountProvider::from_credential_provider(&value)
.is_some()
@@ -10256,6 +10346,11 @@ async fn handle_key(
open_rewind_scope(app, idx);
}
}
+ PickerKind::ForkMessage => {
+ if let Ok(idx) = value.parse::<usize>() {
+ fork_at(app, idx).await;
+ }
+ }
PickerKind::RewindScope => {
if let Some(idx) = app.rewind_target.take() {
rewind_to(app, idx, value == "workspace");
@@ -10888,6 +10983,24 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
description: "Resume a thread (bare: pick interactively)",
alias_of: None,
},
+ SlashCommand {
+ name: "/fork",
+ hint: "",
+ description: "Branch this session at a past message into a new thread, keeping this one",
+ alias_of: None,
+ },
+ SlashCommand {
+ name: "/worktree",
+ hint: "",
+ description: "Show the dedicated checkout this session works in, and what changed there",
+ alias_of: None,
+ },
+ SlashCommand {
+ name: "/tree",
+ hint: "",
+ description: "Show saved threads as a fork tree (bare /threads is the flat list)",
+ alias_of: None,
+ },
SlashCommand {
name: "/model",
hint: "[id]",
@@ -11162,6 +11275,9 @@ async fn run_command(
}
Err(e) => app.note(&format!("failed to list threads: {e}")),
},
+ "fork" => open_fork_picker(app),
+ "worktree" => worktree_command(app),
+ "tree" => open_tree_picker(app),
"resume" => {
if arg.is_empty() {
open_thread_picker(app);
@@ -14586,8 +14702,184 @@ fn restore_todos(app: &mut App, metadata: Option<&serde_json::Value>) {
}
}
+/// Say so when a loaded thread last worked in a different checkout than this
+/// session does. The session's worktree is baked into the frozen
+/// `OrchestrationArgs` its runs share, so this cannot switch to the thread's --
+/// and silently continuing in the wrong tree would have the model reading files
+/// that do not match the conversation it just loaded.
+fn note_workspace_mismatch(app: &mut App, thread: &serde_json::Value) {
+ let Some(recorded) = super::worktree::from_metadata(thread.get("metadata")) else {
+ return;
+ };
+ let here = match app.workspace.as_ref() {
+ Some(live) if live.path == recorded.path => return,
+ Some(live) => tilde_path(&live.path),
+ None => tilde_path(&app.project_root),
+ };
+ app.note(&format!(
+ "this thread last worked in {}; this session stays in {here}",
+ tilde_path(&recorded.path)
+ ));
+}
+
+/// `/worktree`: what this session is working in, and what has changed there.
+///
+/// Read-only on purpose. Getting the work out is the user's own git: this
+/// session must never write to the branch they left behind.
+fn worktree_command(app: &mut App) {
+ let Some(workspace) = app.workspace.clone() else {
+ app.note(
+ "working in the project directory; start with --worktree for a dedicated checkout",
+ );
+ return;
+ };
+ app.note("worktree:");
+ app.system_detail_text(&format!("path {}", tilde_path(&workspace.path)));
+ app.system_detail_text(&format!("branch {}", workspace.branch));
+ let changed = git::changed_paths(&workspace.path);
+ if changed.is_empty() {
+ app.system_detail_text("changes nothing yet");
+ return;
+ }
+ app.system_detail_text(&format!("changes {} file(s)", changed.len()));
+ for path in changed.iter().take(WORKTREE_CHANGE_ROWS) {
+ app.system_detail_text(&format!(" {path}"));
+ }
+ if changed.len() > WORKTREE_CHANGE_ROWS {
+ app.system_detail_text(&format!(
+ " ... and {} more",
+ changed.len() - WORKTREE_CHANGE_ROWS
+ ));
+ }
+ app.system_detail_text(&format!(
+ "review with: git -C {} diff",
+ workspace.path.display()
+ ));
+}
+
+/// Changed paths `/worktree` lists before eliding; the rest are a `git diff`
+/// away and the point of the row is the shape of the change, not the manifest.
+const WORKTREE_CHANGE_ROWS: usize = 20;
+
+/// Branch the session before its `target`-th user message into a new thread and
+/// switch to it, leaving the source whole on disk. The cut turn lands in the
+/// input, as a rewind's does, so the branch opens ready to re-ask it.
+async fn fork_at(app: &mut App, target: usize) {
+ // The fork is cut from what is on disk, so this turn's history and journal
+ // have to be there first; the journal writer is asynchronous.
+ app.persist();
+ app.join_journal();
+ let Some(source) = app.thread_id.clone() else {
+ return app.note("nothing to fork: this session has not been saved yet");
+ };
+ let fill = super::user_turn_index(&app.history, target)
+ .and_then(|i| app.history.get(i))
+ .and_then(|m| m.get("content"))
+ .map(|c| user_content_parts(c).0)
+ .unwrap_or_default();
+
+ let forked = super::fork_thread(&app.agent_dir, &source, Some(target))
+ .and_then(|id| super::cli_get_thread_in(&app.agent_dir, &id));
+ let thread = match forked {
+ Ok(thread) => thread,
+ Err(e) => return app.note(&format!("fork failed: {e}")),
+ };
+ let id: String = thread
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .chars()
+ .take(8)
+ .collect();
+ load_thread(app, &thread, "forked").await;
+ app.input_clear();
+ app.input = fill;
+ app.cursor = app.input.len();
+ app.note(&format!(
+ "forked before message #{} into {id}; the original is still in /resume",
+ target + 1
+ ));
+ // The checkout cannot change under a live session, so the branch shares this
+ // one for now. Its thread records no worktree, so opening it later with
+ // worktrees on gets it one of its own.
+ if let Some(workspace) = app.workspace.as_ref() {
+ let path = tilde_path(&workspace.path);
+ app.note(&format!(
+ "both branches share {path} until you reopen this one with --worktree"
+ ));
+ }
+}
+
+/// Indent for a `/tree` row: the branch glyph at its own depth, plain spaces for
+/// the levels above it.
+fn tree_prefix(depth: usize, last: bool) -> String {
+ if depth == 0 {
+ return String::new();
+ }
+ let arm = if last { "└─ " } else { "├─ " };
+ format!("{}{arm}", " ".repeat(depth - 1))
+}
+
+/// Open `/tree`: this project's saved threads arranged by the forks taken from
+/// them. Enter resumes the selected node; a store with no forks is the flat list
+/// `/resume` shows.
+fn open_tree_picker(app: &mut App) {
+ let threads = match super::list_threads_in(&app.agent_dir) {
+ Ok(threads) => threads,
+ Err(e) => return app.note(&format!("failed to list threads: {e}")),
+ };
+ let base = app.agent_dir.clone();
+ let current = app.thread_id.clone();
+ let items: Vec<PickerItem> = super::thread_forest(threads)
+ .into_iter()
+ .filter_map(|node| {
+ let id = node.thread.get("id").and_then(|v| v.as_str())?.to_string();
+ let name = thread_display_name(
+ &base,
+ &id,
+ node.thread.get("title").and_then(|v| v.as_str()),
+ );
+ let here = if current.as_deref() == Some(id.as_str()) {
+ " (current)"
+ } else {
+ ""
+ };
+ Some(PickerItem {
+ label: format!("{}{name}{here}", tree_prefix(node.depth, node.last)),
+ hint: Some(id.chars().take(8).collect()),
+ value: id,
+ checkbox: None,
+ })
+ })
+ .collect();
+ if items.is_empty() {
+ return app.note("no saved threads found");
+ }
+ let selected = items
+ .iter()
+ .position(|i| current.as_deref() == Some(i.value.as_str()))
+ .unwrap_or(0);
+ app.picker = Some(Picker {
+ kind: PickerKind::ThreadTree,
+ items,
+ selected,
+ armed_delete: None,
+ });
+}
+
/// Open the double-Esc rewind picker listing the conversation's user messages.
fn open_rewind_picker(app: &mut App) {
+ open_turn_picker(app, PickerKind::RewindMessage, "nothing to rewind to");
+}
+
+/// Open the `/fork` picker: the same list of user messages, branching before the
+/// chosen one instead of truncating this thread at it.
+fn open_fork_picker(app: &mut App) {
+ open_turn_picker(app, PickerKind::ForkMessage, "nothing to fork");
+}
+
+/// List the conversation's user messages for a picker that acts on a past turn.
+fn open_turn_picker(app: &mut App, kind: PickerKind, empty: &str) {
let mut items = Vec::new();
let mut ui = 0usize;
for m in &app.history {
@@ -14606,11 +14898,11 @@ fn open_rewind_picker(app: &mut App) {
}
}
if items.is_empty() {
- return app.note("nothing to rewind to");
+ return app.note(empty);
}
let selected = items.len() - 1;
app.picker = Some(Picker {
- kind: PickerKind::RewindMessage,
+ kind,
items,
selected,
armed_delete: None,
@@ -14647,18 +14939,7 @@ fn open_rewind_scope(app: &mut App, user_index: usize) {
/// dropping it and everything after. When `restore_workspace`, also hard-reset
/// the worktree to the checkpoint that preceded that message (or the base commit).
fn rewind_to(app: &mut App, target: usize, restore_workspace: bool) {
- let mut ui = 0usize;
- let mut cut = None;
- for (i, m) in app.history.iter().enumerate() {
- if is_user_turn(m) {
- if ui == target {
- cut = Some(i);
- break;
- }
- ui += 1;
- }
- }
- let Some(cut) = cut else {
+ let Some(cut) = super::user_turn_index(&app.history, target) else {
return app.note("rewind target not found");
};
@@ -14868,22 +15149,27 @@ fn rebuild_transcript(app: &mut App) {
async fn resume_thread(app: &mut App, id_arg: &str) {
// Re-brand the fresh view before the saved conversation is replayed.
app.push_session_banner(false);
- apply_resume(app, &ResumeTarget::Id(id_arg.to_string())).await;
+ apply_resume(
+ app,
+ &ResumeRequest::resume(ResumeTarget::Id(id_arg.to_string())),
+ )
+ .await;
}
-/// Resolve a resume target and load it into the app, reporting why not when it
+/// Resolve a resume request and load it into the app, reporting why not when it
/// cannot be resolved. The session is left untouched on failure.
-async fn apply_resume(app: &mut App, target: &ResumeTarget) {
- match super::find_resume_thread(&app.agent_dir, target) {
- Ok(thread) => load_thread(app, &thread).await,
+async fn apply_resume(app: &mut App, request: &ResumeRequest) {
+ match super::resolve_resume(&app.agent_dir, request) {
+ Ok(thread) => load_thread(app, &thread, "resumed").await,
Err(e) => app.note(&e),
}
}
/// Replace the live session with a saved thread's state: history, transcript,
/// snapshots, goal, and model. Only user/assistant text is replayed (tool calls
-/// are not persisted as messages).
-async fn load_thread(app: &mut App, thread: &serde_json::Value) {
+/// are not persisted as messages). `verb` names how the thread was opened, so a
+/// fork does not report itself as a resume.
+async fn load_thread(app: &mut App, thread: &serde_json::Value, verb: &str) {
let full_id = thread
.get("id")
.and_then(|v| v.as_str())
@@ -14916,6 +15202,15 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value) {
restore_goal(app, thread.get("metadata"));
restore_run_mode(app, thread.get("metadata"));
restore_todos(app, thread.get("metadata"));
+ app.forked_from = thread
+ .get("metadata")
+ .and_then(|m| m.get(super::FORKED_FROM_KEY))
+ .cloned();
+ // A loaded thread brings its own worktree pointer, or none: this session
+ // cannot switch checkouts under a frozen run, so writing the live one into a
+ // thread that did not ask for it would hand two conversations one branch.
+ app.workspace_record = super::worktree::from_metadata(thread.get("metadata"));
+ note_workspace_mismatch(app, thread);
// Mirror the reconstructed todos into the shared registry so the model's
// next `todo` mutation operates on the resumed state, not an empty list.
if let Some(args) = app.args.as_ref() {
@@ -14969,7 +15264,7 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value) {
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.unwrap_or("(untitled)");
- app.note(&format!("resumed \"{title}\" ({count} messages)"));
+ app.note(&format!("{verb} \"{title}\" ({count} messages)"));
if skipped > 0 {
app.note(&format!("{skipped} unreadable message(s) were skipped"));
}
@@ -15134,18 +15429,6 @@ fn build_user_message(text: &str, images: &[PendingImage]) -> serde_json::Value
/// Split a user message's `content` into display text and one label per attached
/// image. Handles plain-string content and the `image_url` content-part array;
/// data-URL parts carry no filename, so their label is empty.
-/// True for a `user` message the user actually authored. Hidden reminders ride
-/// in on the `user` role but are not turns: a rewind target, a recall entry or a
-/// checkpoint key built from one would be a row the user never typed, and would
-/// shift every later index out of step with the display journal, which holds no
-/// reminder at all.
-fn is_user_turn(m: &serde_json::Value) -> bool {
- m.get("role").and_then(|v| v.as_str()) == Some("user")
- && !crate::core::agent::reminder::is_reminder_only(
- m.get("content").unwrap_or(&serde_json::Value::Null),
- )
-}
-
/// What the user typed, recovered from the wire copy: our own reminders
/// removed, their escaped markers put back.
fn user_text(wire: &str) -> String {
@@ -18115,29 +18398,30 @@ mod tests {
use super::{
age_closed_todos, alt_scroll_restore, alt_scroll_save_off, answer_without_reasoning,
apply_repaint, apply_resume, apply_stream_event, assistant_is_awaiting_user_answer,
- assistant_runs, autoscroll_selection, await_branch_poll, await_monitor_ping,
- brand, build_user_message, clipboard_path, compact_tokens,
- context_lines, diff_lines, drain_stream_events, estimate_token_count, finish_account_login,
- finish_compaction, finish_context_report, finish_login, finish_plugin_install,
- finish_tokamak_login, finish_update_install, format_tokens, group_detail_lines,
- group_summary, handle_ask_key, handle_ask_mouse, handle_key, handle_mouse, header_spans,
- image_mime, image_mime_of, input_content_lines, is_user_turn, load_first_file_image,
- load_image_file, message_text, note_update, open_config_screen, open_rewind_picker,
- pairs_to_str, parse_command, partial_json_field, provider_label_for_model, rebuild_recall,
- replay_display_log, restore_goal, restore_run_mode, restore_todos, resume_hint, rewind_to,
- route_paste_event, row_width, run_command, running_group_rows, selection_text, spans_width,
- spawn_branch_poll, split_reasoning, starting_call_lines, startup_modes,
- strip_system_xml_tags, subagent_activity, subagent_name_from_run_id, summarize_result,
- sync_output_for, thinking_open, tilde_path, tokens_per_second, tool_activity,
- tool_finished, transcript_top_padding, unescape_partial_json_string, user_content_parts,
- wave_sweep_line, with_wave_glyph, without_think_tags, App, CompactKind, ContextReport,
+ assistant_runs, autoscroll_selection, await_branch_poll, await_monitor_ping, brand,
+ build_user_message, clipboard_path, compact_tokens, context_lines, diff_lines,
+ drain_stream_events, estimate_token_count, finish_account_login, finish_compaction,
+ finish_context_report, finish_login, finish_plugin_install, finish_tokamak_login,
+ finish_update_install, fork_at, format_tokens, group_detail_lines, group_summary,
+ handle_ask_key, handle_ask_mouse, handle_key, handle_mouse, header_spans, image_mime,
+ image_mime_of, input_content_lines, is_user_turn, load_first_file_image, load_image_file,
+ message_text, note_update, open_config_screen, open_fork_picker, open_rewind_picker,
+ open_tree_picker, pairs_to_str, parse_command, partial_json_field,
+ provider_label_for_model, rebuild_recall, replay_display_log, restore_goal,
+ restore_run_mode, restore_todos, resume_hint, rewind_to, route_paste_event, row_width,
+ run_command, running_group_rows, selection_text, spans_width, spawn_branch_poll,
+ split_reasoning, starting_call_lines, startup_modes, strip_system_xml_tags,
+ subagent_activity, subagent_name_from_run_id, summarize_result, sync_output_for,
+ thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,
+ transcript_top_padding, unescape_partial_json_string, user_content_parts, wave_sweep_line,
+ with_wave_glyph, without_think_tags, worktree_command, App, CompactKind, ContextReport,
ContextSegment, ContextView, CurrentRun, McpField, McpPrompt, MonitorSet, Pending,
- PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeTarget, Row, RowKind,
- Selection, SelectionMode, SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE,
- ALT_SCROLL_SAVE_OFF, COPY_NOTICE, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS,
- DIFF_PREVIEW_MAX_ROWS, KEY_BINDINGS, KITTY_KEYS_OFF, KITTY_KEYS_ON, MAX_IMAGE_BYTES,
- MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON, PROVIDERS_SETTINGS_ROW, SLASH_COMMANDS, SPINNER,
- SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,
+ PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeRequest, ResumeTarget, Row,
+ RowKind, Selection, SelectionMode, SnapshotJob, Status, Worktree, AGENT_SETTINGS,
+ ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF, COPY_NOTICE, DIFF_ADD_BG, DIFF_DEL_BG,
+ DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS, KEY_BINDINGS, KITTY_KEYS_OFF, KITTY_KEYS_ON,
+ MAX_IMAGE_BYTES, MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON, PROVIDERS_SETTINGS_ROW,
+ SLASH_COMMANDS, SPINNER, SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,
};
use super::{
agent_detail_lines, agent_picker_items, agents_column, background_shell_picker_items,
@@ -18640,7 +18924,7 @@ mod tests {
app.join_journal();
let mut restored = test_app();
restored.agent_dir = app.agent_dir.clone();
- apply_resume(&mut restored, &ResumeTarget::Latest).await;
+ apply_resume(&mut restored, &ResumeRequest::resume(ResumeTarget::Latest)).await;
assert_eq!(
restored
.history
@@ -27945,7 +28229,7 @@ mod tests {
let mut fresh = test_app();
fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
let resumed: String = fresh
.transcript
.iter()
@@ -28018,7 +28302,7 @@ mod tests {
let mut fresh = test_app();
fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
let resumed: String = fresh
.transcript
.iter()
@@ -28054,7 +28338,7 @@ mod tests {
let mut fresh = test_app();
fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
assert_eq!(
fresh.history, app.history,
@@ -28084,7 +28368,7 @@ mod tests {
let mut fresh = test_app();
fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
let resumed: String = fresh
.transcript
.iter()
@@ -28098,6 +28382,327 @@ mod tests {
assert!(fresh.display_log.is_empty(), "nothing to journal from");
}
+ fn test_worktree(path: &str) -> Worktree {
+ Worktree {
+ path: std::path::PathBuf::from(path),
+ branch: "jan/agent/abc12345".to_string(),
+ }
+ }
+
+ /// The worktree belongs to the thread, not just the session: a resume has to
+ /// find its way back to the checkout the conversation was written against.
+ #[tokio::test]
+ async fn a_session_records_its_worktree_and_a_resume_reads_it_back() {
+ let mut app = test_app();
+ app.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ app.submit_user("do it".into());
+ app.on_done("stop".into(), None);
+ let id = app.thread_id.clone().expect("saved");
+
+ let thread = super::super::cli_get_thread_in(&app.agent_dir, &id).unwrap();
+ assert_eq!(
+ super::super::worktree::from_metadata(thread.get("metadata")),
+ Some(test_worktree("/tmp/wt-a"))
+ );
+ }
+
+ /// The checkout is frozen in the args a session's runs share, so loading a
+ /// thread from a different one must report the mismatch, not pretend.
+ #[tokio::test]
+ async fn resuming_a_thread_from_another_checkout_says_so() {
+ let mut app = test_app();
+ app.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ app.submit_user("do it".into());
+ app.on_done("stop".into(), None);
+
+ let mut elsewhere = test_app();
+ elsewhere.agent_dir = app.agent_dir.clone();
+ elsewhere.set_workspace(Some(test_worktree("/tmp/wt-b")));
+ apply_resume(&mut elsewhere, &ResumeRequest::resume(ResumeTarget::Latest)).await;
+ let notes: String = elsewhere
+ .transcript
+ .iter()
+ .map(row_text)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(
+ notes.contains("last worked in") && notes.contains("wt-a"),
+ "{notes}"
+ );
+
+ // Same checkout: nothing to warn about.
+ let mut same = test_app();
+ same.agent_dir = app.agent_dir.clone();
+ same.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ apply_resume(&mut same, &ResumeRequest::resume(ResumeTarget::Latest)).await;
+ assert!(!same
+ .transcript
+ .iter()
+ .map(row_text)
+ .any(|t| t.contains("last worked in")));
+ }
+
+ /// `/new` keeps the checkout: it belongs to the invocation, not the thread.
+ #[test]
+ fn a_new_session_stays_in_the_same_worktree() {
+ let mut app = test_app();
+ app.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ app.submit_user("do it".into());
+ app.reset_session();
+ assert_eq!(app.workspace, Some(test_worktree("/tmp/wt-a")));
+ }
+
+ #[test]
+ fn worktree_command_without_one_points_at_the_flag() {
+ let mut app = test_app();
+ worktree_command(&mut app);
+ let notes: String = app
+ .transcript
+ .iter()
+ .map(row_text)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(notes.contains("--worktree"), "{notes}");
+ }
+
+ #[test]
+ fn the_banner_names_the_worktree_only_when_there_is_one() {
+ let mut app = test_app();
+ app.push_session_banner(true);
+ let plain = render_rows(&mut app, 100, 40).join("\n");
+ assert!(!plain.contains("worktree"), "{plain}");
+
+ let mut isolated = test_app();
+ isolated.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ isolated.push_session_banner(true);
+ let shown = render_rows(&mut isolated, 100, 40).join("\n");
+ assert!(
+ shown.contains("worktree") && shown.contains("wt-a"),
+ "the splash must say where the edits land: {shown}"
+ );
+ }
+
+ /// The whole point of a fork over a rewind: the branch opens on the prefix,
+ /// with the tool rows the journal carried, and the source is still there.
+ #[tokio::test]
+ async fn fork_branches_the_prefix_and_leaves_the_source_whole() {
+ let mut app = test_app();
+ record_full_turn(&mut app);
+ app.submit_user("and again".to_string());
+ app.apply(StreamEvent::Token {
+ text: "Second answer.".into(),
+ });
+ app.on_done("stop".into(), None);
+ let source = app.thread_id.clone().expect("saved");
+
+ fork_at(&mut app, 1).await;
+ let forked = app.thread_id.clone().expect("landed on the fork");
+ assert_ne!(forked, source);
+
+ let after: String = app
+ .transcript
+ .iter()
+ .map(row_text)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(
+ after.contains("✓ Wrote a.txt") && after.contains("@@ created file @@"),
+ "the journal was carried, not just the wire history: {after}"
+ );
+ assert!(!after.contains("Second answer."), "{after}");
+ assert_eq!(
+ app.input, "and again",
+ "the forked-away message is ready to re-ask"
+ );
+
+ // The source is untouched: both turns still resumable from it.
+ let mut back = test_app();
+ back.agent_dir = app.agent_dir.clone();
+ apply_resume(
+ &mut back,
+ &ResumeRequest::resume(ResumeTarget::Id(source.clone())),
+ )
+ .await;
+ assert_eq!(back.thread_id.as_deref(), Some(source.as_str()));
+ assert!(back
+ .transcript
+ .iter()
+ .map(row_text)
+ .any(|t| t.contains("Second answer.")));
+ }
+
+ /// A fork is a rewind that keeps the original, so the branch must render
+ /// exactly what rewinding the source to the same turn would have rendered.
+ #[tokio::test]
+ async fn a_fork_replays_the_rows_a_rewind_to_the_same_turn_leaves() {
+ let mut forked = test_app();
+ record_full_turn(&mut forked);
+ forked.submit_user("and again".to_string());
+ forked.apply(StreamEvent::Token {
+ text: "Second answer.".into(),
+ });
+ forked.on_done("stop".into(), None);
+
+ let mut rewound = test_app();
+ rewound.agent_dir = forked.agent_dir.clone();
+ apply_resume(&mut rewound, &ResumeRequest::resume(ResumeTarget::Latest)).await;
+ rewind_to(&mut rewound, 1, false);
+
+ fork_at(&mut forked, 1).await;
+
+ // Notes are transient by design and never journaled, so they are the one
+ // thing the two paths are allowed to disagree on.
+ let rows = |app: &App| {
+ app.transcript
+ .iter()
+ .map(row_text)
+ .filter(|t| !t.trim_start().starts_with('\u{2022}'))
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(rows(&forked), rows(&rewound));
+ assert_eq!(forked.history, rewound.history);
+ assert_eq!(forked.display_log, rewound.display_log);
+ }
+
+ /// The parent pointer has to survive the branch's own first save, which
+ /// rewrites the whole metadata object.
+ #[tokio::test]
+ async fn a_fork_keeps_its_parent_pointer_across_later_saves() {
+ let mut app = test_app();
+ record_full_turn(&mut app);
+ app.submit_user("and again".to_string());
+ app.on_done("stop".into(), None);
+ let source = app.thread_id.clone().expect("saved");
+
+ fork_at(&mut app, 1).await;
+ let forked = app.thread_id.clone().expect("landed on the fork");
+ app.submit_user("a different approach".to_string());
+ app.on_done("stop".into(), None);
+
+ let meta = super::super::cli_get_thread_in(&app.agent_dir, &forked).unwrap();
+ assert_eq!(
+ meta["metadata"][super::super::FORKED_FROM_KEY],
+ json!({ "thread_id": source, "user_turn": 1 })
+ );
+ }
+
+ /// A fork borrows the live checkout for the rest of the session but must not
+ /// record it: the branch it opens later is its own, and two conversations on
+ /// one checkout is what a worktree exists to prevent.
+ #[tokio::test]
+ async fn a_fork_never_records_the_checkout_it_borrows() {
+ let mut app = test_app();
+ app.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ record_full_turn(&mut app);
+ app.submit_user("and again".to_string());
+ app.on_done("stop".into(), None);
+
+ fork_at(&mut app, 1).await;
+ let forked = app.thread_id.clone().expect("landed on the fork");
+ app.submit_user("a different approach".to_string());
+ app.on_done("stop".into(), None);
+
+ let thread = super::super::cli_get_thread_in(&app.agent_dir, &forked).unwrap();
+ assert_eq!(
+ super::super::worktree::from_metadata(thread.get("metadata")),
+ None,
+ "the fork claimed its source's checkout"
+ );
+ assert_eq!(
+ app.workspace,
+ Some(test_worktree("/tmp/wt-a")),
+ "the tools keep writing where the frozen run args point"
+ );
+ }
+
+ /// The pointer belongs to the thread: resuming one from elsewhere (or with no
+ /// worktree at all) must not overwrite the checkout it recorded.
+ #[tokio::test]
+ async fn a_resumed_thread_keeps_the_checkout_it_recorded() {
+ let mut app = test_app();
+ app.set_workspace(Some(test_worktree("/tmp/wt-a")));
+ app.submit_user("do it".into());
+ app.on_done("stop".into(), None);
+ let id = app.thread_id.clone().expect("saved");
+
+ for live in [Some(test_worktree("/tmp/wt-b")), None] {
+ let mut other = test_app();
+ other.agent_dir = app.agent_dir.clone();
+ other.set_workspace(live);
+ apply_resume(&mut other, &ResumeRequest::resume(ResumeTarget::Latest)).await;
+ other.submit_user("more".into());
+ other.on_done("stop".into(), None);
+
+ let thread = super::super::cli_get_thread_in(&app.agent_dir, &id).unwrap();
+ assert_eq!(
+ super::super::worktree::from_metadata(thread.get("metadata")),
+ Some(test_worktree("/tmp/wt-a"))
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn tree_nests_a_fork_under_the_thread_it_came_from() {
+ let mut app = test_app();
+ record_full_turn(&mut app);
+ app.submit_user("and again".to_string());
+ app.on_done("stop".into(), None);
+ fork_at(&mut app, 1).await;
+
+ open_tree_picker(&mut app);
+ let picker = app.picker.as_ref().expect("tree");
+ assert_eq!(picker.kind, PickerKind::ThreadTree);
+ assert_eq!(picker.items.len(), 2);
+ assert!(
+ picker.items[1].label.starts_with("└─ "),
+ "the fork is drawn under its parent: {:?}",
+ picker.items[1].label
+ );
+ assert!(picker.items[1].label.contains("(current)"));
+ assert_eq!(picker.selected, 1, "the session in hand is preselected");
+ }
+
+ /// A store with no forks is the flat list `/resume` already shows.
+ #[test]
+ fn tree_of_an_unforked_store_is_flat() {
+ let mut app = test_app();
+ record_full_turn(&mut app);
+ open_tree_picker(&mut app);
+ let picker = app.picker.as_ref().expect("tree");
+ assert_eq!(picker.items.len(), 1);
+ assert!(!picker.items[0].label.starts_with("└─"));
+ }
+
+ #[test]
+ fn fork_picker_lists_the_same_turns_as_the_rewind_picker() {
+ let mut app = test_app();
+ app.thread_id = Some("t1".into());
+ app.submit_user("first".into());
+ app.status = Status::Idle;
+ app.submit_user("second".into());
+
+ open_rewind_picker(&mut app);
+ let rewind: Vec<String> = app
+ .picker
+ .take()
+ .expect("picker")
+ .items
+ .iter()
+ .map(|i| i.value.clone())
+ .collect();
+ open_fork_picker(&mut app);
+ let picker = app.picker.as_ref().expect("picker");
+ assert_eq!(picker.kind, PickerKind::ForkMessage);
+ assert_eq!(
+ picker
+ .items
+ .iter()
+ .map(|i| i.value.clone())
+ .collect::<Vec<_>>(),
+ rewind
+ );
+ }
+
#[tokio::test]
async fn rewind_keeps_the_kept_turns_tool_rows() {
let mut app = test_app();
@@ -28148,7 +28753,7 @@ mod tests {
let mut fresh = test_app();
fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
assert_eq!(fresh.thread_id.as_deref(), Some(id.as_str()));
assert_eq!(fresh.history, history);
@@ -28195,7 +28800,7 @@ mod tests {
super::super::cli_save_thread(&app.agent_dir, None, "m", &history, None).unwrap();
let mut fresh = test_app();
fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
// History keeps the full template (the model needs it on continuation)...
assert_eq!(fresh.history, history);
@@ -28228,7 +28833,7 @@ mod tests {
fresh.agent_dir = app.agent_dir.clone();
// A line typed before the resume belongs to the session being replaced.
fresh.record_submitted("stale");
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ apply_resume(&mut fresh, &ResumeRequest::resume(ResumeTarget::Latest)).await;
assert_eq!(fresh.input_history, vec!["first", "second"]);
assert!(fresh.recall_prev(), "Up recalls instead of scrolling");
@@ -28241,7 +28846,7 @@ mod tests {
#[tokio::test]
async fn apply_resume_notes_when_nothing_to_resume() {
let mut app = test_app();
- apply_resume(&mut app, &ResumeTarget::Latest).await;
+ apply_resume(&mut app, &ResumeRequest::resume(ResumeTarget::Latest)).await;
let joined: String = app
.transcript
.iter()
diff --git a/src-tauri/src/core/cli/worktree.rs b/src-tauri/src/core/cli/worktree.rs
new file mode 100644
index 000000000..991edbb53
--- /dev/null
+++ b/src-tauri/src/core/cli/worktree.rs
@@ -0,0 +1,239 @@
+//! Per-session git worktrees: the agent gets its own checkout of the user's
+//! repository, on its own branch, so a run they do not like costs a
+//! `git branch -D` rather than a revert of their working tree.
+//!
+//! This is isolation of the *files*, and it composes with the snapshots in
+//! [`crate::core::agent::git`] rather than replacing them: checkpoints and
+//! `rewind --workspace` still work, they just act on the worktree, because
+//! `repo_root` resolves to the checkout the session actually runs in.
+//!
+//! Opt-in, most specific source first: `--worktree`/`--no-worktree`, then a
+//! project's `[agent].worktree`, then `worktree` in `~/.jan/config.toml`. Off by
+//! default, because turning it on moves every edit out of the directory the user
+//! is looking at, which must be their decision rather than ours.
+//!
+//! The checkout lives under `~/.jan/worktrees/<repo-slug>/<id>`, outside the
+//! repository. Inside it (`<project>/.jan/agent/worktrees/...`) the agent's own
+//! `find`/`grep`/`bash` would walk into a second copy of the tree whenever a
+//! session ran in the main checkout, and `git clean` would delete it.
+//!
+//! What a session does *not* get is a way back: merging is the user's own `git`.
+//! `/worktree` names the path, the branch and what changed in it; nothing here
+//! writes to the user's branch or working tree.
+
+use std::path::{Path, PathBuf};
+
+use crate::core::agent::git;
+
+/// A checkout a session works in, and the branch it is on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Worktree {
+ pub path: PathBuf,
+ pub branch: String,
+}
+
+/// Key under a thread's `metadata` recording the checkout it worked in, so a
+/// resume reattaches to the same one instead of branching again.
+pub const WORKTREE_KEY: &str = "worktree";
+
+/// Off: the agent edits the user's own checkout, as it always has.
+const DEFAULT_WORKTREE: bool = false;
+
+/// How many ids to try before giving up, in case a directory is already there.
+const ID_ATTEMPTS: usize = 4;
+
+/// Resolve whether this session works in its own worktree, most specific source
+/// first: the per-invocation flag, then the project's `[agent].worktree`, then
+/// the user's global `worktree`, then the default.
+pub fn resolve_enabled(flag: Option<bool>, configured: Option<bool>) -> bool {
+ flag.or(configured)
+ .or_else(crate::core::agent::global_config::worktree_setting)
+ .unwrap_or(DEFAULT_WORKTREE)
+}
+
+/// `~/.jan/worktrees`, the user-wide home for agent checkouts.
+pub fn worktrees_root() -> Result<PathBuf, String> {
+ Ok(crate::core::agent::global_config::global_jan_dir()?.join("worktrees"))
+}
+
+/// FNV-1a, so the slug for a path is the same in every build. `DefaultHasher`
+/// is explicitly not stable across Rust releases, and a session must find its
+/// checkout again after a toolchain upgrade.
+fn path_hash(path: &Path) -> String {
+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
+ for byte in path.to_string_lossy().as_bytes() {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ format!("{hash:016x}")[..8].to_string()
+}
+
+/// Directory name for a repository: its own name plus a hash of its path, so two
+/// checkouts of the same project do not share a worktree directory.
+pub fn repo_slug(repo: &Path) -> String {
+ let name = repo
+ .file_name()
+ .and_then(|n| n.to_str())
+ .filter(|n| !n.is_empty())
+ .unwrap_or("repo");
+ format!("{name}-{}", path_hash(repo))
+}
+
+/// Branch a session's worktree is checked out on. Namespaced under `jan/agent/`
+/// so it is obvious in `git branch` whose it is, and cannot collide with a
+/// branch the user maintains.
+pub fn branch_for(id: &str) -> String {
+ format!("jan/agent/{id}")
+}
+
+/// Read the pointer a thread recorded. Absent from a thread that never ran in a
+/// worktree, which is every thread saved before this existed.
+pub fn from_metadata(metadata: Option<&serde_json::Value>) -> Option<Worktree> {
+ let entry = metadata?.get(WORKTREE_KEY)?;
+ Some(Worktree {
+ path: PathBuf::from(entry.get("path")?.as_str()?),
+ branch: entry.get("branch")?.as_str()?.to_string(),
+ })
+}
+
+/// The pointer to persist in a thread's `metadata`.
+pub fn to_metadata(worktree: &Worktree) -> serde_json::Value {
+ serde_json::json!({
+ "path": worktree.path.to_string_lossy(),
+ "branch": worktree.branch,
+ })
+}
+
+/// Reattach to `recorded` when it is still a checkout of `repo`, else branch a
+/// new one from `base` (any commit-ish; `HEAD` when the caller has nothing
+/// better).
+///
+/// A recorded worktree the user has since deleted is not an error: the session
+/// gets a fresh one. Refusing to start over a directory the user chose to
+/// remove would make `rm -rf` on a worktree break the thread it belonged to.
+pub fn attach_or_create(
+ repo: &Path,
+ recorded: Option<&Worktree>,
+ base: Option<&str>,
+) -> Result<Worktree, String> {
+ if let Some(worktree) = recorded {
+ if worktree.path.is_dir() && git::worktree_registered(repo, &worktree.path) {
+ return Ok(worktree.clone());
+ }
+ }
+ // A registration whose directory is gone still claims its path, and would
+ // make `worktree add` refuse it.
+ git::worktree_prune(repo);
+
+ let base = base
+ .map(str::to_string)
+ .or_else(|| git::head_sha(repo))
+ .ok_or_else(|| {
+ "this repository has no commits yet, so there is nothing to branch a worktree from"
+ .to_string()
+ })?;
+ let root = worktrees_root()?.join(repo_slug(repo));
+ let mut last = String::new();
+ for _ in 0..ID_ATTEMPTS {
+ let id: String = uuid::Uuid::new_v4().to_string().chars().take(8).collect();
+ let path = root.join(&id);
+ if path.exists() {
+ continue;
+ }
+ let branch = branch_for(&id);
+ match git::worktree_add(repo, &path, &branch, &base) {
+ Ok(()) => return Ok(Worktree { path, branch }),
+ Err(e) => last = e,
+ }
+ }
+ Err(if last.is_empty() {
+ "could not find a free worktree directory".to_string()
+ } else {
+ last
+ })
+}
+
+/// Set up the checkout this session works in, or explain why it cannot.
+///
+/// `recorded` is the resumed thread's pointer, `base` the commit a fresh
+/// checkout starts from. The error is for the surface to show: a session that
+/// cannot get a worktree runs in the project directory rather than refusing to
+/// start, because the fallback is exactly the behaviour every session had
+/// before this feature.
+pub fn for_session(
+ project_root: &Path,
+ recorded: Option<&Worktree>,
+ base: Option<&str>,
+) -> Result<Worktree, String> {
+ let repo = git::repo_root(project_root).ok_or_else(|| {
+ "not a git repository, so there is nothing to make a worktree from".to_string()
+ })?;
+ attach_or_create(&repo, recorded, base)
+}
+
+/// One-line description of a worktree for a banner or a status row.
+pub fn summary(worktree: &Worktree) -> String {
+ let changed = git::changed_paths(&worktree.path).len();
+ let files = if changed == 1 { "file" } else { "files" };
+ format!(
+ "{} on {} ({changed} changed {files})",
+ worktree.path.display(),
+ worktree.branch
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_slug_is_stable_and_separates_two_checkouts_of_one_name() {
+ let a = Path::new("/home/u/src/jan");
+ let b = Path::new("/home/u/work/jan");
+ assert_eq!(repo_slug(a), repo_slug(a), "stable across calls");
+ assert!(repo_slug(a).starts_with("jan-"));
+ assert_ne!(
+ repo_slug(a),
+ repo_slug(b),
+ "two checkouts of the same project must not share a directory"
+ );
+ }
+
+ /// The hash is persisted in thread metadata by way of the path, so it is a
+ /// wire value: pin it rather than letting a refactor quietly move every
+ /// existing session's worktree.
+ #[test]
+ fn the_slug_hash_is_pinned() {
+ assert_eq!(repo_slug(Path::new("/home/u/src/jan")), "jan-582afba2");
+ }
+
+ #[test]
+ fn enabled_follows_the_most_specific_source() {
+ assert!(resolve_enabled(Some(true), Some(false)));
+ assert!(!resolve_enabled(Some(false), Some(true)));
+ assert!(resolve_enabled(None, Some(true)));
+ }
+
+ #[test]
+ fn metadata_round_trips() {
+ let worktree = Worktree {
+ path: PathBuf::from("/home/u/.jan/worktrees/jan-abc/3f7a91c2"),
+ branch: "jan/agent/3f7a91c2".to_string(),
+ };
+ let meta = serde_json::json!({ WORKTREE_KEY: to_metadata(&worktree) });
+ assert_eq!(from_metadata(Some(&meta)), Some(worktree));
+ }
+
+ #[test]
+ fn a_thread_with_no_pointer_reads_as_none() {
+ assert_eq!(from_metadata(None), None);
+ assert_eq!(from_metadata(Some(&serde_json::json!({}))), None);
+ // A half-written pointer is not a worktree either.
+ assert_eq!(
+ from_metadata(Some(
+ &serde_json::json!({ WORKTREE_KEY: { "path": "/tmp/x" } })
+ )),
+ None
+ );
+ }
+}