Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): bound client requests (#1444)
Call White94e279aea1cf
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 2be516000..f189313c2 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -6,7 +6,7 @@// Methods unwrap the frozen envelope ({ok:true, …} | {ok:false, error}) and// throw an Error carrying the machine code on failure, so callers work with// plain domain objects.-import { apiFetch } from '@/lib/apiFetch';+import { apiFetch, isApiFetchDeadlineAbort, withApiDeadline } from '@/lib/apiFetch';import { MODELS_API_MODE } from './featureFlags';import {buildMockAgents,@@ -272,36 +272,61 @@ export const apiFailure = (}: null;+// The server owns the execution ceiling; this browser deadline is only a+// backstop for a server that never answers, so it must outlast that controlled+// failure. The margin covers CSRF acquisition, both transits (including a+// tunnel), one fast CSRF-rejected attempt and replay, handler dispatch, and body+// decoding. Keep the ceiling aligned with model_hub_client.py:_RPC_TIMEOUT_SECONDS.+export const MODEL_HUB_RPC_CEILING_MS = 300_000;+const TRANSPORT_MARGIN_MS = 30_000;+export const MODEL_HUB_REQUEST_DEADLINE_MS =+ MODEL_HUB_RPC_CEILING_MS + TRANSPORT_MARGIN_MS;+async function call<T>(path: string, init?: RequestInit): Promise<T> {- const res = await apiFetch(path, init);- let payload: unknown = null;try {- payload = await res.json();- } catch {- // Invented here, not read off the wire: the request may well have been- // carried out and its answer lost coming back.- throw new ApiCallError('bad_response', `Non-JSON response from ${path}`, false, [], [], [], res.status);- }- const envelope = payload && typeof payload === 'object' ? payload as Record<string, unknown> : {};- if (!res.ok || envelope.ok === false) {- const error = typeof envelope.error === 'string' ? envelope.error : null;- throw new ApiCallError(- error ?? `http_${res.status}`,- typeof envelope.detail === 'string' ? envelope.detail : undefined,- // `payload.error` is the only thing that carries a route's own verdict, so- // its presence IS the answer. `http_502` is this client summarizing a- // response that never gave one.- error !== null,- supplyGaps(envelope.would_interrupt),- supplyGaps(envelope.interrupted_pairs),- routeHopRefs(envelope.would_remove_hops),- res.status,- typeof envelope.observation === 'object' && envelope.observation !== null- ? envelope.observation as SourceObservation- : undefined,+ return await withApiDeadline(+ MODEL_HUB_REQUEST_DEADLINE_MS,+ init?.signal ?? undefined,+ async (signal) => {+ const res = await apiFetch(path, { ...init, signal });+ let payload: unknown = null;+ try {+ payload = await res.json();+ } catch (error) {+ if (signal.aborted) {+ throw signal.reason ?? error;+ }+ // Invented here, not read off the wire: the request may well have been+ // carried out and its answer lost coming back.+ throw new ApiCallError('bad_response', `Non-JSON response from ${path}`, false, [], [], [], res.status);+ }+ const envelope = payload && typeof payload === 'object' ? payload as Record<string, unknown> : {};+ if (!res.ok || envelope.ok === false) {+ const error = typeof envelope.error === 'string' ? envelope.error : null;+ throw new ApiCallError(+ error ?? `http_${res.status}`,+ typeof envelope.detail === 'string' ? envelope.detail : undefined,+ // `payload.error` is the only thing that carries a route's own verdict, so+ // its presence IS the answer. `http_502` is this client summarizing a+ // response that never gave one.+ error !== null,+ supplyGaps(envelope.would_interrupt),+ supplyGaps(envelope.interrupted_pairs),+ routeHopRefs(envelope.would_remove_hops),+ res.status,+ typeof envelope.observation === 'object' && envelope.observation !== null+ ? envelope.observation as SourceObservation+ : undefined,+ );+ }+ return payload as T;+ },);+ } catch (error) {+ if (!isApiFetchDeadlineAbort(error)) throw error;+ // The deadline says the answer did not arrive, not whether the route wrote.+ throw new ApiCallError('bad_response', `Request deadline exceeded for ${path}`, false);}- return payload as T;}const jsonInit = (method: string, body?: unknown): RequestInit => ({diff --git a/ui/src/components/settings/models/modelsApiDeadline.test.ts b/ui/src/components/settings/models/modelsApiDeadline.test.tsnew file mode 100644index 000000000..4d21a9ef7--- /dev/null+++ b/ui/src/components/settings/models/modelsApiDeadline.test.ts@@ -0,0 +1,186 @@+import { readFile } from 'node:fs/promises';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { classifyModelHubFailure } from './asyncLifetime';+import {+ apiFailure,+ ApiCallError,+ MODEL_HUB_REQUEST_DEADLINE_MS,+ MODEL_HUB_RPC_CEILING_MS,+ modelsApi,+} from './modelsApi';++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('Model Hub request deadlines', () => {+ it('keeps the browser backstop beyond the backend RPC ceiling', async () => {+ const backendSource = await readFile('../vibe/model_hub_client.py', 'utf8');+ const match = backendSource.match(/_RPC_TIMEOUT_SECONDS\s*=\s*([\d.]+)/);++ expect(match?.[1]).toBeDefined();+ expect(MODEL_HUB_RPC_CEILING_MS).toBe(Number(match![1]) * 1_000);+ expect(MODEL_HUB_REQUEST_DEADLINE_MS).toBeGreaterThan(MODEL_HUB_RPC_CEILING_MS);+ });++ it('bounds every request issued by every live client method', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=test-token' });+ const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_, reject) => {+ const signal = init?.signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }));+ vi.stubGlobal('fetch', fetchMock);+ const methods = Object.entries(modelsApi).filter(+ (entry): entry is [string, (...args: never[]) => Promise<unknown>] =>+ typeof entry[1] === 'function',+ );+ const issuedSignals: AbortSignal[] = [];++ for (const [name, method] of methods) {+ const callsBefore = fetchMock.mock.calls.length;+ const settled = method().then(() => undefined, () => undefined);+ await vi.advanceTimersByTimeAsync(0);+ const calls = fetchMock.mock.calls.slice(callsBefore);+ expect(calls.length, `${name} must issue a deadline-bound request`).toBeGreaterThan(0);+ for (const [, init] of calls) {+ expect(init?.signal, `${name} dropped its request deadline`).toBeInstanceOf(AbortSignal);+ issuedSignals.push(init!.signal!);+ }+ expect(calls.every(([, init]) => !init?.signal?.aborted)).toBe(true);+ await vi.advanceTimersByTimeAsync(MODEL_HUB_REQUEST_DEADLINE_MS - 1);+ expect(calls.every(([, init]) => !init?.signal?.aborted)).toBe(true);+ await vi.advanceTimersByTimeAsync(1);+ expect(calls.every(([, init]) => init?.signal?.aborted)).toBe(true);+ await settled;+ expect(vi.getTimerCount()).toBe(0);+ }++ expect(issuedSignals).toHaveLength(fetchMock.mock.calls.length);+ expect(issuedSignals.every((signal) => signal.aborted)).toBe(true);+ });++ it('owns the deadline until response decoding settles', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=test-token' });+ let issuedSignal: AbortSignal | undefined;+ let resolveBody!: (value: unknown) => void;+ const body = new Promise<unknown>((resolve) => {+ resolveBody = resolve;+ });+ const response = Response.json({ ok: true });+ vi.spyOn(response, 'json').mockImplementation(() => body);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ issuedSignal = init?.signal ?? undefined;+ return response;+ }),+ );+ const controller = new AbortController();+ const removeEventListener = vi.spyOn(controller.signal, 'removeEventListener');++ const operation = modelsApi.observeApiKeySource({+ vendor: 'openai',+ key: 'test-key',+ }, controller.signal);+ await vi.advanceTimersByTimeAsync(0);++ expect(vi.getTimerCount()).toBe(1);+ expect(issuedSignal?.aborted).toBe(false);++ resolveBody({ ok: true, observation: {} });+ await expect(operation).resolves.toEqual({});+ expect(vi.getTimerCount()).toBe(0);+ expect(removeEventListener).toHaveBeenCalledWith('abort', expect.any(Function));+ controller.abort(new DOMException('settled operation', 'AbortError'));+ expect(issuedSignal?.aborted).toBe(false);+ });++ it('reports a deadline as an inconclusive API call failure', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=test-token' });+ vi.stubGlobal(+ 'fetch',+ vi.fn((_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_, reject) => {+ const signal = init?.signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ })),+ );++ const failure = modelsApi.refreshSource('src_deadline').catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(MODEL_HUB_REQUEST_DEADLINE_MS);++ const error = await failure;+ expect(error).toBeInstanceOf(ApiCallError);+ expect(error).toEqual(expect.objectContaining({+ code: 'bad_response',+ serverNamed: false,+ }));+ expect(vi.getTimerCount()).toBe(0);+ });++ it('keeps a stalled response body inside the inconclusive deadline boundary', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=test-token' });+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ const signal = init?.signal;+ const response = Response.json({ ok: true });+ // Native fetch couples its response body to the request signal. This+ // mock wiring asserts our scope boundary, not browser implementation.+ vi.spyOn(response, 'json').mockImplementation(() =>+ new Promise<unknown>((_, reject) => {+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }));+ return response;+ }),+ );++ const failure = modelsApi.refreshSource('src_body_stall').catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(0);+ expect(vi.getTimerCount()).toBe(1);+ await vi.advanceTimersByTimeAsync(MODEL_HUB_REQUEST_DEADLINE_MS);++ const error = await failure;+ expect(error).toBeInstanceOf(ApiCallError);+ expect(error).toEqual(expect.objectContaining({+ code: 'bad_response',+ serverNamed: false,+ }));+ expect(classifyModelHubFailure(apiFailure(error))).toBe('inconclusive');+ expect(vi.getTimerCount()).toBe(0);+ });++ it('preserves a caller-owned timeout reason', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=test-token' });+ vi.stubGlobal(+ 'fetch',+ vi.fn((_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_, reject) => {+ const signal = init?.signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ })),+ );+ const controller = new AbortController();+ const callerReason = new DOMException('caller deadline', 'TimeoutError');++ const request = modelsApi.observeApiKeySource({+ vendor: 'openai',+ key: 'test-key',+ }, controller.signal);+ const rejected = expect(request).rejects.toBe(callerReason);+ await vi.advanceTimersByTimeAsync(0);+ controller.abort(callerReason);++ await rejected;+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.tsindex a39483383..1bc8f31df 100644--- a/ui/src/lib/apiFetch.test.ts+++ b/ui/src/lib/apiFetch.test.ts@@ -7,7 +7,12 @@ const remoteAuth = vi.hoisted(() => ({vi.mock('./remoteAuth', () => remoteAuth);-import { apiFetch, recoverRemoteAuthFromSessionProbe } from './apiFetch';+import {+ apiFetch,+ isApiFetchDeadlineAbort,+ recoverRemoteAuthFromSessionProbe,+ withApiDeadline,+} from './apiFetch';describe('apiFetch remote auth recovery', () => {beforeEach(() => {@@ -230,6 +235,128 @@ describe('apiFetch remote auth recovery', () => {expect(fetchMock).toHaveBeenCalledTimes(2);});+ it('aborts a deadline-bound request without a caller signal', async () => {+ vi.useFakeTimers();+ let issuedSignal: AbortSignal | undefined;+ vi.stubGlobal(+ 'fetch',+ vi.fn((input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_, reject) => {+ expect(input).toBe('/api/models/sources');+ issuedSignal = init?.signal ?? undefined;+ issuedSignal?.addEventListener('abort', () => reject(issuedSignal?.reason), { once: true });+ })),+ );++ const request = withApiDeadline(+ 1_000,+ undefined,+ (signal) => apiFetch('/api/models/sources', { signal }),+ );+ const failure = request.catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(999);+ expect(issuedSignal?.aborted).toBe(false);++ await vi.advanceTimersByTimeAsync(1);+ const error = await failure;+ expect(error).toMatchObject({ name: 'TimeoutError' });+ expect(isApiFetchDeadlineAbort(error)).toBe(true);+ });++ it('lets a caller abort before the deadline', async () => {+ vi.useFakeTimers();+ let issuedSignal: AbortSignal | undefined;+ vi.stubGlobal(+ 'fetch',+ vi.fn((_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_, reject) => {+ issuedSignal = init?.signal ?? undefined;+ issuedSignal?.addEventListener('abort', () => reject(issuedSignal?.reason), { once: true });+ })),+ );+ const controller = new AbortController();+ const callerReason = new DOMException('caller stopped waiting', 'TimeoutError');++ const request = withApiDeadline(+ 1_000,+ controller.signal,+ (signal) => apiFetch('/api/models/sources', { signal }),+ );+ const rejected = expect(request).rejects.toBe(callerReason);+ controller.abort(callerReason);++ await rejected;+ expect(issuedSignal).not.toBe(controller.signal);+ expect(issuedSignal?.reason).toBe(callerReason);+ expect(isApiFetchDeadlineAbort(callerReason)).toBe(false);+ });++ it('fires the deadline while a shared CSRF fetch is in flight', async () => {+ vi.useFakeTimers();+ const fetchMock = vi.fn()+ .mockImplementationOnce(() => new Promise<Response>(() => undefined))+ .mockResolvedValueOnce(Response.json({ csrf_token: 'fresh-token' }))+ .mockResolvedValueOnce(Response.json({ ok: true }));+ vi.stubGlobal('fetch', fetchMock);++ const stalled = withApiDeadline(+ 1_000,+ undefined,+ (signal) => apiFetch('/api/models/sources', { method: 'POST', signal }),+ );+ const rejected = expect(stalled).rejects.toMatchObject({ name: 'TimeoutError' });+ await vi.advanceTimersByTimeAsync(1_000);++ await rejected;+ await expect(apiFetch('/api/models/sources', { method: 'POST' })).resolves.toMatchObject({+ status: 200,+ });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });++ it.each([+ ['success', false, false],+ ['throw', false, true],+ ['success with a caller signal', true, false],+ ['throw with a caller signal', true, true],+ ])('disposes deadline resources after request %s', async (_label, withCaller, shouldThrow) => {+ vi.useFakeTimers();+ let issuedSignal: AbortSignal | undefined;+ const fetchError = new Error('request failed');+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ issuedSignal = init?.signal ?? undefined;+ if (shouldThrow) throw fetchError;+ return Response.json({ ok: true });+ }),+ );+ const controller = withCaller ? new AbortController() : null;+ const removeEventListener = controller+ ? vi.spyOn(controller.signal, 'removeEventListener')+ : null;++ const request = withApiDeadline(+ 1_000,+ controller?.signal,+ (signal) => apiFetch('/api/models/sources', { signal }),+ );+ if (shouldThrow) {+ await expect(request).rejects.toBe(fetchError);+ } else {+ await expect(request).resolves.toMatchObject({ status: 200 });+ }++ expect(vi.getTimerCount()).toBe(0);+ expect(issuedSignal?.aborted).toBe(false);+ if (controller) {+ expect(issuedSignal).not.toBe(controller.signal);+ expect(removeEventListener).toHaveBeenCalledWith('abort', expect.any(Function));+ controller.abort(new DOMException('settled request', 'AbortError'));+ expect(issuedSignal?.aborted).toBe(false);+ }+ });+it('evicts a stalled shared CSRF fetch after a deadline-bound caller aborts', async () => {const fetchMock = vi.fn().mockImplementationOnce(() => new Promise<Response>(() => undefined))diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.tsindex bcb00f6c5..4c3a17e97 100644--- a/ui/src/lib/apiFetch.ts+++ b/ui/src/lib/apiFetch.ts@@ -9,6 +9,18 @@ const REMOTE_AUTH_RECOVERY_ERRORS = new Set([]);let csrfTokenPromise: Promise<string> | null = null;+// Preserve owned-deadline identity across the operation boundary without+// adding a new public error type to the callers' failure taxonomy.+const deadlineAbortReasons = new WeakSet<object>();++export const isApiFetchDeadlineAbort = (error: unknown): boolean =>+ typeof error === 'object' && error !== null && deadlineAbortReasons.has(error);++type DeadlineSignalHandle = {+ signal: AbortSignal;+ isOwnDeadline(reason: unknown): boolean;+ dispose(): void;+};function readCookie(name: string): string | null {if (typeof document === 'undefined') {@@ -131,7 +143,87 @@ function canReplayRequest(input: RequestInfo | URL, body: BodyInit | null | undereturn !(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream);}-export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {+const signalWithDeadline = (+ callerSignal: AbortSignal | undefined,+ deadlineMs: number,+): DeadlineSignalHandle => {+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {+ throw new TypeError('withApiDeadline deadlineMs must be a positive finite number');+ }+ if (callerSignal?.aborted) {+ return {+ signal: callerSignal,+ isOwnDeadline: () => false,+ dispose: () => undefined,+ };+ }++ const deadlineReason = new DOMException(+ `Request exceeded its ${deadlineMs}ms deadline`,+ 'TimeoutError',+ );+ const deadlineController = new AbortController();+ const deadlineTimer = globalThis.setTimeout(() => {+ deadlineController.abort(deadlineReason);+ }, deadlineMs);+ if (!callerSignal) {+ return {+ signal: deadlineController.signal,+ isOwnDeadline: (reason) => reason === deadlineReason,+ dispose: () => globalThis.clearTimeout(deadlineTimer),+ };+ }++ const composedController = new AbortController();+ let disposed = false;+ const dispose = () => {+ if (disposed) return;+ disposed = true;+ globalThis.clearTimeout(deadlineTimer);+ callerSignal.removeEventListener('abort', abortFromCaller);+ deadlineController.signal.removeEventListener('abort', abortFromDeadline);+ };+ const abortFromCaller = () => abortFrom(callerSignal);+ const abortFromDeadline = () => abortFrom(deadlineController.signal);+ const abortFrom = (source: AbortSignal) => {+ dispose();+ composedController.abort(+ source.reason ?? new DOMException('request aborted', 'AbortError'),+ );+ };+ callerSignal.addEventListener('abort', abortFromCaller, { once: true });+ deadlineController.signal.addEventListener('abort', abortFromDeadline, { once: true });+ return {+ signal: composedController.signal,+ isOwnDeadline: (reason) => reason === deadlineReason,+ dispose,+ };+};++export async function withApiDeadline<T>(+ deadlineMs: number,+ callerSignal: AbortSignal | undefined,+ run: (signal: AbortSignal) => Promise<T>,+): Promise<T> {+ const deadline = signalWithDeadline(callerSignal, deadlineMs);+ try {+ // The caller defines the complete operation. One wall-clock deadline must+ // cover every phase inside it rather than restarting at inner fetches.+ return await run(deadline.signal);+ } catch (error) {+ if (deadline.isOwnDeadline(error) && typeof error === 'object' && error !== null) {+ deadlineAbortReasons.add(error);+ }+ throw error;+ } finally {+ deadline.dispose();+ }+}++export async function apiFetch(+ input: RequestInfo | URL,+ init: RequestInit = {},+): Promise<Response> {const method = (init.method || 'GET').toUpperCase();const nextInit: RequestInit = { ...init };const headers = new Headers(init.headers || {});