Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
2af4dc1
fix: force IPv4-first DNS resolution to avoid WSL2 fetch timeouts
claude May 7, 2026
99eaf57
fix: retry callAnthropic on transient network errors
claude May 7, 2026
97e30d0
chore: add MINT_DEBUG diagnostics for callAnthropic
claude May 7, 2026
3a5c910
Merge remote-tracking branch 'origin/main' into claude/fetch-issues-w…
nujovich May 11, 2026
4688676
Potential fix for pull request finding
nujovich May 11, 2026
b3af586
fix: wire debug diagnostics and retry logic into callAnthropic
Copilot May 11, 2026
a126403
Potential fix for pull request finding
nujovich May 11, 2026
f537abc
fix: narrow setDefaultResultOrder('ipv4first') to WSL2 only
Copilot May 11, 2026
041bf1b
chore: exclude network/debug helpers from v8 coverage
nujovich May 11, 2026
a5a6c40
feat: add callAnthropic import and vi/afterEach to test skeleton
nujovich May 11, 2026
7261b4a
test: add callAnthropic unit tests to close coverage gaps
nujovich May 11, 2026
c66fc1b
feat: export isWSL2 and hasDnsResultOrderOverride for unit testing
nujovich May 11, 2026
f85017d
test: add node:fs mock and new imports for WSL2 detection tests
nujovich May 11, 2026
ecf1df8
test: add hasDnsResultOrderOverride unit tests
nujovich May 11, 2026
6147513
test: add isWSL2 unit tests
nujovich May 11, 2026
bc3b766
Potential fix for pull request finding
nujovich May 11, 2026
c49aa24
refactor: move hasDnsResultOrderOverride and isWSL2 to internal lib/n…
Copilot May 11, 2026
5b3fe10
test: add retry/backoff tests and narrow v8 ignore regions in callAnt…
Copilot May 11, 2026
c2851e6
refactor: rename nonRetryable to nonRetryableError for clarity
Copilot May 11, 2026
e2f58f3
Potential fix for pull request finding
nujovich May 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions lib/__tests__/net-utils.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { readFileSync } from 'node:fs'
import { hasDnsResultOrderOverride, isWSL2 } from '../net-utils.mjs'

vi.mock('node:fs', () => ({
readFileSync: vi.fn(),
}))

describe('hasDnsResultOrderOverride', () => {
let originalExecArgv

beforeEach(() => {
originalExecArgv = process.execArgv
process.execArgv = []
vi.stubEnv('NODE_OPTIONS', '')
})

afterEach(() => {
process.execArgv = originalExecArgv
vi.unstubAllEnvs()
})

it('returns true when NODE_OPTIONS includes --dns-result-order', () => {
vi.stubEnv('NODE_OPTIONS', '--dns-result-order=verbatim')
expect(hasDnsResultOrderOverride()).toBe(true)
})

it('returns true when execArgv contains --dns-result-order', () => {
process.execArgv = ['--dns-result-order']
expect(hasDnsResultOrderOverride()).toBe(true)
})

it('returns true when execArgv contains --dns-result-order=value', () => {
process.execArgv = ['--dns-result-order=verbatim']
expect(hasDnsResultOrderOverride()).toBe(true)
})

it('returns false when neither NODE_OPTIONS nor execArgv signal an override', () => {
expect(hasDnsResultOrderOverride()).toBe(false)
})
})

describe('isWSL2', () => {
afterEach(() => {
vi.mocked(readFileSync).mockReset()
})

it('returns true when /proc/sys/kernel/osrelease contains wsl2', () => {
vi.mocked(readFileSync).mockImplementation((path) => {
if (String(path).includes('osrelease')) return '5.15.153.1-microsoft-standard-WSL2'
throw new Error('ENOENT')
})
expect(isWSL2()).toBe(true)
})

it('returns true when /proc/version matches microsoft.*wsl2 pattern', () => {
vi.mocked(readFileSync).mockImplementation((path) => {
if (String(path).includes('osrelease')) throw new Error('ENOENT')
return 'Linux version 5.15.0-microsoft-standard-WSL2 (gcc)'
})
expect(isWSL2()).toBe(true)
})

it('returns true when /proc/version matches wsl2.*microsoft pattern', () => {
vi.mocked(readFileSync).mockImplementation((path) => {
if (String(path).includes('osrelease')) throw new Error('ENOENT')
return 'Linux WSL2-microsoft kernel'
})
expect(isWSL2()).toBe(true)
})

it('returns false when /proc/version contains microsoft but not wsl2', () => {
vi.mocked(readFileSync).mockImplementation((path) => {
if (String(path).includes('osrelease')) throw new Error('ENOENT')
return 'Linux microsoft version'
})
expect(isWSL2()).toBe(false)
})

it('returns false when /proc/version has no microsoft or wsl2', () => {
vi.mocked(readFileSync).mockImplementation((path) => {
if (String(path).includes('osrelease')) throw new Error('ENOENT')
return 'Linux 5.15.0 Ubuntu'
})
expect(isWSL2()).toBe(false)
})

it('returns false when both reads throw', () => {
vi.mocked(readFileSync).mockImplementation(() => { throw new Error('ENOENT') })
expect(isWSL2()).toBe(false)
})
})
119 changes: 118 additions & 1 deletion lib/__tests__/prompts.test.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { describe, it, expect } from 'vitest'
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import {
stripFences,
resolveTarget,
preprocessCss,
buildAuditPrompt,
buildResolvePrompt,
buildExportPrompt,
callAnthropic,
} from '../prompts.mjs'

describe('stripFences', () => {
Expand Down Expand Up @@ -203,3 +204,119 @@ describe('buildExportPrompt', () => {
expect(result.length).toBeGreaterThan(0)
})
})

describe('callAnthropic', () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.useRealTimers()
})

it('throws when apiKey is missing', async () => {
await expect(callAnthropic({ prompt: 'hello' })).rejects.toThrow(
'ANTHROPIC_API_KEY is required',
)
})

it('returns the text content from a successful response', async () => {
vi.stubGlobal('fetch', async () => ({
ok: true,
json: async () => ({ content: [{ type: 'text', text: 'ok' }] }),
}))
const result = await callAnthropic({ apiKey: 'test-key', prompt: 'hello' })
expect(result).toBe('ok')
})

it('throws on HTTP error response without retrying', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: async () => ({ error: { message: 'Internal Server Error' } }),
})
vi.stubGlobal('fetch', fetchMock)
await expect(callAnthropic({ apiKey: 'test-key', prompt: 'hello' })).rejects.toThrow(
'Internal Server Error',
)
expect(fetchMock).toHaveBeenCalledTimes(1)
})

it('throws on non-retryable network error without retrying', async () => {
const nonRetryableError = Object.assign(new Error('DNS lookup failed'), { code: 'ENOTFOUND' })
const fetchMock = vi.fn().mockRejectedValue(nonRetryableError)
vi.stubGlobal('fetch', fetchMock)
await expect(callAnthropic({ apiKey: 'test-key', prompt: 'hello' })).rejects.toThrow(
'DNS lookup failed',
)
expect(fetchMock).toHaveBeenCalledTimes(1)
})

describe('retry behavior', () => {
beforeEach(() => {
vi.useFakeTimers()
})

it('retries on ETIMEDOUT and succeeds on second attempt', async () => {
const fetchMock = vi.fn()
.mockRejectedValueOnce(Object.assign(new Error('etimedout'), { code: 'ETIMEDOUT' }))
.mockResolvedValueOnce({
ok: true,
json: async () => ({ content: [{ type: 'text', text: 'retried-ok' }] }),
})
vi.stubGlobal('fetch', fetchMock)

const promise = callAnthropic({ apiKey: 'test-key', prompt: 'hello' })
await vi.advanceTimersByTimeAsync(500)
await expect(promise).resolves.toBe('retried-ok')
expect(fetchMock).toHaveBeenCalledTimes(2)
})

it('retries on ECONNRESET (via cause.code) and succeeds on second attempt', async () => {
const wrapped = Object.assign(new Error('socket error'), {
cause: { code: 'ECONNRESET' },
})
const fetchMock = vi.fn()
.mockRejectedValueOnce(wrapped)
.mockResolvedValueOnce({
ok: true,
json: async () => ({ content: [{ type: 'text', text: 'recovered' }] }),
})
vi.stubGlobal('fetch', fetchMock)

const promise = callAnthropic({ apiKey: 'test-key', prompt: 'hello' })
await vi.advanceTimersByTimeAsync(500)
await expect(promise).resolves.toBe('recovered')
expect(fetchMock).toHaveBeenCalledTimes(2)
})

it('retries on undici aggregate error (cause.errors[].code) and succeeds', async () => {
const aggregate = Object.assign(new Error('undici error'), {
cause: { errors: [{ code: 'UND_ERR_SOCKET' }] },
})
const fetchMock = vi.fn()
.mockRejectedValueOnce(aggregate)
.mockResolvedValueOnce({
ok: true,
json: async () => ({ content: [{ type: 'text', text: 'undici-ok' }] }),
})
vi.stubGlobal('fetch', fetchMock)

const promise = callAnthropic({ apiKey: 'test-key', prompt: 'hello' })
await vi.advanceTimersByTimeAsync(500)
await expect(promise).resolves.toBe('undici-ok')
expect(fetchMock).toHaveBeenCalledTimes(2)
})

it('throws after exhausting all retries', async () => {
const err = Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' })
const fetchMock = vi.fn().mockRejectedValue(err)
vi.stubGlobal('fetch', fetchMock)

const promise = callAnthropic({ apiKey: 'test-key', prompt: 'hello' })
// Register the rejection handler before advancing timers to avoid an
// unhandled-rejection warning while the timers are firing.
const assertion = expect(promise).rejects.toThrow('timed out')
await vi.advanceTimersByTimeAsync(2000)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
})
})
})
34 changes: 34 additions & 0 deletions lib/net-utils.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Internal network/environment utilities for lib/prompts.mjs.
// This module may be shipped as an implementation detail, but it is not a
// supported public API; import it directly in tests rather than going through
// prompts.mjs.

import { readFileSync } from 'node:fs'

export function hasDnsResultOrderOverride() {
if (process.env.NODE_OPTIONS?.includes('--dns-result-order')) return true

for (let i = 0; i < process.execArgv.length; i++) {
const arg = process.execArgv[i]
if (arg === '--dns-result-order') return true
if (arg?.startsWith('--dns-result-order=')) return true

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[minor] setDefaultResultOrder('ipv4first') runs at prompts.mjs import time. If PR #58's AnthropicLlmClient (which doesn't import prompts.mjs) lands, this DNS fix won't protect those fetch() calls. Consider a shared init module.

}

return false
}

// Returns true only when running inside WSL2 (Windows Subsystem for Linux v2).
// Generic WSL env vars such as WSL_DISTRO_NAME / WSL_INTEROP are not enough to
// distinguish WSL1 from WSL2, so check kernel metadata for a WSL2-specific
// marker instead.
export function isWSL2() {
try {
if (/wsl2/i.test(readFileSync('/proc/sys/kernel/osrelease', 'utf8'))) return true
} catch {}

try {
return /microsoft.*wsl2|wsl2.*microsoft/i.test(readFileSync('/proc/version', 'utf8'))
} catch {
return false
}
}
Loading
Loading