fabro/apps/fabro-web/app/lib/api-client.ts
Bryan Helmkamp fbe8b50a16
feat(server): add GET /api/v1/providers and /settings/models page (#321)
## Summary

Operators had no UI surface to see which LLM providers their Fabro
server has configured — provider state was only inferable indirectly via
the per-model `configured` flag on `GET /api/v1/models`. This adds a
dedicated **Models** settings tab backed by a new providers endpoint.

- **`fabro_model::Provider`** — a public projection of the internal
`CatalogProvider` that *structurally* excludes credential-bearing fields
(`auth`, `extra_headers`, `billing_policy`, `agent_profile`). Reused by
the generated API client via progenitor `with_replacement`, mirroring
the existing `Model` pattern — no parallel API DTO.
- **`GET /api/v1/providers`** — lists catalog providers with effective
config and a `configured` status stamped per request from
`ready_llm_provider_ids()`. Sorted by the catalog's existing
`provider_order`. No write endpoints.
- **`/settings/models` web page** — new route + nav entry
(`CpuChipIcon`, between Integrations and Security) rendering each
provider with model count, default model, configured status, and a "Get
API key" link for unconfigured providers.

## Key decisions

- Provider sort: reuse catalog `provider_order` (priority desc, id asc)
— zero extra code.
- `adapter` is hidden in the UI row (noisy for first-party providers);
the OpenAPI `adapter` field is pinned to an enum matching the closed
`AdapterKind` type.
- `configured` reflects credential resolution **at the time of the
response**, not a frozen startup snapshot — doc/spec wording corrected
to match.

## Testing

- `fabro-model`: `From<&CatalogProvider>` + serde `skip_serializing_if`
unit tests.
- `fabro-api`: `Provider` type-identity + JSON-parity tests, including
the required/optional field split.
- `fabro-server`: handler tests for configured vs unconfigured
providers, exact `model_count`/`default_model` against catalog truth,
and credential-omission (asserts internal field names *and* the injected
credential value never reach the wire).
- OpenAPI route conformance test covers `GET /api/v1/providers`.
- `cargo build --workspace`, `fmt --check`, `clippy -D warnings` clean;
935 Rust tests pass; web `tsc` typecheck passes.
- Reviewed via a 10-persona `ce:review` (autofix) — no P0/P1 in shipped
code; 8 safe fixes applied.

Not done: manual UI screenshots — the `apps/fabro-web` build is blocked
in this environment by an unrelated missing `@assistant-ui/react`
dependency. Run `bun install` in `apps/fabro-web` to verify
`/settings/models` manually.

## Post-Deploy Monitoring & Validation

- **What to watch:** request logs for `GET /api/v1/providers` — expect
`200`s for authenticated users, `401` for unauthenticated. The handler
resolves LLM credentials per request via `ready_llm_provider_ids()` (the
same path the existing `list_models` handler already uses).
- **Healthy signals:** `/settings/models` renders the provider list;
`configured` matches each provider's actual credential state; no
credential strings appear in any response body or log line.
- **Failure signals / rollback trigger:** any provider object in the
response containing `auth`, `extra_headers`, or a raw key/token value →
roll back immediately (the projection type makes this structurally
impossible, but treat any occurrence as P0). 5xx spikes on the new
route.
- **Validation window / owner:** first 24h after deploy, owned by the
deploying engineer. Pre-existing note (not introduced here): credential
resolution can refresh OAuth tokens and write the vault as a side effect
of this read — shared with `list_models`; flagged for a future caching
pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:05:00 -04:00

357 lines
9.4 KiB
TypeScript

import axios, {
isAxiosError,
type AxiosPromise,
type AxiosResponse,
type RawAxiosRequestConfig,
} from "axios";
import {
AuthApi,
Configuration,
HumanInTheLoopApi,
InsightsApi,
InstallApi,
ModelsApi,
RunInternalsApi,
RunInternalsApiAxiosParamCreator,
RunOutputsApi,
RunsApi,
SettingsApi,
SystemApi,
WorkflowsApi,
} from "@qltysh/fabro-api-client";
export interface PaginatedEnvelope<T> {
data: T[];
meta: { has_more: boolean };
}
export class ApiError extends Error {
readonly status: number;
readonly requestId: string | null;
readonly body: unknown;
constructor({
status,
message,
requestId,
body,
}: {
status: number;
message: string;
requestId: string | null;
body: unknown;
}) {
super(message);
this.name = "ApiError";
this.status = status;
this.requestId = requestId;
this.body = body;
}
}
interface ApiCallOptions {
redirectOnUnauthorized?: boolean;
}
const PAGINATED_API_MAX_PAGES = 50;
const PAGINATED_API_MAX_ITEMS = 5000;
export const generatedAxios = axios.create({
baseURL: "",
withCredentials: true,
});
export const generatedApiConfiguration = new Configuration({
basePath: "",
baseOptions: {
withCredentials: true,
},
});
export const authApi = new AuthApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const humanInTheLoopApi = new HumanInTheLoopApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const insightsApi = new InsightsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const installApi = new InstallApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const modelsApi = new ModelsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const runInternalsApi = new RunInternalsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const runOutputsApi = new RunOutputsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const runsApi = new RunsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const settingsApi = new SettingsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const systemApi = new SystemApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const workflowsApi = new WorkflowsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export function isNotAvailable(status: number): boolean {
return status === 404 || status === 501;
}
export function extractRequestId(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const record = body as Record<string, unknown>;
if (typeof record.request_id === "string") return record.request_id;
if (typeof record.requestId === "string") return record.requestId;
const errors = record.errors;
if (!Array.isArray(errors) || errors.length === 0) return null;
const first = errors[0];
if (!first || typeof first !== "object") return null;
const error = first as Record<string, unknown>;
if (typeof error.request_id === "string") return error.request_id;
if (typeof error.requestId === "string") return error.requestId;
if (typeof error.detail === "string") {
const match = error.detail.match(/request[_ ]id[=:]?\s*([a-zA-Z0-9-_]+)/i);
if (match) return match[1];
}
return null;
}
function requestIdFromHeaders(headers: unknown): string | null {
return (
headerValue(headers, "x-request-id")
?? headerValue(headers, "x-fabro-request-id")
?? headerValue(headers, "request-id")
);
}
function headerValue(headers: unknown, name: string): string | null {
if (!headers || typeof headers !== "object") return null;
const getter = (headers as { get?: (key: string) => unknown }).get;
if (typeof getter === "function") {
const value = getter.call(headers, name);
if (typeof value === "string") return value;
}
const wanted = name.toLowerCase();
for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {
if (key.toLowerCase() !== wanted) continue;
if (typeof value === "string") return value;
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
}
return null;
}
function apiErrorFromAxios(error: unknown): ApiError | null {
if (!isAxiosError(error) || !error.response) return null;
const { response } = error;
const requestId = requestIdFromHeaders(response.headers) ?? extractRequestId(response.data);
return new ApiError({
status: response.status,
message: extractErrorDetail(response.data) ?? (response.statusText || `HTTP ${response.status}`),
requestId,
body: response.data ?? null,
});
}
function extractErrorDetail(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const errors = (body as Record<string, unknown>).errors;
if (!Array.isArray(errors) || errors.length === 0) return null;
const first = errors[0];
if (!first || typeof first !== "object") return null;
const detail = (first as Record<string, unknown>).detail;
return typeof detail === "string" && detail.length > 0 ? detail : null;
}
function redirectToLogin(error: ApiError, options: ApiCallOptions) {
if (error.status !== 401 || options.redirectOnUnauthorized === false) return;
if (typeof window !== "undefined") {
window.location.href = "/login";
}
}
export async function apiData<T>(
call: () => AxiosPromise<T>,
options: ApiCallOptions = {},
): Promise<T> {
try {
const response = await call();
return response.data;
} catch (error) {
const apiError = apiErrorFromAxios(error);
if (!apiError) throw error;
redirectToLogin(apiError, options);
throw apiError;
}
}
export async function apiResponse<T>(
call: () => AxiosPromise<T>,
options: ApiCallOptions = {},
): Promise<AxiosResponse<T>> {
try {
return await call();
} catch (error) {
const apiError = apiErrorFromAxios(error);
if (!apiError) throw error;
redirectToLogin(apiError, options);
throw apiError;
}
}
export async function apiNullableData<T>(
call: () => AxiosPromise<T>,
): Promise<T | null> {
try {
return await apiData(call);
} catch (error) {
if (error instanceof ApiError && isNotAvailable(error.status)) return null;
throw error;
}
}
export async function fetchAllPages<TItem, TExtra extends object = {}>(
label: string,
loadPage: (limit: number, offset: number) => Promise<PaginatedEnvelope<TItem> & TExtra>,
): Promise<PaginatedEnvelope<TItem> & TExtra> {
const limit = 100;
let offset = 0;
const data: TItem[] = [];
let extras: TExtra | null = null;
let pagesLoaded = 0;
while (true) {
const page = await loadPage(limit, offset);
if (extras == null) {
const { data: _data, meta: _meta, ...rest } = page as PaginatedEnvelope<TItem> &
Record<string, unknown>;
extras = rest as TExtra;
}
pagesLoaded += 1;
const remainingItemBudget = PAGINATED_API_MAX_ITEMS - data.length;
const pageItems = remainingItemBudget > 0 ? page.data.slice(0, remainingItemBudget) : [];
data.push(...pageItems);
if (!page.meta.has_more || page.data.length === 0) {
return {
...(extras ?? ({} as TExtra)),
data,
meta: { has_more: false },
};
}
if (
pagesLoaded >= PAGINATED_API_MAX_PAGES
|| pageItems.length < page.data.length
|| data.length >= PAGINATED_API_MAX_ITEMS
) {
console.warn(
`Stopped paginated API fetch for ${label} after ${pagesLoaded} pages and ${data.length} items because the safety cap was reached.`,
);
return {
...(extras ?? ({} as TExtra)),
data,
meta: { has_more: true },
};
}
offset += page.data.length;
}
}
export async function fetchAllStageEvents<TItem extends { seq: number }>(
label: string,
loadPage: (sinceSeq: number, limit: number) => Promise<PaginatedEnvelope<TItem>>,
): Promise<TItem[]> {
const PAGE_LIMIT = 1000;
const MAX_PAGES = 50;
const data: TItem[] = [];
let sinceSeq = 1;
let pagesLoaded = 0;
while (true) {
const page = await loadPage(sinceSeq, PAGE_LIMIT);
pagesLoaded += 1;
if (page.data.length === 0) {
if (page.meta.has_more) {
console.warn(
`Stage events fetch for ${label} returned an empty page with has_more=true; stopping at ${data.length} items to avoid spinning.`,
);
}
return data;
}
data.push(...page.data);
if (!page.meta.has_more) return data;
if (pagesLoaded >= MAX_PAGES) {
console.warn(
`Stopped stage events fetch for ${label} after ${pagesLoaded} pages and ${data.length} items because the safety cap was reached.`,
);
return data;
}
const highestSeq = page.data.reduce((max, event) => Math.max(max, event.seq), sinceSeq - 1);
if (highestSeq < sinceSeq) {
console.warn(
`Stage events fetch for ${label} returned a non-advancing page at since_seq=${sinceSeq}; stopping at ${data.length} items to avoid spinning.`,
);
return data;
}
sinceSeq = highestSeq + 1;
}
}
export function requestSignalOptions(request?: Request): RawAxiosRequestConfig {
return request?.signal ? { signal: request.signal } : {};
}
export async function stageArtifactDownloadUrl(
id: string,
stageId: string,
filename: string,
retry: number,
): Promise<string> {
const requestArgs = await RunInternalsApiAxiosParamCreator(
generatedApiConfiguration,
).getStageArtifact(id, stageId, filename, retry);
return `${generatedApiConfiguration.basePath ?? ""}${requestArgs.url}`;
}