The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): make git worktrees work end-to-end on a remote gateway backend
Tekniumf8f43c95237c
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 63a3fc21a1a..c91a5f7e292 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1634,6 +1634,8 @@ export const ar = defineLocale({newWorktreeDesc: 'سمِّ الفرع لشجرة العمل هذه.',branchPlaceholder: 'مثال: my-feature',startWorkFailed: 'تعذّر إنشاء شجرة العمل',+ worktreeStaleBackend:+ 'حدِّث خادم Hermes لإنشاء أشجار العمل عبر هذا الاتصال البعيد — فهو أقدم من واجهة git worktree.',worktreeProjectLabel: 'المشروع',worktreeProjectPlaceholder: 'ابحث في المشاريع…',worktreeProjectNone: 'لا توجد مشاريع بمجلد',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 66d43c7816f..6334551bc9d 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -2041,6 +2041,8 @@ export const en: Translations = {baseBranchPlaceholder: 'Search branches…',baseBranchNone: 'No branches found',startWorkFailed: 'Could not create worktree',+ worktreeStaleBackend:+ 'Update the Hermes backend to create worktrees over this remote connection — it predates the git worktree API.',worktreeProjectLabel: 'Project',worktreeProjectPlaceholder: 'Search projects…',worktreeProjectNone: 'No projects with a folder',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex b8679913162..3aac0e835aa 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -1799,6 +1799,8 @@ export const ja = defineLocale({baseBranchPlaceholder: 'ブランチを検索…',baseBranchNone: 'ブランチが見つかりません',startWorkFailed: 'ワークツリーを作成できませんでした',+ worktreeStaleBackend:+ 'このリモート接続でワークツリーを作成するには Hermes バックエンドを更新してください — git ワークツリー API 以前のバージョンです。',worktreeProjectLabel: 'プロジェクト',worktreeProjectPlaceholder: 'プロジェクトを検索…',worktreeProjectNone: 'フォルダのあるプロジェクトがありません',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex d72ed6e6ce7..56f7fdff286 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1722,6 +1722,7 @@ export interface Translations {baseBranchPlaceholder: stringbaseBranchNone: stringstartWorkFailed: string+ worktreeStaleBackend: stringworktreeProjectLabel: stringworktreeProjectPlaceholder: stringworktreeProjectNone: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 6ffb40f36db..e99fefd40d1 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -1738,6 +1738,7 @@ export const zhHant = defineLocale({baseBranchPlaceholder: '搜尋分支…',baseBranchNone: '未找到分支',startWorkFailed: '無法建立工作樹',+ worktreeStaleBackend: '請更新 Hermes 後端以在此遠端連線上建立工作樹 —— 該後端早於 git 工作樹 API。',worktreeProjectLabel: '專案',worktreeProjectPlaceholder: '搜尋專案…',worktreeProjectNone: '沒有包含資料夾的專案',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex aabc8411400..bc0289f55b5 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2227,6 +2227,7 @@ export const zh: Translations = {baseBranchPlaceholder: '搜索分支…',baseBranchNone: '未找到分支',startWorkFailed: '无法创建工作树',+ worktreeStaleBackend: '请更新 Hermes 后端以在此远程连接上创建工作树 —— 该后端早于 git 工作树 API。',worktreeProjectLabel: '项目',worktreeProjectPlaceholder: '搜索项目…',worktreeProjectNone: '没有包含文件夹的项目',diff --git a/apps/desktop/src/lib/desktop-git.test.ts b/apps/desktop/src/lib/desktop-git.test.tsindex 68b0b23ed0a..a9452766011 100644--- a/apps/desktop/src/lib/desktop-git.test.ts+++ b/apps/desktop/src/lib/desktop-git.test.ts@@ -21,6 +21,12 @@ const api = vi.fn(async ({ path }: { path: string }) => {return { diff: 'remote-diff' }}+ if (path.startsWith('/api/git/branches')) {+ return {+ branches: [{ checkedOut: false, isDefault: false, isRemote: true, name: 'origin/feature', worktreePath: null }]+ }+ }+return { ok: true }})@@ -96,4 +102,25 @@ describe('desktop git facade', () => {})expect(localGit.review.stage).not.toHaveBeenCalled()})++ // The ⌘⇧B "convert a branch into a worktree" flow (#81724): on a remote+ // gateway both halves must reach the backend mirror — the picker's branch+ // list (which now carries remote-tracking refs) and the worktree add that+ // receives the picked `origin/…` name.+ it('routes the convert-a-branch worktree flow through the backend on a remote gateway', async () => {+ $connection.set({ mode: 'remote' } as never)++ await expect(desktopGit()?.branchList('/srv/work')).resolves.toEqual([+ { checkedOut: false, isDefault: false, isRemote: true, name: 'origin/feature', worktreePath: null }+ ])+ expect(api).toHaveBeenCalledWith({ path: '/api/git/branches?path=%2Fsrv%2Fwork' })++ await desktopGit()?.worktreeAdd('/srv/work', { existingBranch: 'origin/feature' })++ expect(api).toHaveBeenCalledWith({+ body: { existingBranch: 'origin/feature', path: '/srv/work' },+ method: 'POST',+ path: '/api/git/worktree/add'+ })+ })})diff --git a/apps/desktop/src/lib/desktop-git.ts b/apps/desktop/src/lib/desktop-git.tsindex 98f41fbf87e..0009900b722 100644--- a/apps/desktop/src/lib/desktop-git.ts+++ b/apps/desktop/src/lib/desktop-git.ts@@ -115,3 +115,20 @@ export function desktopGit(): GitBridge | undefined {return isDesktopFsRemoteMode() ? remoteGit : window.hermesDesktop?.git}++// True only for "the /api/git route does not exist on this backend" shapes:+// the backend catch-all ('404: {"detail":"No such API endpoint: ...}'), a bare+// FastAPI 404 (directly or through the IPC bridge's "Error invoking remote+// method" wrapper), and the Electron JSON-guard ("endpoint is likely+// missing"). Transient failures (timeouts, 5xx, connection refused) must NOT+// match — they are retryable, not a capability verdict. Mirrors the sidebar+// batch-endpoint detector in hermes.ts.+export function isGitEndpointMissingError(err: unknown): boolean {+ const message = err instanceof Error ? err.message : String(err)++ return (+ /no such api endpoint/i.test(message) ||+ /endpoint is likely missing/i.test(message) ||+ /(?:^\s*|error:\s*)404\b/i.test(message)+ )+}diff --git a/apps/desktop/src/store/coding-status.ts b/apps/desktop/src/store/coding-status.tsindex 9c725f963a9..4b40bf257ec 100644--- a/apps/desktop/src/store/coding-status.ts+++ b/apps/desktop/src/store/coding-status.ts@@ -94,8 +94,9 @@ export function repoStatusForCwd(cwd?: null | string): ReadableAtom<HermesRepoSt* Is this path a git repo? This function reads the probe cache, and probes on* demand when the cache has no entry for the path. Use it to validate any repo* that was picked out of candidate FOLDERS: a path in a project row is not- * evidence that git can branch from it. False on a remote backend, because- * there is no local git truth to probe.+ * evidence that git can branch from it. On a remote gateway the probe is+ * backend-routed (`desktopGit()` returns the REST mirror), so a VPS path is+ * judged by the VPS's git — not by this machine's filesystem (#81724).*/export async function isGitRepoPath(cwd: string): Promise<boolean> {const key = normalizeCwd(cwd)diff --git a/apps/desktop/src/store/projects.test.ts b/apps/desktop/src/store/projects.test.tsindex 304c09683fd..9bdf9734c09 100644--- a/apps/desktop/src/store/projects.test.ts+++ b/apps/desktop/src/store/projects.test.ts@@ -29,6 +29,7 @@ import {refreshWorktrees,resolveNewSessionCwd,scanAndRecordRepos,+ startWorkInRepo,tombstoneSessions} from './projects'@@ -53,7 +54,10 @@ vi.mock('@/store/gateway', () => ({ensureActiveGatewayOpen: vi.fn()}))-vi.mock('@/lib/desktop-git', () => ({ desktopGit: vi.fn() }))+vi.mock('@/lib/desktop-git', async importOriginal => ({+ ...((await importOriginal()) as Record<string, unknown>),+ desktopGit: vi.fn()+}))vi.mock('@/hermes', () => ({getHermesConfig: vi.fn(),@@ -274,6 +278,33 @@ describe('worktree refresh', () => {})})+describe('startWorkInRepo remote capability gate (#81724)', () => {+ it('names the stale-backend remedy when a remote gateway lacks the worktree route', async () => {+ isDesktopFsRemoteMode.mockReturnValue(true)+ desktopGit.mockReturnValue({+ worktreeAdd: vi.fn(async () => {+ throw new Error('Expected JSON from https://vps/api/git/worktree/add but got HTML (status 404). The endpoint is likely missing on the Hermes backend.')+ })+ } as never)++ // The i18n mock echoes keys, so the surfaced error is the catalog key.+ await expect(startWorkInRepo('/srv/repo', { branch: 'x' })).rejects.toThrow(+ 'sidebar.projects.worktreeStaleBackend'+ )+ })++ it('re-throws real git failures untouched (a remote 400 is not a capability verdict)', async () => {+ isDesktopFsRemoteMode.mockReturnValue(true)+ desktopGit.mockReturnValue({+ worktreeAdd: vi.fn(async () => {+ throw new Error("400: fatal: 'stale' is not a commit")+ })+ } as never)++ await expect(startWorkInRepo('/srv/repo', { branch: 'x' })).rejects.toThrow("not a commit")+ })+})+describe('pickProjectFolder', () => {beforeEach(() => {vi.clearAllMocks()diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.tsindex a810eb7b0ee..c0c1a9cfcea 100644--- a/apps/desktop/src/store/projects.ts+++ b/apps/desktop/src/store/projects.ts@@ -9,7 +9,7 @@ import type { HermesGitBaseBranch, HermesGitBranch } from '@/global'import { getHermesConfig, type HermesGateway } from '@/hermes'import { translateNow } from '@/i18n'import { desktopDefaultCwd, isDesktopFsRemoteMode, selectDesktopPaths, writeDesktopFileText } from '@/lib/desktop-fs'-import { desktopGit } from '@/lib/desktop-git'+import { desktopGit, isGitEndpointMissingError } from '@/lib/desktop-git'import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { isUnderPath } from '@/lib/path-compare'import { persistentAtom } from '@/lib/persisted'@@ -1074,7 +1074,22 @@ export async function startWorkInRepo(return null}- const result = await git.worktreeAdd(repoPath, options)+ let result++ try {+ result = await git.worktreeAdd(repoPath, options)+ } catch (err) {+ // Capability gate (#81724): a remote gateway serves worktree ops via the+ // backend's /api/git mirror, and an older backend may predate it. The raw+ // failure ("Expected JSON … but got HTML" / a bare 404) reads like a git+ // error — name the real remedy instead of degrading silently.+ if (isDesktopFsRemoteMode() && isGitEndpointMissingError(err)) {+ throw new Error(translateNow('sidebar.projects.worktreeStaleBackend'))+ }++ throw err+ }+bumpWorktrees()return { branch: result.branch, path: result.path }@@ -1084,7 +1099,8 @@ export async function startWorkInRepo(// local heads, plus the remote-tracking refs that have no local branch yet. A// teammate's branch is therefore reachable, and the user does not check it out// by hand first.-// Empty on a remote backend or a non-repo, where the Electron probe cannot run.+// Empty on a non-repo. On a remote gateway the list comes from the backend's+// /api/git/branches mirror, so it acts on the repo where sessions actually run.export async function listRepoBranches(repoPath: string): Promise<HermesGitBranch[]> {const git = desktopGit()@@ -1097,7 +1113,8 @@ export async function listRepoBranches(repoPath: string): Promise<HermesGitBranc// Local + remote-tracking branches for the base-branch picker in the// new-worktree dialog. The remote default (origin/HEAD) is flagged so the-// UI can preselect it. Empty on a remote backend / non-repo.+// UI can preselect it. Empty on a non-repo; remote gateways serve it from the+// backend's /api/git/base-branches mirror.export async function listBaseBranches(repoPath: string): Promise<HermesGitBaseBranch[]> {const git = desktopGit()diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.pyindex 9b31d877c46..3ea3c77c02f 100644--- a/hermes_cli/web_git.py+++ b/hermes_cli/web_git.py@@ -682,19 +682,46 @@ def _unique_dir(base: str) -> str:return candidate+def _remote_of_ref(cwd: str, name: str) -> str:+ """The remote a ref belongs to ("origin" for "origin/main"), or "" when the+ name is not a remote-tracking ref in this repo. Asks git rather than+ assuming the remote is called "origin" (mirrors the Electron op)."""+ if "/" not in name:+ return ""+ code, _, _ = _git(cwd, ["show-ref", "--verify", "--quiet", f"refs/remotes/{name}"])+ if code != 0:+ return ""+ return name.split("/", 1)[0]++def worktree_add(cwd: str, options: dict) -> dict:_ensure_repo(cwd)root = _main_root(cwd)options = options or {}- existing = _sanitize_branch(options.get("existingBranch") or "")+ requested = _sanitize_branch(options.get("existingBranch") or "")if options.get("existingBranch"):- if not existing:+ if not requested:raise RuntimeError("Branch name is required.")- if existing == _default_branch(root):+ # "origin/feature" is a remote-tracking ref, not a branch git can check+ # out — `git worktree add <dir> origin/feature` detaches HEAD. Create a+ # local branch with the same short name that tracks the remote ref,+ # like `git switch feature` does for a branch on exactly one remote.+ # (Parity with the Electron op; a remote gateway serves this mirror, so+ # the desktop's convert-a-branch flow must behave identically. #81724)+ remote = _remote_of_ref(root, requested)+ existing = requested.split("/", 1)[1] if remote else requested+ if not remote and existing == _default_branch(root):_git_ok(root, ["switch", existing])return {"path": root, "branch": existing, "repoRoot": root}target = _unique_dir(os.path.join(root, ".worktrees", _slugify(existing)))+ if remote:+ # Best-effort freshness: the remote-tracking ref is stale if the+ # user did not fetch recently. On failure (offline, branch gone)+ # the last known ref is still there to branch from.+ _git(root, ["fetch", remote, existing])+ _git_ok(root, ["worktree", "add", "--track", "-b", existing, target, requested])+ return {"path": target, "branch": existing, "repoRoot": root}_git_ok(root, ["worktree", "add", target, existing])return {"path": target, "branch": existing, "repoRoot": root}@@ -711,6 +738,11 @@ def worktree_add(cwd: str, options: dict) -> dict:if base.startswith("origin/"):remote_branch = base[len("origin/"):]_git(root, ["fetch", "origin", remote_branch])+ # Branching off a remote-tracking ref auto-sets up tracking (the+ # new branch silently wired to origin's upstream). The user wants a+ # standalone local branch — like `git checkout origin/main && git+ # checkout -b new` — so suppress it (parity with the Electron op).+ args.append("--no-track")args.append(base)code, _, err = _git(root, args)if code != 0:@@ -732,6 +764,10 @@ def worktree_remove(cwd: str, worktree_path: str, force: bool) -> dict:def branch_list(cwd: str) -> list[dict]:+ """Branches for the convert-a-branch picker: local heads first, then the+ remote-tracking refs that have no local head yet (a teammate's branch is+ reachable without a manual checkout). Parity with the Electron op — a+ remote gateway serves this mirror for the same desktop UI (#81724)."""out = _git_out(cwd, ["for-each-ref", "--format=%(refname:short)", "--sort=-committerdate", "refs/heads"])@@ -740,15 +776,44 @@ def branch_list(cwd: str) -> list[dict]:trees = worktree_list(cwd)path_by_branch = {t["branch"]: t["path"] for t in trees if t["branch"]}trunk = _default_branch(cwd)- return [- {- "name": name,- "checkedOut": name in path_by_branch,- "isDefault": bool(trunk and name == trunk),- "worktreePath": path_by_branch.get(name),- }- for name in (line.strip() for line in out.split("\n"))+ locals_ = [name for name in (line.strip() for line in out.split("\n")) if name]+ local_set = set(locals_)+ remote_out = _git_out(+ cwd, ["for-each-ref", "--format=%(refname:short)", "--sort=-committerdate", "refs/remotes"]+ )+ remotes = [+ name+ for name in (line.strip() for line in remote_out.split("\n"))if name+ # "origin/HEAD" is a symbolic alias for the remote's default branch —+ # not a branch, and a duplicate row in the list.+ and not name.endswith("/HEAD")+ # A remote branch tracked locally is reachable via its local head; a+ # second row is noise, and checking out the remote ref detaches HEAD.+ and name.split("/", 1)[-1] not in local_set+ ]+ return [+ *(+ {+ "name": name,+ "checkedOut": name in path_by_branch,+ "isDefault": bool(trunk and name == trunk),+ "isRemote": False,+ "worktreePath": path_by_branch.get(name),+ }+ for name in locals_+ ),+ *(+ {+ # No local checkout, and never the local trunk.+ "name": name,+ "checkedOut": False,+ "isDefault": False,+ "isRemote": True,+ "worktreePath": None,+ }+ for name in remotes+ ),]diff --git a/tests/hermes_cli/test_web_server_git.py b/tests/hermes_cli/test_web_server_git.pyindex ab573e0d7da..752f76e74d5 100644--- a/tests/hermes_cli/test_web_server_git.py+++ b/tests/hermes_cli/test_web_server_git.py@@ -38,13 +38,13 @@ def repo(tmp_path):_git(root, "init", "-q")_git(root, "config", "user.email", "[email protected]")_git(root, "config", "user.name", "Test")- (root / "a.txt").write_text("one\ntwo\n")+ (root / "a.txt").write_text("one\ntwo\n", encoding="utf-8")_git(root, "add", "-A")_git(root, "commit", "-qm", "init")# A tracked modification + a brand-new untracked file (the new-file case the# rail/review must surface).- (root / "a.txt").write_text("one\ntwo\nthree\n")- (root / "new.py").write_text("print(1)\nprint(2)\n")+ (root / "a.txt").write_text("one\ntwo\nthree\n", encoding="utf-8")+ (root / "new.py").write_text("print(1)\nprint(2)\n", encoding="utf-8")return root@@ -78,7 +78,7 @@ def test_stage_commit_roundtrip_clears_changes(client, repo):def test_worktree_add_initializes_plain_folder(client, tmp_path):folder = tmp_path / "plain-project"folder.mkdir()- (folder / "notes.txt").write_text("not committed\n")+ (folder / "notes.txt").write_text("not committed\n", encoding="utf-8")added = client.post("/api/git/worktree/add", json={"path": str(folder), "branch": "feature/plain"}@@ -103,3 +103,94 @@ def test_git_endpoints_require_auth(repo):assert unauth.get("/api/git/status", params={"path": str(repo)}).status_code == 401assert unauth.post("/api/git/review/stage", json={"path": str(repo)}).status_code == 401+++# ── remote-gateway worktree parity (#81724) ─────────────────────────────────+# The desktop's Electron git ops learned remote-branch conversion and+# no-upstream-tracking base branching; the backend REST mirror (what a remote+# gateway serves) must behave identically or worktree flows break exactly and+# only on remote connections.+++def repo_with_remote(tmp_path):+ """A committed repo with an `origin` remote carrying main + a feature+ branch that has NO local head (the teammate-branch case)."""+ origin = tmp_path / "origin.git"+ origin.mkdir()+ subprocess.run(["git", "init", "-q", "--bare", str(origin)], check=True, capture_output=True)++ root = tmp_path / "clone"+ root.mkdir()+ _git(root, "init", "-q", "-b", "main")+ _git(root, "config", "user.email", "[email protected]")+ _git(root, "config", "user.name", "Test")+ (root / "a.txt").write_text("one\n", encoding="utf-8")+ _git(root, "add", "-A")+ _git(root, "commit", "-qm", "init")+ _git(root, "remote", "add", "origin", str(origin))+ _git(root, "push", "-q", "origin", "main")+ _git(root, "branch", "feature")+ _git(root, "push", "-q", "origin", "feature")+ _git(root, "branch", "-D", "feature")+ _git(root, "fetch", "-q", "origin")+ return root+++def test_branches_include_remote_tracking_refs(client, repo_with_remote):+ branches = client.get(+ "/api/git/branches", params={"path": str(repo_with_remote)}+ ).json()["branches"]+ by_name = {branch["name"]: branch for branch in branches}++ # A teammate's branch (no local head) is reachable, flagged as remote.+ assert "origin/feature" in by_name+ assert by_name["origin/feature"]["isRemote"] is True+ assert by_name["origin/feature"]["checkedOut"] is False+ assert by_name["origin/feature"]["worktreePath"] is None++ # Locals carry the flag too, and shadowed remotes/HEAD aliases are noise.+ assert by_name["main"]["isRemote"] is False+ assert "origin/main" not in by_name+ assert all(not branch["name"].endswith("/HEAD") for branch in branches)+++def test_worktree_add_existing_remote_branch_tracks_not_detaches(client, repo_with_remote):+ added = client.post(+ "/api/git/worktree/add",+ json={"path": str(repo_with_remote), "existingBranch": "origin/feature"},+ ).json()++ # A remote-tracking ref cannot be checked out directly — the mirror must+ # create the local tracking branch, like `git switch feature` would.+ assert added["branch"] == "feature"+ tree = Path(added["path"])+ assert tree.is_dir()++ head = subprocess.run(+ ["git", "symbolic-ref", "--short", "HEAD"],+ cwd=tree, check=True, capture_output=True, text=True,+ ).stdout.strip()+ assert head == "feature" # NOT detached++ upstream = subprocess.run(+ ["git", "rev-parse", "--abbrev-ref", "feature@{upstream}"],+ cwd=tree, check=True, capture_output=True, text=True,+ ).stdout.strip()+ assert upstream == "origin/feature"+++def test_worktree_add_from_origin_base_does_not_track(client, repo_with_remote):+ added = client.post(+ "/api/git/worktree/add",+ json={"path": str(repo_with_remote), "branch": "fresh", "base": "origin/main"},+ ).json()+ assert added["branch"] == "fresh"++ # Branching off origin/main must yield a standalone local branch, not one+ # silently wired to the remote's upstream (parity with the Electron op).+ probe = subprocess.run(+ ["git", "rev-parse", "--abbrev-ref", "fresh@{upstream}"],+ cwd=repo_with_remote, capture_output=True, text=True,+ )+ assert probe.returncode != 0