diff --git a/src/main/git/runner-wsl-gh-fallback.test.ts b/src/main/git/runner-wsl-gh-fallback.test.ts new file mode 100644 index 000000000..c1be98660 --- /dev/null +++ b/src/main/git/runner-wsl-gh-fallback.test.ts @@ -0,0 +1,320 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { execFileMock, execFileSyncMock, spawnMock } = vi.hoisted(() => ({ + execFileMock: vi.fn(), + execFileSyncMock: vi.fn(), + spawnMock: vi.fn() +})) + +vi.mock('child_process', () => ({ + execFile: execFileMock, + execFileSync: execFileSyncMock, + spawn: spawnMock +})) + +import { ghExecFileAsync, glabExecFileAsync } from './runner' + +describe('ghExecFileAsync WSL fallback', () => { + const originalPlatform = process.platform + + beforeEach(() => { + execFileMock.mockReset() + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { + configurable: true, + value: originalPlatform + }) + }) + + it('falls back to host gh for explicit-repo WSL calls when gh is missing in the distro', async () => { + execFileMock.mockImplementation((binary, _args, options, callback) => { + if (typeof options === 'function') { + callback = options + } + if (binary === 'wsl.exe') { + callback( + Object.assign(new Error('Command failed: wsl.exe'), { + stdout: '', + stderr: 'bash: line 1: gh: command not found\n' + }) + ) + return + } + callback(null, { stdout: '[]', stderr: '' }) + }) + + await expect( + ghExecFileAsync(['issue', 'list', '--repo', 'stablyhq/noqa', '--json', 'number,title'], { + cwd: String.raw`\\wsl.localhost\Ubuntu\home\jinwoo\stably\noqa` + }) + ).resolves.toEqual({ stdout: '[]', stderr: '' }) + + expect(execFileMock).toHaveBeenNthCalledWith( + 1, + 'wsl.exe', + [ + '-d', + 'Ubuntu', + '--', + 'bash', + '-c', + "cd '/home/jinwoo/stably/noqa' && gh 'issue' 'list' '--repo' 'stablyhq/noqa' '--json' 'number,title'" + ], + expect.objectContaining({ cwd: undefined }), + expect.any(Function) + ) + expect(execFileMock).toHaveBeenNthCalledWith( + 2, + 'gh', + ['issue', 'list', '--repo', 'stablyhq/noqa', '--json', 'number,title'], + expect.objectContaining({ cwd: undefined }), + expect.any(Function) + ) + }) + + it('does not fall back for repo-context gh calls without explicit repo context', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('Command failed: wsl.exe'), { + stdout: '', + stderr: 'bash: line 1: gh: command not found\n' + }) + ) + }) + + await expect( + ghExecFileAsync(['issue', 'list'], { + cwd: String.raw`\\wsl.localhost\Ubuntu\home\jinwoo\stably\noqa` + }) + ).rejects.toThrow('Command failed: wsl.exe') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('falls back for short-form explicit repo flags used by gh', async () => { + execFileMock.mockImplementation((binary, _args, options, callback) => { + if (typeof options === 'function') { + callback = options + } + if (binary === 'wsl.exe') { + callback( + Object.assign(new Error('Command failed: wsl.exe'), { + stdout: '', + stderr: 'bash: line 1: gh: command not found\n' + }) + ) + return + } + callback(null, { stdout: '[]', stderr: '' }) + }) + + await expect( + ghExecFileAsync(['issue', 'list', '-R', 'stablyhq/noqa'], { + cwd: String.raw`\\wsl.localhost\Ubuntu\home\jinwoo\stably\noqa` + }) + ).resolves.toEqual({ stdout: '[]', stderr: '' }) + + expect(execFileMock).toHaveBeenNthCalledWith( + 2, + 'gh', + ['issue', 'list', '-R', 'stablyhq/noqa'], + expect.objectContaining({ cwd: undefined }), + expect.any(Function) + ) + }) + + it('falls back for compact short-form repo flags used by gh', async () => { + execFileMock.mockImplementation((binary, _args, options, callback) => { + if (typeof options === 'function') { + callback = options + } + if (binary === 'wsl.exe') { + callback( + Object.assign(new Error('Command failed: wsl.exe'), { + stdout: '', + stderr: 'bash: line 1: gh: command not found\n' + }) + ) + return + } + callback(null, { stdout: '[]', stderr: '' }) + }) + + await expect( + ghExecFileAsync(['issue', 'list', '-Rstablyhq/noqa'], { + cwd: String.raw`\\wsl.localhost\Ubuntu\home\jinwoo\stably\noqa` + }) + ).resolves.toEqual({ stdout: '[]', stderr: '' }) + + expect(execFileMock).toHaveBeenNthCalledWith( + 2, + 'gh', + ['issue', 'list', '-Rstablyhq/noqa'], + expect.objectContaining({ cwd: undefined }), + expect.any(Function) + ) + }) + + it('does not fall back for gh api calls that depend on repo-context placeholders', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('Command failed: wsl.exe'), { + stdout: '', + stderr: 'bash: line 1: gh: command not found\n' + }) + ) + }) + + await expect( + ghExecFileAsync(['api', 'repos/stablyhq/noqa/branches/{branch}'], { + cwd: String.raw`\\wsl.localhost\Ubuntu\home\jinwoo\stably\noqa` + }) + ).rejects.toThrow('Command failed: wsl.exe') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('retries idempotent gh GraphQL query transient failures', async () => { + execFileMock + .mockImplementationOnce((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + .mockImplementationOnce((_binary, _args, _options, callback) => { + callback(null, { stdout: '{"data":{}}', stderr: '' }) + }) + + await expect( + ghExecFileAsync(['api', 'graphql', '-f', 'query=query { viewer { login } }']) + ).resolves.toEqual({ stdout: '{"data":{}}', stderr: '' }) + + expect(execFileMock).toHaveBeenCalledTimes(2) + }) + + it('does not retry non-idempotent gh API transient failures', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + + await expect( + ghExecFileAsync(['api', '-X', 'POST', 'repos/stablyai/orca/issues']) + ).rejects.toThrow('HTTP 502 Bad Gateway') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('does not retry gh GraphQL mutation transient failures', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + + await expect( + ghExecFileAsync([ + 'api', + 'graphql', + '-f', + 'query=mutation { addStar(input: {}) { starrable { id } } }' + ]) + ).rejects.toThrow('HTTP 502 Bad Gateway') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('does not retry high-level gh edit transient failures', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + + await expect( + ghExecFileAsync(['issue', 'edit', '5', '--repo', 'stablyai/orca']) + ).rejects.toThrow('HTTP 502 Bad Gateway') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('does not retry non-idempotent glab transient failures', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + + await expect( + glabExecFileAsync(['api', '-X', 'POST', 'projects/stablyai%2Forca/issues/5/notes'], { + cwd: String.raw`C:\repo` + }) + ).rejects.toThrow('HTTP 502 Bad Gateway') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('does not retry high-level glab update transient failures', async () => { + execFileMock.mockImplementation((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + + await expect( + glabExecFileAsync(['issue', 'update', '5', '-R', 'stablyai/orca'], { + cwd: String.raw`C:\repo` + }) + ).rejects.toThrow('HTTP 502 Bad Gateway') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('still retries idempotent glab transient failures', async () => { + execFileMock + .mockImplementationOnce((_binary, _args, _options, callback) => { + callback( + Object.assign(new Error('HTTP 502 Bad Gateway'), { + stdout: '', + stderr: 'HTTP 502 Bad Gateway' + }) + ) + }) + .mockImplementationOnce((_binary, _args, _options, callback) => { + callback(null, { stdout: '[]', stderr: '' }) + }) + + await expect( + glabExecFileAsync(['api', 'projects/stablyai%2Forca/issues'], { + cwd: String.raw`C:\repo` + }) + ).resolves.toEqual({ stdout: '[]', stderr: '' }) + + expect(execFileMock).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts index c589b7b20..dffc475ec 100644 --- a/src/main/git/runner.ts +++ b/src/main/git/runner.ts @@ -55,6 +55,72 @@ function translateArgsForWsl(args: string[]): string[] { }) } +function hasExplicitRepoArg(args: string[]): boolean { + for (let i = 0; i < args.length; i++) { + if ( + (args[i] === '--repo' || args[i] === '-R') && + typeof args[i + 1] === 'string' && + args[i + 1].trim() + ) { + return true + } + if (args[i].startsWith('--repo=') || args[i].startsWith('-R=')) { + return args[i].slice(args[i].indexOf('=') + 1).trim().length > 0 + } + if (args[i].startsWith('-R') && args[i].length > 2) { + return args[i].slice(2).trim().length > 0 + } + } + return false +} + +function argsUseGhApiPlaceholders(args: string[]): boolean { + return args.some( + (arg) => arg.includes('{owner}') || arg.includes('{repo}') || arg.includes('{branch}') + ) +} + +function canRunGitHubCliWithoutRepoCwd(args: string[]): boolean { + if (hasExplicitRepoArg(args)) { + return true + } + if (args[0] === 'api') { + return !argsUseGhApiPlaceholders(args) + } + return args[0] === 'auth' +} + +function isMissingCommandInWsl(stderr: string, command: string): boolean { + const s = stderr.toLowerCase() + const c = command.toLowerCase() + return s.includes(`${c}: command not found`) || s.includes(`${c}: not found`) +} + +function canFallBackToHostGitHubCli( + command: 'gh', + args: string[], + resolved: ResolvedCommand, + stderr: string +): boolean { + return ( + process.platform === 'win32' && + resolved.wsl !== null && + isMissingCommandInWsl(stderr, command) && + canRunGitHubCliWithoutRepoCwd(args) + ) +} + +function resolveHostGitHubCli(command: 'gh', args: string[]): ResolvedCommand { + return { + binary: command, + args, + // Why: host gh cannot use a WSL UNC cwd reliably. We only fall back + // for commands with explicit repo/API context, so no repo cwd is required. + cwd: undefined, + wsl: null + } +} + /** * Given a command, its arguments, and a working directory, resolve whether * the invocation should be routed through wsl.exe. @@ -227,6 +293,7 @@ const NON_IDEMPOTENT_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']) const NON_IDEMPOTENT_GH_VERBS = new Set([ 'create', 'edit', + 'update', 'delete', 'close', 'reopen', @@ -245,6 +312,8 @@ const NON_IDEMPOTENT_GH_VERBS = new Set([ function argsLookIdempotent(args: string[]): boolean { let explicitMethodSeen = false let hasApiBodyField = false + let hasGraphQlQuery = false + const isGraphQlApi = args[0] === 'api' && args[1] === 'graphql' for (let i = 0; i < args.length; i++) { const a = args[i] if (a === '-X' || a === '--method') { @@ -278,6 +347,7 @@ function argsLookIdempotent(args: string[]): boolean { // `gh api graphql -f query=mutation(...){ ... }` — detect mutation queries // so writes via the GraphQL endpoint also fail fast on transient errors. if (a.startsWith('query=')) { + hasGraphQlQuery = true const trimmed = a.slice('query='.length).trimStart().toLowerCase() if (trimmed.startsWith('mutation')) { return false @@ -286,8 +356,14 @@ function argsLookIdempotent(args: string[]): boolean { } // `gh api ... -f foo=bar` with no explicit method: gh switches to POST. // Treat as non-idempotent so a transient 5xx after the server applied - // the write doesn't retry and duplicate it. - if (args[0] === 'api' && hasApiBodyField && !explicitMethodSeen) { + // the write doesn't retry and duplicate it. GraphQL reads are the exception: + // gh sends them as POST body fields, but a query operation is idempotent. + if ( + args[0] === 'api' && + hasApiBodyField && + !explicitMethodSeen && + !(isGraphQlApi && hasGraphQlQuery) + ) { return false } // `gh issue close`, `gh pr edit`, `gh pr merge`, etc. The first arg is the @@ -423,8 +499,9 @@ export async function ghExecFileAsync( args: string[], options: GhExecOptions = {} ): Promise<{ stdout: string; stderr: string }> { - const resolved = resolveCommand('gh', args, options.cwd, options.wslDistro) + let resolved = resolveCommand('gh', args, options.cwd, options.wslDistro) let lastError: unknown + let attemptedHostFallback = false for (let attempt = 0; attempt <= GH_RETRY_DELAYS_MS.length; attempt++) { try { const { stdout, stderr } = await execFileAsync(resolved.binary, resolved.args, { @@ -438,6 +515,12 @@ export async function ghExecFileAsync( } catch (err) { lastError = err const { stderr } = extractExecError(err) + if (!attemptedHostFallback && canFallBackToHostGitHubCli('gh', args, resolved, stderr)) { + resolved = resolveHostGitHubCli('gh', args) + attemptedHostFallback = true + attempt = -1 + continue + } const isLastAttempt = attempt >= GH_RETRY_DELAYS_MS.length // Why: only retry idempotent calls. A 5xx/socket reset can arrive // after the server already applied a POST/PATCH/PUT/DELETE; retrying @@ -479,7 +562,11 @@ export async function ghExecFileAsync( // helpers since HTTP-status- and TCP-error-based classification is // provider-agnostic. -type GlabExecOptions = Omit & { cwd?: string; wslDistro?: string } +type GlabExecOptions = Omit & { + cwd?: string + wslDistro?: string + idempotent?: boolean +} /** * Async glab CLI execution. Drop-in replacement for @@ -507,7 +594,11 @@ export async function glabExecFileAsync( lastError = err const { stderr } = extractExecError(err) const isLastAttempt = attempt >= GH_RETRY_DELAYS_MS.length - if (!isLastAttempt && isTransientGhError(stderr)) { + // Why: mirror gh's write-safety gate. A transient error after GitLab + // applies a POST/PATCH/PUT/DELETE must not create duplicate comments, + // issues, or merge actions through an automatic retry. + const idempotent = options.idempotent ?? argsLookIdempotent(args) + if (idempotent && !isLastAttempt && isTransientGhError(stderr)) { const retryAfterMs = parseRetryAfterMs(stderr) const delayMs = retryAfterMs !== null diff --git a/src/main/github/client.ts b/src/main/github/client.ts index cde6e71f3..a34bd6ff0 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -1211,13 +1211,10 @@ export async function getPRComments( // Each source is parsed independently; failed sources contribute zero // comments instead of aborting the entire fetch. const [issueResult, threadsResult, reviewsResult] = await Promise.allSettled([ - execFileAsync( - 'gh', - ['api', ...cacheArgs, `${base}/issues/${prNumber}/comments?per_page=100`], - { cwd: repoPath, encoding: 'utf-8' } - ), - execFileAsync( - 'gh', + ghExecFileAsync(['api', ...cacheArgs, `${base}/issues/${prNumber}/comments?per_page=100`], { + cwd: repoPath + }), + ghExecFileAsync( [ 'api', 'graphql', @@ -1230,17 +1227,15 @@ export async function getPRComments( '-F', `pr=${prNumber}` ], - { cwd: repoPath, encoding: 'utf-8' } + { cwd: repoPath } ), // Why: review summaries (approve, request changes, general comments) live // under pulls/{n}/reviews, not under issue comments or review threads. // Without this, a reviewer who submits "LGTM" without inline threads // would have their comment silently dropped from the panel. - execFileAsync( - 'gh', - ['api', ...cacheArgs, `${base}/pulls/${prNumber}/reviews?per_page=100`], - { cwd: repoPath, encoding: 'utf-8' } - ) + ghExecFileAsync(['api', ...cacheArgs, `${base}/pulls/${prNumber}/reviews?per_page=100`], { + cwd: repoPath + }) ]) // Parse issue comments (REST) @@ -1387,10 +1382,11 @@ export async function getPRComments( } // Fallback: non-GitHub remote — use gh pr view (only returns issue-level comments) - const { stdout } = await execFileAsync( - 'gh', + const { stdout } = await ghExecFileAsync( ['pr', 'view', String(prNumber), '--json', 'comments'], - { cwd: repoPath, encoding: 'utf-8' } + { + cwd: repoPath + } ) const data = JSON.parse(stdout) as { comments: {