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: bound review preparation and retain failures across batches (#13291)

[._.]/ Adam Eivy291f020af636
diff --git a/server/lib/README.md b/server/lib/README.md
index 0812e7d946..cc2ef38a69 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -517,7 +517,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). `insecureFetch` size-cap rejections carry `code: RESPONSE_TOO_LARGE`. |
-| `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. |
+| `abortTimeout.js` | `awaitWithAbort(promise, signal)` cancels a caller's wait while owning eventual rejection of shared preparation; `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. |
| `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |
| `tailnetPeer.js` | `isTailnetPeer(peer)` — fail-closed security predicate for "is this peer reachable only over the tailnet". Deliberately separate from `instances.js`'s `peerRequiresTailscale()` probe-deferral heuristic so a polling-noise tweak can't widen a privacy boundary; required by the unattended-routing gate in ADR 2026-08-20-federated-visual-prompts. |
| `federatedMediaRequest.js` | Builds and validates the versioned federated-media submission body for a visual kind, so every call site that persists a remote-job marker projects local params onto the wire identically. |
diff --git a/server/lib/abortTimeout.js b/server/lib/abortTimeout.js
index 3ca65f1c0c..078be32105 100644
--- a/server/lib/abortTimeout.js
+++ b/server/lib/abortTimeout.js
@@ -22,3 +22,22 @@ export async function withAbortTimeout(timeoutMs, fn) {
clearTimeout(timer);
}
}
+
+/** Cancel waiting without cancelling work shared by other callers. The original
+ * promise remains rejection-owned; its eventual completion cannot resume this caller.
+ */
+export function awaitWithAbort(promise, signal) {
+ if (!signal) return promise;
+ return new Promise((resolve, reject) => {
+ const onAbort = () => reject(signal.reason || new DOMException('Operation aborted', 'AbortError'));
+ if (signal.aborted) onAbort();
+ else signal.addEventListener('abort', onAbort, { once: true });
+ Promise.resolve(promise).then(value => {
+ signal.removeEventListener('abort', onAbort);
+ resolve(value);
+ }, error => {
+ signal.removeEventListener('abort', onAbort);
+ reject(error);
+ });
+ });
+}
diff --git a/server/lib/codeReviewBatches.js b/server/lib/codeReviewBatches.js
index bb1c50b4e9..fadcdbcb80 100644
--- a/server/lib/codeReviewBatches.js
+++ b/server/lib/codeReviewBatches.js
@@ -12,7 +12,16 @@ export function isReviewContextCapacityFailure(result) {
// Successful JSON verdicts may legitimately discuss context-capacity bugs.
// Classify structured errors or plain vendor refusals, never their quoted text.
const plain = value => typeof value === 'string' && !/^[\s]*[\[{`]/.test(value) ? value : null;
- return [result?.error, result?.error?.message,
+ const streamErrors = [];
+ if (result?.streamFormat === 'stream-json' && typeof result.text === 'string') {
+ for (const line of result.text.split('\n')) {
+ try {
+ const event = JSON.parse(line);
+ if (event?.is_error || event?.type === 'error') streamErrors.push(event.error?.message, event.error, event.message, event.result);
+ } catch { /* Incomplete stream lines cannot establish a capacity refusal. */ }
+ }
+ }
+ return [...streamErrors, result?.error, result?.error?.message,
result?.error || result?.partial ? result?.stderr : null,
plain(result?.text), plain(result?.content)].some(value =>
typeof value === 'string' && /prompt is too long|context[_ ](?:length[_ ]exceeded|window[_ ]exceeded)|maximum context length|exceeds? (?:the |your )?(?:model.s? )?(?:context|input) (?:window|limit|length)|input (?:is )?too (?:long|large)/i.test(value));
@@ -80,7 +89,8 @@ export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, max
continue;
}
const input = batch.files.map(file => file.diff).join('');
- const result = await runBatch(input, remainingMs, budget);
+ const result = await Promise.resolve().then(() => runBatch(input, remainingMs, budget))
+ .catch(() => ({ ok: false, code: 'REVIEW_BATCH_FAILED', error: 'A review batch failed before returning a verdict; review coverage is incomplete.' }));
identity = { ...identity, ...Object.fromEntries(['backend', 'model', 'effort', 'effortUnsupported'].filter(key => result[key] !== undefined).map(key => [key, result[key]])) };
const capacity = isReviewContextCapacityFailure(result) || result.code === 'REVIEW_CONTEXT_CAPACITY';
batches.push({ files: batch.files.map(file => file.id), diffSha256: digest(input), outcome: result.ok ? result.verdict : capacity ? 'context_capacity' : 'inconclusive', attempted: true });
@@ -116,7 +126,7 @@ export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, max
error: failure?.code === 'REVIEW_CONTEXT_CAPACITY'
? 'The selected reviewer could not cover every file within its context capacity; review coverage is incomplete.'
: failure?.code === 'REVIEW_BUDGET_EXHAUSTED'
- ? 'The configured review budget ended before every file received a verdict; review coverage is incomplete.'
+ ? failure?.error || 'The configured review budget ended before every file received a verdict; review coverage is incomplete.'
: failure?.error || 'A review batch returned no usable verdict; review coverage is incomplete.',
} : {}),
};
diff --git a/server/lib/codeReviewBatches.test.js b/server/lib/codeReviewBatches.test.js
new file mode 100644
index 0000000000..12fb3784a6
--- /dev/null
+++ b/server/lib/codeReviewBatches.test.js
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import { runCodeReviewBatches, takeCodeReviewCallBudget } from './codeReviewBatches.js';
+
+// This state-machine edge cannot be simulated by an HTTP error: it is the
+// orchestration callback itself rejecting after earlier validated findings.
+describe('code review batch exceptions', () => {
+ it('keeps completed findings and exact coverage when later preparation throws', async () => {
+ const section = name => `diff --git a/${name} b/${name}\n+${'x'.repeat(700)}\n`;
+ let calls = 0;
+ const result = await runCodeReviewBatches({ diff: section('a.js') + section('b.js'), headSha: 'a'.repeat(40), budgetMs: 1000, maxBatchBytes: 1024,
+ runBatch: async (_input, remainingMs, budget) => {
+ takeCodeReviewCallBudget(budget, remainingMs);
+ if (calls++) throw new Error('/private/preparation');
+ return { ok: true, verdict: 'findings', findings: 'Serialize the persisted write.' };
+ },
+ });
+ expect(result).toMatchObject({ ok: false, code: 'REVIEW_BATCH_FAILED', verdict: 'findings', findings: 'Serialize the persisted write.', coverage: { headSha: 'a'.repeat(40), complete: false, calls: 2, reviewedFiles: [0], remainingFiles: [1] } });
+ expect(JSON.stringify(result)).not.toContain('/private/preparation');
+ });
+});
diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.js
index b1c66ca002..f7b969650c 100644
--- a/server/lib/credentialBootstrap.js
+++ b/server/lib/credentialBootstrap.js
@@ -103,7 +103,8 @@ const BOOTSTRAP_ENV_TTL_MS = 60_000;
* the wrap (see module doc), and returns `{}` here. Nothing about a review
* requires an `envCommand`.
*/
-export async function resolveBootstrapEnv(provider, { safetyProfile = null } = {}) {
+export async function resolveBootstrapEnv(provider, { safetyProfile = null, timeoutMs = 15_000, signal = undefined } = {}) {
+ if (signal?.aborted) throw new Error('Bootstrap credential command cancelled.');
const argv = provider?.credentialBootstrap?.envCommand;
if (!argv) return {};
if (safetyProfile && !isPublicReviewNoToolProfile(safetyProfile)) {
@@ -127,7 +128,7 @@ export async function resolveBootstrapEnv(provider, { safetyProfile = null } = {
// output, and never propagate stderr/stdout or the command in an error.
execFile(spawnConfig.command, spawnConfig.args, {
cwd, env: childEnv,
- shell: false, timeout: 15_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
+ shell: false, timeout: Math.max(1, Math.min(15_000, timeoutMs)), signal, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
}, (error, stdout) => {
if (error) return reject(new Error('Bootstrap credential command failed.'));
const entries = String(stdout).split(/\r?\n/).flatMap(line => {
diff --git a/server/lib/credentialBootstrap.test.js b/server/lib/credentialBootstrap.test.js
index a99d276034..c4666e95ee 100644
--- a/server/lib/credentialBootstrap.test.js
+++ b/server/lib/credentialBootstrap.test.js
@@ -346,6 +346,21 @@ describe('resolveBootstrapEnv', () => {
expect(spawn).toHaveBeenCalledTimes(3);
});
+ it('passes the review deadline and cancellation signal to credential preparation', async () => {
+ const controller = new AbortController();
+ const spawn = vi.spyOn(childProcess, 'execFile').mockImplementation((_command, _args, options, callback) => {
+ expect(options.timeout).toBe(42);
+ expect(options.signal).toBe(controller.signal);
+ options.signal.addEventListener('abort', () => callback(new Error('private diagnostic')), { once: true });
+ return { pid: 123 };
+ });
+ const pending = resolveBootstrapEnv(record('cancelled-credentials', 'unused'), { ...profile, timeoutMs: 42, signal: controller.signal });
+ controller.abort();
+ await expect(pending).rejects.toThrow(/^Bootstrap credential command failed\.$/);
+ await expect(resolveBootstrapEnv(record('already-cancelled', 'unused'), { ...profile, signal: controller.signal })).rejects.toThrow('cancelled');
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
it('rejects actions before executing and never exposes failed command output', async () => {
const provider = record('failure-example', 'console.error("example-private-value"); process.exit(1)');
await expect(resolveBootstrapEnv(provider, { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE })).rejects.toThrow('only for tool-free');
diff --git a/server/services/aiProvider.js b/server/services/aiProvider.js
index d2adc2dd7c..31cc9075e4 100644
--- a/server/services/aiProvider.js
+++ b/server/services/aiProvider.js
@@ -1,3 +1,4 @@
+import { awaitWithAbort } from '../lib/abortTimeout.js';
/**
* Shared AI provider utilities for LLM calls.
* Used by insightsService, identity, goalCheckIn, taste-questionnaire, etc.
@@ -461,6 +462,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
// subscription quota for an answer nobody is waiting for. The HTTP path
// manages its own AbortController from `timeout`.
signal = null,
+ deadlineMs = null,
// Internal: the status op an outer attempt already opened. `startAIOp` mints
// a fresh id per call and the client tracks ops BY ID, so a fallback leg that
// opened its own would leave the outer one's loading toast spinning forever
@@ -468,6 +470,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
// one op: "falling back to X…" → "done".
__statusOp = null,
} = options;
+ if (signal?.aborted || (Number.isFinite(deadlineMs) && Date.now() >= deadlineMs)) return { error: 'Provider request deadline expired.' };
if (provider.type !== 'api' && !isSubscriptionText(provider)) {
return { error: 'This operation requires an API-based provider' };
}
@@ -540,14 +543,19 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
// doesn't get a bare connection refusal.
// Provider selection and parsing need none of the managed daemon graph.
const { ensureManagedRuntimeReady } = await import('./providerExecutionReadiness.js');
- const ready = await ensureManagedRuntimeReady(provider, {
+ const ready = await awaitWithAbort(ensureManagedRuntimeReady(provider, {
onStarting: (label) => statusOp.update('provider:starting', `Starting ${label} if needed…`, { providerId: provider.id }),
- });
+ }), signal).catch(() => ({ success: false, error: 'Provider readiness cancelled.' }));
if (!ready.success) {
statusOp.error(ready.error);
return { error: ready.error };
}
+ if (signal?.aborted || (Number.isFinite(deadlineMs) && Date.now() >= deadlineMs)) {
+ statusOp.error('Provider request deadline expired.');
+ return { error: 'Provider request deadline expired.' };
+ }
+ if (Number.isFinite(deadlineMs)) opts.timeout = Math.min(opts.timeout, deadlineMs - Date.now());
const first = await postChatCompletion(provider, model, body, opts);
if (!first.error) {
statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, throughput(first.tokens));
diff --git a/server/services/aiProvider.test.js b/server/services/aiProvider.test.js
index 6d8435b586..9d20141428 100644
--- a/server/services/aiProvider.test.js
+++ b/server/services/aiProvider.test.js
@@ -583,3 +583,41 @@ describe('HTTP provider body cancellation', () => {
expect(vi.getTimerCount()).toBe(0);
});
});
+
+
+describe('provider review preparation deadline', () => {
+ afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
+
+ it('cancels readiness waiting and never dispatches inference when shared startup finishes later', async () => {
+ const { ensureProviderReady, isOllamaProvider } = await import('./ollamaManager.js');
+ vi.mocked(isOllamaProvider).mockReturnValue(true);
+ let finishReady;
+ let entered;
+ const started = new Promise(resolve => { entered = resolve; });
+ vi.mocked(ensureProviderReady).mockImplementationOnce(() => { entered(); return new Promise(resolve => { finishReady = resolve; }); });
+ const controller = new AbortController();
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+ const pending = callProviderAISimple({ id: 'deadline-local', type: 'api', endpoint: 'http://localhost:11434/v1' }, 'm', 'prompt', { signal: controller.signal, deadlineMs: Date.now() + 1000, allowModelRecovery: false });
+ await started;
+ controller.abort();
+ expect(await pending).toMatchObject({ error: 'Provider readiness cancelled.' });
+ finishReady({ success: true });
+ await Promise.resolve();
+ expect(fetch).not.toHaveBeenCalled();
+ vi.mocked(isOllamaProvider).mockReturnValue(false);
+ });
+
+ it('rechecks the absolute deadline after readiness before sending the completion', async () => {
+ const { ensureProviderReady, isOllamaProvider } = await import('./ollamaManager.js');
+ let now = 0;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ vi.mocked(isOllamaProvider).mockReturnValue(true);
+ vi.mocked(ensureProviderReady).mockImplementationOnce(async () => { now = 200; return { success: true }; });
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+ expect(await callProviderAISimple({ id: 'deadline-after-ready', type: 'api', endpoint: 'http://localhost:11434/v1' }, 'm', 'prompt', { deadlineMs: 100, allowModelRecovery: false })).toMatchObject({ error: 'Provider request deadline expired.' });
+ expect(fetch).not.toHaveBeenCalled();
+ vi.mocked(isOllamaProvider).mockReturnValue(false);
+ });
+});
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 9d800f91ec..81225b5369 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -13,6 +13,7 @@
*/
import { CODE_REVIEW_BATCH_BYTES, CODE_REVIEW_MAX_BATCHES, runCodeReviewBatches, takeCodeReviewCallBudget, isReviewContextCapacityFailure, reviewContextCapacityFailure } from '../lib/codeReviewBatches.js'
+import { withAbortTimeout, awaitWithAbort } from '../lib/abortTimeout.js'
import { effortLevelsForProvider } from '../lib/providerModels.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readResponseJson } from '../lib/readResponseJson.js'
@@ -842,12 +843,17 @@ export function __resetThinkingUnsupportedCache() { thinkingUnsupportedModels.cl
* fall through to the request (and its 400-retry) rather than silently
* dropping a level the model does in fact accept.
*/
-async function modelRejectsThinking(backend, model) {
+async function modelRejectsThinking(backend, model, reviewBudget = null) {
const cacheKey = thinkingCacheKey(backend, model)
if (thinkingUnsupportedModels.get(cacheKey) === true) return true
if (backend !== 'ollama') return false
const capabilities = await import('./ollamaManager.js')
- .then(({ getModelCapabilities }) => getModelCapabilities(model))
+ .then(({ getModelCapabilities }) => {
+ if (!reviewBudget) return getModelCapabilities(model)
+ const remainingMs = reviewBudget.deadline - Date.now()
+ if (remainingMs <= 0) return null
+ return withAbortTimeout(remainingMs, signal => awaitWithAbort(getModelCapabilities(model, { signal, timeout: remainingMs }), signal))
+ })
.catch(() => null)
if (!Array.isArray(capabilities) || capabilities.length === 0) return false
if (capabilities.includes('thinking')) return false
@@ -1001,8 +1007,9 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
const { callProviderAISimple } = await import('./aiProvider.js')
budgetMs = takeCodeReviewCallBudget(reviewBudget, budgetMs)
if (budgetMs === null) return { ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', error: 'The configured review budget is exhausted.' }
- result = await callProviderAISimple({ ...provider, apiKey: provider.apiKey, timeout: budgetMs, fallbackProvider: null }, model,
- prompt, { max_tokens: 8192, allowModelRecovery: false })
+ result = await withAbortTimeout(budgetMs, signal => awaitWithAbort(callProviderAISimple({ ...provider, apiKey: provider.apiKey, timeout: budgetMs, fallbackProvider: null }, model,
+ prompt, { max_tokens: 8192, allowModelRecovery: false, signal, deadlineMs: reviewBudget?.deadline }), signal))
+ .catch(() => ({ error: 'Reviewer preparation or execution failed within its shared budget.', code: reviewBudget && Date.now() >= reviewBudget.deadline ? 'REVIEW_BUDGET_EXHAUSTED' : 'REVIEW_BATCH_FAILED' }))
} else {
if (!transport.transport) return { ok: false, code: transport.code, error: transport.error }
const { runCliProviderPrompt } = await import('../lib/cliProviderRun.js')
@@ -1021,12 +1028,14 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
const cwd = isolatedCwd || reviewCwd
result = await Promise.resolve().then(async () => {
const { resolveBootstrapEnv } = await import('../lib/credentialBootstrap.js')
- const bootstrapEnv = await resolveBootstrapEnv(provider, { safetyProfile })
+ const preparationMs = reviewBudget ? reviewBudget.deadline - Date.now() : timeoutMs
+ if (preparationMs <= 0) return { error: 'The configured review budget is exhausted.', code: 'REVIEW_BUDGET_EXHAUSTED' }
+ const bootstrapEnv = await withAbortTimeout(preparationMs, signal => awaitWithAbort(resolveBootstrapEnv(provider, { safetyProfile, signal, timeoutMs: preparationMs }), signal))
const remainingMs = takeCodeReviewCallBudget(reviewBudget, timeoutMs)
if (remainingMs === null) return { error: 'The configured review budget is exhausted.', code: 'REVIEW_BUDGET_EXHAUSTED' }
return runCliProviderPrompt({ provider, model, prompt, cwd, timeoutMs: remainingMs, bootstrapEnv, exactPins: true,
safetyProfile, codeReview: true })
- }).catch(() => ({ error: 'Reviewer credential setup or execution failed.' }))
+ }).catch(() => ({ error: 'Reviewer credential setup or execution failed.', code: reviewBudget && Date.now() >= reviewBudget.deadline ? 'REVIEW_BUDGET_EXHAUSTED' : 'REVIEW_BATCH_FAILED' }))
.finally(() => isolatedCwd && rm(isolatedCwd, { recursive: true, force: true }))
// A failed headless command request is a configuration fault, not a verdict.
// Replace vendor prose with a bounded remedy before health or bridge output.
@@ -1124,7 +1133,7 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
// Probe only when there is actually a level to drop — an unpinned effort
// sends no field either way, so a capability round-trip would buy nothing.
const requestedEffort = normalizeReviewerEffort(effort, backend) || null
- let effortUnsupported = requestedEffort ? await modelRejectsThinking(backend, model) : false
+ let effortUnsupported = requestedEffort ? await modelRejectsThinking(backend, model, reviewBudget) : false
let resolvedEffort = effortUnsupported ? null : requestedEffort
let remainingMs = takeCodeReviewCallBudget(reviewBudget, timeoutMs)
@@ -1292,6 +1301,7 @@ async function runSingleCodeReview({ backend, model, diff, effort = null, timeou
userMessage: { role: 'user', content: `Review this PR diff:\n\n${fence}diff\n${trimmedDiff}\n${fence}` },
})
if (isReviewContextCapacityFailure(result)) return { ...reviewContextCapacityFailure(), backend, model: result.model || model, effort }
+ if (result.code === 'REVIEW_BUDGET_EXHAUSTED') return { ...result, error: localCodeReviewTimeoutError({ backend, timeoutMs: reviewBudget?.budgetMs ?? reviewTimeoutMs, diffSizeBytes, phase: 'reviewer-process' }) }
if (!result.ok) return result
const { verdict, reason } = normalizeCodeReviewVerdict(result.content)
if (!verdict) return {
diff --git a/server/services/codeReview.providers.test.js b/server/services/codeReview.providers.test.js
index 86ec628004..dc7c89c002 100644
--- a/server/services/codeReview.providers.test.js
+++ b/server/services/codeReview.providers.test.js
@@ -217,6 +217,44 @@ describe('configured provider reviewers', () => {
expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false });
});
+ it.each([true, false])('classifies Claude stream capacity refusals without leaking events or paths (partial=%s)', async partial => {
+ getProviderById.mockResolvedValue({ ...provider, type: 'tui', command: 'claude' });
+ runCliProviderPrompt.mockResolvedValue({ text: JSON.stringify({ type: 'result', is_error: true, result: 'Prompt is too long /private/example' }), partial, streamFormat: 'stream-json' });
+ const result = await runLocalCodeReview({ backend, diff: 'example diff' });
+ expect(result).toMatchObject({ ok: false, code: 'REVIEW_CONTEXT_CAPACITY', coverage: { complete: false, remainingFiles: [0] } });
+ expect(JSON.stringify(result)).not.toContain('/private/example');
+ expect(result).not.toHaveProperty('text');
+ expect(result).not.toHaveProperty('verdict');
+ });
+
+ it('retains prior findings and immutable coverage when the next provider batch rejects', async () => {
+ const section = name => `diff --git a/${name} b/${name}\n+${'x'.repeat(700)}\n`;
+ callProviderAISimple.mockResolvedValueOnce({ text: JSON.stringify({ verdict: 'findings', findings: [{ severity: 'blocking', location: 'a.js:1', outcome: 'Write loses data.', fix: 'Serialize writes.' }] }) }).mockRejectedValueOnce(new Error('/private/provider/setup'));
+ const result = await runLocalCodeReview({ backend, diff: section('a.js') + section('b.js'), maxBatchBytes: 1024 });
+ expect(result).toMatchObject({ ok: false, verdict: 'findings', coverage: { reviewedFiles: [0], remainingFiles: [1] } });
+ expect(result.findings).toContain('Write loses data.');
+ expect(JSON.stringify(result)).not.toContain('/private/provider/setup');
+ });
+
+ it('cancels pending reviewer preparation at the absolute deadline without accepting a late verdict', async () => {
+ vi.useFakeTimers();
+ try {
+ let entered;
+ const started = new Promise(resolve => { entered = resolve; });
+ let capturedSignal;
+ callProviderAISimple.mockImplementationOnce((_provider, _model, _prompt, options) => {
+ capturedSignal = options.signal;
+ entered();
+ return new Promise(() => {});
+ });
+ const pending = runLocalCodeReview({ backend, diff: 'example diff', timeoutMs: 100 });
+ await started;
+ await vi.advanceTimersByTimeAsync(100);
+ expect(await pending).toMatchObject({ ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', coverage: { complete: false, calls: 1 } });
+ expect(capturedSignal.aborted).toBe(true);
+ } finally { vi.useRealTimers(); }
+ });
+
it('reports an oversized-input spawn failure as a specific non-verdict, not a credential fault (#10273)', async () => {
getProviderById.mockResolvedValue({ ...provider, type: 'tui', command: 'claude' });
runCliProviderPrompt.mockResolvedValue({ error: "Prompt is too large for agy's command-line transport (E2BIG); the run was not started. Reduce the input size.", code: 'E2BIG' });
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 06e4ad92b2..c75c6fde14 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -1229,13 +1229,13 @@ const modelDetailsCache = new Map() // name -> { contextLength: number|null, cap
* @param {string} name
* @returns {Promise<{ contextLength: number|null, capabilities: string[]|null }>}
*/
-async function getModelDetails(name) {
+async function getModelDetails(name, requestOptions = {}) {
const miss = { contextLength: null, capabilities: null }
if (!name) return miss
if (modelDetailsCache.has(name)) return modelDetailsCache.get(name)
// /api/show documents the id under `model`; current Ollama also accepts the
// legacy `name`, so send both (extra fields are ignored) for cross-version safety.
- const data = await ollamaRequest('/api/show', { method: 'POST', body: JSON.stringify({ model: name, name }) }).catch(() => null)
+ const data = await ollamaRequest('/api/show', { ...requestOptions, method: 'POST', body: JSON.stringify({ model: name, name }) }).catch(() => null)
// A transient /api/show failure must NOT be cached — that would pin the model
// with no context label / wrong vision flag until restart. Only cache when the
// daemon actually answered; a present-but-missing field legitimately caches
@@ -1263,8 +1263,8 @@ async function getModelDetails(name) {
* @param {string} name
* @returns {Promise<string[]|null>}
*/
-async function getModelCapabilities(name) {
- return (await getModelDetails(name)).capabilities
+async function getModelCapabilities(name, requestOptions = {}) {
+ return (await getModelDetails(name, requestOptions)).capabilities
}
/** Add `contextLength` + `capabilities` to each model (parallel, cached). */
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index 9716cd64c2..cab87e4b15 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -194,6 +194,21 @@ describe('ollamaManager model capability sentinel', () => {
await expect(getModelCapabilities('example-model')).resolves.toBeNull()
})
+ it('cancels a pending capability probe at the caller deadline', async () => {
+ const controller = new AbortController();
+ let entered;
+ const started = new Promise(resolve => { entered = resolve; });
+ vi.stubGlobal('fetch', vi.fn((_url, options) => {
+ entered();
+ return new Promise((_resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true }));
+ }));
+ const { getModelCapabilities } = await loadManager();
+ const pending = getModelCapabilities('deadline-example', { signal: controller.signal, timeout: 42 });
+ await started;
+ controller.abort();
+ await expect(pending).resolves.toBeNull();
+ });
+
it('keeps an answered empty capability set distinct from a failed probe', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,