mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 10:39:37 +08:00
feat(web): expose safe multi-worker runtime health
This commit is contained in:
@@ -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.")}
|
||||
</p>
|
||||
|
||||
<div className="mb-7">
|
||||
<RuntimeHealthCard
|
||||
snapshot={runtime}
|
||||
onRefresh={runtime.refresh}
|
||||
showDetails
|
||||
/>
|
||||
{runtime.data ? (
|
||||
<TurnCoordinationSettings
|
||||
value={{
|
||||
backendWorkers: runtime.data.workerCount,
|
||||
coordinationMode: runtime.data.coordinationMode,
|
||||
developmentReload: false,
|
||||
leaseTtlSeconds: runtime.data.leaseTtlSeconds,
|
||||
recoveryIntervalSeconds: runtime.data.recoveryIntervalSeconds,
|
||||
}}
|
||||
redisConfigured={runtime.data.redisConfigured}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ChatResponseTimeoutSection />
|
||||
|
||||
{loading && (
|
||||
|
||||
@@ -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() {
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<RuntimeHealthCard snapshot={runtime} compact />
|
||||
<MemoryUsageItem />
|
||||
</section>
|
||||
);
|
||||
|
||||
128
web/features/runtime-status/RuntimeHealthCard.tsx
Normal file
128
web/features/runtime-status/RuntimeHealthCard.tsx
Normal file
@@ -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<void>;
|
||||
showDetails?: boolean;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
const tone: Record<RuntimeHealth, StatusTone> = {
|
||||
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 ? <Skeleton className="h-6 w-28" /> : <Skeleton className="h-36 w-full" />;
|
||||
}
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[13px] font-medium text-foreground">{t("Turn runtime")}</span>
|
||||
<StatusChip tone={tone[snapshot.health]}>{label}</StatusChip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const status = snapshot.data;
|
||||
return (
|
||||
<section className="rounded-2xl border border-border bg-card p-5 shadow-sm" aria-labelledby="runtime-health-title">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-xl bg-muted text-muted-foreground">
|
||||
<ServerCog aria-hidden className="h-5 w-5" />
|
||||
</span>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 id="runtime-health-title" className="text-sm font-semibold text-foreground">
|
||||
{t("Turn runtime")}
|
||||
</h2>
|
||||
<StatusChip tone={tone[snapshot.health]}>{label}</StatusChip>
|
||||
</div>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">
|
||||
{healthDescription(snapshot.health, t)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{onRefresh ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => void onRefresh()}
|
||||
loading={snapshot.loading}
|
||||
icon={<RefreshCw aria-hidden className="h-4 w-4" />}
|
||||
>
|
||||
{t("Refresh")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{snapshot.error ? (
|
||||
<InlineAlert tone={status ? "warning" : "danger"} className="mt-4">
|
||||
{status
|
||||
? t("The latest refresh failed. Showing the last safe snapshot.")
|
||||
: t("Runtime health could not be loaded.")}
|
||||
</InlineAlert>
|
||||
) : null}
|
||||
|
||||
{status && showDetails ? (
|
||||
<dl className="mt-5 grid grid-cols-2 gap-x-4 gap-y-4 border-t border-border pt-4 md:grid-cols-4">
|
||||
<Metric label={t("Workers")} value={String(status.workerCount)} />
|
||||
<Metric label={t("Coordination")} value={status.coordinationMode === "redis" ? "Redis" : t("In process")} />
|
||||
<Metric label={t("Active owner turns")} value={String(status.ownerTurnCount)} />
|
||||
<Metric label={t("Recovery backlog")} value={String(status.recoveryBacklog)} />
|
||||
<Metric label={t("Redis")} value={redisLabel(status.redisStatus, t)} />
|
||||
<Metric label={t("Leader")} value={status.leaderHealthy === false ? t("Unhealthy") : status.leaderId || t("Not applicable")} />
|
||||
<Metric label={t("Protocol")} value={status.protocolVersion} />
|
||||
<Metric label={t("Worker ID")} value={status.workerId} />
|
||||
</dl>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Metric({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<dt className="text-[11px] font-medium text-muted-foreground">{label}</dt>
|
||||
<dd className="mt-1 truncate text-sm font-semibold text-foreground" title={value}>
|
||||
{value}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
142
web/features/runtime-status/TurnCoordinationSettings.tsx
Normal file
142
web/features/runtime-status/TurnCoordinationSettings.tsx
Normal file
@@ -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<void>;
|
||||
}
|
||||
|
||||
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<TurnCoordinationDraft>) => 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 (
|
||||
<section className="mt-6 rounded-2xl border border-border bg-card p-5">
|
||||
<h2 className="text-sm font-semibold text-foreground">{t("Turn coordination")}</h2>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">
|
||||
{readOnly
|
||||
? t("These startup settings are shown from the active runtime.")
|
||||
: t("Changes apply after the backend restarts.")}
|
||||
</p>
|
||||
|
||||
<div className="mt-5 grid gap-4 md:grid-cols-2">
|
||||
<Field label={t("Backend workers")}>
|
||||
<input
|
||||
className={controlClass}
|
||||
type="number"
|
||||
min={1}
|
||||
max={32}
|
||||
disabled={readOnly}
|
||||
value={value.backendWorkers}
|
||||
onChange={(event) => update({ backendWorkers: Number(event.target.value) })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("Coordination backend")}>
|
||||
<select
|
||||
className={controlClass}
|
||||
disabled={readOnly}
|
||||
value={value.coordinationMode}
|
||||
onChange={(event) => update({ coordinationMode: event.target.value as "memory" | "redis" })}
|
||||
>
|
||||
<option value="memory">{t("In process")}</option>
|
||||
<option value="redis">Redis</option>
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{onSaveRedisUrl ? (
|
||||
<div className="mt-4 flex items-end gap-2">
|
||||
<Field
|
||||
label={t("Redis URL")}
|
||||
hint={redisConfigured ? t("A Redis secret is configured. Enter a new value only to replace it.") : t("The value is encrypted at rest and is never returned by the server.")}
|
||||
error={secretError || undefined}
|
||||
className="min-w-0 flex-1"
|
||||
>
|
||||
<input
|
||||
className={controlClass}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={redisUrl}
|
||||
onChange={(event) => setRedisUrl(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Button loading={savingSecret} disabled={!redisUrl.trim()} onClick={() => void saveSecret()}>
|
||||
{t("Save secret")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<details className="mt-5 border-t border-border pt-4">
|
||||
<summary className="cursor-pointer text-sm font-medium text-foreground">{t("Advanced")}</summary>
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-2">
|
||||
<Field label={t("Lease TTL (seconds)")}>
|
||||
<input
|
||||
className={controlClass}
|
||||
type="number"
|
||||
min={5}
|
||||
max={300}
|
||||
disabled={readOnly}
|
||||
value={value.leaseTtlSeconds}
|
||||
onChange={(event) => update({ leaseTtlSeconds: Number(event.target.value) })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("Recovery interval (seconds)")}>
|
||||
<input
|
||||
className={controlClass}
|
||||
type="number"
|
||||
min={1}
|
||||
max={60}
|
||||
disabled={readOnly}
|
||||
value={value.recoveryIntervalSeconds}
|
||||
onChange={(event) => update({ recoveryIntervalSeconds: Number(event.target.value) })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
{errors.length ? (
|
||||
<InlineAlert tone="warning" title={t("Check runtime settings")} className="mt-4">
|
||||
<ul className="list-disc space-y-1 pl-4">
|
||||
{errors.map((error) => <li key={error}>{t(error)}</li>)}
|
||||
</ul>
|
||||
</InlineAlert>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
13
web/features/runtime-status/api.ts
Normal file
13
web/features/runtime-status/api.ts
Normal file
@@ -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<RuntimeStatusModel> {
|
||||
const payload = await requestJson<unknown>(RUNTIME_STATUS_PATH, {
|
||||
cache: "no-store",
|
||||
signal,
|
||||
scope: "runtime",
|
||||
});
|
||||
return parseRuntimeStatus(payload);
|
||||
}
|
||||
16
web/features/runtime-status/index.ts
Normal file
16
web/features/runtime-status/index.ts
Normal file
@@ -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";
|
||||
159
web/features/runtime-status/model.ts
Normal file
159
web/features/runtime-status/model.ts
Normal file
@@ -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<object>()): 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<string, unknown>)) {
|
||||
if (SECRET_KEY.test(key)) return true;
|
||||
if (hasCredentialLikeKey(child, seen)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new TypeError("Runtime status must be an object");
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
98
web/features/runtime-status/useRuntimeStatus.ts
Normal file
98
web/features/runtime-status/useRuntimeStatus.ts
Normal file
@@ -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<typeof setTimeout> | null = null;
|
||||
let request: Promise<void> | 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<void> {
|
||||
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<void> } {
|
||||
const current = useSyncExternalStore(subscribe, () => snapshot, () => INITIAL);
|
||||
return { ...current, refresh: refreshRuntimeStatus };
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
|
||||
@@ -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 秒之间。"
|
||||
}
|
||||
|
||||
82
web/tests/integration/runtime-health.spec.tsx
Normal file
82
web/tests/integration/runtime-health.spec.tsx
Normal file
@@ -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(<RuntimeHealthCard snapshot={snapshot} />);
|
||||
expect(screen.getByText("Healthy")).toBeVisible();
|
||||
expect(screen.queryByText("worker-a")).not.toBeInTheDocument();
|
||||
rerender(<RuntimeHealthCard snapshot={snapshot} showDetails />);
|
||||
expect(screen.getByText("worker-a")).toBeVisible();
|
||||
expect(screen.getByText("worker-b")).toBeVisible();
|
||||
});
|
||||
|
||||
it("keeps stale safe data visible when refresh fails", () => {
|
||||
render(
|
||||
<RuntimeHealthCard
|
||||
snapshot={{ ...snapshot, error: "request failed" }}
|
||||
showDetails
|
||||
/>,
|
||||
);
|
||||
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(
|
||||
<TurnCoordinationSettings
|
||||
value={{
|
||||
backendWorkers: 1,
|
||||
coordinationMode: "memory",
|
||||
developmentReload: false,
|
||||
leaseTtlSeconds: 30,
|
||||
recoveryIntervalSeconds: 5,
|
||||
}}
|
||||
redisConfigured={false}
|
||||
onChange={() => 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");
|
||||
});
|
||||
});
|
||||
88
web/tests/runtime-status.test.ts
Normal file
88
web/tests/runtime-status.test.ts
Normal file
@@ -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.",
|
||||
]);
|
||||
});
|
||||
Reference in New Issue
Block a user