Skip to content

The agent that grows with you

fix(review): surface real gh stderr in PR-create errors

pasmud8b7a1620a168
diff --git a/apps/desktop/electron/git-review-ops.test.ts b/apps/desktop/electron/git-review-ops.test.ts
index c1c28303578..5aa195af515 100644
--- a/apps/desktop/electron/git-review-ops.test.ts
+++ b/apps/desktop/electron/git-review-ops.test.ts
@@ -4,9 +4,18 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
-import { afterEach, test } from 'vitest'
+import { afterEach, test, vi } from 'vitest'
-import { gitFor, repoStatus, resolveRenamePath, REVIEW_FILE_CAP, reviewList } from './git-review-ops'
+import { gitFor, repoStatus, resolveRenamePath, REVIEW_FILE_CAP, reviewCreatePr, reviewList } from './git-review-ops'
+
+// `runGh` shells to the `gh` CLI via execFile. Mock it so reviewCreatePr's gh
+// invocation is controllable (real `gh` may be absent or slow in CI) while the
+// repo setup below still uses the real execFileSync.
+vi.mock('node:child_process', async importOriginal => {
+ const actual = await importOriginal<{ execFile: unknown; execFileSync: unknown }>()
+
+ return { ...actual, execFile: vi.fn() }
+})
const tempDirs: string[] = []
@@ -97,3 +106,44 @@ test('reviewList caps the file payload returned to the renderer', async () => {
assert.equal(result.files.length, REVIEW_FILE_CAP)
})
+
+const mockExecFile = vi.mocked(await import('node:child_process')).execFile
+
+type ExecFileCallback = (error: Error | null, stdout?: string, stderr?: string) => void
+
+// `execFile` has overloaded declarations returning ChildProcess; the mock
+// implementation only needs to drive its callback, so view it as a plain
+// callable and set the implementation through the Mock typing.
+function failGh(stderr: string): void {
+ ;(
+ mockExecFile as unknown as {
+ mockImplementation: (
+ impl: (file: string, args: string[], options: object, callback: ExecFileCallback) => void
+ ) => unknown
+ }
+ ).mockImplementation((_bin: string, _args: string[], _opts: object, callback: ExecFileCallback) => {
+ const error = new Error('command failed')
+
+ if (stderr) {
+ ;(error as Error & { stderr?: string }).stderr = stderr
+ }
+
+ callback(error, '', stderr)
+ })
+}
+
+test('reviewCreatePr surfaces gh stderr when pr create fails', async () => {
+ const dir = makeRepo()
+
+ failGh('no commits between main and feature')
+
+ await assert.rejects(reviewCreatePr(dir, 'git', 'gh'), /no commits between main and feature/)
+})
+
+test('reviewCreatePr falls back to the generic message when gh reports no stderr', async () => {
+ const dir = makeRepo()
+
+ failGh('')
+
+ await assert.rejects(reviewCreatePr(dir, 'git', 'gh'), /is gh installed and authenticated\?/)
+})
diff --git a/apps/desktop/electron/git-review-ops.ts b/apps/desktop/electron/git-review-ops.ts
index 03d3c8b46d7..73b4ca09296 100644
--- a/apps/desktop/electron/git-review-ops.ts
+++ b/apps/desktop/electron/git-review-ops.ts
@@ -31,15 +31,16 @@ function ghEnv(ghBin) {
return { ...process.env, PATH: [...extra, process.env.PATH].filter(Boolean).join(path.delimiter) }
}
-// Run the `gh` CLI in a repo. Resolves { ok, stdout } so callers branch on
-// availability/auth without a throw. gh missing/unauthed → ok:false.
-function runGh(args, cwd, ghBin): Promise<{ ok: boolean; stdout: string }> {
+// Run the `gh` CLI in a repo. Resolves { ok, stdout, stderr } so callers branch
+// on availability/auth without a throw. gh missing/unauthed → ok:false.
+function runGh(args, cwd, ghBin): Promise<{ ok: boolean; stdout: string; stderr: string }> {
return new Promise(resolve => {
execFile(
ghBin || 'gh',
args,
{ cwd, env: ghEnv(ghBin), windowsHide: true, timeout: 30_000, maxBuffer: 8 * 1024 * 1024 },
- (err, stdout) => resolve({ ok: !err, stdout: String(stdout || '') })
+ (err, stdout, stderr) =>
+ resolve({ ok: !err, stdout: String(stdout || ''), stderr: String(err?.stderr ?? stderr ?? '') })
)
})
}
@@ -712,7 +713,12 @@ async function reviewCreatePr(repoPath, gitBin, ghBin) {
const created = await runGh(['pr', 'create', '--fill'], cwd, ghBin)
if (!created.ok) {
- throw new Error('gh pr create failed (is gh installed and authenticated?)')
+ // gh's own stderr says why the create failed (e.g. "no commits between
+ // main and feature", missing auth, a repo in an uncreatable state). Surface
+ // it instead of the generic fallback, which lied whenever gh was fine.
+ const reason = created.stderr.trim() || 'is gh installed and authenticated?'
+
+ throw new Error(`gh pr create failed: ${reason}`)
}
const url = created.stdout.trim().split('\n').filter(Boolean).pop() || ''
diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.py
index cef77ee936d..42365b201e0 100644
--- a/hermes_cli/web_git.py
+++ b/hermes_cli/web_git.py
@@ -20,6 +20,9 @@ from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_en
_GIT_TIMEOUT = 30
_GH_TIMEOUT = 30
+# How much of a failed gh command's stderr rides into the surfaced error. A
+# toast can carry the informative tail; the full traceback helps nobody (#87731).
+_GH_ERR_TAIL_CHARS = 400
_UNTRACKED_LINE_MAX_BYTES = 1024 * 1024
_UNTRACKED_SCAN_CAP = 500
_COMMIT_CONTEXT_DIFF_MAX_CHARS = 120_000
@@ -383,21 +386,23 @@ def review_commit_context(cwd: str) -> dict:
# ── ship flow (gh) ───────────────────────────────────────────────────────────
-def _gh(cwd: str, args: list[str]) -> tuple[bool, str]:
+def _gh(cwd: str, args: list[str]) -> tuple[bool, str, str]:
+ """``(ok, stdout, stderr)`` of ``gh`` in ``cwd``. Never raises on non-zero exit —
+ the caller decides what a failure means, and the real reason rides in stderr."""
if not shutil.which("gh"):
- return False, ""
+ return False, "", ""
# GH_PROMPT_DISABLED: gh's documented kill-switch for interactive prompts.
env = noninteractive_git_env()
env["GH_PROMPT_DISABLED"] = "1"
proc = _run(["gh", *args], cwd, _GH_TIMEOUT, env)
if proc is None:
- return False, ""
- return proc.returncode == 0, proc.stdout or ""
+ return False, "", ""
+ return proc.returncode == 0, proc.stdout or "", proc.stderr or ""
def _gh_json(cwd: str, args: list[str]):
"""Parsed JSON stdout of a successful gh call, else None."""
- ok, out = _gh(cwd, args)
+ ok, out, _stderr = _gh(cwd, args)
if not ok:
return None
try:
@@ -463,7 +468,7 @@ def review_pr_list(cwd: str, branches: list[str], numbers: list[int] = None) ->
by_number = list(dict.fromkeys(int(n) for n in (numbers or []) if n))[:_PR_QUERY_BRANCH_CAP]
if not wanted and not by_number:
return not_ready
- repo_ok, repo_out = _gh(cwd, ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])
+ repo_ok, repo_out, _repo_err = _gh(cwd, ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])
owner, _, name = repo_out.strip().partition("/")
if not repo_ok or not owner or not name:
# gh missing, unauthenticated, or no GitHub remote — all "nothing to badge".
@@ -490,9 +495,15 @@ def review_create_pr(cwd: str) -> dict:
_review_push(cwd)
except RuntimeError:
pass
- created, out = _gh(cwd, ["pr", "create", "--fill"])
+ created, out, err = _gh(cwd, ["pr", "create", "--fill"])
if not created:
- raise RuntimeError("gh pr create failed (is gh installed and authenticated?)")
+ # gh's own stderr says why the create failed ("no commits between main
+ # and feature", a missing upstream, a publish-email refusal). The generic
+ # fallback lied whenever gh itself was fine — keep it only for the case
+ # gh reported nothing (#87731). Bounded: a toast carries the tail, not
+ # the whole traceback.
+ detail = err.strip()[-_GH_ERR_TAIL_CHARS:] or "is gh installed and authenticated?"
+ raise RuntimeError(f"gh pr create failed: {detail}")
url = next((line for line in reversed(out.strip().splitlines()) if line.strip()), "")
return {"url": url}
diff --git a/tests/hermes_cli/test_web_git_gh_stderr.py b/tests/hermes_cli/test_web_git_gh_stderr.py
new file mode 100644
index 00000000000..4581148ebf7
--- /dev/null
+++ b/tests/hermes_cli/test_web_git_gh_stderr.py
@@ -0,0 +1,90 @@
+"""Behavioral tests for the gh wrappers' failure reporting (#87731).
+
+`_gh` used to collapse every non-zero exit to `(False, "")` and
+`review_create_pr` raised a generic "is gh installed and authenticated?"
+message — which lied whenever gh was fine and the failure was real
+("no commits between main and feature", a missing upstream, a refused
+push). These tests pin the contract that stderr survives the wrapper and
+reaches the surfaced error, with the generic text reserved for the case
+gh itself reported nothing.
+"""
+
+from subprocess import CompletedProcess
+from unittest.mock import patch
+
+import pytest
+
+import hermes_cli.web_git as web_git
+
+
+def _proc(returncode: int = 0, stdout: str = "", stderr: str = "") -> CompletedProcess:
+ return CompletedProcess(args=["gh"], returncode=returncode, stdout=stdout, stderr=stderr)
+
+
+def _make_gh(returncode: int, stdout: str = "", stderr: str = ""):
+ """Patch gh as installed (shutil.which) and running with the given result."""
+ return patch.object(web_git, "_run", return_value=_proc(returncode, stdout, stderr))
+
+
+class TestGhRetainsStderr:
+ def test_success_returns_ok_with_stdout_and_stderr(self, tmp_path):
+ with patch.object(web_git.shutil, "which", return_value="/usr/bin/gh"), _make_gh(0, "ok\n", ""):
+ ok, out, err = web_git._gh(str(tmp_path), ["auth", "status"])
+
+ assert ok is True
+ assert out == "ok\n"
+ assert err == ""
+
+ def test_nonzero_exit_keeps_exit_status_and_stderr(self, tmp_path):
+ with patch.object(web_git.shutil, "which", return_value="/usr/bin/gh"), _make_gh(
+ 1, "", "no commits between main and feature"
+ ):
+ ok, out, err = web_git._gh(str(tmp_path), ["pr", "create", "--fill"])
+
+ assert ok is False
+ assert out == ""
+ assert err == "no commits between main and feature"
+
+ def test_missing_gh_binary_is_not_ok_without_raising(self, tmp_path):
+ with patch.object(web_git.shutil, "which", return_value=None):
+ ok, out, err = web_git._gh(str(tmp_path), ["auth", "status"])
+
+ assert (ok, out, err) == (False, "", "")
+
+
+class TestReviewCreatePrSurfacesGhStderr:
+ def test_failure_message_carries_gh_stderr_marker(self, tmp_path):
+ # A unique marker: the assertion fails if the wrapper regresses to the
+ # generic message or drops stderr anywhere between exec and the raise.
+ with patch.object(web_git.shutil, "which", return_value="/usr/bin/gh"), _make_gh(
+ 1, "", "gh: no commits between main and bb/fix-wave2g"
+ ):
+ with pytest.raises(RuntimeError, match="no commits between main and bb/fix-wave2g"):
+ web_git.review_create_pr(str(tmp_path))
+
+ def test_failure_message_still_names_gh_when_stderr_is_empty(self, tmp_path):
+ with patch.object(web_git.shutil, "which", return_value="/usr/bin/gh"), _make_gh(1, "", " "):
+ with pytest.raises(RuntimeError, match="is gh installed and authenticated"):
+ web_git.review_create_pr(str(tmp_path))
+
+ def test_success_path_returns_the_pr_url(self, tmp_path):
+ with patch.object(web_git.shutil, "which", return_value="/usr/bin/gh"), _make_gh(
+ 0, "https://github.com/org/repo/pull/1234\n", ""
+ ):
+ result = web_git.review_create_pr(str(tmp_path))
+
+ assert result == {"url": "https://github.com/org/repo/pull/1234"}
+
+ def test_oversized_stderr_is_bounded_to_its_tail(self, tmp_path):
+ marker = "TRAILING-MARKER-reason"
+ stderr = "x" * 5_000 + "\n" + marker
+ with patch.object(web_git.shutil, "which", return_value="/usr/bin/gh"), _make_gh(1, "", stderr):
+ with pytest.raises(RuntimeError) as excinfo:
+ web_git.review_create_pr(str(tmp_path))
+
+ message = str(excinfo.value)
+ assert marker in message
+ # The 5_000-char noise prefix does not ride along: the surfaced detail
+ # is bounded to the configured tail, not the whole stderr.
+ assert len(message) <= len("gh pr create failed: ") + web_git._GH_ERR_TAIL_CHARS
+ assert "x" * web_git._GH_ERR_TAIL_CHARS not in message