Panels become devices: per-device documents in the flow repo, a Devices tab

- flow/devices.py: DeviceDef in FLOWS_DIR/_devices/<id>.json, committed under
  the flow store's write lock, 409 on a stale version; nonces in DEVICES_FILE
  outside git; in-memory presence announced as device_status
- api/routes/devices.py: CRUD, pairing with an optional {name, board,
  firmware}, a pending list adopted without a code from the LAN only, unpair;
  /panels/pair, /panels/pair/{code} and GET /panels/{id} kept as aliases,
  PUT /panels/ gone
- _device_may replaces _panel_may, JWT claims unchanged
- panels.json moves into devices once at startup, then .migrated
- MCP list_devices, get_device; search category device
- Devices tab (list, detail with presence, pairing, ordered dashboards,
  touch, I/O), PanelsDialog removed, serialised optimistic saves
This commit is contained in:
Melvin Strobl
2026-10-16 15:48:36 +02:00
parent 3c0912a3fe
commit 28a565e501
56 changed files with 3539 additions and 2404 deletions
@@ -0,0 +1,747 @@
import { useQuery } from "@tanstack/react-query"
import { Link } from "@tanstack/react-router"
import { ArrowDown, ArrowUp, Plus, X } from "lucide-react"
import { useState } from "react"
import {
type ApiError,
CloudService,
type DeviceDef,
type DevicePort,
type DevicePublic,
DevicesService,
} from "@/client"
import { initials, resolveIcon } from "@/components/Dashboard/icons"
import { MessagePicker } from "@/components/Dashboard/panels"
import { dashboardsQueryOptions } from "@/components/Dashboard/queries"
import { qualifiedProblem } from "@/components/Flow/deriveEdges"
import { JsonField } from "@/components/Flow/JsonField"
import { InfoTip, PanelSection } from "@/components/Flow/SidePanel"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Segmented } from "@/components/ui/segmented"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Switch } from "@/components/ui/switch"
import useAuth from "@/hooks/useAuth"
import useCustomToast from "@/hooks/useCustomToast"
import { ago, cn } from "@/lib/utils"
import { handleError } from "@/utils"
import {
devicesQueryOptions,
pendingQueryOptions,
usePairDevice,
useSaveDevice,
useUnpairDevice,
} from "./queries"
const CARD = "rounded-lg border border-border bg-card p-4 shadow-e1"
/** As many characters as a device puts on the wall. */
const CODE_LENGTH = 6
/** Port names the panel firmware knows; `gpio.` takes a pin number. */
// ponytail: free-text ports until a device reports what it has (PUT /devices/{id}/report)
const PORT_SUGGESTIONS = ["gpio.", "backlight", "touch", "mic", "speaker"]
const DIRECTIONS = [
["in", "In"],
["out", "Out"],
] as const
/** What the server accepts as a port name. */
const portOf = (value: string) =>
value.toLowerCase().replace(/[^a-z0-9_.]/g, "")
/** A new port the server will take: a name, and a message named with its flow. */
const ready = (port: DevicePort) =>
Boolean(port.port) && qualifiedProblem(port.message) === null
const objectOnly = (value: unknown) =>
value && typeof value === "object" && !Array.isArray(value)
? null
: "Config is a JSON object"
/** "Online", or when it was last heard from. */
export function presenceText(device: DevicePublic) {
if (device.online) return "Online"
return device.last_seen ? `Seen ${ago(device.last_seen)}` : "Not seen yet"
}
/**
* One device: whether it is there, how it pairs, what it shows and its own
* hardware.
*
* Every change saves as it is made, against the version it was read at, so
* there is no form to submit and no draft to publish: a device is a thing on
* the wall rather than a document.
*/
export function DeviceDetail({ id }: { id: string }) {
const { data, isPending } = useQuery(devicesQueryOptions())
const { user } = useAuth()
const save = useSaveDevice(id)
const { showErrorToast } = useCustomToast()
// Reading devices is any account's, every change to them a superuser's.
const canEdit = Boolean(user?.is_superuser)
if (isPending) return <Skeleton className="h-96 w-full rounded-lg" />
const device = data?.data?.find((one) => one.id === id)
if (!device) {
return (
<div className="grid gap-2">
<Link
to="/devices"
className="text-muted-foreground text-sm hover:underline"
>
Devices
</Link>
<p className="text-sm text-muted-foreground">No device named {id}.</p>
</div>
)
}
const write = (changes: Partial<DeviceDef>) =>
save.mutate(changes, {
onError: (error) =>
(error as ApiError).status === 409
? showErrorToast(
"Someone else changed this device first. Their version is shown now, so make the change again.",
)
: handleError.call(showErrorToast, error as ApiError),
})
return (
<div className="flex min-w-0 flex-col gap-4">
<header className="flex flex-wrap items-center gap-3">
<Link
to="/devices"
className="text-muted-foreground text-sm hover:underline"
>
Devices
</Link>
<h1 className="min-w-0 truncate text-2xl">
{device.title || device.id}
</h1>
<Badge
variant="outline"
data-testid="device-presence"
className={cn(
device.online &&
"border-transparent bg-status-success/15 text-status-success",
)}
>
{presenceText(device)}
</Badge>
</header>
<div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0">
<div className="grid content-start gap-4 [&>*]:min-w-0">
<section className={cn(CARD, "grid gap-4")}>
<Basics device={device} canEdit={canEdit} onChange={write} />
</section>
<section className={CARD}>
<Dashboards device={device} canEdit={canEdit} onChange={write} />
</section>
</div>
<div className="grid content-start gap-4 [&>*]:min-w-0">
<section className={CARD}>
<Pairing
id={device.id}
host={data?.frontend_host ?? ""}
canEdit={canEdit}
/>
</section>
<section className={CARD}>
<DeviceIo device={device} canEdit={canEdit} onChange={write} />
</section>
</div>
</div>
</div>
)
}
function Basics({
device,
canEdit,
onChange,
}: {
device: DeviceDef
canEdit: boolean
onChange: (changes: Partial<DeviceDef>) => void
}) {
return (
<PanelSection title="Device">
<div className="flex items-center gap-2">
<Input
// Saved on blur or Enter, not per keystroke. Remounted with whatever
// was saved, so a refused title snaps back.
key={device.title}
defaultValue={device.title}
placeholder={device.id}
aria-label={`Title of ${device.id}`}
disabled={!canEdit}
data-testid="device-title"
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur()
}}
onBlur={(event) => {
const title = event.currentTarget.value.trim()
event.currentTarget.value = title
if (title !== device.title) onChange({ title })
}}
/>
<span className="shrink-0 font-mono text-sm text-muted-foreground">
{device.id}
</span>
</div>
<label
htmlFor={`touch-${device.id}`}
className="flex items-center gap-2 text-sm"
>
<span className="flex-1">Touch friendly</span>
<InfoTip label="Touch friendly">
Bigger controls and a bigger rail, and nothing that only happens on
hover. Set on the device because the same dashboard may also hang
somewhere with a mouse.
</InfoTip>
<Switch
id={`touch-${device.id}`}
checked={device.touch === true}
disabled={!canEdit}
data-testid="device-touch"
onCheckedChange={(touch) => onChange({ touch })}
/>
</label>
</PanelSection>
)
}
/** Which dashboards the device shows, in the order its rail carries them. */
function Dashboards({
device,
canEdit,
onChange,
}: {
device: DeviceDef
canEdit: boolean
onChange: (changes: Partial<DeviceDef>) => void
}) {
const { data } = useQuery(dashboardsQueryOptions())
const known = data?.data ?? []
const assigned = device.dashboards ?? []
const byName = new Map(known.map((dashboard) => [dashboard.name, dashboard]))
const free = known.filter((dashboard) => !assigned.includes(dashboard.name))
const set = (dashboards: string[]) => onChange({ dashboards })
const move = (from: number, by: number) => {
const next = [...assigned]
const [name] = next.splice(from, 1)
next.splice(from + by, 0, name)
set(next)
}
return (
<PanelSection
title="Dashboards"
help="The first one is what the device opens with, and its rail follows this order."
>
{assigned.length === 0 ? (
<p className="text-sm text-muted-foreground">
No dashboards yet. The device shows nothing until it has one.
</p>
) : (
<ol className="grid gap-1" data-testid="device-dashboards">
{assigned.map((name, index) => {
const dashboard = byName.get(name)
const title = dashboard?.title || name
// What this dashboard draws on the rail.
const Glyph = resolveIcon(dashboard?.icon ?? "")
return (
<li key={name} className="flex items-center gap-2 text-sm">
<span className="w-4 shrink-0 text-xs text-muted-foreground">
{index + 1}
</span>
<span
aria-hidden
className="flex size-5 shrink-0 items-center justify-center text-xs font-medium text-muted-foreground"
>
{Glyph ? <Glyph className="size-4" /> : initials(title)}
</span>
{dashboard ? (
<Link
to="/dashboards/$name"
params={{ name }}
className="min-w-0 flex-1 truncate hover:underline"
>
{title}
</Link>
) : (
// Deleted since: the device skips it.
<span className="min-w-0 flex-1 truncate text-muted-foreground line-through">
{name}
</span>
)}
{canEdit ? (
<span className="flex shrink-0 items-center">
<Button
variant="ghost"
size="icon-touch"
className="text-muted-foreground"
aria-label={`Move ${title} up`}
disabled={index === 0}
onClick={() => move(index, -1)}
>
<ArrowUp />
</Button>
<Button
variant="ghost"
size="icon-touch"
className="text-muted-foreground"
aria-label={`Move ${title} down`}
disabled={index === assigned.length - 1}
onClick={() => move(index, 1)}
>
<ArrowDown />
</Button>
<Button
variant="ghost"
size="icon-touch"
className="text-muted-foreground"
aria-label={`Remove ${title}`}
onClick={() => set(assigned.filter((n) => n !== name))}
>
<X />
</Button>
</span>
) : null}
</li>
)
})}
</ol>
)}
{canEdit && free.length > 0 ? (
<Select value="" onValueChange={(name) => set([...assigned, name])}>
<SelectTrigger
className="justify-self-start"
aria-label="Add a dashboard"
data-testid="add-dashboard"
>
<SelectValue placeholder="Add a dashboard" />
</SelectTrigger>
<SelectContent>
{free.map((dashboard) => (
<SelectItem key={dashboard.name} value={dashboard.name}>
{dashboard.title || dashboard.name}
</SelectItem>
))}
</SelectContent>
</Select>
) : null}
</PanelSection>
)
}
/**
* How a screen gets its credential: by the code it shows, or picked from the
* devices asking on this network. Plus the addresses to point one at, and the
* way to sign the current one out.
*/
function Pairing({
id,
host,
canEdit,
}: {
id: string
/** Where this instance answers, as it knows itself. */
host: string
canEdit: boolean
}) {
const { showSuccessToast, showErrorToast } = useCustomToast()
const [code, setCode] = useState("")
// Unpairing cannot be undone from here, since the screen has to be at hand
// to read out a new code, so the button asks a second time before it fires.
const [confirmUnpair, setConfirmUnpair] = useState(false)
const pair = usePairDevice(id)
const unpair = useUnpairDevice(id)
const typed = code.trim().toUpperCase()
// Where a screen that cannot reach this instance pairs instead. The issuer
// is the portal as a browser reaches it.
const { data: cloud } = useQuery({
queryKey: ["cloud", "status"],
queryFn: async () =>
(await CloudService.readStatus()) as {
enrolled: boolean
issuer: string | null
instance_id: string | null
},
})
const remoteLink =
cloud?.enrolled && cloud.issuer && cloud.instance_id
? `${cloud.issuer.replace(/\/$/, "")}/i/${cloud.instance_id}/panel`
: ""
// The instance's own address, not this browser's: administering through
// the portal puts the page on the portal's origin, which a screen on this
// network cannot be sent to.
const link = host ? `${host}/panel/${id}` : ""
const { data: pending } = useQuery({
...pendingQueryOptions(),
enabled: canEdit,
})
// Approving a code adopts whatever holds it, so say what that is while
// there is still time to stop.
const { data: waiting } = useQuery({
queryKey: ["pending-device", typed],
queryFn: () => DevicesService.pendingDevice({ code: typed }),
enabled: canEdit && typed.length === CODE_LENGTH,
retry: false,
})
const paired = {
onSuccess: () => {
setCode("")
showSuccessToast("Paired. The screen switches over within a few seconds.")
},
onError: (error: Error) =>
handleError.call(showErrorToast, error as ApiError),
}
return (
<PanelSection
title="Pairing"
help="Open the link on the device. It shows a code, which you enter here, or it appears below when it is on this network."
>
<div className="grid gap-2">
<Input
readOnly
value={link}
placeholder="This instance has no address set"
aria-label={`Link for ${id}`}
className="text-muted-foreground"
data-testid="device-link"
onFocus={(event) => event.currentTarget.select()}
/>
{remoteLink ? (
<Input
readOnly
value={remoteLink}
aria-label={`Portal link for ${id}`}
className="text-muted-foreground"
data-testid="device-remote-link"
onFocus={(event) => event.currentTarget.select()}
/>
) : null}
</div>
{canEdit ? (
<>
<form
className="flex gap-2"
onSubmit={(event) => {
event.preventDefault()
if (typed) pair.mutate({ code: typed }, paired)
}}
>
<Input
value={code}
placeholder="Code shown on the screen"
aria-label={`Pairing code for ${id}`}
autoComplete="off"
maxLength={CODE_LENGTH}
data-testid="pair-code"
onChange={(event) => setCode(event.target.value.toUpperCase())}
/>
<Button
type="submit"
variant="outline"
disabled={!typed || pair.isPending}
data-testid="pair-device"
>
Pair
</Button>
</form>
{typed.length === CODE_LENGTH ? (
<p
className="text-xs text-muted-foreground"
data-testid="pending-code"
>
{waiting
? `${waiting.name || waiting.device}${waiting.remote ? " · via portal" : ""}`
: "No device is waiting on that code."}
</p>
) : null}
<div className="grid gap-1" data-testid="pending-devices">
<span className="text-xs text-muted-foreground">
{pending?.length
? "Waiting to be paired"
: "No device is waiting"}
</span>
{(pending ?? []).map((entry) => (
<div
key={entry.request}
className="flex items-center gap-2 rounded-sm text-sm"
>
<span className="grid min-w-0 flex-1">
<span className="truncate">
{entry.name || entry.board || "Unnamed device"}
{entry.firmware ? (
<span className="text-muted-foreground">
{" "}
· {entry.firmware}
</span>
) : null}
</span>
<span className="truncate text-xs text-muted-foreground">
{entry.device}
</span>
</span>
{entry.needs_code ? (
<span className="shrink-0 text-xs text-muted-foreground">
{entry.remote ? "Via portal, " : ""}needs its code
</span>
) : (
<Button
variant="outline"
size="sm-touch"
className="shrink-0"
disabled={pair.isPending}
data-testid="adopt-device"
onClick={() =>
pair.mutate({ request: entry.request }, paired)
}
>
Pair this one
</Button>
)}
</div>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
variant={confirmUnpair ? "destructive" : "outline"}
disabled={unpair.isPending}
data-testid="unpair-device"
onBlur={() => setConfirmUnpair(false)}
onClick={() => {
if (!confirmUnpair) {
setConfirmUnpair(true)
return
}
setConfirmUnpair(false)
unpair.mutate(undefined, {
onSuccess: () =>
showSuccessToast(
"Unpaired. The screen asks for a new code.",
),
onError: (error) =>
handleError.call(showErrorToast, error as ApiError),
})
}}
>
{confirmUnpair
? "Confirm: sign this screen out"
: "Unpair screen"}
</Button>
<InfoTip label="Unpair screen">
Sends the screen back to a pairing code and keeps the device and
its dashboards. A screen paired through the portal is revoked
there instead.
</InfoTip>
</div>
</>
) : null}
</PanelSection>
)
}
/**
* The device's own inputs and outputs, each wired to a message.
*
* A new port is held here until it has a name and a qualified message, since
* the server refuses a port without either.
*/
function DeviceIo({
device,
canEdit,
onChange,
}: {
device: DeviceDef
canEdit: boolean
onChange: (changes: Partial<DeviceDef>) => void
}) {
const [draft, setDraft] = useState<DevicePort | null>(null)
const io = device.io ?? []
const listId = `ports-${device.id}`
const write = (io: DevicePort[]) => onChange({ io })
const keepDraft = (next: DevicePort) => {
if (!ready(next)) return setDraft(next)
setDraft(null)
write([...io, next])
}
return (
<PanelSection
title="I/O"
help="Hardware on the device itself, such as a GPIO pin or its microphone. In publishes to the message, Out follows it, and Config goes to the device as it is."
>
<datalist id={listId}>
{PORT_SUGGESTIONS.map((port) => (
<option key={port} value={port} />
))}
</datalist>
{/* `disabled` on a fieldset reaches every control inside it. */}
<fieldset disabled={!canEdit} className="grid min-w-0 gap-4">
{io.length === 0 && !draft ? (
<p className="text-sm text-muted-foreground">No ports yet.</p>
) : null}
{io.map((row, index) => (
<IoRow
// Ports have no id, and two may share a name until one is renamed.
key={index}
row={row}
listId={listId}
testId={`io-${device.id}-${index}`}
onChange={(next) =>
write(io.map((one, at) => (at === index ? next : one)))
}
onRemove={() => write(io.filter((_, at) => at !== index))}
/>
))}
{draft ? (
<IoRow
row={draft}
listId={listId}
testId={`io-${device.id}-new`}
onChange={keepDraft}
onType={(port) => setDraft({ ...draft, port })}
onRemove={() => setDraft(null)}
/>
) : null}
{canEdit && !draft ? (
<Button
variant="outline"
size="sm-touch"
className="justify-self-start"
data-testid={`add-port-${device.id}`}
onClick={() => setDraft({ port: "", message: "", direction: "in" })}
>
<Plus />
Add port
</Button>
) : null}
</fieldset>
</PanelSection>
)
}
function IoRow({
row,
listId,
testId,
onChange,
onType,
onRemove,
}: {
row: DevicePort
/** The datalist of port names to suggest. */
listId: string
testId: string
onChange: (next: DevicePort) => void
/** A new port's name as it is typed. A saved port commits on blur instead. */
onType?: (port: string) => void
onRemove: () => void
}) {
const name = row.port || "new port"
const problem = row.message ? qualifiedProblem(row.message) : null
return (
<div className="grid gap-2" data-testid={testId}>
<div className="flex items-center gap-2">
{onType ? (
<Input
value={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onChange={(event) => onType(portOf(event.currentTarget.value))}
onBlur={() => onChange(row)}
/>
) : (
<Input
// Remounted with whatever was saved, so a refused name snaps back.
key={row.port}
defaultValue={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onBlur={(event) => {
const port = portOf(event.currentTarget.value)
event.currentTarget.value = port || row.port
if (port && port !== row.port) onChange({ ...row, port })
}}
/>
)}
<div className="shrink-0">
<Segmented
value={row.direction}
options={DIRECTIONS}
label={`Direction of ${name}`}
onChange={(direction) =>
onChange({
...row,
direction: direction as DevicePort["direction"],
})
}
/>
</div>
<Button
variant="ghost"
size="icon-touch"
className="shrink-0 text-muted-foreground"
aria-label={`Remove ${name}`}
title={`Remove ${name}`}
onClick={onRemove}
>
<X />
</Button>
</div>
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<MessagePicker
value={row.message}
label={`Message of ${name}`}
hideLabel
// A port the device publishes from needs a message a flow takes in.
filter={
row.direction === "in"
? (message) => message.writable !== false
: undefined
}
onPick={(message) => onChange({ ...row, message })}
/>
</div>
<JsonField
value={row.config ?? {}}
label={`Config of ${name}`}
check={objectOnly}
className="h-9 w-28 shrink-0"
onChange={(config) =>
onChange({ ...row, config: config as DevicePort["config"] })
}
/>
</div>
{problem ? <p className="text-xs text-destructive">{problem}</p> : null}
</div>
)
}