Skip to content

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

fix(host-core): close the remaining gaps around merge and subagents

renwanga17eb68471524
diff --git a/crates/host-core/src/session_worktrees/delegate.rs b/crates/host-core/src/session_worktrees/delegate.rs
index d2571f807..56abf5909 100644
--- a/crates/host-core/src/session_worktrees/delegate.rs
+++ b/crates/host-core/src/session_worktrees/delegate.rs
@@ -23,10 +23,12 @@ use super::lifecycle::{
discard_failed_creation, ensure_branch_free, env_for, missing_error, port_is_free, run_setup,
setup_command, short_id, unmerged_commits, SharedState, WorktreeSummary,
};
-use super::merge::{self, commit_all, commits_ahead, land, merge_in_progress};
+use super::merge::{self, commit_all, commits_ahead, ensure_own_branch, land, merge_in_progress};
use super::probe::BRANCH_NAMESPACE;
use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};
-use super::remove::{drop_admin_entry, is_real_dir, is_real_dir_chain, remove_worktree};
+use super::remove::{
+ drop_admin_entry, is_real_dir, is_real_dir_chain, remove_entry, remove_worktree,
+};
use super::{repo_lock, WorktreeError};
use crate::db::Database;
use crate::sessions;
@@ -154,6 +156,8 @@ async fn checkpoint_session(
"the session has an unfinished merge conflict; resolve it first",
));
}
+ // A branch the parent switched to never receives the checkpoint.
+ ensure_own_branch(git, session).await?;
commit_all(git, root, message).await?;
Ok(hold)
}
@@ -227,6 +231,11 @@ pub async fn create_delegate_worktree(
}
return Ok(summary(&row));
}
+ // The registered folder was replaced by a link: drop that entry
+ // (never its target) so the branch can be re-attached there.
+ if std::fs::symlink_metadata(&row.path).is_ok() {
+ remove_entry(Path::new(&row.path))?;
+ }
if let Some(row) = reattach(state, git, &session, row.clone()).await? {
return Ok(summary(&row));
}
@@ -385,6 +394,7 @@ pub async fn settle_delegate_worktree(
// An unfinished merge is concluded by `land` once its markers are gone;
// committing it here could seal unresolved conflict markers.
if !resolving {
+ ensure_own_branch(git, &row).await?;
commit_all(git, worktree, "pi: subagent changes").await?;
}
let commits = commits_ahead(git, &row).await?;
diff --git a/crates/host-core/src/session_worktrees/delegate/tests.rs b/crates/host-core/src/session_worktrees/delegate/tests.rs
index 7ed6894b2..88c5e8de0 100644
--- a/crates/host-core/src/session_worktrees/delegate/tests.rs
+++ b/crates/host-core/src/session_worktrees/delegate/tests.rs
@@ -6,7 +6,7 @@ use tokio::sync::Mutex;
use super::*;
use crate::session_worktrees::lifecycle::{self, create_session_worktree};
-use crate::session_worktrees::test_support::{git_cmd, init_repo};
+use crate::session_worktrees::test_support::{git_cmd, init_repo, link_dir};
use crate::state::AppState;
struct Env {
@@ -343,3 +343,60 @@ async fn subagent_branches_do_not_hide_session_work_when_the_owner_is_gone() {
.unwrap();
assert!(pending.unmerged_commits >= 1, "{pending:?}");
}
+
+/// The parent switched its worktree to another branch: no checkpoint lands
+/// on that branch, no subagent worktree is created, and a subagent whose own
+/// worktree was switched is not committed or merged either.
+#[tokio::test]
+async fn a_switched_branch_never_receives_a_subagent_checkpoint() {
+ let env = env().await;
+ let a = env.create("chain-a").await;
+ fs::write(a.join("sub.txt"), "sub").unwrap();
+ git_cmd(&a, &["checkout", "-q", "-b", "sub-side"]);
+ let kept = settle_delegate_worktree(&env.state, &env.git, &env.session, "chain-a", true)
+ .await
+ .unwrap_err();
+ assert_eq!(kept.code, "WORKTREE_SESSION_BRANCH_CHANGED");
+ assert_eq!(git_cmd(&a, &["status", "--porcelain"]).trim(), "?? sub.txt");
+
+ git_cmd(&env.session_root, &["checkout", "-q", "-b", "side"]);
+ fs::write(env.session_root.join("parent.txt"), "draft").unwrap();
+ let error = create_delegate_worktree(&env.state, &env.git, &env.session, "chain-b")
+ .await
+ .unwrap_err();
+ assert_eq!(error.code, "WORKTREE_SESSION_BRANCH_CHANGED");
+ assert_eq!(
+ git_cmd(&env.session_root, &["status", "--porcelain"]).trim(),
+ "?? parent.txt"
+ );
+ assert!(env.row("chain-b").await.is_none());
+}
+
+/// A subagent folder replaced by a link (a junction on Windows) is not used;
+/// a resume drops the link, never its target, and re-attaches the branch.
+#[tokio::test]
+async fn a_subagent_folder_replaced_by_a_link_is_reattached_without_its_target() {
+ let env = env().await;
+ let a = env.create("chain-a").await;
+ fs::write(a.join("g.txt"), "committed").unwrap();
+ git_cmd(&a, &["add", "g.txt"]);
+ git_cmd(&a, &["commit", "-q", "-m", "subagent work"]);
+ let outside = env._dir.path().join("user-folder");
+ fs::create_dir_all(&outside).unwrap();
+ fs::write(outside.join("KEEP_ME.txt"), "keep").unwrap();
+ crate::session_worktrees::remove::clear_contents(&a).unwrap();
+ fs::remove_dir_all(&a).unwrap();
+ link_dir(&outside, &a);
+
+ assert_eq!(
+ tool_root(&env.state.lock().await.db, &env.session, Some("chain-a"))
+ .unwrap_err()
+ .code,
+ "WORKTREE_MISSING"
+ );
+ assert_eq!(env.create("chain-a").await, a);
+ assert!(fs::symlink_metadata(&a).unwrap().is_dir());
+ assert_eq!(read(&a.join("g.txt")), "committed");
+ assert_eq!(read(&outside.join("KEEP_ME.txt")), "keep");
+ assert!(!outside.join("g.txt").exists());
+}
diff --git a/crates/host-core/src/session_worktrees/lifecycle.rs b/crates/host-core/src/session_worktrees/lifecycle.rs
index 7e46a4b92..1c7a5c4bd 100644
--- a/crates/host-core/src/session_worktrees/lifecycle.rs
+++ b/crates/host-core/src/session_worktrees/lifecycle.rs
@@ -566,6 +566,11 @@ pub async fn merge_session(
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?;
+ // Checked again now that nothing of the session can run: the folder may
+ // have been replaced while this waited for the locks.
+ if !is_real_dir(Path::new(&target.row.path)) {
+ return Err(missing_error());
+ }
let result = merge::merge(
git,
&target.row,
@@ -680,6 +685,9 @@ pub async fn sync_session(
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?;
+ if !is_real_dir(Path::new(&target.row.path)) {
+ return Err(missing_error());
+ }
let result =
merge::sync_from_owner(git, &target.row, &merge::commit_message(&target.title)).await;
let status = match &result {
@@ -729,8 +737,9 @@ pub async fn refresh_conflict_status(
match settled {
Ok(true) => {
let st = state.lock().await;
- match registry::set_status(&st.db, &row.id, WorktreeStatus::Active) {
- Ok(_) => true,
+ match registry::clear_conflict(&st.db, &row.id) {
+ // `false` when a concurrent merge or sync changed it meanwhile.
+ Ok(cleared) => cleared,
Err(error) => {
tracing::warn!(%error, "could not clear the worktree conflict status");
false
diff --git a/crates/host-core/src/session_worktrees/merge.rs b/crates/host-core/src/session_worktrees/merge.rs
index c484cca46..a7a3295a7 100644
--- a/crates/host-core/src/session_worktrees/merge.rs
+++ b/crates/host-core/src/session_worktrees/merge.rs
@@ -262,7 +262,10 @@ async fn ensure_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> {
+pub(super) 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(());
}
@@ -295,10 +298,11 @@ async fn rev_parse(git: &GitRunner, dir: &Path, rev: &str) -> Result<String, Wor
.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.
+/// After the fast-forward: the owner branch, still checked out in the owner
+/// checkout, must now contain the commit that was checked. 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. A commit
+/// made on the owner branch right after the merge still counts as landed.
async fn verify_landed(
git: &GitRunner,
owner_checkout: &Path,
@@ -306,7 +310,19 @@ async fn verify_landed(
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 {
+ let contained = git
+ .output(
+ owner_checkout,
+ &[
+ "merge-base",
+ "--is-ancestor",
+ landing,
+ &head_ref(&row.owner_branch),
+ ],
+ )
+ .await?
+ .success();
+ if contained {
return Ok(());
}
Err(WorktreeError::new(
diff --git a/crates/host-core/src/session_worktrees/merge/tests.rs b/crates/host-core/src/session_worktrees/merge/tests.rs
index 61ce1b9c5..03edcab7b 100644
--- a/crates/host-core/src/session_worktrees/merge/tests.rs
+++ b/crates/host-core/src/session_worktrees/merge/tests.rs
@@ -485,4 +485,9 @@ async fn a_landing_on_a_switched_target_is_reported() {
verify_landed(&git, &f.repo, &f.row, &landing)
.await
.unwrap();
+ // A commit made on the project right after the merge still counts.
+ git_cmd(&f.repo, &["commit", "-q", "--allow-empty", "-m", "after"]);
+ 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 dfe43f496..b796e86bc 100644
--- a/crates/host-core/src/session_worktrees/registry.rs
+++ b/crates/host-core/src/session_worktrees/registry.rs
@@ -245,6 +245,17 @@ pub fn set_status(db: &Database, id: &str, status: WorktreeStatus) -> Result<boo
)? > 0)
}
+/// Clear a `conflict` status back to `active`, only if it is still
+/// `conflict`: a check that ran without the repo lock never overwrites a
+/// status a concurrent merge or sync set meanwhile.
+pub fn clear_conflict(db: &Database, id: &str) -> Result<bool> {
+ Ok(db.conn().execute(
+ "UPDATE worktrees SET status = 'active', updated_at = ?2
+ WHERE id = ?1 AND status = 'conflict'",
+ params![id, now_ms()],
+ )? > 0)
+}
+
pub fn set_setup_status(
db: &Database,
id: &str,
@@ -360,6 +371,27 @@ mod tests {
assert_eq!(orphaned[0].session_id, None);
}
+ /// The conflict check runs without the repo lock: clearing a conflict
+ /// never overwrites a status a merge or sync set in the meantime.
+ #[test]
+ fn clearing_a_conflict_leaves_any_newer_status_alone() {
+ let (_dir, db, session) = db_with_session();
+ let row = insert(&db, &new(&session, None, "/w/own")).unwrap();
+ set_status(&db, &row.id, WorktreeStatus::Conflict).unwrap();
+ assert!(clear_conflict(&db, &row.id).unwrap());
+ assert_eq!(
+ get(&db, &row.id).unwrap().unwrap().status,
+ WorktreeStatus::Active
+ );
+
+ set_status(&db, &row.id, WorktreeStatus::Merged).unwrap();
+ assert!(!clear_conflict(&db, &row.id).unwrap());
+ assert_eq!(
+ get(&db, &row.id).unwrap().unwrap().status,
+ WorktreeStatus::Merged
+ );
+ }
+
#[test]
fn port_blocks_skip_held_and_busy_bases() {
let (_dir, db, session) = db_with_session();
diff --git a/crates/host-core/src/session_worktrees/remove.rs b/crates/host-core/src/session_worktrees/remove.rs
index 9d3b2e142..676eb36f8 100644
--- a/crates/host-core/src/session_worktrees/remove.rs
+++ b/crates/host-core/src/session_worktrees/remove.rs
@@ -54,7 +54,7 @@ pub fn clear_contents(root: &Path) -> io::Result<()> {
Ok(())
}
-fn remove_entry(path: &Path) -> io::Result<()> {
+pub(super) fn remove_entry(path: &Path) -> io::Result<()> {
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
remove_link(path, &metadata)