git.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. """Git dashboard routes — the remote half of the desktop coding rail + review pane.
  2. The desktop runs these as Electron-local git; over a remote gateway that's the wrong
  3. filesystem, so they are mirrored here with the same auth gate + path hardening as
  4. /api/fs. Logic lives in ``hermes_cli.web_git``; these are thin executor-offloaded
  5. wrappers (git/gh can block).
  6. """
  7. import asyncio
  8. import shutil
  9. import time
  10. from functools import partial
  11. from pathlib import Path
  12. from typing import Optional
  13. from fastapi import APIRouter, HTTPException, Request
  14. from hermes_cli import web_git as _web_git
  15. from hermes_cli._subprocess_compat import bounded_probe_run
  16. from hermes_cli.web_deps import late
  17. from hermes_cli.web_server_files import _fs_path, _hosted_fs_path_allowed, _hosted_fs_read_guard
  18. from hermes_cli.web_models import (
  19. GitBranchSwitchBody,
  20. GitCommitBody,
  21. GitFileBody,
  22. GitPathBody,
  23. GitPrListBody,
  24. GitWorktreeAddBody,
  25. GitWorktreeRemoveBody,
  26. )
  27. router = APIRouter()
  28. # Late-bound so a test's monkeypatch on the owning module wins at call time.
  29. async def _git_op(fn, *args):
  30. """Run a (blocking) git op off the event loop; map a failed mutation to 400."""
  31. loop = asyncio.get_running_loop()
  32. try:
  33. return await loop.run_in_executor(None, fn, *args)
  34. except RuntimeError as exc:
  35. raise HTTPException(status_code=400, detail=str(exc) or "git operation failed")
  36. def _git_path(path: str) -> str:
  37. return str(_fs_path(path))
  38. @router.get("/api/git/status")
  39. async def git_status_route(path: str):
  40. return await _git_op(_web_git.repo_status, _git_path(path))
  41. # Cached `gh auth status` for the desktop composer's GitHub suggestion pill. GitHub
  42. # deliberately has NO MCP catalog entry (hosted MCP needs a per-host OAuth app; the
  43. # gh-CLI skills are the better integration), so the pill offers `/github-auth` —
  44. # only to users who aren't already authenticated.
  45. _GH_AUTH_TTL_S = 300.0
  46. _gh_auth_cache: Optional[tuple] = None # (monotonic_ts, payload)
  47. _gh_auth_probe_task: Optional[asyncio.Task] = None
  48. _gh_auth_probe_started = 0.0 # monotonic start of _gh_auth_probe_task
  49. def _probe_gh_auth() -> dict:
  50. gh = shutil.which("gh")
  51. if not gh:
  52. return {"available": False, "authenticated": False}
  53. try:
  54. # Exits 0 when at least one host is logged in; DEVNULL stdin guards against any prompt.
  55. proc = bounded_probe_run([gh, "auth", "status"], timeout=10)
  56. return {"available": True, "authenticated": bool(proc and proc.returncode == 0)}
  57. except Exception:
  58. return {"available": True, "authenticated": False}
  59. def _clear_gh_auth_probe_task(completed_task: asyncio.Task) -> None:
  60. """Release a completed shared probe even if all requesters disconnected."""
  61. global _gh_auth_probe_task
  62. if _gh_auth_probe_task is completed_task:
  63. _gh_auth_probe_task = None
  64. @router.get("/api/git/gh-auth")
  65. async def gh_auth_status_route(refresh: bool = False):
  66. """``{"available", "authenticated"}`` for the `gh` CLI; cached 5 min
  67. (``refresh=true`` bypasses so the pill withdraws right after a login)."""
  68. global _gh_auth_cache, _gh_auth_probe_task, _gh_auth_probe_started
  69. asked = time.monotonic()
  70. if not refresh and _gh_auth_cache and asked - _gh_auth_cache[0] < _GH_AUTH_TTL_S:
  71. return _gh_auth_cache[1]
  72. while True:
  73. if _gh_auth_probe_task is None or _gh_auth_probe_task.done():
  74. _gh_auth_probe_task = asyncio.create_task(asyncio.to_thread(_probe_gh_auth))
  75. _gh_auth_probe_started = time.monotonic()
  76. _gh_auth_probe_task.add_done_callback(_clear_gh_auth_probe_task)
  77. probe_task, started = _gh_auth_probe_task, _gh_auth_probe_started
  78. # Shield the shared probe: disconnecting one requester must not cancel the
  79. # probe that other refreshes/cache misses are awaiting.
  80. payload = await asyncio.shield(probe_task)
  81. # A refresh must not accept a probe that started before it was asked for (it may predate
  82. # `gh auth login`, and its answer would then be cached for the full TTL): wait that one out,
  83. # then start or join the next. Still only one `gh` runs at a time.
  84. if not refresh or started >= asked:
  85. break
  86. _gh_auth_cache = (time.monotonic(), payload)
  87. return payload
  88. @router.get("/api/git/worktrees")
  89. async def git_worktrees_route(path: str):
  90. return {"worktrees": await _git_op(_web_git.worktree_list, _git_path(path))}
  91. @router.get("/api/git/branches")
  92. async def git_branches_route(path: str):
  93. return {"branches": await _git_op(_web_git.branch_list, _git_path(path))}
  94. @router.get("/api/git/base-branches")
  95. async def git_base_branches_route(path: str):
  96. return {"branches": await _git_op(_web_git.base_branch_list, _git_path(path))}
  97. @router.get("/api/git/review/list")
  98. async def git_review_list_route(path: str, scope: str = "uncommitted", base: Optional[str] = None):
  99. return await _git_op(_web_git.review_list, _git_path(path), scope, base)
  100. @router.get("/api/git/review/diff")
  101. async def git_review_diff_route(
  102. path: str, file: str, request: Request,
  103. scope: str = "uncommitted", base: Optional[str] = None, staged: bool = False
  104. ):
  105. cwd = _git_path(path)
  106. target = _fs_path(file, cwd=cwd)
  107. _hosted_fs_read_guard(target, request)
  108. return {"diff": await _git_op(_web_git.review_diff, cwd, str(target), scope, base, staged)}
  109. @router.get("/api/git/file-diff")
  110. async def git_file_diff_route(path: str, file: str, request: Request):
  111. cwd = _git_path(path)
  112. target = _fs_path(file, cwd=cwd)
  113. _hosted_fs_read_guard(target, request)
  114. return {"diff": await _git_op(_web_git.file_diff_vs_head, cwd, str(target))}
  115. @router.get("/api/git/review/commit-context")
  116. async def git_commit_context_route(path: str, request: Request):
  117. cwd = _git_path(path)
  118. root = _hosted_fs_read_guard(Path(cwd), request)
  119. allowed = partial(_hosted_fs_path_allowed, root) if root is not None else None
  120. return await _git_op(_web_git.review_commit_context, cwd, allowed)
  121. @router.get("/api/git/review/rev-parse")
  122. async def git_rev_parse_route(path: str, ref: Optional[str] = None):
  123. return {"sha": await _git_op(_web_git.review_rev_parse, _git_path(path), ref)}
  124. @router.get("/api/git/review/ship-info")
  125. async def git_ship_info_route(path: str):
  126. return await _git_op(_web_git.review_ship_info, _git_path(path))
  127. @router.post("/api/git/review/pr-list")
  128. async def git_pr_list_route(body: GitPrListBody):
  129. return await _git_op(_web_git.review_pr_list, _git_path(body.path), body.branches, body.numbers)
  130. @router.post("/api/git/review/stage")
  131. async def git_stage_route(body: GitFileBody):
  132. return await _git_op(_web_git.review_stage, _git_path(body.path), body.file)
  133. @router.post("/api/git/review/unstage")
  134. async def git_unstage_route(body: GitFileBody):
  135. return await _git_op(_web_git.review_unstage, _git_path(body.path), body.file)
  136. @router.post("/api/git/review/revert")
  137. async def git_revert_route(body: GitFileBody):
  138. return await _git_op(_web_git.review_revert, _git_path(body.path), body.file)
  139. @router.post("/api/git/review/commit")
  140. async def git_commit_route(body: GitCommitBody):
  141. return await _git_op(_web_git.review_commit, _git_path(body.path), body.message, body.push)
  142. @router.post("/api/git/review/push")
  143. async def git_push_route(body: GitPathBody):
  144. return await _git_op(_web_git.review_push, _git_path(body.path))
  145. @router.post("/api/git/review/create-pr")
  146. async def git_create_pr_route(body: GitPathBody):
  147. return await _git_op(_web_git.review_create_pr, _git_path(body.path))
  148. @router.post("/api/git/worktree/add")
  149. async def git_worktree_add_route(body: GitWorktreeAddBody):
  150. options = {
  151. key: value
  152. for key, value in body.model_dump(include={"name", "branch", "base", "existingBranch"}).items()
  153. if value
  154. }
  155. return await _git_op(_web_git.worktree_add, _git_path(body.path), options)
  156. @router.post("/api/git/worktree/remove")
  157. async def git_worktree_remove_route(body: GitWorktreeRemoveBody):
  158. return await _git_op(
  159. _web_git.worktree_remove, _git_path(body.path), _git_path(body.worktreePath), body.force
  160. )
  161. @router.post("/api/git/branch/switch")
  162. async def git_branch_switch_route(body: GitBranchSwitchBody):
  163. return await _git_op(_web_git.branch_switch, _git_path(body.path), body.branch)