Files
Homelab-manager/web/src/pages/HomeAssistant.tsx
T
bobbanandClaude Sonnet 5.5 18ceed62e8 Racks, notes and to-do, OS support, suggested dependencies, Nginx Proxy Manager and Home Assistant
- Racks page and a network diagram (UniFi tree with servers, printable)
- Notes on servers and devices; To do list shown in Coming up and My work
- Agents report the operating system (Linux 7, Windows 6); end-of-life badge and alert
- Suggested dependencies from where a service is reached
- Nginx Proxy Manager integration: proxy hosts page, certificate and host alerts, suggested checks
- Home Assistant integration: watch chosen entities, history chart, limit and unavailable alerts
- TimeChart gets a "value" scale that fits negatives; docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:47:56 +02:00

401 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useMemo, useState } from "react";
import { api, type CurrentUser, type HaEntityChoice, type HaOverview, type HaWatchedEntity } from "../api/client";
import DetailDrawer from "../components/DetailDrawer";
import RangeSelect from "../components/RangeSelect";
import TimeAgo from "../components/TimeAgo";
import TimeChart from "../components/TimeChart";
import EmptyState from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { useChartRange } from "../utils/chartRanges";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
type Integration = HaOverview["integrations"][number];
const shownName = (w: HaWatchedEntity) => w.name ?? w.entity?.friendlyName ?? w.entityId;
const numberWords = (v: number, unit: string | null) => `${Math.round(v * 100) / 100}${unit ? ` ${unit}` : ""}`;
function StateCell({ w, problem }: { w: HaWatchedEntity; problem: boolean }) {
const e = w.entity;
if (!e) return <span className="text-secondary">not read yet</span>;
if (e.unavailableSince !== null || e.state === "missing") {
return (
<span className="badge bg-yellow-lt text-yellow" title={`Since ${e.unavailableSince ?? "?"}`}>
{e.state === "missing" ? "Not in Home Assistant" : e.state}
{e.unavailableSince ? <> · <TimeAgo value={e.unavailableSince} /></> : null}
</span>
);
}
return <strong className={problem ? "text-red" : ""}>{e.value !== null ? numberWords(e.value, e.unit) : e.state}</strong>;
}
function limitsWords(w: HaWatchedEntity): string {
const unit = w.entity?.unit ? ` ${w.entity.unit}` : "";
if (w.below !== null && w.above !== null) return `${w.below}–${w.above}${unit}`;
if (w.below !== null) return `not under ${w.below}${unit}`;
if (w.above !== null) return `not over ${w.above}${unit}`;
return "";
}
/** A watched number over time, from what this app has kept (up to 35 days). */
function HistoryDrawer({ integrationId, w, onClose }: { integrationId: number; w: HaWatchedEntity; onClose: () => void }) {
const [days, setDays] = useChartRange(7);
const shown = days > 30 ? 30 : days;
const [points, setPoints] = useState<{ t: string; v: number }[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [to, setTo] = useState(() => Date.now());
useEffect(() => {
let alive = true;
api.homeAssistant
.history(integrationId, w.entityId, shown)
.then((res) => {
if (!alive) return;
setPoints(res.points);
setTo(Date.now());
setError(null);
})
.catch((err) => alive && setError(readableError(err)));
return () => {
alive = false;
};
}, [integrationId, w.entityId, shown]);
const unit = w.entity?.unit ?? "";
const series = useMemo(() => [{ name: shownName(w), color: "#4299e1", points: points ?? [] }], [points, w]);
return (
<DetailDrawer title={shownName(w)} subtitle={w.entityId} onClose={onClose}>
<div className="mb-3">
<RangeSelect value={shown} onChange={setDays} only={[1, 7, 30]} />
</div>
<ErrorNotice error={error} />
{!points && !error && <BlockSkeleton lines={5} />}
{points && <TimeChart series={series} unit="value" from={to - shown * 86_400_000} to={to} label={`${shownName(w)} over time`} format={(v) => numberWords(v, unit)} empty="Nothing kept for this in this stretch yet — a reading is added every few minutes." />}
<div className="text-secondary small mt-2">Readings are kept for 35 days.</div>
</DetailDrawer>
);
}
/** Change what is said about an entity already watched: its name and its limits. */
function EditDrawer({ integrationId, w, onClose, onSaved }: { integrationId: number; w: HaWatchedEntity; onClose: () => void; onSaved: () => void }) {
const numeric = w.entity?.value !== null && w.entity?.value !== undefined;
const [name, setName] = useState(w.name ?? "");
const [below, setBelow] = useState(w.below === null ? "" : String(w.below));
const [above, setAbove] = useState(w.above === null ? "" : String(w.above));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function save() {
const parse = (s: string) => (s.trim() === "" ? null : Number(s));
const b = parse(below);
const a = parse(above);
if ((b !== null && !Number.isFinite(b)) || (a !== null && !Number.isFinite(a))) return setError("The limits have to be numbers.");
setBusy(true);
try {
await api.homeAssistant.watch(integrationId, { entityId: w.entityId, name: name.trim() || null, below: b, above: a });
onSaved();
onClose();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
return (
<DetailDrawer title={shownName(w)} subtitle={w.entityId} onClose={onClose}>
<ErrorNotice error={error} />
<div className="mb-3">
<label className="form-label" htmlFor="ha-name">
Name shown here
</label>
<input id="ha-name" className="form-control" value={name} maxLength={80} placeholder={w.entity?.friendlyName ?? w.entityId} onChange={(e) => setName(e.target.value)} />
</div>
{numeric ? (
<div className="row g-2 mb-3">
<div className="col-6">
<label className="form-label" htmlFor="ha-below">
Alert when under{w.entity?.unit ? ` (${w.entity.unit})` : ""}
</label>
<input id="ha-below" className="form-control" inputMode="decimal" value={below} onChange={(e) => setBelow(e.target.value)} placeholder="no limit" />
</div>
<div className="col-6">
<label className="form-label" htmlFor="ha-above">
Alert when over{w.entity?.unit ? ` (${w.entity.unit})` : ""}
</label>
<input id="ha-above" className="form-control" inputMode="decimal" value={above} onChange={(e) => setAbove(e.target.value)} placeholder="no limit" />
</div>
</div>
) : (
<div className="text-secondary mb-3">This one isn&rsquo;t a number, so there are no limits to set. It is an alert when it has been unavailable for 15 minutes.</div>
)}
<button className="btn btn-primary" onClick={() => void save()} disabled={busy}>
{busy ? "Saving…" : "Save"}
</button>
</DetailDrawer>
);
}
/** Pick entities to watch: search what Home Assistant has, read live. */
function PickDrawer({ integration, onClose, onChanged }: { integration: Integration; onClose: () => void; onChanged: () => void }) {
const [q, setQ] = useState("");
const [found, setFound] = useState<{ total: number; entities: HaEntityChoice[] } | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
useEffect(() => {
let alive = true;
const timer = setTimeout(() => {
api.homeAssistant
.entities(integration.id, q)
.then((res) => {
if (!alive) return;
setFound(res);
setError(null);
})
.catch((err) => alive && setError(readableError(err)));
}, 250);
return () => {
alive = false;
clearTimeout(timer);
};
}, [integration.id, q]);
async function watch(e: HaEntityChoice) {
setBusy(e.entityId);
try {
await api.homeAssistant.watch(integration.id, { entityId: e.entityId });
setFound((f) => (f ? { ...f, entities: f.entities.map((x) => (x.entityId === e.entityId ? { ...x, watched: true } : x)) } : f));
onChanged();
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(null);
}
}
return (
<DetailDrawer title="Watch something" subtitle={integration.name} onClose={onClose}>
<div className="text-secondary mb-2">Search by name or id, like &ldquo;battery&rdquo; or &ldquo;freezer&rdquo;. Limits are set afterwards, from the list.</div>
<input className="form-control mb-3" type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search Home Assistant…" aria-label="Search entities" autoFocus />
<ErrorNotice error={error} />
{!found && !error && <BlockSkeleton lines={4} />}
{found && (
<>
<div className="list-group list-group-flush">
{found.entities.map((e) => (
<div className="list-group-item d-flex align-items-center gap-2 px-0" key={e.entityId}>
<div className="flex-fill" style={{ minWidth: 0 }}>
<div className="text-truncate">{e.name}</div>
<div className="text-secondary small font-monospace text-truncate">
{e.entityId} · {e.state}
{e.unit ? ` ${e.unit}` : ""}
</div>
</div>
{e.watched ? (
<span className="badge bg-green-lt text-green">Watching</span>
) : (
<button className="btn btn-sm btn-outline-primary" disabled={busy === e.entityId} onClick={() => void watch(e)}>
Watch
</button>
)}
</div>
))}
</div>
{found.entities.length === 0 && <div className="text-secondary">Nothing matches.</div>}
<div className="text-secondary small mt-2">
{found.entities.length >= 60 ? "The first 60 of " : ""}
{found.total} in Home Assistant.
</div>
</>
)}
</DetailDrawer>
);
}
/**
* The few things worth watching in Home Assistant — a UPS battery, a freezer, a door sensor, a pump — chosen here, not all several hundred entities. Each is read every
* few minutes and kept with its history; it is an alert when it has said nothing for 15 minutes, or a number goes past a limit that was set. Nothing is ever written
* to Home Assistant.
*/
export default function HomeAssistant({ user }: { user: CurrentUser }) {
const canAct = user.role === "admin" || user.role === "operator";
const [data, setData] = useState<HaOverview | null>(null);
const [error, setError] = useState<string | null>(null);
const [reading, setReading] = useState(false);
const [picking, setPicking] = useState<Integration | null>(null);
const [editing, setEditing] = useState<{ id: number; w: HaWatchedEntity } | null>(null);
const [charting, setCharting] = useState<{ id: number; w: HaWatchedEntity } | null>(null);
const load = useCallback(
() =>
api.homeAssistant
.overview()
.then((res) => {
setData(res);
setError(null);
})
.catch((err) => setError(readableError(err))),
[],
);
useEffect(() => {
void load();
const timer = setInterval(() => void load(), 60_000);
return () => clearInterval(timer);
}, [load]);
async function readNow() {
setReading(true);
try {
const res = await api.homeAssistant.sync();
const failed = Object.values(res.statuses).filter((s) => !s.ok);
if (failed.length > 0) toast.error(`Couldn't read Home Assistant: ${failed[0].error ?? "no answer"}`);
else toast.success("Read from Home Assistant.");
await load();
} catch (err) {
toast.error(readableError(err));
} finally {
setReading(false);
}
}
async function stop(id: number, w: HaWatchedEntity) {
try {
await api.homeAssistant.unwatch(id, w.entityId);
toast.success(`No longer watching ${shownName(w)}.`);
await load();
} catch (err) {
toast.error(readableError(err));
}
}
const live = data?.integrations ?? [];
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">Home Assistant</h2>
{canAct && live.length > 0 && (
<div className="ms-auto btn-list">
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
{reading ? "Reading…" : "Read now"}
</button>
</div>
)}
</div>
<div className="text-secondary mb-3">
The few things worth an alert in Home Assistant — a UPS battery, a freezer, a pump — chosen here rather than every entity it has. Each is read every five minutes and its history is kept for 35 days. It only
reads; nothing is ever sent to Home Assistant.
</div>
<ErrorNotice error={error} />
{data === null && !error && <BlockSkeleton lines={4} />}
{data && live.length === 0 && (
<div className="card">
<EmptyState
title="No Home Assistant connected"
hint="Add a Home Assistant integration with a long-lived access token (made at the bottom of your profile page in Home Assistant), then choose what to watch."
action={user.role === "admin" ? { label: "Add Home Assistant", to: "/integrations" } : undefined}
/>
</div>
)}
{live.map((i) => (
<div className="card mb-3" key={i.id}>
<div className="card-header">
<div>
<h3 className="card-title">{i.name}</h3>
<div className={`small ${i.status && !i.status.ok ? "text-red" : "text-secondary"}`}>
{!i.enabled ? (
"Switched off"
) : !i.status ? (
"Not read yet"
) : i.status.ok ? (
<>
Read <TimeAgo value={i.status.at} /> · watching {i.status.entities}
</>
) : (
<>
Couldn&rsquo;t be read: {i.status.error}. Showing what was read <TimeAgo value={i.status.at} />; its alerts are held until it can be read again.
</>
)}
</div>
</div>
{canAct && i.enabled && (
<div className="card-actions">
<button className="btn btn-primary btn-sm" onClick={() => setPicking(i)}>
Watch something
</button>
</div>
)}
</div>
{i.watched.length === 0 ? (
<EmptyState title="Nothing is being watched yet" hint="Pick the entities that matter — a battery level, a temperature, a switch — and set the limits that should raise an alert." action={canAct && i.enabled ? { label: "Watch something", onClick: () => setPicking(i) } : undefined} />
) : (
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Name</th>
<th>Now</th>
<th>Alert when</th>
<th>Last changed</th>
<th className="w-1">
<span className="visually-hidden">Actions</span>
</th>
</tr>
</thead>
<tbody>
{i.watched.map((w) => {
const problem = i.problems.some((p) => p.key.endsWith(`:${w.entityId}`));
return (
<tr key={w.entityId}>
<td className="stack-wide">
<strong>{shownName(w)}</strong>
<div className="text-secondary small font-monospace">{w.entityId}</div>
</td>
<td className="stack-label" data-label="Now">
<StateCell w={w} problem={problem} />
</td>
<td className="stack-label" data-label="Alert when">
{limitsWords(w) || <span className="text-secondary">unavailable for 15 min</span>}
</td>
<td className="stack-label" data-label="Last changed">
{w.entity?.lastChanged ? <TimeAgo value={w.entity.lastChanged} /> : <span className="text-secondary">—</span>}
</td>
<td className="text-nowrap stack-wide">
<div className="btn-list flex-nowrap">
{w.entity?.value !== null && w.entity?.value !== undefined && (
<button className="btn btn-sm btn-outline-secondary" onClick={() => setCharting({ id: i.id, w })}>
History
</button>
)}
{canAct && (
<>
<button className="btn btn-sm btn-outline-secondary" onClick={() => setEditing({ id: i.id, w })}>
Limits
</button>
<button className="btn btn-sm btn-outline-danger" onClick={() => void stop(i.id, w)} aria-label={`Stop watching ${shownName(w)}`}>
Stop
</button>
</>
)}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
))}
{picking && <PickDrawer integration={picking} onClose={() => setPicking(null)} onChanged={() => void load()} />}
{editing && <EditDrawer integrationId={editing.id} w={editing.w} onClose={() => setEditing(null)} onSaved={() => void load()} />}
{charting && <HistoryDrawer integrationId={charting.id} w={charting.w} onClose={() => setCharting(null)} />}
</>
);
}