diff --git a/web/app/(utility)/settings/network/page.tsx b/web/app/(utility)/settings/network/page.tsx index 84c805175..e62989be8 100644 --- a/web/app/(utility)/settings/network/page.tsx +++ b/web/app/(utility)/settings/network/page.tsx @@ -19,6 +19,11 @@ import { writeStoredChatResponseTimeout, } from "@/context/app-shell-storage"; import { apiFetch, apiUrl } from "@/lib/api"; +import { + RuntimeHealthCard, + TurnCoordinationSettings, + useRuntimeStatus, +} from "@/features/runtime-status"; type NetworkSettings = { backend_port: number; @@ -210,6 +215,7 @@ function ChatResponseTimeoutSection() { export default function NetworkSettingsPage() { const { t } = useTranslation(); + const runtime = useRuntimeStatus(); const { registerExtension, pendingExtensionPayload, draftRevision } = useSettings(); const apiBasePlaceholder = "https://api.example.com"; @@ -328,6 +334,26 @@ export default function NetworkSettingsPage() { {t("Network changes take effect after restart.")}

+
+ + {runtime.data ? ( + + ) : null} +
+ {loading && ( diff --git a/web/components/settings/SettingsStatusPanel.tsx b/web/components/settings/SettingsStatusPanel.tsx index 9943fba61..603e5cedd 100644 --- a/web/components/settings/SettingsStatusPanel.tsx +++ b/web/components/settings/SettingsStatusPanel.tsx @@ -5,6 +5,10 @@ import { useTranslation } from "react-i18next"; import MemoryUsageItem from "@/components/settings/MemoryUsageItem"; import { useSettings } from "@/components/settings/SettingsContext"; import { statusDotClass } from "@/components/settings/shared"; +import { + RuntimeHealthCard, + useRuntimeStatus, +} from "@/features/runtime-status"; /** * Resident status module on the settings hub — the old `/settings/status` page @@ -21,6 +25,7 @@ import { statusDotClass } from "@/components/settings/shared"; export default function SettingsStatusPanel() { const { t } = useTranslation(); const { status } = useSettings(); + const runtime = useRuntimeStatus(); const online = status?.backend.status === "online"; @@ -42,6 +47,7 @@ export default function SettingsStatusPanel() { + ); diff --git a/web/features/runtime-status/RuntimeHealthCard.tsx b/web/features/runtime-status/RuntimeHealthCard.tsx new file mode 100644 index 000000000..afeacb546 --- /dev/null +++ b/web/features/runtime-status/RuntimeHealthCard.tsx @@ -0,0 +1,128 @@ +"use client"; + +import { RefreshCw, ServerCog } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Button, InlineAlert, Skeleton, StatusChip, type StatusTone } from "@/shared/ui"; +import type { RuntimeHealth, RuntimeStatusSnapshot } from "./model"; + +export interface RuntimeHealthCardProps { + snapshot: RuntimeStatusSnapshot; + onRefresh?: () => void | Promise; + showDetails?: boolean; + compact?: boolean; +} + +const tone: Record = { + healthy: "success", + degraded: "warning", + recovering: "warning", + unavailable: "danger", +}; + +export function RuntimeHealthCard({ + snapshot, + onRefresh, + showDetails = false, + compact = false, +}: RuntimeHealthCardProps) { + const { t } = useTranslation(); + const label = { + healthy: t("Healthy"), + degraded: t("Degraded"), + recovering: t("Recovering"), + unavailable: t("Unavailable"), + }[snapshot.health]; + + if (snapshot.loading && !snapshot.data) { + return compact ? : ; + } + + if (compact) { + return ( +
+ {t("Turn runtime")} + {label} +
+ ); + } + + const status = snapshot.data; + return ( +
+
+
+ + + +
+
+

+ {t("Turn runtime")} +

+ {label} +
+

+ {healthDescription(snapshot.health, t)} +

+
+
+ {onRefresh ? ( + + ) : null} +
+ + {snapshot.error ? ( + + {status + ? t("The latest refresh failed. Showing the last safe snapshot.") + : t("Runtime health could not be loaded.")} + + ) : null} + + {status && showDetails ? ( +
+ + + + + + + + +
+ ) : null} +
+ ); +} + +function Metric({ label, value }: { label: string; value: string }) { + return ( +
+
{label}
+
+ {value} +
+
+ ); +} + +function redisLabel(status: "ok" | "unavailable" | "not_configured", t: (key: string) => string) { + if (status === "ok") return t("Connected"); + if (status === "unavailable") return t("Unavailable"); + return t("Not configured"); +} + +function healthDescription(health: RuntimeHealth, t: (key: string) => string) { + if (health === "healthy") return t("Turn ownership and recovery services are operating normally."); + if (health === "recovering") return t("The runtime is reconciling interrupted work."); + if (health === "degraded") return t("Turn coordination needs operator attention."); + return t("The runtime status endpoint is not available."); +} diff --git a/web/features/runtime-status/TurnCoordinationSettings.tsx b/web/features/runtime-status/TurnCoordinationSettings.tsx new file mode 100644 index 000000000..9704ff74d --- /dev/null +++ b/web/features/runtime-status/TurnCoordinationSettings.tsx @@ -0,0 +1,142 @@ +"use client"; + +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Button, Field, InlineAlert } from "@/shared/ui"; +import { + validateTurnCoordination, + type TurnCoordinationDraft, +} from "./model"; + +export interface TurnCoordinationSettingsProps { + value: TurnCoordinationDraft; + redisConfigured: boolean; + onChange?: (next: TurnCoordinationDraft) => void; + onSaveRedisUrl?: (url: string) => Promise; +} + +const controlClass = + "min-h-10 w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60"; + +export function TurnCoordinationSettings({ + value, + redisConfigured, + onChange, + onSaveRedisUrl, +}: TurnCoordinationSettingsProps) { + const { t } = useTranslation(); + const [redisUrl, setRedisUrl] = useState(""); + const [savingSecret, setSavingSecret] = useState(false); + const [secretError, setSecretError] = useState(""); + const errors = validateTurnCoordination(value, redisConfigured); + const readOnly = !onChange; + const update = (patch: Partial) => onChange?.({ ...value, ...patch }); + + const saveSecret = async () => { + if (!onSaveRedisUrl || !redisUrl.trim()) return; + setSavingSecret(true); + setSecretError(""); + try { + await onSaveRedisUrl(redisUrl.trim()); + setRedisUrl(""); + } catch (error) { + setSecretError(error instanceof Error ? error.message : t("Failed to save.")); + } finally { + setSavingSecret(false); + } + }; + + return ( +
+

{t("Turn coordination")}

+

+ {readOnly + ? t("These startup settings are shown from the active runtime.") + : t("Changes apply after the backend restarts.")} +

+ +
+ + update({ backendWorkers: Number(event.target.value) })} + /> + + + + +
+ + {onSaveRedisUrl ? ( +
+ + setRedisUrl(event.target.value)} + /> + + +
+ ) : null} + +
+ {t("Advanced")} +
+ + update({ leaseTtlSeconds: Number(event.target.value) })} + /> + + + update({ recoveryIntervalSeconds: Number(event.target.value) })} + /> + +
+
+ + {errors.length ? ( + +
    + {errors.map((error) =>
  • {t(error)}
  • )} +
+
+ ) : null} +
+ ); +} diff --git a/web/features/runtime-status/api.ts b/web/features/runtime-status/api.ts new file mode 100644 index 000000000..75852ce09 --- /dev/null +++ b/web/features/runtime-status/api.ts @@ -0,0 +1,13 @@ +import { requestJson } from "@/shared/api/client"; +import { parseRuntimeStatus, type RuntimeStatusModel } from "./model"; + +export const RUNTIME_STATUS_PATH = "/api/v1/system/runtime"; + +export async function fetchRuntimeStatus(signal?: AbortSignal): Promise { + const payload = await requestJson(RUNTIME_STATUS_PATH, { + cache: "no-store", + signal, + scope: "runtime", + }); + return parseRuntimeStatus(payload); +} diff --git a/web/features/runtime-status/index.ts b/web/features/runtime-status/index.ts new file mode 100644 index 000000000..7bff9de16 --- /dev/null +++ b/web/features/runtime-status/index.ts @@ -0,0 +1,16 @@ +export { fetchRuntimeStatus, RUNTIME_STATUS_PATH } from "./api"; +export { + parseRuntimeStatus, + runtimeHealth, + validateTurnCoordination, + UnsafeRuntimePayloadError, +} from "./model"; +export type { + RuntimeHealth, + RuntimeStatusModel, + RuntimeStatusSnapshot, + TurnCoordinationDraft, +} from "./model"; +export { RuntimeHealthCard } from "./RuntimeHealthCard"; +export { TurnCoordinationSettings } from "./TurnCoordinationSettings"; +export { refreshRuntimeStatus, useRuntimeStatus } from "./useRuntimeStatus"; diff --git a/web/features/runtime-status/model.ts b/web/features/runtime-status/model.ts new file mode 100644 index 000000000..39f1e1ae5 --- /dev/null +++ b/web/features/runtime-status/model.ts @@ -0,0 +1,159 @@ +export type RuntimeHealth = "healthy" | "degraded" | "recovering" | "unavailable"; + +export interface RuntimeStatusModel { + workerId: string; + workerCount: number; + coordinationMode: "memory" | "redis"; + redisConfigured: boolean; + redisStatus: "ok" | "unavailable" | "not_configured"; + leaderId: string | null; + leaderHealthy: boolean | null; + ownerTurnCount: number; + recoveryBacklog: number; + leaseTtlSeconds: number; + renewIntervalSeconds: number; + recoveryIntervalSeconds: number; + protocolVersion: string; + minimumWebProtocolVersion: string; +} + +export interface RuntimeStatusSnapshot { + data: RuntimeStatusModel | null; + health: RuntimeHealth; + error: string | null; + loading: boolean; + lastUpdated: number | null; +} + +const SECRET_KEY = /(?:password|passwd|secret|token|credential|api[_-]?key|redis[_-]?url|dsn)/i; + +export class UnsafeRuntimePayloadError extends Error { + constructor() { + super("Runtime status contained a credential-like field"); + this.name = "UnsafeRuntimePayloadError"; + } +} + +function hasCredentialLikeKey(value: unknown, seen = new Set()): boolean { + if (!value || typeof value !== "object") return false; + if (seen.has(value)) return false; + seen.add(value); + if (Array.isArray(value)) return value.some((item) => hasCredentialLikeKey(item, seen)); + for (const [key, child] of Object.entries(value as Record)) { + if (SECRET_KEY.test(key)) return true; + if (hasCredentialLikeKey(child, seen)) return true; + } + return false; +} + +function record(value: unknown): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new TypeError("Runtime status must be an object"); + } + return value as Record; +} + +function integer(value: unknown, field: string, minimum = 0): number { + if (!Number.isInteger(value) || Number(value) < minimum) { + throw new TypeError(`Runtime status field ${field} is invalid`); + } + return Number(value); +} + +function text(value: unknown, field: string): string { + if (typeof value !== "string" || !value.trim()) { + throw new TypeError(`Runtime status field ${field} is invalid`); + } + return value.trim(); +} + +export function parseRuntimeStatus(raw: unknown): RuntimeStatusModel { + if (hasCredentialLikeKey(raw)) throw new UnsafeRuntimePayloadError(); + const envelope = record(raw); + const source = record(envelope.runtime_status ?? envelope); + const coordinationMode = source.coordination_mode; + const redisStatus = source.redis_status; + if (coordinationMode !== "memory" && coordinationMode !== "redis") { + throw new TypeError("Runtime coordination mode is invalid"); + } + if (redisStatus !== "ok" && redisStatus !== "unavailable" && redisStatus !== "not_configured") { + throw new TypeError("Runtime Redis status is invalid"); + } + if (typeof source.redis_configured !== "boolean") { + throw new TypeError("Runtime Redis configuration flag is invalid"); + } + if (source.leader_healthy !== null && source.leader_healthy !== undefined && typeof source.leader_healthy !== "boolean") { + throw new TypeError("Runtime leader health is invalid"); + } + + return { + workerId: text(source.worker_id, "worker_id"), + workerCount: integer(source.worker_count, "worker_count", 1), + coordinationMode, + redisConfigured: source.redis_configured, + redisStatus, + leaderId: source.leader_id == null ? null : text(source.leader_id, "leader_id"), + leaderHealthy: source.leader_healthy == null ? null : source.leader_healthy, + ownerTurnCount: integer(source.owner_turn_count ?? 0, "owner_turn_count"), + recoveryBacklog: integer(source.recovery_backlog ?? 0, "recovery_backlog"), + leaseTtlSeconds: integer(source.lease_ttl_seconds, "lease_ttl_seconds", 1), + renewIntervalSeconds: integer(source.renew_interval_seconds, "renew_interval_seconds", 1), + recoveryIntervalSeconds: integer(source.recovery_interval_seconds, "recovery_interval_seconds", 1), + protocolVersion: text(source.protocol_version ?? "2.0", "protocol_version"), + minimumWebProtocolVersion: text( + source.minimum_web_protocol_version ?? "2.0", + "minimum_web_protocol_version", + ), + }; +} + +export function runtimeHealth(status: RuntimeStatusModel | null): RuntimeHealth { + if (!status) return "unavailable"; + if (status.recoveryBacklog > 0) return "recovering"; + const redisRequired = status.workerCount > 1 || status.coordinationMode === "redis"; + if ( + (redisRequired && (!status.redisConfigured || status.redisStatus !== "ok")) || + status.leaderHealthy === false + ) { + return "degraded"; + } + return "healthy"; +} + +export interface TurnCoordinationDraft { + backendWorkers: number; + coordinationMode: "memory" | "redis"; + developmentReload: boolean; + leaseTtlSeconds: number; + recoveryIntervalSeconds: number; +} + +export function validateTurnCoordination( + draft: TurnCoordinationDraft, + redisConfigured: boolean, +): string[] { + const errors: string[] = []; + if (!Number.isInteger(draft.backendWorkers) || draft.backendWorkers < 1 || draft.backendWorkers > 32) { + errors.push("Worker count must be between 1 and 32."); + } + if (draft.backendWorkers > 1 && draft.coordinationMode !== "redis") { + errors.push("Multiple workers require Redis coordination."); + } + if (draft.backendWorkers > 1 && !redisConfigured) { + errors.push("Configure Redis before enabling multiple workers."); + } + if (draft.backendWorkers > 1 && draft.developmentReload) { + errors.push("Development reload and multiple workers cannot run together."); + } + if (!Number.isInteger(draft.leaseTtlSeconds) || draft.leaseTtlSeconds < 5 || draft.leaseTtlSeconds > 300) { + errors.push("Lease TTL must be between 5 and 300 seconds."); + } + if ( + !Number.isInteger(draft.recoveryIntervalSeconds) || + draft.recoveryIntervalSeconds < 1 || + draft.recoveryIntervalSeconds > 60 + ) { + errors.push("Recovery interval must be between 1 and 60 seconds."); + } + return errors; +} diff --git a/web/features/runtime-status/useRuntimeStatus.ts b/web/features/runtime-status/useRuntimeStatus.ts new file mode 100644 index 000000000..f2c39b13e --- /dev/null +++ b/web/features/runtime-status/useRuntimeStatus.ts @@ -0,0 +1,98 @@ +"use client"; + +import { useSyncExternalStore } from "react"; +import { fetchRuntimeStatus } from "./api"; +import { runtimeHealth, type RuntimeStatusSnapshot } from "./model"; + +const listeners = new Set<() => void>(); +const INITIAL: RuntimeStatusSnapshot = { + data: null, + health: "unavailable", + error: null, + loading: true, + lastUpdated: null, +}; +let snapshot = INITIAL; +let timer: ReturnType | null = null; +let request: Promise | null = null; +let controller: AbortController | null = null; +let failures = 0; + +function emit(next: RuntimeStatusSnapshot) { + snapshot = next; + for (const listener of listeners) listener(); +} + +function visible(): boolean { + return typeof document === "undefined" || document.visibilityState === "visible"; +} + +function clearTimer() { + if (timer) clearTimeout(timer); + timer = null; +} + +function schedule() { + clearTimer(); + if (!listeners.size || !visible()) return; + const delay = failures ? Math.min(120_000, 5_000 * 2 ** Math.min(failures - 1, 5)) : 30_000; + timer = setTimeout(() => void refreshRuntimeStatus(), delay); +} + +export function refreshRuntimeStatus(): Promise { + if (request) return request; + controller = new AbortController(); + if (!snapshot.data) emit({ ...snapshot, loading: true, error: null }); + request = fetchRuntimeStatus(controller.signal) + .then((data) => { + failures = 0; + emit({ data, health: runtimeHealth(data), error: null, loading: false, lastUpdated: Date.now() }); + }) + .catch((error: unknown) => { + if (controller?.signal.aborted) return; + failures += 1; + emit({ + ...snapshot, + health: snapshot.data ? runtimeHealth(snapshot.data) : "unavailable", + error: error instanceof Error ? error.message : "Runtime status is unavailable", + loading: false, + }); + }) + .finally(() => { + request = null; + controller = null; + schedule(); + }); + return request; +} + +function handleVisibility() { + if (visible()) void refreshRuntimeStatus(); + else { + clearTimer(); + controller?.abort(); + } +} + +function subscribe(listener: () => void) { + listeners.add(listener); + if (listeners.size === 1 && typeof window !== "undefined") { + window.addEventListener("focus", handleVisibility); + document.addEventListener("visibilitychange", handleVisibility); + void refreshRuntimeStatus(); + } + return () => { + listeners.delete(listener); + if (!listeners.size && typeof window !== "undefined") { + clearTimer(); + controller?.abort(); + window.removeEventListener("focus", handleVisibility); + document.removeEventListener("visibilitychange", handleVisibility); + } + }; +} + +export function useRuntimeStatus(): RuntimeStatusSnapshot & { refresh: () => Promise } { + const current = useSyncExternalStore(subscribe, () => snapshot, () => INITIAL); + return { ...current, refresh: refreshRuntimeStatus }; +} diff --git a/web/locales/en/app.json b/web/locales/en/app.json index 6963e469f..49fced508 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -4550,5 +4550,45 @@ "Frontend update required": "Frontend update required", "Reload": "Reload", "This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.": "This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.", - "an incompatible version": "an incompatible version" + "an incompatible version": "an incompatible version", + "Healthy": "Healthy", + "Degraded": "Degraded", + "Recovering": "Recovering", + "Turn runtime": "Turn runtime", + "Turn ownership and recovery services are operating normally.": "Turn ownership and recovery services are operating normally.", + "The runtime is reconciling interrupted work.": "The runtime is reconciling interrupted work.", + "Turn coordination needs operator attention.": "Turn coordination needs operator attention.", + "The runtime status endpoint is not available.": "The runtime status endpoint is not available.", + "The latest refresh failed. Showing the last safe snapshot.": "The latest refresh failed. Showing the last safe snapshot.", + "Runtime health could not be loaded.": "Runtime health could not be loaded.", + "Workers": "Workers", + "Coordination": "Coordination", + "Active owner turns": "Active owner turns", + "Recovery backlog": "Recovery backlog", + "Redis": "Redis", + "Leader": "Leader", + "Protocol": "Protocol", + "Worker ID": "Worker ID", + "Unhealthy": "Unhealthy", + "Not applicable": "Not applicable", + "In process": "In process", + "Turn coordination": "Turn coordination", + "These startup settings are shown from the active runtime.": "These startup settings are shown from the active runtime.", + "Changes apply after the backend restarts.": "Changes apply after the backend restarts.", + "Backend workers": "Backend workers", + "Coordination backend": "Coordination backend", + "Redis URL": "Redis URL", + "A Redis secret is configured. Enter a new value only to replace it.": "A Redis secret is configured. Enter a new value only to replace it.", + "The value is encrypted at rest and is never returned by the server.": "The value is encrypted at rest and is never returned by the server.", + "Save secret": "Save secret", + "Advanced": "Advanced", + "Lease TTL (seconds)": "Lease TTL (seconds)", + "Recovery interval (seconds)": "Recovery interval (seconds)", + "Check runtime settings": "Check runtime settings", + "Worker count must be between 1 and 32.": "Worker count must be between 1 and 32.", + "Multiple workers require Redis coordination.": "Multiple workers require Redis coordination.", + "Configure Redis before enabling multiple workers.": "Configure Redis before enabling multiple workers.", + "Development reload and multiple workers cannot run together.": "Development reload and multiple workers cannot run together.", + "Lease TTL must be between 5 and 300 seconds.": "Lease TTL must be between 5 and 300 seconds.", + "Recovery interval must be between 1 and 60 seconds.": "Recovery interval must be between 1 and 60 seconds." } diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json index c3b98b2b5..eb71c8886 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -4550,5 +4550,45 @@ "Frontend update required": "需要更新前端", "Reload": "重新加载", "This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.": "当前页面使用协议 {{clientVersion}},但服务端报告为 {{serverVersion}}。", - "an incompatible version": "不兼容版本" + "an incompatible version": "不兼容版本", + "Healthy": "健康", + "Degraded": "降级", + "Recovering": "恢复中", + "Turn runtime": "对话运行时", + "Turn ownership and recovery services are operating normally.": "对话所有权与恢复服务运行正常。", + "The runtime is reconciling interrupted work.": "运行时正在协调被中断的任务。", + "Turn coordination needs operator attention.": "对话协调服务需要运维人员处理。", + "The runtime status endpoint is not available.": "运行时状态接口当前不可用。", + "The latest refresh failed. Showing the last safe snapshot.": "最新刷新失败,当前显示上一次安全快照。", + "Runtime health could not be loaded.": "无法加载运行时健康状态。", + "Workers": "Worker 数量", + "Coordination": "协调方式", + "Active owner turns": "Owner 活跃对话", + "Recovery backlog": "恢复积压", + "Redis": "Redis", + "Leader": "Leader", + "Protocol": "协议", + "Worker ID": "Worker ID", + "Unhealthy": "异常", + "Not applicable": "不适用", + "In process": "进程内", + "Turn coordination": "对话协调", + "These startup settings are shown from the active runtime.": "以下启动设置来自当前运行时,仅供查看。", + "Changes apply after the backend restarts.": "修改将在后端重启后生效。", + "Backend workers": "后端 Worker 数量", + "Coordination backend": "协调后端", + "Redis URL": "Redis URL", + "A Redis secret is configured. Enter a new value only to replace it.": "Redis 密钥已配置;仅在需要替换时输入新值。", + "The value is encrypted at rest and is never returned by the server.": "该值会加密存储,服务端不会再次返回。", + "Save secret": "保存密钥", + "Advanced": "高级", + "Lease TTL (seconds)": "租约 TTL(秒)", + "Recovery interval (seconds)": "恢复间隔(秒)", + "Check runtime settings": "检查运行时设置", + "Worker count must be between 1 and 32.": "Worker 数量必须在 1 到 32 之间。", + "Multiple workers require Redis coordination.": "多 Worker 模式必须使用 Redis 协调。", + "Configure Redis before enabling multiple workers.": "启用多 Worker 前请先配置 Redis。", + "Development reload and multiple workers cannot run together.": "开发热重载不能与多 Worker 同时启用。", + "Lease TTL must be between 5 and 300 seconds.": "租约 TTL 必须在 5 到 300 秒之间。", + "Recovery interval must be between 1 and 60 seconds.": "恢复间隔必须在 1 到 60 秒之间。" } diff --git a/web/tests/integration/runtime-health.spec.tsx b/web/tests/integration/runtime-health.spec.tsx new file mode 100644 index 000000000..8f9776074 --- /dev/null +++ b/web/tests/integration/runtime-health.spec.tsx @@ -0,0 +1,82 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; +import { + RuntimeHealthCard, + TurnCoordinationSettings, +} from "@/features/runtime-status"; +import type { RuntimeStatusSnapshot } from "@/features/runtime-status/model"; +import { initI18n } from "@/i18n/init"; + +initI18n("en"); + +const snapshot: RuntimeStatusSnapshot = { + health: "healthy", + loading: false, + error: null, + lastUpdated: 1, + data: { + workerId: "worker-a", + workerCount: 4, + coordinationMode: "redis", + redisConfigured: true, + redisStatus: "ok", + leaderId: "worker-b", + leaderHealthy: true, + ownerTurnCount: 2, + recoveryBacklog: 0, + leaseTtlSeconds: 30, + renewIntervalSeconds: 10, + recoveryIntervalSeconds: 5, + protocolVersion: "2.0", + minimumWebProtocolVersion: "2.0", + }, +}; + +describe("runtime health UI", () => { + it("shows aggregate health and gates operator details", () => { + const { rerender } = render(); + expect(screen.getByText("Healthy")).toBeVisible(); + expect(screen.queryByText("worker-a")).not.toBeInTheDocument(); + rerender(); + expect(screen.getByText("worker-a")).toBeVisible(); + expect(screen.getByText("worker-b")).toBeVisible(); + }); + + it("keeps stale safe data visible when refresh fails", () => { + render( + , + ); + expect(screen.getByRole("status")).toHaveTextContent("last safe snapshot"); + expect(screen.getByText("worker-a")).toBeVisible(); + expect(screen.queryByText("request failed")).not.toBeInTheDocument(); + }); + + it("never echoes a saved Redis URL", async () => { + const save = vi.fn(async () => undefined); + const user = userEvent.setup(); + render( + undefined} + onSaveRedisUrl={save} + />, + ); + const input = screen.getByLabelText("Redis URL"); + await user.type(input, "redis://user:password@host"); + await user.click(screen.getByRole("button", { name: "Save secret" })); + expect(save).toHaveBeenCalledWith("redis://user:password@host"); + expect(input).toHaveValue(""); + expect(document.body).not.toHaveTextContent("redis://user:password@host"); + }); +}); diff --git a/web/tests/runtime-status.test.ts b/web/tests/runtime-status.test.ts new file mode 100644 index 000000000..1ad589a6f --- /dev/null +++ b/web/tests/runtime-status.test.ts @@ -0,0 +1,88 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + parseRuntimeStatus, + runtimeHealth, + UnsafeRuntimePayloadError, + validateTurnCoordination, +} from "../features/runtime-status/model"; + +const healthyPayload = { + worker_id: "worker-a", + worker_count: 4, + coordination_mode: "redis", + redis_configured: true, + redis_status: "ok", + leader_id: "worker-b", + leader_healthy: true, + owner_turn_count: 3, + recovery_backlog: 0, + lease_ttl_seconds: 30, + renew_interval_seconds: 10, + recovery_interval_seconds: 5, + protocol_version: "2.0", + minimum_web_protocol_version: "2.0", +}; + +test("runtime status parses only the public operational contract", () => { + const status = parseRuntimeStatus({ runtime_status: healthyPayload, harmless_extra: true }); + assert.deepEqual(status, { + workerId: "worker-a", + workerCount: 4, + coordinationMode: "redis", + redisConfigured: true, + redisStatus: "ok", + leaderId: "worker-b", + leaderHealthy: true, + ownerTurnCount: 3, + recoveryBacklog: 0, + leaseTtlSeconds: 30, + renewIntervalSeconds: 10, + recoveryIntervalSeconds: 5, + protocolVersion: "2.0", + minimumWebProtocolVersion: "2.0", + }); +}); + +test("credential-like keys reject the entire runtime payload", () => { + for (const secret of [ + { redis_url: "redis://user:password@host" }, + { nested: { password: "value" } }, + { apiToken: "value" }, + { credentials: { value: "secret" } }, + ]) { + assert.throws( + () => parseRuntimeStatus({ ...healthyPayload, ...secret }), + UnsafeRuntimePayloadError, + ); + } +}); + +test("health prioritizes recovery, then coordination failures", () => { + const healthy = parseRuntimeStatus(healthyPayload); + assert.equal(runtimeHealth(healthy), "healthy"); + assert.equal(runtimeHealth({ ...healthy, recoveryBacklog: 2 }), "recovering"); + assert.equal(runtimeHealth({ ...healthy, redisStatus: "unavailable" }), "degraded"); + assert.equal(runtimeHealth({ ...healthy, leaderHealthy: false }), "degraded"); + assert.equal(runtimeHealth(null), "unavailable"); +}); + +test("multi-worker validation requires Redis and disables development reload", () => { + const errors = validateTurnCoordination( + { + backendWorkers: 4, + coordinationMode: "memory", + developmentReload: true, + leaseTtlSeconds: 2, + recoveryIntervalSeconds: 90, + }, + false, + ); + assert.deepEqual(errors, [ + "Multiple workers require Redis coordination.", + "Configure Redis before enabling multiple workers.", + "Development reload and multiple workers cannot run together.", + "Lease TTL must be between 5 and 300 seconds.", + "Recovery interval must be between 1 and 60 seconds.", + ]); +});