Repository Public
1"use client";2import Link from "next/link";3import { useQueryClient } from "@tanstack/react-query";4import { useState } from "react";5import { apiPatch, type Schemas } from "@/api/client";6import { invalidatePaths, useApiList, useApiQuery } from "@/api/query";7import { ActionButton, useActionLauncher } from "@/features/actions/ActionFlow";8import { isTerminal } from "@/features/actions/ActionView";9import { NodeLink } from "@/features/shared/nodes";10import { useI18n } from "@/i18n";11import { Page, RequirePermission } from "@/shell/AppShell";12import { useEvent } from "@/shell/realtime";13import { useSession } from "@/shell/session";14import { Badge, Banner, Button, DataStamp, Dialog, EmptyState, ErrorState, FreshnessBadge, KeyValue, LoadMore, LogView, Observed, QueryBoundary, Skeleton, StateDot, Switch, TextField, actionIcon, actionTone, cx, healthTone, serviceTone, useErrorMessage, useToast, type Tone } from "@/ui";15import { HealthCell } from "./ServicesScreen";16import { When } from "./url";17import { useActionOutput } from "./useActionOutput";1819type Service = Schemas["Service"];20type HistoryEntry = Schemas["ServiceHistoryEntry"];2122const HISTORY_TONE: Record<HistoryEntry["kind"], Tone> = { restart: "warning", state_change: "info", action: "info", deploy: "ok", appeared: "ok", disappeared: "offline" };2324export function ServiceDetail({ id }: { id: string }) {25 const { t } = useI18n();26 const qc = useQueryClient();27 const q = useApiQuery("/services/{id}", { path: { id } }, { refetchInterval: 30_000 });28 useEvent("service.changed", (e) => {29 if (e.service_id === id) void invalidatePaths(qc, "/services");30 });31 return (32 <RequirePermission permission="services.read">33 <Page title={q.data?.name ?? t("services.detail.title")} sub={q.data ? <span className="row-wrap"><NodeLink id={q.data.node_id} alias={q.data.node_alias} /><span className="mono faint">{id}</span></span> : <span className="mono">{id}</span>}34 actions={<DataStamp at={q.data?.observed_at ?? (q.data ? q.dataUpdatedAt : undefined)} freshness={q.data?.freshness} label={q.data?.observed_at ? t("services.detail.observed") : undefined} />}>35 <div data-testid="screen-service-detail" className="stack-lg">36 <QueryBoundary query={q}>{(s) => <Body service={s} />}</QueryBoundary>37 </div>38 </Page>39 </RequirePermission>40 );41}4243function Body({ service: s }: { service: Service }) {44 const { t, fmt } = useI18n();45 const { can } = useSession();46 const [editing, setEditing] = useState(false);47 const target = { kind: "service" as const, id: s.id };48 const metaEntries = s.meta ? Object.keys(s.meta) : [];49 return (50 <>51 <div className="row-between svc-head">52 <div className="row-wrap" data-testid="service-state" data-state={s.state}>53 {s.gone_at ? <Badge tone="offline">{t("services.goneSince", { time: fmt.dateTime(s.gone_at) })}</Badge> : <StateDot tone={serviceTone(s.state)} label={t(`states.service.${s.state}`)} />}54 <span className="row gap-2"><span className="caps">{t("services.col.health")}</span><HealthCell health={s.health} /></span>55 <FreshnessBadge freshness={s.freshness} subtle />56 {s.managed ? <Badge tone="info" icon="check">{t("services.managed.yes")}</Badge> : <Badge tone="neutral" icon="lock">{t("services.managed.no")}</Badge>}57 </div>58 <div className="row-wrap" role="group" aria-label={t("common.actions")}>59 <ActionButton icon="restart" request={{ type: "service.restart", target, targetLabel: s.name }}>{t("services.action.restart")}</ActionButton>60 <ActionButton icon="play" request={{ type: "service.start", target, targetLabel: s.name }}>{t("services.action.start")}</ActionButton>61 <ActionButton icon="stop" variant="danger" request={{ type: "service.stop", target, targetLabel: s.name }}>{t("services.action.stop")}</ActionButton>62 <ActionButton icon="ok" request={{ type: "service.health_check", target, targetLabel: s.name }}>{t("services.action.healthCheck")}</ActionButton>63 {can("settings.manage") ? <Button icon="edit" onClick={() => setEditing(true)} data-testid="service-edit">{t("services.edit.open")}</Button> : null}64 </div>65 </div>66 {!s.managed ? <Banner tone="info" icon="lock"><span data-testid="service-unmanaged">{t("services.unmanagedNote")} {can("settings.manage") ? t("services.unmanagedAdmin") : t("services.unmanagedAsk")}</span></Banner> : null}6768 <div className="cols-2">69 <section className="section" aria-labelledby="svc-id-h">70 <h2 id="svc-id-h">{t("services.detail.identity")}</h2>71 <KeyValue items={[72 { label: t("services.col.manager"), value: t(`states.manager.${s.manager}`) },73 { label: t("services.col.app"), value: <Observed value={s.app}>{(v) => v}</Observed> },74 { label: t("services.detail.version"), value: <Observed value={s.version}>{(v) => <span className="mono">{v}</span>}</Observed> },75 { label: t("services.detail.pid"), value: <Observed value={s.pid}>{(v) => <span className="mono">{v}</span>}</Observed> },76 { label: t("services.col.ports"), value: s.ports.length > 0 ? <span className="mono">{s.ports.join(", ")}</span> : <span className="faint">{t("services.noPorts")}</span> },77 { label: t("services.col.url"), value: s.public_url ? <a href={s.public_url} target="_blank" rel="noopener noreferrer">{s.public_url}</a> : <span className="faint">{t("services.noUrl")}</span> },78 { label: t("services.detail.firstSeen"), value: <span className="num">{fmt.dateTime(s.first_seen_at)}</span> },79 { label: t("services.col.lastSeen"), value: <span className="num">{fmt.dateTime(s.last_seen_at, { seconds: true })}</span> },80 ]} />81 </section>82 <section className="section" aria-labelledby="svc-run-h">83 <h2 id="svc-run-h">{t("services.detail.runtime")}</h2>84 <KeyValue items={[85 { label: t("services.col.restarts"), value: <Observed value={s.restarts}>{(v) => fmt.integer(v)}</Observed> },86 { label: t("services.col.uptime"), value: <Observed value={s.uptime_s}>{(v) => fmt.duration(v)}</Observed> },87 { label: t("services.col.cpu"), value: <Observed value={s.cpu_pct}>{(v) => fmt.percent(v, 1)}</Observed> },88 { label: t("services.col.mem"), value: <Observed value={s.mem_bytes}>{(v) => fmt.bytes(v)}</Observed> },89 { label: t("services.col.health"), value: s.health ? (90 <span className="stack-sm">91 <StateDot tone={healthTone(s.health.status)} label={t(`states.health.${s.health.status}`)} />92 {s.health.detail ? <span className="muted pre">{s.health.detail}</span> : null}93 <span className="faint">{s.health.checked_at ? <>{t("services.health.checked")} <When at={s.health.checked_at} /></> : t("services.health.neverChecked")}{s.health.latency_ms !== undefined ? ` · ${fmt.ms(s.health.latency_ms)}` : ""}</span>94 </span>95 ) : <span className="mcc-unmeasured">{t("services.health.none")}</span> },96 ...(metaEntries.length > 0 ? [{ label: t("services.detail.meta"), value: <code className="pre">{JSON.stringify(s.meta, null, 2)}</code> }] : []),97 ]} />98 </section>99 </div>100101 <LogTail service={s} />102 <History id={s.id} />103 {editing ? <EditDialog service={s} onClose={() => setEditing(false)} /> : null}104 </>105 );106}107108function LogTail({ service: s }: { service: Service }) {109 const { t } = useI18n();110 const { can } = useSession();111 const launch = useActionLauncher();112 const [actionId, setActionId] = useState<string | null>(null);113 return (114 <section className="section" aria-labelledby="svc-log-h" data-testid="service-logs">115 <div className="section-head">116 <h2 id="svc-log-h">{t("services.logs.title")}</h2>117 <Button icon="terminal" disabled={!can("logs.read")} data-testid="service-logs-tail"118 onClick={() => launch({ type: "service.logs.tail", target: { kind: "service", id: s.id }, targetLabel: s.name, stay: true, onCreated: (a) => setActionId(a.id) })}>119 {actionId ? t("services.logs.again") : t("services.logs.tail")}120 </Button>121 </div>122 <p className="mcc-hint">{t("services.logs.note")}</p>123 {!can("logs.read") ? <Banner tone="offline" icon="denied">{t("errors.forbidden.bodyPermission", { permission: "logs.read" })}</Banner>124 : actionId ? <TailOutput key={actionId} actionId={actionId} />125 : <EmptyState compact icon="terminal" title={t("services.logs.emptyTitle")}>{t("services.logs.emptyBody")}</EmptyState>}126 </section>127 );128}129130function TailOutput({ actionId }: { actionId: string }) {131 const { t } = useI18n();132 const q = useApiQuery("/actions/{id}", { path: { id: actionId } }, { refetchInterval: (query) => (query.state.data && isTerminal(query.state.data.action.state) ? false : 2000) });133 const state = q.data?.action.state;134 const live = !state || !isTerminal(state);135 const out = useActionOutput(actionId, live);136 return (137 <div className="stack">138 <div className="row-wrap" role="status" aria-live="polite">139 {state ? <StateDot tone={actionTone(state)} icon={actionIcon(state)} label={t(`states.action.${state}`)} /> : <Skeleton width="25" />}140 <Link href={`/actions/${actionId}`}>{t("services.logs.openAction")}</Link>141 </div>142 {q.data?.action.error_message ? <Banner tone="critical" role="alert"><span className="mono">{q.data.action.error_code}</span> {q.data.action.error_message}</Banner> : null}143 {q.data?.action.outcome_unknown ? <Banner tone="warning" icon="unknown">{t("actions.view.outcomeUnknownBody")}</Banner> : null}144 {out.error && out.lines.length === 0 ? <ErrorState error={out.error} compact /> : null}145 <LogView lines={out.lines} label={t("services.logs.title")} truncated={out.truncated} empty={<EmptyState compact icon="terminal" title={live ? t("services.logs.waiting") : t("services.logs.noLines")} />} />146 </div>147 );148}149150function History({ id }: { id: string }) {151 const { t, fmt } = useI18n();152 const list = useApiList("/services/{id}/history", { path: { id }, query: { limit: 50 } });153 return (154 <section className="section" aria-labelledby="svc-hist-h" data-testid="service-history">155 <div className="section-head"><h2 id="svc-hist-h">{t("services.history.title")}</h2><DataStamp at={list.ready ? list.updatedAt : undefined} /></div>156 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : !list.ready ? <Skeleton width="60" label={t("common.loading")} /> : list.items.length === 0 ? (157 <EmptyState compact icon="history" title={t("services.history.emptyTitle")}>{t("services.history.emptyBody")}</EmptyState>158 ) : (159 <ol className="mcc-timeline">160 {list.items.map((h, i) => (161 <li key={`${h.ts}-${i}`} className={cx(`tone-${HISTORY_TONE[h.kind]}`)}>162 <span className="pt" aria-hidden="true" />163 <div>164 <div className="row-wrap">165 <strong>{t(`services.history.kind.${h.kind}`)}</strong>166 {h.from_state || h.to_state ? <span className="muted">{h.from_state ? t(`states.service.${h.from_state}`) : "?"} → {h.to_state ? t(`states.service.${h.to_state}`) : "?"}</span> : null}167 {h.version ? <span className="mono muted">{h.version}</span> : null}168 </div>169 <div className="pre">{h.summary}</div>170 <div className="meta">171 <span className="num">{fmt.dateTime(h.ts, { seconds: true })}</span>172 {h.actor_display_name ? ` · ${h.actor_display_name}` : ""}173 {h.action_id ? <> · <Link href={`/actions/${h.action_id}`}>{t("services.history.viewAction")}</Link></> : null}174 </div>175 </div>176 </li>177 ))}178 </ol>179 )}180 <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />181 </section>182 );183}184185function EditDialog({ service: s, onClose }: { service: Service; onClose: () => void }) {186 const { t } = useI18n();187 const qc = useQueryClient();188 const toast = useToast();189 const explain = useErrorMessage();190 const [managed, setManaged] = useState(s.managed);191 const [url, setUrl] = useState(s.public_url ?? "");192 const [busy, setBusy] = useState(false);193 const invalid = url.trim() !== "" && !/^https?:\/\/\S+$/.test(url.trim());194 const save = async () => {195 if (invalid) return;196 setBusy(true);197 try {198 await apiPatch("/services/{id}", { path: { id: s.id }, body: { managed, ...(url.trim() !== (s.public_url ?? "") ? { public_url: url.trim() } : {}) } });199 await invalidatePaths(qc, "/services");200 toast({ tone: "ok", title: t("common.saved") });201 onClose();202 } catch (e) {203 toast({ tone: "critical", ...explain(e) });204 setBusy(false);205 }206 };207 return (208 <Dialog open onClose={onClose} title={t("services.edit.title", { name: s.name })} description={t("services.edit.body")} dismissable={!busy}209 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} disabled={invalid} onClick={() => void save()} data-testid="service-edit-save">{t("common.save")}</Button></>}>210 <Switch label={t("services.edit.managed")} hint={t("services.edit.managedHint")} checked={managed} onChange={setManaged} />211 <TextField label={t("services.col.url")} hint={t("services.edit.urlHint")} value={url} onChange={setUrl} type="url" inputMode="url" error={invalid ? t("services.edit.urlInvalid") : undefined} />212 </Dialog>213 );214}215