Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: scale local code review timeout by diff size (#8009)

[._.]/ Adam Eivyd1ba8f86b580
diff --git a/server/scripts/run-local-code-review.mjs b/server/scripts/run-local-code-review.mjs
index 9f20fef64a..df5ffcf485 100644
--- a/server/scripts/run-local-code-review.mjs
+++ b/server/scripts/run-local-code-review.mjs
@@ -26,7 +26,11 @@ try {
const review = request.kind === 'claim-comments'
? runLocalClaimCommentReview
: runLocalCodeReview;
- const result = await review({ ...request, model, effort, cwd: process.cwd() });
+ const requestedTimeoutMs = request.timeoutMs;
+ const reviewRequest = { ...request };
+ delete reviewRequest.timeoutMs;
+ if (Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0) reviewRequest.timeoutMs = requestedTimeoutMs;
+ const result = await review({ ...reviewRequest, model, effort, cwd: process.cwd() });
process.stdout.write(`${JSON.stringify(result)}\n`);
const recordOutcome = result.ok
? reportReviewerSuccess(request.backend)
diff --git a/server/scripts/run-local-code-review.test.js b/server/scripts/run-local-code-review.test.js
index 00738a2df9..274c4811c3 100644
--- a/server/scripts/run-local-code-review.test.js
+++ b/server/scripts/run-local-code-review.test.js
@@ -276,7 +276,9 @@ it('shuts down the Codex app-server child and cleans up scratch resources after
expect(timeoutRes.code).toBe(1);
const timeoutStdout = JSON.parse(timeoutRes.stdout.trim());
- expect(timeoutStdout).toMatchObject({ ok: false, error: expect.stringMatching(/turn did not finish/i) });
+ expect(timeoutStdout).toMatchObject({ ok: false, error: expect.stringMatching(/did not finish/i) });
+ expect(timeoutStdout.error).toContain('250ms');
+ expect(timeoutStdout.error).toContain('1 KiB');
expect(timeoutRes.stderr).toContain('Codex app-server stopped');
const pid2 = parseInt(await readFile(pidFile2, 'utf8'), 10);
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 0a1f2ec458..66047493bf 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -154,6 +154,49 @@ export function isLocalLlmReviewer(backend) {
return LOCAL_LLM_REVIEWERS.includes(backend)
}
+const KIBIBYTE = 1024
+export const LOCAL_CODE_REVIEW_TIMEOUT_FLOOR_MS = 120_000
+export const LOCAL_CODE_REVIEW_TIMEOUT_CEILING_MS = 300_000
+export const LOCAL_CODE_REVIEW_TIMEOUT_PER_KIB_MS = 2_000
+
+/**
+ * Derive the default wall-clock budget for a code-review diff.
+ *
+ * The first KiB keeps today's 120-second cold-load floor. Each additional
+ * (partial) KiB adds two seconds for prefill and generation, up to the
+ * five-minute ceiling shared by the CLI provider runner. A positive explicit
+ * `timeoutMs` passed to `runLocalCodeReview` is an operator override and is
+ * intentionally not capped by this derived default.
+ */
+export function getLocalCodeReviewTimeoutMs(diff) {
+ const diffBytes = typeof diff === 'string' ? Buffer.byteLength(diff, 'utf8') : 0
+ const additionalKib = Math.max(0, Math.ceil(diffBytes / KIBIBYTE) - 1)
+ return Math.min(
+ LOCAL_CODE_REVIEW_TIMEOUT_CEILING_MS,
+ LOCAL_CODE_REVIEW_TIMEOUT_FLOOR_MS + additionalKib * LOCAL_CODE_REVIEW_TIMEOUT_PER_KIB_MS,
+ )
+}
+
+const diffSizeLabel = (diffSizeBytes) => {
+ const bytes = Math.max(0, Number(diffSizeBytes) || 0)
+ return `${Math.max(1, Math.ceil(bytes / KIBIBYTE))} KiB (${bytes} bytes)`
+}
+
+const isTimeoutFailure = (error) => /timed out after\s+\d+\s*ms|did not finish within\s+\d+(?:ms|s)|operation was aborted|request was aborted|abort(?:ed|ing)?/i.test(String(error || ''))
+
+function localCodeReviewTimeoutError({ backend, timeoutMs, diffSizeBytes, phase }) {
+ const description = phase === 'no-response'
+ ? 'backend never answered'
+ : phase === 'response-body'
+ ? 'backend was reachable but did not finish'
+ : 'reviewer process did not finish'
+ return `${backend} ${description} — timed out after ${timeoutMs}ms for a ${diffSizeLabel(diffSizeBytes)} diff.`
+}
+
+const effectiveLocalCodeReviewTimeout = (timeoutMs, diff) => (
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : getLocalCodeReviewTimeoutMs(diff)
+)
+
/**
* The reviewer chain the user actually configured, with aliases mapped and
* unknown enum values dropped — empty when they have configured none.
@@ -645,8 +688,15 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
return { ok: true, backend, model, effort: effort || provider.effort || null, content: result.text.trim() }
}
-async function runReviewerCompletion({ backend, model: pinnedModel, messages, effort, timeoutMs, baseUrl: requestedBaseUrl = null, cwd, toolFree = true }) {
- if (isProviderReviewer(backend)) return runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, effort, timeoutMs, cwd, toolFree })
+async function runReviewerCompletion({ backend, model: pinnedModel, messages, effort, timeoutMs, baseUrl: requestedBaseUrl = null, cwd, toolFree = true, diffSizeBytes = null }) {
+ if (isProviderReviewer(backend)) {
+ const result = await runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, effort, timeoutMs, cwd, toolFree })
+ if (result.ok || !Number.isFinite(diffSizeBytes) || !isTimeoutFailure(result.error)) return result
+ return {
+ ...result,
+ error: localCodeReviewTimeoutError({ backend, timeoutMs, diffSizeBytes, phase: 'reviewer-process' }),
+ }
+ }
if (!isLocalLlmReviewer(backend)) {
return { ok: false, error: `Unsupported reviewer backend: ${backend}` }
}
@@ -689,11 +739,32 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, ef
}
if (!attempt.ok) {
- if (attempt.error) return { ok: false, backend, model, error: `${backend} ${attempt.error}` }
+ if (attempt.error) {
+ return {
+ ok: false,
+ backend,
+ model,
+ error: Number.isFinite(diffSizeBytes) && isTimeoutFailure(attempt.error)
+ ? localCodeReviewTimeoutError({ backend, timeoutMs, diffSizeBytes, phase: 'no-response' })
+ : `${backend} ${attempt.error}`,
+ }
+ }
return { ok: false, backend, model, error: `${backend} API error ${attempt.status}: ${(attempt.text || '').slice(0, 300)}` }
}
- const data = await readResponseJson(attempt.response, { fallback: (raw) => ({ _nonJson: raw }) })
+ let data
+ try {
+ data = await readResponseJson(attempt.response, { fallback: (raw) => ({ _nonJson: raw }) })
+ } catch (err) {
+ return {
+ ok: false,
+ backend,
+ model,
+ error: Number.isFinite(diffSizeBytes) && isTimeoutFailure(err)
+ ? localCodeReviewTimeoutError({ backend, timeoutMs, diffSizeBytes, phase: 'response-body' })
+ : `${backend} response failed: ${err.message}`,
+ }
+ }
if (data?._nonJson !== undefined) {
return { ok: false, backend, model, error: `${backend} returned a non-JSON response: ${data._nonJson.slice(0, 300)}` }
}
@@ -732,12 +803,13 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, ef
* request), and `absent` is the only spelling of "use the model's own
* default". The response carries `effortUnsupported: true` when a pinned
* level was dropped for that reason.
- * @param {number} [opts.timeoutMs=120000] - 2 min default — LM Studio cold-
- * load of a large coder model regularly exceeds 30s but rarely 2 min.
+ * @param {number} [opts.timeoutMs] - positive explicit wall-clock override;
+ * otherwise a diff-size budget keeps the 2 min cold-load floor and grows to
+ * the documented 5 min ceiling.
* @param {string} [opts.baseUrl] - Validated local OpenAI-compatible base URL;
* defaults to the backend manager's current URL.
*/
-export async function runLocalCodeReview({ backend, model, diff, effort = null, timeoutMs = 120000, baseUrl = null, cwd = null, toolFree = false } = {}) {
+export async function runLocalCodeReview({ backend, model, diff, effort = null, timeoutMs = undefined, baseUrl = null, cwd = null, toolFree = false } = {}) {
if (!isToolFreeReviewer(backend)) {
return { ok: false, error: `Unsupported reviewer backend: ${backend}` }
}
@@ -749,6 +821,8 @@ export async function runLocalCodeReview({ backend, model, diff, effort = null,
return { ok: false, error: 'Empty diff — nothing to review.' }
}
+ const diffSizeBytes = Buffer.byteLength(trimmedDiff, 'utf8')
+ const reviewTimeoutMs = effectiveLocalCodeReviewTimeout(timeoutMs, trimmedDiff)
// The diff is untrusted content flowing into a fenced code block — a diff
// touching a file that itself contains a ``` sequence (e.g. editing this
// very prompt-fence, or a markdown/doc file) would close the fence early,
@@ -761,7 +835,8 @@ export async function runLocalCodeReview({ backend, model, diff, effort = null,
backend,
model,
effort,
- timeoutMs,
+ timeoutMs: reviewTimeoutMs,
+ diffSizeBytes,
baseUrl,
cwd,
toolFree,
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index a6987055dc..269e3542ba 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -50,6 +50,9 @@ import {
runLocalGoalFidelityReview,
getGoalFidelityConfig,
runLocalCodeReview,
+ getLocalCodeReviewTimeoutMs,
+ LOCAL_CODE_REVIEW_TIMEOUT_FLOOR_MS,
+ LOCAL_CODE_REVIEW_TIMEOUT_CEILING_MS,
getReviewerCliInstalled,
getReviewerConfigHealth,
reportReviewerFailure,
@@ -608,6 +611,42 @@ describe('codeReview helpers', () => {
expect(r.error).toMatch(/Empty diff/)
})
+ it('scales the default timeout with diff size and enforces its ceiling', () => {
+ const small = getLocalCodeReviewTimeoutMs('x'.repeat(1024))
+ const large = getLocalCodeReviewTimeoutMs('x'.repeat(20 * 1024))
+ const huge = getLocalCodeReviewTimeoutMs('x'.repeat(200 * 1024))
+
+ expect(small).toBe(LOCAL_CODE_REVIEW_TIMEOUT_FLOOR_MS)
+ expect(large).toBeGreaterThan(small)
+ expect(huge).toBe(LOCAL_CODE_REVIEW_TIMEOUT_CEILING_MS)
+ })
+
+ it('reports a backend that never answers with the effective budget and diff size', async () => {
+ const abortError = Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })
+ global.fetch = vi.fn().mockRejectedValue(abortError)
+ const diff = 'x'.repeat(20 * 1024)
+ const result = await runLocalCodeReview({ backend: 'ollama', model: 'm', diff })
+
+ expect(result.ok).toBe(false)
+ expect(result.error).toContain('backend never answered')
+ expect(result.error).toContain(`timed out after ${getLocalCodeReviewTimeoutMs(diff)}ms`)
+ expect(result.error).toContain('20 KiB (20480 bytes) diff')
+ })
+
+ it('distinguishes a reachable backend whose response body does not finish', async () => {
+ const abortError = Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ text: vi.fn().mockRejectedValue(abortError),
+ })
+ const result = await runLocalCodeReview({ backend: 'lmstudio', model: 'm', diff: 'x'.repeat(2048) })
+
+ expect(result.ok).toBe(false)
+ expect(result.error).toContain('backend was reachable but did not finish')
+ expect(result.error).toContain('2 KiB (2048 bytes) diff')
+ })
+
it('omits reasoning_effort entirely when no effort is pinned — absent is the only spelling of the model default', async () => {
await runLocalCodeReview({ backend: 'ollama', model: 'codellama', diff: 'd' })
const body = JSON.parse(global.fetch.mock.calls[0][1].body)