Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(host-core): close the isolated-session gaps from the PR review

renwanga0eb6c2db8487
diff --git a/apps/desktop/src/features/worktree/worktree-actions.ts b/apps/desktop/src/features/worktree/worktree-actions.ts
index 101652235..1a4c579d3 100644
--- a/apps/desktop/src/features/worktree/worktree-actions.ts
+++ b/apps/desktop/src/features/worktree/worktree-actions.ts
@@ -15,6 +15,7 @@ const ERROR_KEYS: Record<string, string> = {
[WorktreeErrorCodes.BUSY]: "worktree.errors.busy",
[WorktreeErrorCodes.CHANGED_SINCE_PREVIEW]: "worktree.errors.changedSincePreview",
[WorktreeErrorCodes.OWNER_BRANCH_CHANGED]: "worktree.errors.ownerBranchChanged",
+ [WorktreeErrorCodes.SESSION_BRANCH_CHANGED]: "worktree.errors.sessionBranchChanged",
[WorktreeErrorCodes.PROJECT_DIRTY]: "worktree.errors.projectDirty",
[WorktreeErrorCodes.MISSING]: "worktree.errors.missing",
[WorktreeErrorCodes.COMMIT_FAILED]: "worktree.errors.commitFailed",
diff --git a/crates/host-core/src/session_worktrees/delegate.rs b/crates/host-core/src/session_worktrees/delegate.rs
index 99dab6f41..d2571f807 100644
--- a/crates/host-core/src/session_worktrees/delegate.rs
+++ b/crates/host-core/src/session_worktrees/delegate.rs
@@ -26,7 +26,7 @@ use super::lifecycle::{
use super::merge::{self, commit_all, commits_ahead, land, merge_in_progress};
use super::probe::BRANCH_NAMESPACE;
use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};
-use super::remove::{drop_admin_entry, remove_worktree};
+use super::remove::{drop_admin_entry, is_real_dir, is_real_dir_chain, remove_worktree};
use super::{repo_lock, WorktreeError};
use crate::db::Database;
use crate::sessions;
@@ -65,7 +65,9 @@ pub fn tool_root(
return Ok(None);
};
let root = row.workspace_root();
- if row.status == WorktreeStatus::Missing || !root.is_dir() {
+ if row.status == WorktreeStatus::Missing
+ || !is_real_dir_chain(Path::new(&row.path), &row.prefix)
+ {
return Err(missing_error());
}
Ok(Some(root))
@@ -99,15 +101,16 @@ async fn session_row(state: &SharedState, session_id: &str) -> Result<WorktreeRo
"the session has no isolated worktree",
)
})?;
- if row.status == WorktreeStatus::Missing || !Path::new(&row.path).is_dir() {
+ if row.status == WorktreeStatus::Missing || !is_real_dir(Path::new(&row.path)) {
return Err(missing_error());
}
Ok(row)
}
-/// How long a subagent's create/merge waits for the session's in-flight tools
-/// before it falls back to holding only the write permit.
-const SESSION_QUIET_WAIT: Duration = Duration::from_secs(5);
+/// How long a merge, sync, or subagent create/merge waits for the session's
+/// in-flight tools before it gives up (or, for a subagent, falls back to
+/// holding only the write permit).
+pub(super) const SESSION_QUIET_WAIT: Duration = Duration::from_secs(5);
/// Keeps the session's own tools away from its worktree while held.
enum SessionHold {
@@ -214,7 +217,7 @@ pub async fn create_delegate_worktree(
if let Some(row) = existing {
let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;
if row.status != WorktreeStatus::Creating {
- if Path::new(&row.path).is_dir() {
+ if is_real_dir(Path::new(&row.path)) {
// A re-attach that failed after `worktree add` left the
// folder back but the row `missing`; the folder decides.
if row.status == WorktreeStatus::Missing {
@@ -356,7 +359,7 @@ pub async fn settle_delegate_worktree(
};
let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;
let worktree = Path::new(&row.path);
- if !worktree.is_dir() {
+ if !is_real_dir(worktree) {
// The folder vanished; its branch may still hold committed work,
// which a resume re-attaches instead of deleting.
if unmerged_commits(git, &row).await? > 0 {
diff --git a/crates/host-core/src/session_worktrees/lifecycle.rs b/crates/host-core/src/session_worktrees/lifecycle.rs
index 54cc474ab..7e46a4b92 100644
--- a/crates/host-core/src/session_worktrees/lifecycle.rs
+++ b/crates/host-core/src/session_worktrees/lifecycle.rs
@@ -19,7 +19,7 @@ use super::include::{copy_included, IncludeReport};
use super::merge::{self, MergeOutcome, MergePreview, SyncOutcome};
use super::probe::{probe, BRANCH_NAMESPACE};
use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};
-use super::remove::remove_worktree;
+use super::remove::{is_real_dir, is_real_dir_chain, remove_worktree};
use super::{fnv1a64, repo_lock, WorktreeError};
use crate::db::Database;
use crate::sessions;
@@ -145,7 +145,7 @@ pub fn tool_root(db: &Database, session_id: &str) -> Result<Option<PathBuf>, Wor
WorktreeStatus::Missing => Err(missing_error()),
_ => {
let root = row.workspace_root();
- if root.is_dir() {
+ if is_real_dir_chain(Path::new(&row.path), &row.prefix) {
Ok(Some(root))
} else {
Err(missing_error())
@@ -497,7 +497,7 @@ async fn merge_target(state: &SharedState, session_id: &str) -> Result<MergeTarg
"the session has no isolated worktree",
)
})?;
- if row.status == WorktreeStatus::Missing || !Path::new(&row.path).is_dir() {
+ if row.status == WorktreeStatus::Missing || !is_real_dir(Path::new(&row.path)) {
return Err(missing_error());
}
let summary = sessions::session_summary(&st.db, session_id)?
@@ -522,6 +522,31 @@ fn ensure_idle(db: &Database, session_id: &str) -> Result<(), WorktreeError> {
Ok(())
}
+/// Hold the session's own tools for the whole of a merge or sync: once no
+/// tool of the session is in flight, every new Write, Edit, or Bash call of
+/// it queues until the returned permit drops, so nothing can land between
+/// the preview check, the checkpoint commit, and the merge. Taken after the
+/// repo lock, the same order as the subagent merge-back.
+async fn hold_session(
+ state: &SharedState,
+ session_id: &str,
+) -> Result<crate::tool_budget::SessionExclusivePermit, WorktreeError> {
+ let budget = state.lock().await.tool_budget.clone();
+ let permit = budget
+ .acquire_session_exclusive(session_id, super::delegate::SESSION_QUIET_WAIT)
+ .await
+ .ok_or_else(|| {
+ WorktreeError::new(
+ "WORKTREE_BUSY",
+ "a tool of the session is still running; wait for it to finish",
+ )
+ })?;
+ // A turn may have started while this waited; its tools now queue, but a
+ // running session is still not merged.
+ ensure_idle(&state.lock().await.db, session_id)?;
+ Ok(permit)
+}
+
pub async fn preview_session(
state: &SharedState,
git: &GitRunner,
@@ -540,6 +565,7 @@ pub async fn merge_session(
let target = merge_target(state, session_id).await?;
ensure_idle(&state.lock().await.db, session_id)?;
let _guard = repo_lock::lock(Path::new(&target.row.common_dir)).await;
+ let _hold = hold_session(state, session_id).await?;
let result = merge::merge(
git,
&target.row,
@@ -615,7 +641,7 @@ pub async fn behind_all(
row.status,
WorktreeStatus::Missing | WorktreeStatus::Creating
)
- || !Path::new(&row.path).is_dir()
+ || !is_real_dir(Path::new(&row.path))
{
continue;
}
@@ -653,6 +679,7 @@ pub async fn sync_session(
let target = merge_target(state, session_id).await?;
ensure_idle(&state.lock().await.db, session_id)?;
let _guard = repo_lock::lock(Path::new(&target.row.common_dir)).await;
+ let _hold = hold_session(state, session_id).await?;
let result =
merge::sync_from_owner(git, &target.row, &merge::commit_message(&target.title)).await;
let status = match &result {
@@ -689,6 +716,9 @@ pub async fn refresh_conflict_status(
}
};
let root = Path::new(&row.path);
+ if !is_real_dir(root) {
+ return false;
+ }
let settled = async {
Ok::<bool, WorktreeError>(
!merge::merge_in_progress(git, root).await?
@@ -782,7 +812,7 @@ pub async fn pending_work(
// still holds commits is still reported before it is deleted.
pending.unmerged_commits += unmerged_commits(git, &row).await?;
let root = Path::new(&row.path);
- if root.is_dir() && !merge::worktree_status(git, root).await?.is_empty() {
+ if is_real_dir(root) && !merge::worktree_status(git, root).await?.is_empty() {
pending.uncommitted_changes = true;
}
}
@@ -862,7 +892,7 @@ pub async fn reconcile(state: SharedState, git: GitRunner) {
continue;
}
let root = Path::new(&row.path);
- if !root.is_dir() {
+ if !is_real_dir(root) {
let st = state.lock().await;
let _ = registry::set_status(&st.db, &row.id, WorktreeStatus::Missing);
continue;
diff --git a/crates/host-core/src/session_worktrees/lifecycle/tests.rs b/crates/host-core/src/session_worktrees/lifecycle/tests.rs
index 7a31a2c1a..708d6855c 100644
--- a/crates/host-core/src/session_worktrees/lifecycle/tests.rs
+++ b/crates/host-core/src/session_worktrees/lifecycle/tests.rs
@@ -3,7 +3,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use super::*;
-use crate::session_worktrees::test_support::{git_cmd, init_repo};
+use crate::session_worktrees::test_support::{git_cmd, init_repo, link_dir};
struct Env {
_dir: tempfile::TempDir,
@@ -683,3 +683,88 @@ async fn failed_merges_and_outside_resolutions_do_not_leave_a_stale_badge() {
assert!(behind.statuses_changed);
assert_eq!(status(&env), WorktreeStatus::Active);
}
+
+/// A tool of the session still in flight blocks a merge and a sync, so no
+/// write can interleave with the checkpoint commit or the merge, and neither
+/// changes anything. Once the tool ends, the same merge goes through.
+#[tokio::test]
+async fn a_running_tool_blocks_merge_and_sync_without_changing_anything() {
+ let env = env();
+ let (session, _created, root) = isolated(&env).await;
+ fs::write(root.join("f.txt"), "session\n").unwrap();
+ git_cmd(
+ &env.project,
+ &["commit", "-q", "--allow-empty", "-m", "ahead"],
+ );
+ let token = preview_session(&env.state, &env.git, &session)
+ .await
+ .unwrap()
+ .preview_token;
+ let budget = env.state.lock().await.tool_budget.clone();
+ let running = budget.acquire(&session, "Bash").await.unwrap();
+
+ let error = merge_session(&env.state, &env.git, &session, &token)
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_BUSY");
+ let error = sync_session(&env.state, &env.git, &session)
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_BUSY");
+ assert_eq!(git_cmd(&root, &["status", "--porcelain"]).trim(), "M f.txt");
+ assert_eq!(git_cmd(&root, &["rev-list", "--count", "HEAD"]).trim(), "2");
+ assert_eq!(
+ fs::read_to_string(env.project.join("f.txt")).unwrap(),
+ "base\n"
+ );
+
+ drop(running);
+ assert!(matches!(
+ merge_session(&env.state, &env.git, &session, &token)
+ .await
+ .unwrap(),
+ MergeOutcome::Merged { .. }
+ ));
+}
+
+/// A registered worktree folder replaced by a link (a junction on Windows)
+/// is never used as a tool root, merged, or emptied; deleting the session
+/// removes the link itself and the branch, never the link's target.
+#[tokio::test]
+async fn a_worktree_folder_replaced_by_a_link_is_never_followed() {
+ let env = env();
+ let (session, created, root) = isolated(&env).await;
+ let outside = env._dir.path().join("user-folder");
+ fs::create_dir_all(outside.join("nested")).unwrap();
+ fs::write(outside.join("KEEP_ME.txt"), "keep").unwrap();
+ fs::write(outside.join("nested/KEEP_TOO.txt"), "keep").unwrap();
+ fs::rename(&root, env._dir.path().join("moved-away")).unwrap();
+ link_dir(&outside, &root);
+
+ let error = tool_root(&env.state.lock().await.db, &session).unwrap_err();
+ assert_eq!(error.code, "WORKTREE_MISSING");
+ let error = preview_session(&env.state, &env.git, &session)
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_MISSING");
+ let error = sync_session(&env.state, &env.git, &session)
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_MISSING");
+ let pending = pending_work(&env.state, &env.git, &session).await.unwrap();
+ assert!(!pending.uncommitted_changes);
+
+ remove_session_worktrees(&env.state, &env.git, &session)
+ .await
+ .unwrap();
+ assert!(fs::symlink_metadata(&root).is_err());
+ assert_eq!(
+ fs::read_to_string(outside.join("KEEP_ME.txt")).unwrap(),
+ "keep"
+ );
+ assert_eq!(
+ fs::read_to_string(outside.join("nested/KEEP_TOO.txt")).unwrap(),
+ "keep"
+ );
+ assert!(!git_cmd(&env.project, &["branch", "--list"]).contains(&created.worktree.branch));
+}
diff --git a/crates/host-core/src/session_worktrees/merge.rs b/crates/host-core/src/session_worktrees/merge.rs
index 3b4c94fa8..c484cca46 100644
--- a/crates/host-core/src/session_worktrees/merge.rs
+++ b/crates/host-core/src/session_worktrees/merge.rs
@@ -112,13 +112,27 @@ pub async fn preview(git: &GitRunner, row: &WorktreeRow) -> Result<MergePreview,
let conflict = merge_in_progress(git, worktree).await?;
let head = git.run(worktree, &["rev-parse", "HEAD"]).await?;
+ // The merge brings the owner branch in too, so a project commit made
+ // after the preview must invalidate it like a session change does.
+ let owner_tip = git
+ .run(
+ worktree,
+ &[
+ "rev-parse",
+ "--verify",
+ "--quiet",
+ &head_ref(&row.owner_branch),
+ ],
+ )
+ .await?;
let content = content_fingerprint(git, worktree, &status).await?;
let token = format!(
"{:016x}",
fnv1a64(
format!(
- "{}\n{}\n{}\n{:016x}",
+ "{}\n{}\n{}\n{}\n{:016x}",
head.trim(),
+ owner_tip.trim(),
conflict,
status,
content
@@ -149,7 +163,7 @@ pub async fn merge(
if current.preview_token != preview_token {
return Err(WorktreeError::new(
"WORKTREE_CHANGED_SINCE_PREVIEW",
- "the session changed after the preview; review the changes again",
+ "the session or the project branch changed after the preview; review the changes again",
));
}
if current.is_empty() {
@@ -177,18 +191,8 @@ pub async fn land(
) -> Result<(), WorktreeError> {
let worktree = Path::new(&row.path);
// Checked before anything is committed, so a refusal changes nothing.
- let checked_out = git
- .output(owner_checkout, &["symbolic-ref", "--quiet", "HEAD"])
- .await?;
- if !checked_out.success() || checked_out.stdout.trim() != head_ref(&row.owner_branch) {
- return Err(WorktreeError::new(
- "WORKTREE_OWNER_BRANCH_CHANGED",
- format!(
- "the target is no longer on `{}`; check that branch out again to merge",
- row.owner_branch
- ),
- ));
- }
+ ensure_owner_branch(git, owner_checkout, row).await?;
+ ensure_own_branch(git, row).await?;
if merge_in_progress(git, worktree).await? {
conclude_resolved_merge(git, worktree).await?;
@@ -197,16 +201,22 @@ pub async fn land(
// One retry covers the owner branch moving between the two steps.
for attempt in 0..2 {
+ ensure_own_branch(git, row).await?;
sync_owner_into_session(git, worktree, &row.owner_branch).await?;
+ // Bound to the exact commit just built and checked again right
+ // before the only write to the owner checkout.
+ let landing = rev_parse(git, worktree, &head_ref(&row.branch)).await?;
+ ensure_owner_branch(git, owner_checkout, row).await?;
let forwarded = git
.output(
owner_checkout,
- &["merge", "--ff-only", "--no-edit", &head_ref(&row.branch)],
+ &["merge", "--ff-only", "--no-edit", &landing],
)
.await?;
if forwarded.success() {
- return Ok(());
+ return verify_landed(git, owner_checkout, row, &landing).await;
}
+ ensure_owner_branch(git, owner_checkout, row).await?;
let owner_contained = git
.output(
owner_checkout,
@@ -214,7 +224,7 @@ pub async fn land(
"merge-base",
"--is-ancestor",
&head_ref(&row.owner_branch),
- &head_ref(&row.branch),
+ &landing,
],
)
.await?
@@ -232,6 +242,82 @@ pub async fn land(
unreachable!("the loop returns on its second attempt")
}
+/// Refuse unless the owner checkout still has the owner branch checked out.
+async fn ensure_owner_branch(
+ git: &GitRunner,
+ owner_checkout: &Path,
+ row: &WorktreeRow,
+) -> Result<(), WorktreeError> {
+ if checked_out_branch(git, owner_checkout).await? == head_ref(&row.owner_branch) {
+ return Ok(());
+ }
+ Err(WorktreeError::new(
+ "WORKTREE_OWNER_BRANCH_CHANGED",
+ format!(
+ "the target is no longer on `{}`; check that branch out again to merge",
+ row.owner_branch
+ ),
+ ))
+}
+
+/// Refuse unless `row`'s worktree still has its own branch checked out, so a
+/// branch the agent switched to never receives a checkpoint or a merge.
+async fn ensure_own_branch(git: &GitRunner, row: &WorktreeRow) -> Result<(), WorktreeError> {
+ if checked_out_branch(git, Path::new(&row.path)).await? == head_ref(&row.branch) {
+ return Ok(());
+ }
+ Err(WorktreeError::new(
+ "WORKTREE_SESSION_BRANCH_CHANGED",
+ format!(
+ "the worktree is no longer on `{}`; check that branch out again in it",
+ row.branch
+ ),
+ ))
+}
+
+/// The full ref checked out in `checkout`; empty for a detached `HEAD`.
+async fn checked_out_branch(git: &GitRunner, checkout: &Path) -> Result<String, WorktreeError> {
+ let head = git
+ .output(checkout, &["symbolic-ref", "--quiet", "HEAD"])
+ .await?;
+ Ok(if head.success() {
+ head.stdout.trim().to_string()
+ } else {
+ String::new()
+ })
+}
+
+async fn rev_parse(git: &GitRunner, dir: &Path, rev: &str) -> Result<String, WorktreeError> {
+ Ok(git
+ .run(dir, &["rev-parse", "--verify", "--quiet", rev])
+ .await?
+ .trim()
+ .to_string())
+}
+
+/// After the fast-forward: the owner branch must now be exactly the commit
+/// that was checked, still checked out in the owner checkout. A branch switch
+/// in the instant between the last check and git's own `HEAD` read would
+/// have moved the other branch instead; that is reported, not hidden.
+async fn verify_landed(
+ git: &GitRunner,
+ owner_checkout: &Path,
+ row: &WorktreeRow,
+ landing: &str,
+) -> Result<(), WorktreeError> {
+ ensure_owner_branch(git, owner_checkout, row).await?;
+ if rev_parse(git, owner_checkout, &head_ref(&row.owner_branch)).await? == landing {
+ return Ok(());
+ }
+ Err(WorktreeError::new(
+ "WORKTREE_OWNER_BRANCH_CHANGED",
+ format!(
+ "`{}` did not receive the merge because the target switched branches meanwhile",
+ row.owner_branch
+ ),
+ ))
+}
+
/// Commit every change in `worktree` with `message`; nothing to do when clean.
pub async fn commit_all(
git: &GitRunner,
@@ -287,6 +373,7 @@ pub async fn sync_from_owner(
message: &str,
) -> Result<SyncOutcome, WorktreeError> {
let worktree = Path::new(&row.path);
+ ensure_own_branch(git, row).await?;
if merge_in_progress(git, worktree).await? {
conclude_resolved_merge(git, worktree).await?;
}
@@ -295,6 +382,7 @@ pub async fn sync_from_owner(
return Ok(SyncOutcome::UpToDate);
}
commit_all(git, worktree, message).await?;
+ ensure_own_branch(git, row).await?;
sync_owner_into_session(git, worktree, &row.owner_branch).await?;
Ok(SyncOutcome::Synced { commits: behind })
}
@@ -559,11 +647,6 @@ async fn content_fingerprint(
.map_err(|error| WorktreeError::new("WORKTREE_INTERNAL", error.to_string()))
}
-/// Bytes of one untracked file read into a preview token. Larger files add
-/// their size and modification time instead, so a huge file cannot stall the
-/// host; the agent cannot change one without changing either.
-const FINGERPRINT_FILE_LIMIT: u64 = 16 * 1024 * 1024;
-
fn fnv_extend(mut hash: u64, bytes: &[u8]) -> u64 {
for byte in bytes {
hash ^= u64::from(*byte);
@@ -573,7 +656,10 @@ fn fnv_extend(mut hash: u64, bytes: &[u8]) -> u64 {
}
/// Never follows a link and never opens anything but a regular file, so a
-/// link to `/dev/zero` or a FIFO cannot hang or exhaust the host.
+/// link to `/dev/zero` or a FIFO cannot hang or exhaust the host. The whole
+/// file is hashed in fixed-size chunks, so a same-length rewrite that
+/// restores the modification time still changes the token, and a large file
+/// never sits in memory. Callers run this off the async workers.
fn untracked_entry_hash(hash: u64, path: &Path) -> u64 {
use std::io::Read;
let Ok(metadata) = std::fs::symlink_metadata(path) else {
@@ -589,25 +675,19 @@ fn untracked_entry_hash(hash: u64, path: &Path) -> u64 {
if !metadata.is_file() {
return fnv_extend(hash, b"special");
}
- let modified = metadata
- .modified()
- .ok()
- .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
- .map_or(0, |duration| duration.as_nanos());
let hash = fnv_extend(hash, &metadata.len().to_le_bytes());
- if metadata.len() > FINGERPRINT_FILE_LIMIT {
- return fnv_extend(hash, &modified.to_le_bytes());
- }
- let Ok(file) = std::fs::File::open(path) else {
+ let Ok(mut file) = std::fs::File::open(path) else {
return fnv_extend(hash, b"unreadable");
};
- let mut reader = file.take(FINGERPRINT_FILE_LIMIT);
- let mut buffer = [0u8; 64 * 1024];
+ let mut buffer = vec![0u8; 64 * 1024];
let mut hash = hash;
loop {
- match reader.read(&mut buffer) {
- Ok(0) | Err(_) => break hash,
+ match file.read(&mut buffer) {
+ Ok(0) => break hash,
Ok(read) => hash = fnv_extend(hash, &buffer[..read]),
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
+ // A read that fails part-way still yields a stable, distinct token.
+ Err(_) => break fnv_extend(hash, b"read-error"),
}
}
}
diff --git a/crates/host-core/src/session_worktrees/merge/tests.rs b/crates/host-core/src/session_worktrees/merge/tests.rs
index 6c6fd4fef..61ce1b9c5 100644
--- a/crates/host-core/src/session_worktrees/merge/tests.rs
+++ b/crates/host-core/src/session_worktrees/merge/tests.rs
@@ -375,3 +375,114 @@ fn porcelain_entries_keep_rename_targets_and_mark_untracked() {
]
);
}
+
+/// The merge brings the project branch in too, so a project commit made
+/// after the preview invalidates the token instead of landing unseen.
+#[tokio::test]
+async fn a_project_commit_after_the_preview_stops_the_merge() {
+ let f = fixture("a\n");
+ fs::write(wt(&f).join("s.txt"), "s").unwrap();
+ let git = GitRunner::default();
+ let token = preview(&git, &f.row).await.unwrap().preview_token;
+ fs::write(f.repo.join("p.txt"), "p").unwrap();
+ git_cmd(&f.repo, &["add", "p.txt"]);
+ git_cmd(&f.repo, &["commit", "-q", "-m", "project moved on"]);
+
+ let error = merge(&git, &f.row, &f.repo, "t", &token).await.unwrap_err();
+ assert_eq!(error.code, "WORKTREE_CHANGED_SINCE_PREVIEW");
+ assert!(!f.repo.join("s.txt").exists());
+ assert!(!wt(&f).join("p.txt").exists());
+
+ let fresh = preview(&git, &f.row).await.unwrap().preview_token;
+ assert!(matches!(
+ merge(&git, &f.row, &f.repo, "t", &fresh).await.unwrap(),
+ MergeOutcome::Merged { .. }
+ ));
+}
+
+/// A large untracked file rewritten in place with the same length and its
+/// old modification time still invalidates the preview: the whole file is
+/// hashed, not only its size and time.
+#[tokio::test]
+async fn a_large_untracked_rewrite_that_keeps_size_and_time_stops_the_merge() {
+ let f = fixture("a\n");
+ let big = wt(&f).join("big.bin");
+ let size = 17 * 1024 * 1024;
+ fs::write(&big, vec![b'a'; size]).unwrap();
+ let modified = fs::metadata(&big).unwrap().modified().unwrap();
+ let git = GitRunner::default();
+ let token = preview(&git, &f.row).await.unwrap().preview_token;
+
+ let mut rewritten = vec![b'a'; size];
+ rewritten[size - 1] = b'b';
+ fs::write(&big, rewritten).unwrap();
+ fs::File::options()
+ .write(true)
+ .open(&big)
+ .unwrap()
+ .set_modified(modified)
+ .unwrap();
+ assert_eq!(fs::metadata(&big).unwrap().modified().unwrap(), modified);
+
+ let error = merge(&git, &f.row, &f.repo, "t", &token).await.unwrap_err();
+ assert_eq!(error.code, "WORKTREE_CHANGED_SINCE_PREVIEW");
+ assert!(!f.repo.join("big.bin").exists());
+}
+
+/// When the session worktree is on another branch (for example after the
+/// agent ran `git checkout`), nothing is committed there and nothing merges.
+#[tokio::test]
+async fn a_worktree_on_another_branch_is_neither_committed_nor_merged() {
+ let f = fixture("a\n");
+ git_cmd(wt(&f), &["checkout", "-q", "-b", "side"]);
+ fs::write(wt(&f).join("s.txt"), "s").unwrap();
+ git_cmd(&f.repo, &["commit", "-q", "--allow-empty", "-m", "project"]);
+ let git = GitRunner::default();
+ let token = preview(&git, &f.row).await.unwrap().preview_token;
+
+ let error = merge(&git, &f.row, &f.repo, "t", &token).await.unwrap_err();
+ assert_eq!(error.code, "WORKTREE_SESSION_BRANCH_CHANGED");
+ let error = sync_from_owner(&git, &f.row, "t").await.unwrap_err();
+ assert_eq!(error.code, "WORKTREE_SESSION_BRANCH_CHANGED");
+ assert_eq!(
+ git_cmd(wt(&f), &["status", "--porcelain"]).trim(),
+ "?? s.txt"
+ );
+ assert_eq!(
+ git_cmd(&f.repo, &["rev-parse", "side"]),
+ git_cmd(&f.repo, &["rev-parse", "pi-desktop/s1"])
+ );
+ assert!(!f.repo.join("s.txt").exists());
+}
+
+/// The fast-forward is checked after the fact: if the project switched
+/// branches in the instant before git read its `HEAD`, the wrong branch is
+/// reported instead of a silent success.
+#[tokio::test]
+async fn a_landing_on_a_switched_target_is_reported() {
+ let f = fixture("a\n");
+ fs::write(wt(&f).join("f.txt"), "b\n").unwrap();
+ git_cmd(wt(&f), &["commit", "-q", "-am", "s"]);
+ let git = GitRunner::default();
+ let landing = rev_parse(&git, wt(&f), &head_ref(&f.row.branch))
+ .await
+ .unwrap();
+
+ // `other`, not `main`, received the session's commit.
+ git_cmd(&f.repo, &["checkout", "-q", "-b", "other"]);
+ git_cmd(&f.repo, &["merge", "-q", "--ff-only", &landing]);
+ let error = verify_landed(&git, &f.repo, &f.row, &landing)
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_OWNER_BRANCH_CHANGED");
+ git_cmd(&f.repo, &["checkout", "-q", "main"]);
+ let error = verify_landed(&git, &f.repo, &f.row, &landing)
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_OWNER_BRANCH_CHANGED");
+
+ git_cmd(&f.repo, &["merge", "-q", "--ff-only", &landing]);
+ verify_landed(&git, &f.repo, &f.row, &landing)
+ .await
+ .unwrap();
+}
diff --git a/crates/host-core/src/session_worktrees/registry.rs b/crates/host-core/src/session_worktrees/registry.rs
index 00be75b0e..dfe43f496 100644
--- a/crates/host-core/src/session_worktrees/registry.rs
+++ b/crates/host-core/src/session_worktrees/registry.rs
@@ -275,17 +275,21 @@ pub fn remove(db: &Database, id: &str) -> Result<bool> {
> 0)
}
-/// Lowest port block not held by any row whose first port `is_free` accepts.
-/// The unique index on `port_base` still guards the insert against a race.
+/// Lowest port block not held by any row whose every port `is_free` accepts:
+/// the agent may use any port of its block, so one busy port rules the block
+/// out. The unique index on `port_base` still guards the insert against a
+/// race.
pub fn next_port_base(db: &Database, is_free: impl Fn(u16) -> bool) -> Result<Option<i64>> {
let used: std::collections::HashSet<i64> = db
.conn()
.prepare_cached("SELECT port_base FROM worktrees WHERE port_base IS NOT NULL")?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
+ let block_is_free =
+ |base: i64| (base..base + PORT_BLOCK).all(|port| u16::try_from(port).is_ok_and(&is_free));
let mut base = PORT_RANGE_START;
while base <= PORT_RANGE_LAST_BASE {
- if !used.contains(&base) && u16::try_from(base).is_ok_and(&is_free) {
+ if !used.contains(&base) && block_is_free(base) {
return Ok(Some(base));
}
base += PORT_BLOCK;
@@ -374,4 +378,21 @@ mod tests {
);
assert_eq!(next_port_base(&db, |_| false).unwrap(), None);
}
+
+ /// A block whose base is free but whose fifth port another program
+ /// holds is skipped: the agent may use any port of its block.
+ #[test]
+ fn a_busy_port_inside_a_block_skips_the_whole_block() {
+ let (_dir, db, _session) = db_with_session();
+ let busy = (PORT_RANGE_START + 5) as u16;
+ assert_eq!(
+ next_port_base(&db, |port| port != busy).unwrap(),
+ Some(PORT_RANGE_START + PORT_BLOCK)
+ );
+ let last = (PORT_RANGE_START + PORT_BLOCK - 1) as u16;
+ assert_eq!(
+ next_port_base(&db, |port| port != last).unwrap(),
+ Some(PORT_RANGE_START + PORT_BLOCK)
+ );
+ }
}
diff --git a/crates/host-core/src/session_worktrees/remove.rs b/crates/host-core/src/session_worktrees/remove.rs
index 2c77f32e9..9d3b2e142 100644
--- a/crates/host-core/src/session_worktrees/remove.rs
+++ b/crates/host-core/src/session_worktrees/remove.rs
@@ -14,6 +14,28 @@ use super::git::GitRunner;
use super::registry::WorktreeRow;
use super::WorktreeError;
+/// Whether `path` is a real directory, never following a link. A symbolic
+/// link or a Windows junction is not one (`symlink_metadata` reports both as
+/// links; a cloud-file placeholder folder still counts as a directory). A
+/// registered worktree folder replaced by a link to somewhere else must never
+/// become a tool root, be merged in, or be emptied.
+pub fn is_real_dir(path: &Path) -> bool {
+ fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir())
+}
+
+/// `is_real_dir` for `root` and every directory from it down to
+/// `root/<prefix>` (a project that is a repository subdirectory).
+pub fn is_real_dir_chain(root: &Path, prefix: &str) -> bool {
+ if !is_real_dir(root) {
+ return false;
+ }
+ let mut current = root.to_path_buf();
+ Path::new(prefix).components().all(|component| {
+ current.push(component);
+ is_real_dir(&current)
+ })
+}
+
/// Delete everything inside `root` except its `.git` link file. Links are
/// removed as links; their targets are never traversed.
pub fn clear_contents(root: &Path) -> io::Result<()> {
@@ -81,19 +103,26 @@ pub async fn remove_worktree(git: &GitRunner, row: &WorktreeRow) -> Result<(), W
let root = Path::new(&row.path);
let common_dir = Path::new(&row.common_dir);
let repository_exists = common_dir.is_dir();
- if root.exists() {
- if repository_exists {
- // Not locked when creation failed half-way; that is fine.
- let _ = git.output(root, &["worktree", "unlock", &row.path]).await;
- }
- clear_contents(root)?;
- if repository_exists {
- git.run_git_dir(common_dir, &["worktree", "remove", "--force", &row.path])
- .await?;
- }
- if root.exists() {
- fs::remove_dir_all(root)?;
+ match fs::symlink_metadata(root) {
+ // The registered folder was replaced by a link (or a file): remove
+ // that entry alone; its target is never read or emptied.
+ Ok(metadata) if !metadata.is_dir() => remove_entry(root)?,
+ Ok(_) => {
+ if repository_exists {
+ // Not locked when creation failed half-way; that is fine.
+ let _ = git.output(root, &["worktree", "unlock", &row.path]).await;
+ }
+ clear_contents(root)?;
+ if repository_exists {
+ git.run_git_dir(common_dir, &["worktree", "remove", "--force", &row.path])
+ .await?;
+ }
+ if is_real_dir(root) {
+ fs::remove_dir_all(root)?;
+ }
}
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error.into()),
}
if repository_exists {
drop_admin_entry(common_dir, root)?;
diff --git a/docs/adr/0329-session-worktree-isolation.md b/docs/adr/0329-session-worktree-isolation.md
index 5f50e5666..5bc65d11c 100644
--- a/docs/adr/0329-session-worktree-isolation.md
+++ b/docs/adr/0329-session-worktree-isolation.md
@@ -42,7 +42,12 @@ the project directory.
branch into the session branch inside the worktree (conflicts stay there),
then fast-forwards the project branch. The project never enters a
merge-in-progress state and git refuses to overwrite uncommitted project
- changes.
+ changes. The preview token also covers the project branch tip and the
+ full content of untracked files, so nothing the user did not see lands.
+ Both checkouts' branches are checked before every write, the
+ fast-forward is bound to the checked commit and verified afterwards, and
+ the session's own tools are held for the whole merge or sync (at most
+ five seconds' wait for a running tool, then `WORKTREE_BUSY`).
5. Inside an isolated session, a subagent whose tools include Write or Edit
gets its own temporary worktree and is merged back automatically with the
same algorithm; a conflict is reported to the parent, which can resume the
@@ -50,7 +55,9 @@ the project directory.
6. Deleting an isolated session removes its worktrees and branches after a
loss warning; there is no separate discard. Removal deletes links as links
before calling git, because Git for Windows follows directory junctions
- during `git worktree remove --force` (openai/codex#34702, #49995).
+ during `git worktree remove --force` (openai/codex#34702, #49995). A
+ registered worktree folder that was itself replaced by a link is treated
+ as missing everywhere and only the link is removed.
7. Every git command host-core runs disables hooks and `core.fsmonitor` and
sets `safe.bareRepository=explicit`. A relative `core.hooksPath` resolves
inside the worktree, so a hook written with Write/Edit alone would
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 30db403c7..0d6594981 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -378,8 +378,9 @@ project changes are not copied; git-ignored files listed in
(a missing worktree fails with a `WORKTREE_*` error);
- `AGENTS.md` instructions are read from the worktree, while project identity
(memory, skills, plugins, MCP, subagents) stays keyed to the project path;
-- Bash receives `PI_PORT` (first port of a 10-port block in 41000–48999),
- `PI_PROJECT_ROOT`, and `PI_WORKTREE_ROOT`;
+- Bash receives `PI_PORT` (first port of a 10-port block in 41000–48999; a
+ block is assigned only when all ten ports are free), `PI_PROJECT_ROOT`, and
+ `PI_WORKTREE_ROOT`;
- the optional per-project setup command runs once in each new worktree, with
the same variables, in the user's default command shell
(`defaultCommandShell`, otherwise the platform default: Windows PowerShell on
@@ -388,7 +389,12 @@ project changes are not copied; git-ignored files listed in
`&&` on Windows PowerShell 5.1) unless a POSIX shell such as Git Bash is
the configured default;
- git hooks and fsmonitor are disabled for host-run git commands in the
- worktree, and removal never follows links out of it.
+ worktree, and removal never follows links out of it;
+- the registered worktree folder must be a real directory: if it (or a
+ directory down to the project subdirectory) was replaced by a symbolic
+ link or a Windows junction, it is treated as missing (`WORKTREE_MISSING`)
+ and is never used as a tool root, merged, or synced, and deleting the
+ session removes only the link, never its target.
Merging into the project is an explicit user action (preview, then merge with
the preview token); it syncs the project branch into the worktree and only
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 1f7e58323..1e674a39a 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -615,11 +615,20 @@ Additive `worktree.*` methods; no protocol version bump. Failures use code
`session.create` refuses `isolated: true` for a remote-host project with the
same code before any session is created.
- `worktree.preview({ sessionId })` → `{ preview }` with the commits and files
- that would land and a `previewToken`.
-- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`. A stale token
- is `WORKTREE_CHANGED_SINCE_PREVIEW`; a dirty project is
+ that would land and a `previewToken`. The token covers the session `HEAD`,
+ the project branch tip, the conflict state, and the full content of every
+ uncommitted and untracked file.
+- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`. A token
+ that no longer matches (the session or the project branch changed) is
+ `WORKTREE_CHANGED_SINCE_PREVIEW`; a dirty project is
`WORKTREE_PROJECT_DIRTY`; a conflict is `WORKTREE_CONFLICT` and leaves the
- worktree conflicted and the project untouched.
+ worktree conflicted and the project untouched. The project checkout must
+ still be on the session's owner branch and the worktree on its own branch,
+ checked again before every write (`WORKTREE_OWNER_BRANCH_CHANGED`,
+ `WORKTREE_SESSION_BRANCH_CHANGED`); the fast-forward is bound to the exact
+ commit that was checked and verified afterwards. While it runs, host-core
+ holds the session's tools: it waits up to five seconds for a running tool,
+ then fails with `WORKTREE_BUSY`, and queues new ones until it is done.
- `worktree.behind({ sessionId })` → `{ commits }`, project-branch commits the
session does not have yet.
- `worktree.behindAll()` → `{ counts, statusesChanged }`: the same count for
@@ -630,9 +639,10 @@ Additive `worktree.*` methods; no protocol version bump. Failures use code
sidebar marker.
- `worktree.sync({ sessionId })` → `{ outcome }` (`synced` with `commits`, or
`upToDate`): "Sync from project" merges the project branch into the session
- worktree after committing pending session work. The project checkout is not
- touched; a conflict is `WORKTREE_CONFLICT`, stays in the worktree, and marks
- the session like a merge conflict.
+ worktree after committing pending session work, under the same tool hold
+ and own-branch check as a merge. The project checkout is not touched; a
+ conflict is `WORKTREE_CONFLICT`, stays in the worktree, and marks the
+ session like a merge conflict.
- `worktree.pendingWork({ sessionId })` → `{ pending }`, the unmerged work a
delete would discard.
- `worktree.setupLog({ sessionId })` → `{ setupStatus, log }`.
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index e0760a896..83a48b2f4 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -314,15 +314,18 @@ type ReviewChange = {
`WORKTREE_*` 错误);
- `AGENTS.md` 指令从 worktree 读取,而项目身份(记忆、技能、插件、MCP、子代理)仍以
项目路径为键;
-- Bash 获得 `PI_PORT`(41000–48999 中一个 10 端口块的首端口)、`PI_PROJECT_ROOT`
- 和 `PI_WORKTREE_ROOT`;
+- Bash 获得 `PI_PORT`(41000–48999 中一个 10 端口块的首端口;只有整段 10 个端口都空闲时才分配该块)、
+ `PI_PROJECT_ROOT` 和 `PI_WORKTREE_ROOT`;
- 可选的项目初始化命令在每个新 worktree 中运行一次,带同样的变量,使用用户的默认命令
shell(`defaultCommandShell`,未设置时用平台默认:Windows 上为 Windows PowerShell,
其他平台为 bash)。命令不会在方言之间转换,因此在 Windows 上必须使用 PowerShell 语法
(`$env:PI_PORT`;Windows PowerShell 5.1 用 `;` 而不是 `&&`),除非默认 shell 配置为
Git Bash 等 POSIX shell;
- 宿主在 worktree 中运行的 git 命令禁用 hooks 和 fsmonitor,删除时绝不跟随链接越出
- worktree。
+ worktree;
+- 登记的 worktree 文件夹必须是真实目录:若它(或通往项目子目录的某一级目录)被替换为符号链接或
+ Windows junction,即视为缺失(`WORKTREE_MISSING`),不会被用作工具根目录、合并或同步;删除会话时
+ 只删除链接本身,绝不删除其目标。
合并到项目是显式的用户操作(先预览,再携带预览令牌合并):先把项目分支同步进
worktree,项目只做快进,因此冲突留在 worktree 中。删除隔离会话即丢弃其 worktree
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 3de0badd3..5b7a66211 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -421,17 +421,20 @@ off | minimal | low | medium | high | xhigh | max
`{ available: false, errorCode, message }`。`session.create` 对远程主机项目的 `isolated: true` 以同一代码拒绝,
不会创建任何会话。
- `worktree.preview({ sessionId })` → `{ preview }`,包含将要合入的提交、文件及
- `previewToken`。
-- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`。令牌过期为
+ `previewToken`。令牌覆盖会话 `HEAD`、项目分支最新提交、冲突状态,以及所有未提交和未跟踪文件的完整内容。
+- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`。令牌不再匹配(会话或项目分支有变化)为
`WORKTREE_CHANGED_SINCE_PREVIEW`;项目有未提交改动为 `WORKTREE_PROJECT_DIRTY`;冲突为
- `WORKTREE_CONFLICT`,worktree 保持冲突状态,项目不受影响。
+ `WORKTREE_CONFLICT`,worktree 保持冲突状态,项目不受影响。项目检出必须仍在会话的所属分支上、worktree
+ 必须仍在自己的分支上,每次写入前都会重新检查(`WORKTREE_OWNER_BRANCH_CHANGED`、
+ `WORKTREE_SESSION_BRANCH_CHANGED`);快进绑定到检查过的那个提交,完成后再核对。执行期间宿主持有会话的工具:
+ 最多等待正在运行的工具五秒,超时返回 `WORKTREE_BUSY`,新的工具调用排队等到结束。
- `worktree.behind({ sessionId })` → `{ commits }`,即会话尚未包含的项目分支提交数。
- `worktree.behindAll()` → `{ counts, statusesChanged }`:以会话 id 为键给出每个隔离会话的同一计数
(读不到的会话省略),每次并发检查少量会话。处于冲突状态的会话会先检查是否已解决;
`statusesChanged` 提示渲染层刷新会话列表。渲染层在后台读取,用于侧边栏标记。
- `worktree.sync({ sessionId })` → `{ outcome }`(`synced` 及 `commits`,或 `upToDate`):
- “从项目同步”先提交会话中待提交的工作,再把项目分支合入会话 worktree。不改动项目检出;
- 冲突为 `WORKTREE_CONFLICT`,留在 worktree 中,并像合并冲突一样标记会话。
+ “从项目同步”先提交会话中待提交的工作,再把项目分支合入会话 worktree,与合并一样持有会话工具并检查自身分支。
+ 不改动项目检出;冲突为 `WORKTREE_CONFLICT`,留在 worktree 中,并像合并冲突一样标记会话。
- `worktree.pendingWork({ sessionId })` → `{ pending }`,即删除会丢弃的未合并工作。
- `worktree.setupLog({ sessionId })` → `{ setupStatus, log }`。
- `worktree.location({ sessionId })` → `{ path }`;仅供 Electron Main 的“在文件夹中显示”
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 94417b1ae..bf51b92a8 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -63,8 +63,9 @@ export const de = {
"gitTooOld": "Isolierte Sitzungen benötigen Git 2.29 oder neuer.",
"branchNamespaceTaken": "Ein Branch namens pi-desktop existiert. Benenne ihn um, um isolierte Sitzungen zu nutzen.",
"busy": "Die Sitzung läuft noch. Warte, bis sie fertig ist.",
- "changedSincePreview": "Die Sitzung hat sich nach der Vorschau geändert. Prüfe die aktualisierten Änderungen.",
+ "changedSincePreview": "Die Sitzung oder der Projekt-Branch hat sich nach der Vorschau geändert. Prüfe die aktualisierten Änderungen.",
"ownerBranchChanged": "Das Projekt ist nicht mehr auf dem Branch, auf dem diese Sitzung begann. Wechsle zurück, um zusammenzuführen.",
+ "sessionBranchChanged": "Der Worktree der Sitzung ist nicht mehr auf seinem eigenen Branch. Wechsle zurück, um zusammenzuführen oder zu synchronisieren.",
"projectDirty": "Nicht committete Projektänderungen würden überschrieben. Committe oder stashe sie und führe dann erneut zusammen.",
"missing": "Der isolierte Worktree-Ordner existiert nicht mehr. Lösche diese Sitzung.",
"commitFailed": "Git konnte die Änderungen der Sitzung nicht committen.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index fe6e8d426..1a38ec96c 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -61,8 +61,9 @@ export const en = {
gitTooOld: "Isolated sessions need Git 2.29 or newer.",
branchNamespaceTaken: "A branch named pi-desktop exists. Rename it to use isolated sessions.",
busy: "The session is still running. Wait for it to finish.",
- changedSincePreview: "The session changed after the preview. Review the updated changes.",
+ changedSincePreview: "The session or the project branch changed after the preview. Review the updated changes.",
ownerBranchChanged: "The project is no longer on the branch this session started from. Switch back to merge.",
+ sessionBranchChanged: "The session's worktree is no longer on its own branch. Switch it back to merge or sync.",
projectDirty: "Uncommitted project changes would be overwritten. Commit or stash them, then merge again.",
missing: "The isolated worktree folder no longer exists. Delete this session.",
commitFailed: "Git could not commit the session's changes.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index bc524cd2b..3b434a2a8 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -63,8 +63,9 @@ export const es = {
"gitTooOld": "Las sesiones aisladas requieren Git 2.29 o posterior.",
"branchNamespaceTaken": "Existe una rama llamada pi-desktop. Cámbiale el nombre para usar sesiones aisladas.",
"busy": "La sesión sigue en ejecución. Espera a que termine.",
- "changedSincePreview": "La sesión cambió después de la vista previa. Revisa los cambios actualizados.",
+ "changedSincePreview": "La sesión o la rama del proyecto cambió después de la vista previa. Revisa los cambios actualizados.",
"ownerBranchChanged": "El proyecto ya no está en la rama donde empezó esta sesión. Vuelve a ella para fusionar.",
+ "sessionBranchChanged": "El worktree de la sesión ya no está en su propia rama. Vuelve a ella para fusionar o sincronizar.",
"projectDirty": "Se sobrescribirían cambios sin confirmar del proyecto. Confírmalos o guárdalos con stash y vuelve a fusionar.",
"missing": "La carpeta del worktree aislado ya no existe. Elimina esta sesión.",
"commitFailed": "Git no pudo confirmar los cambios de la sesión.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index cf91ba9a6..8cad1aa64 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -63,8 +63,9 @@ export const fr = {
"gitTooOld": "Les sessions isolées nécessitent Git 2.29 ou plus récent.",
"branchNamespaceTaken": "Une branche nommée pi-desktop existe. Renommez-la pour utiliser les sessions isolées.",
"busy": "La session est toujours en cours. Attendez qu'elle se termine.",
- "changedSincePreview": "La session a changé après l'aperçu. Vérifiez les modifications mises à jour.",
+ "changedSincePreview": "La session ou la branche du projet a changé après l'aperçu. Vérifiez les modifications mises à jour.",
"ownerBranchChanged": "Le projet n'est plus sur la branche de départ de cette session. Revenez-y pour fusionner.",
+ "sessionBranchChanged": "Le worktree de la session n'est plus sur sa propre branche. Revenez-y pour fusionner ou synchroniser.",
"projectDirty": "Des modifications non validées du projet seraient écrasées. Validez-les ou mettez-les de côté, puis fusionnez à nouveau.",
"missing": "Le dossier du worktree isolé n'existe plus. Supprimez cette session.",
"commitFailed": "Git n'a pas pu valider les modifications de la session.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 89379aa4a..24c992907 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -63,8 +63,9 @@ export const ko = {
gitTooOld: "격리 세션에는 Git 2.29 이상이 필요합니다.",
branchNamespaceTaken: "pi-desktop이라는 브랜치가 있습니다. 이름을 바꾼 뒤 격리 세션을 사용하세요.",
busy: "세션이 아직 실행 중입니다. 끝날 때까지 기다리세요.",
- changedSincePreview: "미리보기 이후 세션이 변경되었습니다. 업데이트된 변경 사항을 확인하세요.",
+ changedSincePreview: "미리보기 이후 세션 또는 프로젝트 브랜치가 변경되었습니다. 업데이트된 변경 사항을 확인하세요.",
ownerBranchChanged: "프로젝트가 이 세션이 시작된 브랜치에 있지 않습니다. 원래 브랜치로 전환한 뒤 병합하세요.",
+ sessionBranchChanged: "세션의 worktree가 자체 브랜치에 있지 않습니다. 원래 브랜치로 전환한 뒤 병합하거나 동기화하세요.",
projectDirty: "프로젝트의 커밋되지 않은 변경 사항을 덮어쓰게 됩니다. 커밋하거나 stash한 뒤 다시 병합하세요.",
missing: "격리 worktree 폴더가 더 이상 없습니다. 이 세션을 삭제하세요.",
commitFailed: "Git이 세션의 변경 사항을 커밋하지 못했습니다.",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 3f9e2c6fe..c1771e395 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -63,8 +63,9 @@ export const ptBR = {
gitTooOld: "Sessões isoladas exigem Git 2.29 ou mais recente.",
branchNamespaceTaken: "Existe um branch chamado pi-desktop. Renomeie-o para usar sessões isoladas.",
busy: "A sessão ainda está em execução. Aguarde ela terminar.",
- changedSincePreview: "A sessão mudou depois da prévia. Revise as alterações atualizadas.",
+ changedSincePreview: "A sessão ou o branch do projeto mudou depois da prévia. Revise as alterações atualizadas.",
ownerBranchChanged: "O projeto não está mais no branch em que esta sessão começou. Volte para ele para mesclar.",
+ sessionBranchChanged: "O worktree da sessão não está mais no próprio branch. Volte para ele para mesclar ou sincronizar.",
projectDirty: "Alterações não confirmadas do projeto seriam sobrescritas. Confirme ou guarde com stash e mescle novamente.",
missing: "A pasta do worktree isolado não existe mais. Exclua esta sessão.",
commitFailed: "O Git não conseguiu confirmar as alterações da sessão.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 6ed820a19..96226e893 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -63,8 +63,9 @@ export const tr = {
gitTooOld: "Yalıtılmış oturumlar Git 2.29 veya daha yenisini gerektirir.",
branchNamespaceTaken: "pi-desktop adlı bir dal var. Yalıtılmış oturumları kullanmak için yeniden adlandırın.",
busy: "Oturum hâlâ çalışıyor. Bitmesini bekleyin.",
- changedSincePreview: "Oturum önizlemeden sonra değişti. Güncellenen değişiklikleri inceleyin.",
+ changedSincePreview: "Oturum veya proje dalı önizlemeden sonra değişti. Güncellenen değişiklikleri inceleyin.",
ownerBranchChanged: "Proje artık bu oturumun başladığı dalda değil. Birleştirmek için o dala geri dönün.",
+ sessionBranchChanged: "Oturumun worktree'si artık kendi dalında değil. Birleştirmek veya eşitlemek için o dala geri dönün.",
projectDirty: "Projedeki commit edilmemiş değişikliklerin üzerine yazılır. Önce commit edin veya stash'leyin, sonra yeniden birleştirin.",
missing: "Yalıtılmış worktree klasörü artık yok. Bu oturumu silin.",
commitFailed: "Git oturumun değişikliklerini commit edemedi.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 3bfb716b6..9a221a64a 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -63,8 +63,9 @@ export const zhCN = {
gitTooOld: "隔离会话需要 Git 2.29 或更高版本。",
branchNamespaceTaken: "已存在名为 pi-desktop 的分支。请重命名后再使用隔离会话。",
busy: "会话仍在运行,请等待其结束。",
- changedSincePreview: "预览后会话有了变化,请查看更新后的改动。",
+ changedSincePreview: "预览后会话或项目分支有了变化,请查看更新后的改动。",
ownerBranchChanged: "项目已不在本会话创建时的分支上。请切回该分支再合并。",
+ sessionBranchChanged: "会话的 worktree 已不在它自己的分支上。请切回该分支再合并或同步。",
projectDirty: "项目中未提交的改动会被覆盖。请先提交或暂存后再合并。",
missing: "隔离 worktree 文件夹已不存在,请删除该会话。",
commitFailed: "Git 无法提交会话的改动。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 4075c3049..0f567bb6a 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -63,8 +63,9 @@ export const zhTW = {
gitTooOld: "隔離工作階段需要 Git 2.29 或更新版本。",
branchNamespaceTaken: "已存在名為 pi-desktop 的分支。請重新命名後再使用隔離工作階段。",
busy: "工作階段仍在執行,請等待其結束。",
- changedSincePreview: "預覽後工作階段有了變化,請查看更新後的變更。",
+ changedSincePreview: "預覽後工作階段或專案分支有了變化,請查看更新後的變更。",
ownerBranchChanged: "專案已不在本工作階段建立時的分支上。請切回該分支再合併。",
+ sessionBranchChanged: "工作階段的 worktree 已不在它自己的分支上。請切回該分支再合併或同步。",
projectDirty: "專案中未提交的變更會被覆寫。請先提交或暫存後再合併。",
missing: "隔離 worktree 資料夾已不存在,請刪除此工作階段。",
commitFailed: "Git 無法提交工作階段的變更。",
diff --git a/packages/shared/src/types/worktree.ts b/packages/shared/src/types/worktree.ts
index 3ae6b6ed2..c7a4c030d 100644
--- a/packages/shared/src/types/worktree.ts
+++ b/packages/shared/src/types/worktree.ts
@@ -31,6 +31,8 @@ export const WorktreeErrorCodes = {
CONFLICT: "WORKTREE_CONFLICT",
CHANGED_SINCE_PREVIEW: "WORKTREE_CHANGED_SINCE_PREVIEW",
OWNER_BRANCH_CHANGED: "WORKTREE_OWNER_BRANCH_CHANGED",
+ /** The session's (or subagent's) worktree no longer has its own branch checked out. */
+ SESSION_BRANCH_CHANGED: "WORKTREE_SESSION_BRANCH_CHANGED",
PROJECT_DIRTY: "WORKTREE_PROJECT_DIRTY",
MERGE_FAILED: "WORKTREE_MERGE_FAILED",
COMMIT_FAILED: "WORKTREE_COMMIT_FAILED",