Files
punktfunk/web/src/sections/Host/view.tsx
T
enricobuehlerandClaude Opus 5 4a5d4b0a71 feat(web): the console follows the host's events instead of asking ten times a minute
The host has published every lifecycle transition on GET /api/v1/events since the
API existed — client connect/disconnect, session and stream start/end, pairing
decisions, display create/release, library, store and plugin changes — and
nothing consumed a byte of it. The console instead polled ten endpoints on 1-5 s
timers, so a change was up to 5 s stale and two pages could disagree while you
looked at them. The Library page polled not at all: install a game in Steam and
it never appeared until a full reload.

The console now subscribes once and invalidates exactly the queries an event
affects. Events never carry data into the cache — they only say "this is stale" —
so an unknown future kind costs nothing and a missed event degrades to the
polling that is still there underneath, now at a slow safety-net interval. The
fast ticks that remain are the ones events cannot express: the live stream
numbers while streaming, and a lingering display's teardown countdown.

Four things had to be true for this to work, and none of them were. Each was
found by measuring, not by reading:

- Nitro's `localFetch` accumulates the response and only builds it when the
  handler returns, so nothing streams through the deployed Bun server. Three
  frames sent a second apart arrived together, three seconds late, when the
  upstream closed — and an SSE stream never closes, so nothing would ever have
  arrived. /api/v1/events gets its own route that hands back a web Response
  wrapping the upstream stream, which passes straight through.
- Hydration mounts the app shell and discards it ~15 ms later. A subscription
  owned by that effect opened, closed, and never came back. It is a refcounted
  module singleton now, with a grace period so a remount re-attaches instead of
  reconnecting.
- `getRouter()` runs more than once in the browser, and each call built its own
  QueryClient. The subscription held the first, the live pages read the second,
  and every invalidation went to a cache nobody was reading. One client per
  browser session; the server still gets a fresh one per request, which it must.
- `invalidateQueries` only refetches queries that currently have an observer.
  An event means the HOST changed, so every cached copy is wrong whether or not
  something is watching it.

Two features fall out of the same work:

- **Automation** — a page for GET/PUT /api/v1/hooks. The host has run these
  hooks all along and the console never showed them, so the only way to see what
  your machine does when a stream starts was to open the config file. Writing one
  means writing a shell command the host will execute, so saving re-asks for the
  console password, like an update or an unreviewed install.
- The Host page warns when another Moonlight-compatible server (Sunshine,
  Apollo) is running on the same machine. The host has detected this at startup
  for ages and reported it in /local/summary; nothing surfaced it. It is the most
  common reason a host looks installed and working but no client can reach it.

Verified in a real browser against a mock host: three events drive three
refetches of a query with no polling timer, the conflicts card names the
intruder, the hook list and its dialog render, and the console reports no errors.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 00:20:10 +02:00

178 lines
5.7 KiB
TypeScript

import Section from "@unom/ui/section";
import type { FC, ReactNode } from "react";
import type { AvailableCompositor } from "@/api/gen/model/availableCompositor";
import type { HostInfo } from "@/api/gen/model/hostInfo";
import { OsIcon } from "@/components/os-icon";
import { QueryState } from "@/components/query-state";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { Loadable } from "@/lib/query";
import { m } from "@/paraglide/messages";
export const HostView: FC<{
host: Loadable<HostInfo>;
compositors: Loadable<AvailableCompositor[]>;
/** The GPU inventory/selection card (a self-contained container — see `GpuCard.tsx`). */
gpu?: ReactNode;
/** The update-check card (a self-contained container — see `UpdateCard.tsx`). */
update?: ReactNode;
/** Warning about other Moonlight-compatible servers on this machine — renders nothing when
* there are none (see `ConflictsCard.tsx`). Sits at the top: it explains "nothing can connect". */
conflicts?: ReactNode;
}> = ({ host, compositors, gpu, update, conflicts }) => {
const h = host.data;
return (
<Section maxWidth={false}>
<div className="flex flex-col gap-card">
<h1 className="text-2xl font-semibold">{m.nav_host()}</h1>
{conflicts}
<QueryState
isLoading={host.isLoading}
error={host.error}
refetch={host.refetch}
>
{h && (
<div className="grid gap-card lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>{m.host_identity()}</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-1 gap-3">
<Row label={m.host_hostname()} value={h.hostname} />
{/* The OS mark resolves from the identity chain (h.os), which also
serves as the tooltip for the curious; the text is the pretty name. */}
<Row
label={m.host_os()}
value={h.os_name}
title={h.os}
icon={<OsIcon os={h.os} className="size-4 shrink-0" />}
/>
<Row label={m.host_local_ip()} value={h.local_ip} mono />
<Row
label={m.host_version()}
value={`${h.app_version} (${h.version})`}
/>
<Row label={m.host_abi()} value={String(h.abi_version)} />
<Row label={m.host_uniqueid()} value={h.uniqueid} mono />
</dl>
</CardContent>
</Card>
<div className="space-y-card">
<Card>
<CardHeader>
<CardTitle>{m.host_codecs()}</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap gap-2">
{h.codecs.map((c) => (
<Badge key={c} variant="secondary">
{c.toUpperCase()}
</Badge>
))}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>{m.host_ports()}</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-sm tabular-nums">
{Object.entries(h.ports).map(([k, v]) => (
<div key={k} className="flex justify-between">
<dt className="text-muted-foreground uppercase">
{k}
</dt>
<dd className="font-medium">{v as number}</dd>
</div>
))}
</dl>
</CardContent>
</Card>
</div>
</div>
)}
</QueryState>
{update}
{gpu}
<Card>
<CardHeader>
<CardTitle>{m.host_compositors()}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">
{m.host_compositors_help()}
</p>
<QueryState
isLoading={compositors.isLoading}
error={compositors.error}
refetch={compositors.refetch}
>
{/* Empty is a real answer, not a load failure: a Windows host drives the
pf-vdisplay driver and has no compositor backends at all. */}
{compositors.data?.length === 0 ? (
<p className="rounded-md border p-4 text-sm text-muted-foreground">
{m.compositor_none()}
</p>
) : (
<ul className="divide-y rounded-md border">
{compositors.data?.map((c) => (
<li
key={c.id}
className="flex items-center justify-between gap-4 px-4 py-3"
>
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium">{c.label}</span>
{c.default && (
<Badge variant="secondary">
{m.compositor_default()}
</Badge>
)}
</div>
<code className="text-xs text-muted-foreground">
{c.id}
</code>
</div>
<Badge variant={c.available ? "default" : "outline"}>
{c.available
? m.compositor_available()
: m.compositor_unavailable()}
</Badge>
</li>
))}
</ul>
)}
</QueryState>
</CardContent>
</Card>
</div>
</Section>
);
};
const Row: FC<{
label: string;
value: string;
mono?: boolean;
/** Optional leading glyph inside the value cell (the OS mark). */
icon?: ReactNode;
/** Tooltip override — defaults to the value itself (which may be truncated). */
title?: string;
}> = ({ label, value, mono, icon, title }) => (
<div className="flex items-baseline justify-between gap-4">
<dt className="text-sm text-muted-foreground">{label}</dt>
<dd
className={`${mono ? "truncate font-mono text-xs" : "font-medium"}${icon ? " flex items-center gap-2" : ""}`}
title={title ?? value}
>
{icon}
{value}
</dd>
</div>
);