Python
Sessions whose worktree was removed reopen in the repo root
Rohit C Prasadd5c802d57a1f
diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 32269ef0..549cbad7 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -3262,6 +3262,9 @@ def create_app(manager: SessionManager) -> FastAPI:manager.inbox.resolve(pend[0].id, resolution, by=viewer_actor)workspace = ws.query_params.get("workspace")+ # A feature worktree that no longer exists (archive cleanup, a hand delete) means+ # the repo root — never a "no valid workspace" close the client would retry forever.+ workspace = manager.resolve_missing_worktree(session_id, workspace)mcp_tools = await manager.prepare_mcp_tools(session_id, workspace=workspace, agent=agent)diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 5c520a01..c92cb5ce 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -6025,7 +6025,14 @@ class SessionManager:return {"ok": False, "error": "this session is already inside a feature worktree"}settings = self.worktree_settings(str(root))try:- info = wt.create_worktree(root, task, settings)+ # A session resumed after cleanup gets its own branch back, not a fresh one.+ if existing.get("removed") and existing.get("branch"):+ try:+ info = wt.reattach_worktree(root, existing, settings)+ except wt.WorktreeError:+ info = wt.create_worktree(root, task, settings)+ else:+ info = wt.create_worktree(root, task, settings)except wt.WorktreeError as exc:return {"ok": False, "error": str(exc)}resolved = Path(info["path"]).resolve()@@ -6106,14 +6113,43 @@ class SessionManager:record = record if record is not None else self.session_store.load(session_id)info = (record.worktree if record else {}) or {}path, root = str(info.get("path") or ""), str(info.get("repo_root") or "")- if not path or not root:+ if not path or not root or info.get("removed"):returnif not self.worktree_settings(root).cleanup_on_archive:returntry:- wt.remove_worktree(root, path) # False when dirty: left alone on purpose+ removed = wt.remove_worktree(root, path) # False when dirty: left alone on purposeexcept Exception:- pass+ removed = False+ if removed:+ self._mark_worktree_removed(record, info)++ def _mark_worktree_removed(self, record, info: dict[str, Any]) -> None:+ """The folder is gone (cleanup, or the person deleted it): the session lives in the+ repo root again, remembers its branch, and any live engine is dropped so the next+ connect rebuilds there instead of in a folder that no longer exists."""+ root = str(info.get("repo_root") or "")+ if record is not None and root:+ record.workspace = root+ self.session_store.save(record, touch=False)+ self.session_store.set_worktree(record.session_id, {**info, "removed": True})+ self._drop_engine(record.session_id)++ def resolve_missing_worktree(self, session_id: str, workspace: Optional[str]) -> Optional[str]:+ """Called when a session socket opens: a workspace that was this session's feature+ worktree and no longer exists becomes the repo root (and the record is repaired), so+ a reopened session connects instead of failing "no valid workspace" forever."""+ record = self.session_store.load(session_id)+ info = (record.worktree if record else {}) or {}+ path, root = str(info.get("path") or ""), str(info.get("repo_root") or "")+ if not path or not root or Path(path).is_dir() or not Path(root).is_dir():+ return workspace+ asked = workspace or (record.workspace if record else "")+ if not asked or Path(asked) != Path(path):+ return workspace+ if not info.get("removed") or (record and record.workspace == path):+ self._mark_worktree_removed(record, info)+ return rootdef set_scratch_base(self, path: str) -> dict[str, Any]:"""Set + persist the common area where each Cowork conversation's scratch directory isdiff --git a/coworker/worktrees.py b/coworker/worktrees.pyindex e3e04fae..3ffa96f1 100644--- a/coworker/worktrees.py+++ b/coworker/worktrees.py@@ -234,20 +234,7 @@ def create_worktree(root: Path, task: str, s: WorktreeSettings) -> dict[str, Anyraise WorktreeError(f"git could not create the worktree: {err.strip()[:200]}")if s.location == "in_repo":ensure_excluded(root)- setup: Optional[dict[str, Any]] = None- if s.setup_command:- try:- proc = subprocess.run(- s.setup_command, shell=True, cwd=str(path), capture_output=True, text=True,- timeout=_SETUP_TIMEOUT_S, env={**os.environ},- )- tail = (proc.stdout + proc.stderr)[-1500:]- setup = {"command": s.setup_command, "exit_code": proc.returncode, "output": tail}- if proc.returncode != 0:- warnings.append(f"the setup command exited {proc.returncode}")- except subprocess.TimeoutExpired:- setup = {"command": s.setup_command, "exit_code": None, "output": "timed out"}- warnings.append("the setup command timed out")+ setup = _run_setup(path, s, warnings)return {"path": str(path),"branch": branch,@@ -262,6 +249,54 @@ def create_worktree(root: Path, task: str, s: WorktreeSettings) -> dict[str, Any}+def reattach_worktree(root: Path, previous: dict[str, Any], s: WorktreeSettings) -> dict[str, Any]:+ """A session resumed after its worktree was removed (archive cleanup) gets the SAME+ branch back in a fresh worktree — its commits are still there; only the folder went."""+ branch = str(previous.get("branch") or "")+ if not branch or not _branch_exists(root, branch):+ raise WorktreeError(f"branch {branch or '?'} no longer exists")+ warnings: list[str] = []+ slug = Path(str(previous.get("path") or branch.rsplit("/", 1)[-1])).name+ path = plan_path(root, slug, s)+ if path.exists():+ _, path = _unique(root, "", path)+ path.parent.mkdir(parents=True, exist_ok=True)+ _, err = _git(["-C", str(root), "worktree", "add", str(path), branch], timeout=_FETCH_TIMEOUT_S)+ if err:+ raise WorktreeError(f"git could not re-create the worktree: {err.strip()[:200]}")+ if s.location == "in_repo":+ ensure_excluded(root)+ setup = _run_setup(path, s, warnings)+ return {+ **{k: previous[k] for k in ("base", "start", "fetched") if k in previous},+ "path": str(path),+ "branch": branch,+ "repo_root": str(root),+ "location": s.location,+ "created": time.time(),+ "reattached": True,+ "setup": setup,+ "warnings": warnings,+ }+++def _run_setup(path: Path, s: WorktreeSettings, warnings: list[str]) -> Optional[dict[str, Any]]:+ if not s.setup_command:+ return None+ try:+ proc = subprocess.run(+ s.setup_command, shell=True, cwd=str(path), capture_output=True, text=True,+ timeout=_SETUP_TIMEOUT_S, env={**os.environ},+ )+ tail = (proc.stdout + proc.stderr)[-1500:]+ if proc.returncode != 0:+ warnings.append(f"the setup command exited {proc.returncode}")+ return {"command": s.setup_command, "exit_code": proc.returncode, "output": tail}+ except subprocess.TimeoutExpired:+ warnings.append("the setup command timed out")+ return {"command": s.setup_command, "exit_code": None, "output": "timed out"}++def is_clean(path: str | Path) -> bool:"""No uncommitted changes and no untracked files — the only state a worktree may beremoved in without the person's say-so."""diff --git a/tests/test_start_worktree.py b/tests/test_start_worktree.pyindex 9113abc1..235fb1ba 100644--- a/tests/test_start_worktree.py+++ b/tests/test_start_worktree.py@@ -102,6 +102,40 @@ def test_archive_removes_a_clean_worktree_but_keeps_a_dirty_one(tmp_path, repo,# The branch is still there.out = subprocess.run(["git", "branch", "--list", res["branch"]], cwd=repo, capture_output=True, text=True).stdoutassert res["branch"] in out+ # The session lives in the repo root again (no "no valid workspace" loop on reopen),+ # remembers its branch, and its engine was dropped so the next connect rebuilds.+ record = mgr.session_store.load(sid)+ assert Path(record.workspace) == repo+ assert record.worktree["removed"] is True and record.worktree["branch"] == res["branch"]+ assert sid not in mgr._engines+++def test_a_resumed_session_gets_its_branch_back(tmp_path, repo, monkeypatch):+ mgr, sid, engine = _manager_with_session(tmp_path, repo, monkeypatch)+ first = mgr.start_worktree(sid, "resume me")+ subprocess.run(["git", "commit", "-q", "--allow-empty", "-m", "wip"], cwd=first["path"], check=True)+ mgr.set_session_flags(sid, archived=True)+ assert not Path(first["path"]).exists()+ # Back in the repo root; the next start_worktree reattaches the same branch.+ mgr._engines[sid] = engine+ engine.executor.cwd = str(repo)+ again = mgr.start_worktree(sid, "something else entirely")+ assert again["ok"] and again.get("reattached") and again["branch"] == first["branch"]+ assert Path(again["path"]).is_dir()+ log = subprocess.run(["git", "log", "--oneline", "-1"], cwd=again["path"], capture_output=True, text=True).stdout+ assert "wip" in log+++def test_connect_repairs_a_session_whose_worktree_folder_vanished(tmp_path, repo, monkeypatch):+ mgr, sid, engine = _manager_with_session(tmp_path, repo, monkeypatch)+ res = mgr.start_worktree(sid, "vanishing act")+ subprocess.run(["git", "worktree", "remove", "--force", res["path"]], cwd=repo, check=True)+ # The GUI asks for the folder it last knew; the server answers with the repo root.+ assert Path(mgr.resolve_missing_worktree(sid, res["path"])) == repo+ record = mgr.session_store.load(sid)+ assert Path(record.workspace) == repo and record.worktree["removed"] is True+ # An unrelated workspace request is left alone.+ assert mgr.resolve_missing_worktree(sid, str(tmp_path)) == str(tmp_path)def test_worktree_settings_round_trip_and_repo_override(tmp_path, repo):