DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(web): centralize API and error handling
Bingxi Zhao (Frank)bdab77f3f155
diff --git a/web/lib/api.ts b/web/lib/api.tsindex 0ce83b451..a99ecdd75 100644--- a/web/lib/api.ts+++ b/web/lib/api.ts@@ -1,96 +1,6 @@-// API configuration and utility functions.-//-// The frontend bundle is now URL-agnostic: the browser issues requests against-// the frontend origin (`:3782/api/...` and `:3782/api/.../ws`), and-// `web/proxy.ts` rewrites `/api/*` and `/ws/*` to the configured backend on-// every request. This means there is no build-time or runtime URL substitution-// in the bundle, and no placeholder token to keep alive. `apiUrl` and `wsUrl`-// stay as one-liner pass-throughs so the dozens of existing call sites continue-// to compile and work without modification.-/**- * Construct a full API URL from a path.- *- * Pass-through: returns the path unchanged. The actual backend URL is- * determined at request time by `web/proxy.ts`, which reads- * `DEEPTUTOR_API_BASE_URL` (exported by the container entrypoint from- * `data/user/settings/system.json`).- *- * @param path - API path (e.g., '/api/v1/knowledge/list')- * @returns The same path, unchanged+ * @deprecated Import from `@/shared/api/client`. This compatibility export is+ * removed after the feature-client migration in frontend plan Task 24.*/-export function apiUrl(path: string): string {- return path;-}--/**- * Construct a WebSocket URL from a path.- *- * Pass-through: returns the path unchanged. `proxy.ts` rewrites `/ws/*` to- * the configured backend, and the runtime upgrades to `ws://` /- * `wss://` based on the backend's scheme.- *- * @param path - WebSocket path (e.g., '/api/v1/solve')- * @returns The same path, unchanged- */-export function wsUrl(path: string): string {- return path;-}--/**- * Parse a "DEEPTUTOR_AUTH_ENABLED"-style flag at runtime.- *- * Used by both `apiFetch` (frontend) and `web/proxy.ts` (auth redirect) to- * decide whether to gate requests. Evaluated with a runtime regex so the- * value can be set by the container entrypoint on every start (no build-time- * inlining).- */-export function parseAuthEnabled(raw: string | undefined): boolean {- return /^(1|true|yes|on)$/i.test((raw ?? "").trim());-}--// Whether auth is enabled, learned at runtime — NOT from a build-time env var.-// The browser bundle never sees `DEEPTUTOR_AUTH_ENABLED` (it isn't a-// `NEXT_PUBLIC_` var, so Next.js does not inline it), and auth is a runtime-// setting that must not be baked at build time anyway. `fetchAuthStatus()` in-// `web/lib/auth.ts` calls `setRuntimeAuthEnabled()` once the backend reports the-// real state. Until then it defaults to `false`, so a stray 401 in the default-// auth-disabled deployment never bounces the user to /login. The server-side-// gate (web/proxy.ts middleware) enforces auth independently; this flag only-// drives the client's in-session 401 → /login redirect.-let runtimeAuthEnabled = false;--/** Record the backend-reported auth state for `apiFetch`'s 401 redirect gate. */-export function setRuntimeAuthEnabled(enabled: boolean): void {- runtimeAuthEnabled = enabled;-}--/**- * Authenticated fetch wrapper. Behaves identically to `fetch` but automatically- * redirects to /login when the backend returns 401 (expired / invalid token).- *- * Pass `skipAuthRedirect: true` for endpoints where a 401 is an expected,- * recoverable response that the caller wants to handle inline — most notably- * the login/register endpoints, where 401 means "wrong credentials" and must- * surface as a form error rather than reload the page.- */-export async function apiFetch(- input: RequestInfo | URL,- init?: RequestInit & { skipAuthRedirect?: boolean },-): Promise<Response> {- const { skipAuthRedirect, ...fetchInit } = init ?? {};- const res = await fetch(input, { credentials: "include", ...fetchInit });-- if (- res.status === 401 &&- runtimeAuthEnabled &&- !skipAuthRedirect &&- typeof window !== "undefined"- ) {- const next = encodeURIComponent(window.location.pathname);- window.location.href = `/login?next=${next}`;- return new Promise(() => {});- }-- return res;-}+export * from "@/shared/api/client";+export * from "@/shared/api/errors";diff --git a/web/shared/api/client.ts b/web/shared/api/client.tsnew file mode 100644index 000000000..22befbdc0--- /dev/null+++ b/web/shared/api/client.ts@@ -0,0 +1,182 @@+import { ApiError, type AppError, type AppErrorScope } from "./errors";++export interface RequestOptions extends RequestInit {+ scope?: AppErrorScope;+ skipAuthRedirect?: boolean;+}++let runtimeAuthEnabled = false;++export function apiUrl(path: string): string {+ return path;+}++export function wsUrl(path: string): string {+ return path;+}++export function parseAuthEnabled(raw: string | undefined): boolean {+ return /^(1|true|yes|on)$/i.test((raw ?? "").trim());+}++export function setRuntimeAuthEnabled(enabled: boolean): void {+ runtimeAuthEnabled = enabled;+}++export async function apiFetch(+ input: RequestInfo | URL,+ init?: RequestInit & { skipAuthRedirect?: boolean },+): Promise<Response> {+ const { skipAuthRedirect, ...fetchInit } = init ?? {};+ const response = await fetch(input, { credentials: "include", ...fetchInit });++ if (+ response.status === 401 &&+ runtimeAuthEnabled &&+ !skipAuthRedirect &&+ typeof window !== "undefined"+ ) {+ const next = encodeURIComponent(window.location.pathname);+ window.location.href = `/login?next=${next}`;+ return new Promise(() => {});+ }++ return response;+}++function correlationId(response: Response): string | undefined {+ return (+ response.headers.get("x-correlation-id") ??+ response.headers.get("x-request-id") ??+ undefined+ );+}++function messageFromBody(body: unknown, fallback: string): string {+ if (!body || typeof body !== "object") return fallback;+ const value = body as Record<string, unknown>;+ if (typeof value.message === "string" && value.message.trim()) return value.message;+ if (typeof value.detail === "string" && value.detail.trim()) return value.detail;+ if (value.detail && typeof value.detail === "object") {+ const detail = value.detail as Record<string, unknown>;+ if (typeof detail.message === "string" && detail.message.trim()) return detail.message;+ }+ return fallback;+}++function normalizedHttpError(+ response: Response,+ body: unknown,+ scope: AppErrorScope,+): AppError {+ const value = body && typeof body === "object" ? (body as Record<string, unknown>) : {};+ const detail =+ value.detail && typeof value.detail === "object"+ ? (value.detail as Record<string, unknown>)+ : {};+ return {+ code:+ (typeof value.error_code === "string" && value.error_code) ||+ (typeof detail.error_code === "string" && detail.error_code) ||+ `http_${response.status}`,+ message: messageFromBody(body, response.statusText || "Request failed"),+ retryable:+ (typeof value.retryable === "boolean" && value.retryable) ||+ (typeof detail.retryable === "boolean" && detail.retryable) ||+ response.status === 408 ||+ response.status === 429 ||+ response.status >= 500,+ scope,+ correlationId:+ (typeof value.correlation_id === "string" && value.correlation_id) ||+ correlationId(response),+ status: response.status,+ };+}++async function responseBody(response: Response): Promise<unknown> {+ const text = await response.text();+ if (!text.trim()) return undefined;+ try {+ return JSON.parse(text) as unknown;+ } catch {+ return text;+ }+}++async function performRequest(+ input: RequestInfo | URL,+ options: RequestOptions = {},+): Promise<{ response: Response; body: unknown }> {+ const { scope = "network", ...init } = options;+ try {+ const response = await apiFetch(input, init);+ const body = await responseBody(response);+ if (!response.ok) throw new ApiError(normalizedHttpError(response, body, scope));+ return { response, body };+ } catch (error) {+ if (error instanceof ApiError) throw error;+ const aborted = error instanceof DOMException && error.name === "AbortError";+ throw new ApiError(+ {+ code: aborted ? "request_aborted" : "network_error",+ message: aborted ? "Request was cancelled" : "Unable to reach the server",+ retryable: !aborted,+ scope,+ },+ { cause: error },+ );+ }+}++export async function requestJson<T>(+ input: RequestInfo | URL,+ options: RequestOptions = {},+): Promise<T> {+ const { response, body } = await performRequest(input, options);+ if (body === undefined || typeof body === "string") {+ throw new ApiError({+ code: "invalid_response",+ message: "The server returned an invalid JSON response",+ retryable: true,+ scope: options.scope ?? "network",+ correlationId: correlationId(response),+ status: response.status,+ });+ }+ return body as T;+}++export async function requestVoid(+ input: RequestInfo | URL,+ options: RequestOptions = {},+): Promise<void> {+ await performRequest(input, options);+}++export async function requestBlob(+ input: RequestInfo | URL,+ options: RequestOptions = {},+): Promise<Blob> {+ const { scope = "network", ...init } = options;+ try {+ const response = await apiFetch(input, init);+ if (!response.ok) {+ const body = await responseBody(response);+ throw new ApiError(normalizedHttpError(response, body, scope));+ }+ return await response.blob();+ } catch (error) {+ if (error instanceof ApiError) throw error;+ const aborted = error instanceof DOMException && error.name === "AbortError";+ throw new ApiError(+ {+ code: aborted ? "request_aborted" : "network_error",+ message: aborted ? "Request was cancelled" : "Unable to reach the server",+ retryable: !aborted,+ scope,+ },+ { cause: error },+ );+ }+}diff --git a/web/shared/api/errors.ts b/web/shared/api/errors.tsnew file mode 100644index 000000000..bc7708d26--- /dev/null+++ b/web/shared/api/errors.ts@@ -0,0 +1,40 @@+export type AppErrorScope = "turn" | "session" | "runtime" | "settings" | "network";++export interface AppError {+ code: string;+ message: string;+ retryable: boolean;+ scope: AppErrorScope;+ correlationId?: string;+ status?: number;+}++export class ApiError extends Error {+ readonly appError: AppError;++ constructor(appError: AppError, options?: ErrorOptions) {+ super(appError.message, options);+ this.name = "ApiError";+ this.appError = appError;+ }++ get code(): string {+ return this.appError.code;+ }++ get retryable(): boolean {+ return this.appError.retryable;+ }++ get correlationId(): string | undefined {+ return this.appError.correlationId;+ }++ get status(): number | undefined {+ return this.appError.status;+ }+}++export function isApiError(error: unknown): error is ApiError {+ return error instanceof ApiError;+}diff --git a/web/shared/api/runtime.ts b/web/shared/api/runtime.tsnew file mode 100644index 000000000..ab409875c--- /dev/null+++ b/web/shared/api/runtime.ts@@ -0,0 +1,11 @@+import type { RuntimeStatus } from "@/contracts/generated/turn-protocol";++import { requestJson } from "./client";++export function fetchRuntimeStatus(signal?: AbortSignal): Promise<RuntimeStatus> {+ return requestJson<RuntimeStatus>("/api/v1/system/runtime", {+ cache: "no-store",+ signal,+ scope: "runtime",+ });+}diff --git a/web/tests/api-client.test.ts b/web/tests/api-client.test.tsnew file mode 100644index 000000000..3ba31626c--- /dev/null+++ b/web/tests/api-client.test.ts@@ -0,0 +1,128 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ requestBlob,+ requestJson,+ requestVoid,+ setRuntimeAuthEnabled,+} from "../shared/api/client";+import { ApiError } from "../shared/api/errors";++function withFetch(stub: typeof fetch): () => void {+ const original = globalThis.fetch;+ globalThis.fetch = stub;+ return () => {+ globalThis.fetch = original;+ };+}++async function expectApiError(run: () => Promise<unknown>): Promise<ApiError> {+ try {+ await run();+ } catch (error) {+ assert.ok(error instanceof ApiError);+ return error;+ }+ assert.fail("expected an ApiError");+}++test("requestJson returns typed JSON and requestVoid accepts empty success", async () => {+ let count = 0;+ const restore = withFetch(async () => {+ count += 1;+ return count === 1+ ? Response.json({ worker_count: 4 })+ : new Response(null, { status: 204 });+ });+ try {+ assert.deepEqual(await requestJson<{ worker_count: number }>("/runtime"), {+ worker_count: 4,+ });+ await requestVoid("/turn", { method: "DELETE" });+ } finally {+ restore();+ }+});++test("requestBlob preserves binary bodies", async () => {+ const restore = withFetch(async () => new Response("artifact"));+ try {+ assert.equal(await (await requestBlob("/artifact")).text(), "artifact");+ } finally {+ restore();+ }+});++test("structured server errors retain stable fields and correlation IDs", async () => {+ const restore = withFetch(+ async () =>+ Response.json(+ { error_code: "worker_lost", message: "Owner exited", retryable: true },+ { status: 503, headers: { "x-correlation-id": "corr-7" } },+ ),+ );+ try {+ const error = await expectApiError(() =>+ requestJson("/turn", { scope: "turn" }),+ );+ assert.deepEqual(error.appError, {+ code: "worker_lost",+ message: "Owner exited",+ retryable: true,+ scope: "turn",+ correlationId: "corr-7",+ status: 503,+ });+ } finally {+ restore();+ }+});++test("invalid JSON success becomes a normalized response error", async () => {+ const restore = withFetch(+ async () => new Response("not-json", { headers: { "x-request-id": "req-1" } }),+ );+ try {+ const error = await expectApiError(() => requestJson("/broken"));+ assert.equal(error.code, "invalid_response");+ assert.equal(error.correlationId, "req-1");+ } finally {+ restore();+ }+});++test("abort and network failures are distinguishable", async () => {+ const restoreAbort = withFetch(async () => {+ throw new DOMException("aborted", "AbortError");+ });+ try {+ const aborted = await expectApiError(() => requestJson("/turn"));+ assert.equal(aborted.code, "request_aborted");+ assert.equal(aborted.retryable, false);+ } finally {+ restoreAbort();+ }++ const restoreNetwork = withFetch(async () => {+ throw new TypeError("offline");+ });+ try {+ const offline = await expectApiError(() => requestJson("/turn"));+ assert.equal(offline.code, "network_error");+ assert.equal(offline.retryable, true);+ } finally {+ restoreNetwork();+ }+});++test("the shared boundary keeps the single apiFetch auth redirect gate", async () => {+ setRuntimeAuthEnabled(false);+ const restore = withFetch(async () => Response.json({ detail: "no" }, { status: 401 }));+ try {+ const error = await expectApiError(() => requestJson("/private"));+ assert.equal(error.status, 401);+ } finally {+ restore();+ }+});