Skip to content

Build and run agents you can see, understand and trust.

feat(app): add health endpoint and check it before entering the web UI (#2237)

DavdGaob024c4651942
diff --git a/examples/web_ui/frontend/src/api/client.ts b/examples/web_ui/frontend/src/api/client.ts
index 2ba6e6fd2..a7bc0c956 100644
--- a/examples/web_ui/frontend/src/api/client.ts
+++ b/examples/web_ui/frontend/src/api/client.ts
@@ -25,10 +25,20 @@ interface RequestOptions {
params?: Record<string, string>;
/** When true, suppresses the automatic error toast. Useful when the caller shows its own inline error UI. */
silent?: boolean;
+ signal?: AbortSignal;
+ /** Overrides the stored server URL. Lets the setup page probe an address before persisting it. */
+ baseUrl?: string;
+ /** Overrides the stored username, for the same reason as `baseUrl`. */
+ userId?: string;
+ /** Gives up after this many ms and reports {@link TIMEOUT_STATUS}. Off by default — a streaming chat is meant to stay open. */
+ timeoutMs?: number;
}
-function buildHeaders(hasBody: boolean): Record<string, string> {
- const headers: Record<string, string> = { 'X-User-ID': getUserId() };
+/** Reported when `timeoutMs` elapses. Real 408s come from a server, so either way the request did not complete in time. */
+export const TIMEOUT_STATUS = 408;
+
+function buildHeaders(hasBody: boolean, userId?: string): Record<string, string> {
+ const headers: Record<string, string> = { 'X-User-ID': userId ?? getUserId() };
if (hasBody) headers['Content-Type'] = 'application/json';
return headers;
}
@@ -46,47 +56,55 @@ async function extractErrorDetail(res: Response): Promise<string> {
return text || res.statusText;
}
-async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
- const { method = 'GET', body, params, silent = false } = options;
- const url = new URL(path, getBaseUrl());
+async function streamRequest(path: string, options: RequestOptions = {}): Promise<Response> {
+ const {
+ method = 'GET',
+ body,
+ params,
+ signal,
+ silent = false,
+ baseUrl,
+ userId,
+ timeoutMs,
+ } = options;
+ const url = new URL(path, baseUrl ?? getBaseUrl());
if (params) {
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
}
- const res = await fetch(url.toString(), {
- method,
- headers: buildHeaders(body !== undefined),
- body: body ? JSON.stringify(body) : undefined,
- });
+ // AbortSignal.timeout aborts with a TimeoutError, which is what lets the
+ // catch below tell "too slow" apart from the caller's own cancellation.
+ const deadline = timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined;
+ const combined =
+ deadline && signal ? AbortSignal.any([signal, deadline]) : (deadline ?? signal);
- if (!res.ok) {
- const detail = await extractErrorDetail(res);
- const error = new ApiError(res.status, detail);
- if (!silent) toast.error(detail);
+ let res: Response;
+ try {
+ res = await fetch(url.toString(), {
+ method,
+ headers: buildHeaders(body !== undefined, userId),
+ body: body ? JSON.stringify(body) : undefined,
+ signal: combined,
+ });
+ } catch (e) {
+ // An abort is the caller's own doing — pass it through untouched.
+ if (e instanceof DOMException && e.name === 'AbortError') throw e;
+ // A server that accepts the connection then stalls would otherwise
+ // leave the caller waiting forever.
+ const timedOut = e instanceof DOMException && e.name === 'TimeoutError';
+ // Otherwise fetch only rejects when the request never reached the
+ // server: wrong address, DNS failure, refused connection, blocked
+ // preflight. Status 0 distinguishes that from any HTTP-level failure.
+ const error = timedOut
+ ? new ApiError(TIMEOUT_STATUS, 'The server took too long to respond.')
+ : new ApiError(
+ 0,
+ 'Cannot reach the server. Check the server address and your network.',
+ );
+ if (!silent) toast.error(error.detail);
throw error;
}
- if (res.status === 204) return undefined as T;
- return res.json() as Promise<T>;
-}
-
-async function streamRequest(
- path: string,
- options: RequestOptions & { signal?: AbortSignal } = {},
-): Promise<Response> {
- const { method = 'GET', body, params, signal, silent = false } = options;
- const url = new URL(path, getBaseUrl());
- if (params) {
- Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
- }
-
- const res = await fetch(url.toString(), {
- method,
- headers: buildHeaders(body !== undefined),
- body: body ? JSON.stringify(body) : undefined,
- signal,
- });
-
if (!res.ok) {
const detail = await extractErrorDetail(res);
const error = new ApiError(res.status, detail);
@@ -97,9 +115,18 @@ async function streamRequest(
return res;
}
+async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
+ const res = await streamRequest(path, options);
+ if (res.status === 204) return undefined as T;
+ return res.json() as Promise<T>;
+}
+
export const client = {
- get: <T>(path: string, params?: Record<string, string>) =>
- request<T>(path, { method: 'GET', params }),
+ get: <T>(
+ path: string,
+ params?: Record<string, string>,
+ options?: { silent?: boolean; baseUrl?: string; userId?: string; timeoutMs?: number },
+ ) => request<T>(path, { method: 'GET', params, ...options }),
post: <T>(
path: string,
body?: unknown,
@@ -114,6 +141,5 @@ export const client = {
) => request<T>(path, { method: 'PATCH', body, params, silent: options?.silent }),
delete: <T = void>(path: string, params?: Record<string, string>) =>
request<T>(path, { method: 'DELETE', params }),
- stream: (path: string, options?: RequestOptions & { signal?: AbortSignal }) =>
- streamRequest(path, options),
+ stream: (path: string, options?: RequestOptions) => streamRequest(path, options),
};
diff --git a/examples/web_ui/frontend/src/api/health.ts b/examples/web_ui/frontend/src/api/health.ts
new file mode 100644
index 000000000..abc8eecab
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/health.ts
@@ -0,0 +1,19 @@
+import { client } from './client';
+import type { HealthResponse } from './types';
+
+/** The probe is I/O-free on the server, so anything this slow is a stalled backend. */
+const HEALTH_TIMEOUT_MS = 10_000;
+
+export const healthApi = {
+ /**
+ * Probe a backend before its address and username are persisted, which
+ * is why both are passed explicitly instead of read from localStorage.
+ */
+ check: (baseUrl: string, userId: string) =>
+ client.get<HealthResponse>('/health', undefined, {
+ silent: true,
+ baseUrl,
+ userId,
+ timeoutMs: HEALTH_TIMEOUT_MS,
+ }),
+};
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 5b03ea5ab..5f1c5afec 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -10,3 +10,4 @@ export { skillApi } from './skill';
export { scheduleApi } from './schedule';
export { embeddingModelApi, modelApi, ttsModelApi } from './model';
export { knowledgeBaseApi } from './knowledgeBase';
+export { healthApi } from './health';
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index aa556ed0d..46cb458d6 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -950,3 +950,14 @@ export interface ListTTSModelResponse {
models: TTSModelCard[];
total: number;
}
+
+// ─── Health ───────────────────────────────────────────────────────────────────
+
+/** `disabled` means the deployment turned an optional feature off, not that it is down. */
+export type ComponentStatus = 'ok' | 'not_ready' | 'disabled';
+
+export interface HealthResponse {
+ status: 'ok' | 'not_ready';
+ version: string;
+ components: Record<string, ComponentStatus>;
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index ffc3763eb..a1b9b65ee 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -486,6 +486,12 @@
"username": "Username",
"usernamePlaceholder": "Your username",
"submit": "Get Started",
+ "checking": "Connecting...",
+ "errorUnreachable": "Cannot reach this server. Check the address, make sure the service is running, and that it allows cross-origin requests.",
+ "errorTimeout": "The server accepted the connection but did not respond in time. It may be overloaded or stuck starting up.",
+ "errorNotAgentScope": "Reached the address, but it is not an AgentScope service — check the URL, or upgrade a backend too old to expose a health endpoint.",
+ "errorUnauthorized": "The server rejected this username. Enter a valid one.",
+ "errorNotReady": "The server is reachable but not ready. These subsystems failed to start:",
"hint": "This is a frontend-only application, and all data are served from the Server URL above. The username is used solely for server-side authentication."
},
"tour": {
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index b3202166d..0c7c14886 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -486,6 +486,12 @@
"username": "用户名",
"usernamePlaceholder": "请输入用户名",
"submit": "开始使用",
+ "checking": "连接中...",
+ "errorUnreachable": "无法连接到该服务器。请检查地址是否正确、服务是否已启动,以及是否允许跨域请求。",
+ "errorTimeout": "服务器已建立连接,但在超时时间内没有响应。可能负载过高或启动卡住了。",
+ "errorNotAgentScope": "地址可以访问,但它不是 AgentScope 服务。请检查地址,或升级尚未提供健康检查接口的旧版本后端。",
+ "errorUnauthorized": "服务器拒绝了该用户名,请填写有效的用户名。",
+ "errorNotReady": "服务器可以连接,但尚未就绪。以下子系统启动失败:",
"hint": "此应用仅提供前端服务,所有数据均来自填写的服务器地址,用户名仅用于服务端鉴权。"
},
"tour": {
diff --git a/examples/web_ui/frontend/src/pages/setup/index.tsx b/examples/web_ui/frontend/src/pages/setup/index.tsx
index 6997409c1..32a1a7fd6 100644
--- a/examples/web_ui/frontend/src/pages/setup/index.tsx
+++ b/examples/web_ui/frontend/src/pages/setup/index.tsx
@@ -1,5 +1,10 @@
+import { CircleAlert, Loader2 } from 'lucide-react';
import { useState } from 'react';
+import { healthApi } from '@/api';
+import { ApiError, TIMEOUT_STATUS } from '@/api/client.ts';
+import type { HealthResponse } from '@/api/types.ts';
+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';
import { Button } from '@/components/ui/button.tsx';
import {
Card,
@@ -11,6 +16,7 @@ import {
import { Field, FieldDescription, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';
import { Input } from '@/components/ui/input.tsx';
import { useTranslation } from '@/i18n/useI18n.ts';
+import { formatApiErrorForAlert } from '@/lib/api-error.ts';
import { cn } from '@/lib/utils.ts';
interface Props {
@@ -18,16 +24,75 @@ interface Props {
className?: string;
}
+/** Pull the failing subsystem names out of a 503 body, if it is a health report. */
+function notReadyComponents(detail: string): string {
+ try {
+ const body = JSON.parse(detail) as HealthResponse;
+ return Object.entries(body.components ?? {})
+ .filter(([, status]) => status === 'not_ready')
+ .map(([name]) => name)
+ .join(', ');
+ } catch {
+ return '';
+ }
+}
+
export const SetupPage = ({ onComplete, className }: Props) => {
const { t } = useTranslation();
const [url, setUrl] = useState(() => localStorage.getItem('server_url') ?? '');
const [username, setUsername] = useState(() => localStorage.getItem('username') ?? '');
+ const [checking, setChecking] = useState(false);
+ const [errorMsg, setErrorMsg] = useState('');
- const handleSubmit = (e: React.FormEvent) => {
+ const describeFailure = (e: unknown): string => {
+ if (e instanceof ApiError) {
+ // Status 0 means the request never reached a server at all.
+ if (e.status === 0) return t('setup.errorUnreachable');
+ if (e.status === TIMEOUT_STATUS) return t('setup.errorTimeout');
+ // Something answered, but it has no /health — wrong address, or
+ // a backend too old to have one.
+ if (e.status === 404) return t('setup.errorNotAgentScope');
+ if (e.status === 401 || e.status === 422) return t('setup.errorUnauthorized');
+ if (e.status === 503) {
+ const down = notReadyComponents(e.detail);
+ return down ? `${t('setup.errorNotReady')}\n${down}` : t('setup.errorNotReady');
+ }
+ }
+ // A 200 whose body will not parse as JSON: an SPA dev server or a
+ // catch-all proxy answering with HTML, not our backend.
+ if (e instanceof SyntaxError) return t('setup.errorNotAgentScope');
+ return formatApiErrorForAlert(e);
+ };
+
+ const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
- localStorage.setItem('server_url', url);
- localStorage.setItem('username', username);
- onComplete();
+ const trimmedUrl = url.trim().replace(/\/+$/, '');
+ const trimmedName = username.trim();
+
+ setChecking(true);
+ setErrorMsg('');
+ try {
+ // Persist only after the backend confirms both the address and
+ // the username work, so a failed attempt cannot leave the app
+ // holding a config that sends every later page into errors.
+ const health = (await healthApi.check(
+ trimmedUrl,
+ trimmedName,
+ )) as Partial<HealthResponse>;
+ // Valid JSON that is not a health report means the address points
+ // at some other service that happens to answer 200.
+ if (typeof health.version !== 'string' || !health.components) {
+ setErrorMsg(t('setup.errorNotAgentScope'));
+ return;
+ }
+ localStorage.setItem('server_url', trimmedUrl);
+ localStorage.setItem('username', trimmedName);
+ onComplete();
+ } catch (err) {
+ setErrorMsg(describeFailure(err));
+ } finally {
+ setChecking(false);
+ }
};
return (
@@ -67,9 +132,20 @@ export const SetupPage = ({ onComplete, className }: Props) => {
required
/>
</Field>
+ {errorMsg && (
+ <Alert variant="destructive">
+ <CircleAlert />
+ {/* The failing-component list is appended on its
+ own line, so newlines have to survive. */}
+ <AlertDescription className="whitespace-pre-wrap">
+ {errorMsg}
+ </AlertDescription>
+ </Alert>
+ )}
<Field>
- <Button type="submit" className="w-full">
- {t('setup.submit')}
+ <Button type="submit" className="w-full" disabled={checking}>
+ {checking && <Loader2 className="size-3.5 animate-spin" />}
+ {checking ? t('setup.checking') : t('setup.submit')}
</Button>
</Field>
</FieldGroup>
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index 3e6c57fa4..fcda800b3 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -12,6 +12,7 @@ from ._router import (
agent_router,
chat_router,
credential_router,
+ health_router,
hub_router,
knowledge_base_router,
embedding_model_router,
@@ -301,6 +302,7 @@ def create_app(
agent_router,
chat_router,
credential_router,
+ health_router,
hub_router,
knowledge_base_router,
mcp_router,
diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.py
index 8f530d06a..a646b527b 100644
--- a/src/agentscope/app/_router/__init__.py
+++ b/src/agentscope/app/_router/__init__.py
@@ -4,6 +4,7 @@ from ._agent import agent_router
from ._chat import chat_router
from ._credential import credential_router
from ._embedding_model import embedding_model_router
+from ._health import health_router
from ._hub import hub_router
from ._knowledge_base import knowledge_base_router
from ._mcp import mcp_router
@@ -21,6 +22,7 @@ __all__ = [
"tts_model_router",
"chat_router",
"credential_router",
+ "health_router",
"hub_router",
"knowledge_base_router",
"mcp_router",
diff --git a/src/agentscope/app/_router/_health.py b/src/agentscope/app/_router/_health.py
new file mode 100644
index 000000000..dc51b126c
--- /dev/null
+++ b/src/agentscope/app/_router/_health.py
@@ -0,0 +1,89 @@
+# -*- coding: utf-8 -*-
+"""The health router."""
+
+from fastapi import APIRouter, Depends, Request, Response, status
+
+from ._schema import ComponentStatus, HealthResponse
+from ..deps import get_current_user_id
+
+health_router = APIRouter(tags=["health"])
+
+# Attached by ``create_app`` before the server starts serving.
+_EAGER_COMPONENTS = ("storage", "message_bus", "workspace_manager")
+
+# Built during the lifespan startup, in the order they are created.
+_LIFESPAN_COMPONENTS = (
+ "background_task_manager",
+ "chat_run_registry",
+ "scheduler_manager",
+ "resource_access_service",
+ "chat_service",
+ "session_service",
+)
+
+# Optional hubs, attached eagerly — empty means the deployment
+# registered none, which is a healthy state, not a failure.
+_OPTIONAL_HUBS = ("mcp_hubs", "skill_hubs")
+
+
+@health_router.get(
+ "/health",
+ response_model=HealthResponse,
+ summary="Report service liveness and per-component readiness",
+)
+async def get_health(
+ request: Request,
+ response: Response,
+ _: str = Depends(get_current_user_id),
+) -> HealthResponse:
+ """Report whether the service is ready to serve requests.
+
+ The check is deliberately I/O-free — it only inspects what is
+ attached to ``app.state``, so probing it never touches Redis, the
+ database or a workspace backend.
+
+ Under a plain ``uvicorn.run(app)`` the ``not_ready`` status is
+ effectively unreachable: uvicorn completes the lifespan startup
+ before it accepts connections, so anything that reaches this handler
+ already has the lifespan components in place. What it does catch is
+ the mount-as-sub-app deployment documented in
+ :func:`~agentscope.app.create_app` — Starlette does not run a mounted
+ sub-app's lifespan, so every lifespan component stays missing and
+ all business endpoints are broken. Reporting 503 here turns that
+ silent misconfiguration into one clear signal.
+
+ Args:
+ request (`Request`): The incoming FastAPI request.
+ response (`Response`): The outgoing response, whose status code
+ is downgraded to ``503`` when the service is not ready.
+
+ Returns:
+ `HealthResponse`: The overall status, API version and the
+ per-component readiness map.
+ """
+ state = request.app.state
+ components: dict[str, ComponentStatus] = {
+ name: "ok" if getattr(state, name, None) is not None else "not_ready"
+ for name in _EAGER_COMPONENTS + _LIFESPAN_COMPONENTS
+ }
+ for name in _OPTIONAL_HUBS:
+ components[name] = "ok" if getattr(state, name, None) else "disabled"
+
+ # The KB feature is off when no manager was passed to create_app; only
+ # when it is on does a missing service mean the startup fell short.
+ if getattr(state, "knowledge_base_manager", None) is None:
+ components["knowledge_base"] = "disabled"
+ elif getattr(state, "knowledge_base_service", None) is not None:
+ components["knowledge_base"] = "ok"
+ else:
+ components["knowledge_base"] = "not_ready"
+
+ ready = all(value != "not_ready" for value in components.values())
+ if not ready:
+ response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+
+ return HealthResponse(
+ status="ok" if ready else "not_ready",
+ version=request.app.version,
+ components=components,
+ )
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index b96f588a6..a6ac01b1a 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -2,6 +2,7 @@
"""Schema models for the agent service."""
from ._chat import ChatRequest, ChatTriggerResponse
+from ._health import ComponentStatus, HealthResponse
from ._hub import HubInfo
from ._hub_mcp import InstallMCPRequest, MCPView, UpdateMCPRequest
from ._hub_skill import SkillView
@@ -72,6 +73,9 @@ from ._session import (
)
__all__ = [
+ # Health
+ "ComponentStatus",
+ "HealthResponse",
# Hub
"HubInfo",
"InstallMCPRequest",
diff --git a/src/agentscope/app/_router/_schema/_health.py b/src/agentscope/app/_router/_schema/_health.py
new file mode 100644
index 000000000..5427f8be8
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_health.py
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+"""The service health report, used as DTO layer."""
+
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+ComponentStatus = Literal["ok", "not_ready", "disabled"]
+
+
+class HealthResponse(BaseModel):
+ """The service health response."""
+
+ status: Literal["ok", "not_ready"] = Field(
+ description="Overall service status. ``not_ready`` when any "
+ "required component is missing; disabled optional features do "
+ "not affect it.",
+ )
+ version: str = Field(
+ description="The API version this app was created with.",
+ )
+ components: dict[str, ComponentStatus] = Field(
+ description="Per-subsystem readiness. ``disabled`` marks an "
+ "optional feature the deployment did not enable.",
+ )
diff --git a/tests/health_router_test.py b/tests/health_router_test.py
new file mode 100644
index 000000000..2379ed231
--- /dev/null
+++ b/tests/health_router_test.py
@@ -0,0 +1,111 @@
+# -*- coding: utf-8 -*-
+"""Health router test case — readiness reporting, without any I/O."""
+import tempfile
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+from fastapi.testclient import TestClient
+
+from agentscope.app import create_app
+from agentscope.app.message_bus import RedisMessageBus
+from agentscope.app.storage import RedisStorage
+from agentscope.app.workspace_manager import LocalWorkspaceManager
+
+HEADERS = {"X-User-ID": "alice"}
+
+
+def _fake_backends() -> tuple:
+ """Build a fakeredis-backed storage and message bus."""
+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+
+ class _Storage(RedisStorage):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ class _Bus(RedisMessageBus):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ return _Storage(), _Bus()
+
+
+class HealthRouterTest(IsolatedAsyncioTestCase):
+ """Probe the health endpoint on a fully started app."""
+
+ def setUp(self) -> None:
+ """Start an app with the knowledge base feature left disabled."""
+ # enterContext is the unittest-native way to bind a context
+ # manager to the test's lifetime; pylint does not recognise it.
+ # pylint: disable=consider-using-with
+ workdir = self.enterContext(tempfile.TemporaryDirectory())
+ storage, bus = _fake_backends()
+ app = create_app(
+ storage=storage,
+ message_bus=bus,
+ workspace_manager=LocalWorkspaceManager(workdir),
+ enable_index_worker=False,
+ )
+ self._app = app
+ self._client = self.enterContext(TestClient(app))
+
+ def test_health_reports_ok_once_started(self) -> None:
+ """A fully started app reports ok with its configured version."""
+ response = self._client.get("/health", headers=HEADERS)
+
+ self.assertEqual(response.status_code, 200)
+ body = response.json()
+ self.assertEqual(body["status"], "ok")
+ self.assertEqual(body["version"], self._app.version)
+
+ # Both the eagerly attached and the lifespan-built components
+ # must be present, otherwise "ok" would be meaningless.
+ self.assertEqual(body["components"]["storage"], "ok")
+ self.assertEqual(body["components"]["chat_service"], "ok")
+
+ def test_health_requires_user_id(self) -> None:
+ """The endpoint is not exempt from the X-User-ID requirement."""
+ response = self._client.get("/health")
+
+ self.assertEqual(response.status_code, 422)
+
+ def test_disabled_features_do_not_break_health(self) -> None:
+ """An unconfigured optional feature reads as disabled, not down."""
+ body = self._client.get("/health", headers=HEADERS).json()
+
+ self.assertEqual(body["components"]["knowledge_base"], "disabled")
+ self.assertEqual(body["components"]["mcp_hubs"], "disabled")
+ self.assertEqual(body["status"], "ok")
+
+ def test_missing_lifespan_reports_not_ready(self) -> None:
+ """Mounting without running the lifespan reports 503 with detail.
+
+ This is the deployment mistake the endpoint exists to catch —
+ Starlette skips a mounted sub-app's lifespan, so nothing the
+ lifespan builds is ever attached.
+ """
+ with tempfile.TemporaryDirectory() as workdir:
+ storage, bus = _fake_backends()
+ app = create_app(
+ storage=storage,
+ message_bus=bus,
+ workspace_manager=LocalWorkspaceManager(workdir),
+ enable_index_worker=False,
+ )
+ # No `with`: the lifespan never runs, mimicking a bare mount.
+ response = TestClient(app).get("/health", headers=HEADERS)
+
+ self.assertEqual(response.status_code, 503)
+ body = response.json()
+ self.assertEqual(body["status"], "not_ready")
+ self.assertEqual(body["components"]["chat_service"], "not_ready")
+ # Eagerly attached state survives — the report pinpoints the gap.
+ self.assertEqual(body["components"]["storage"], "ok")