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>
This commit is contained in:
2026-08-01 00:20:10 +02:00
co-authored by Claude Opus 5
parent 55e01c1460
commit 4a5d4b0a71
18 changed files with 1090 additions and 8 deletions
+88
View File
@@ -0,0 +1,88 @@
// GET /api/v1/events — the host's SSE lifecycle stream, proxied with the body left STREAMING.
//
// Why this route exists at all, when the `/api/**` catch-all already proxies everything:
// the generic path cannot stream. h3's `proxyRequest` pumps the upstream body into the node-style
// response with `res.write`, and under the deployed Bun entry that response is a `node-mock-http`
// object whose writes are accumulated and only turned into a real Response when the handler
// returns. Measured: three frames sent one second apart arrive at the browser together, ~3 s late,
// when the upstream closes. For an SSE stream that is fatal — it never closes, so nothing ever
// arrives, and every event-driven update in the console would silently never fire.
//
// Returning a WEB `Response` whose body is the upstream's own `ReadableStream` sidesteps the
// node-response emulation entirely: h3 hands it back as-is and the Bun entry passes it through.
//
// Everything else matches the catch-all: session-gated by middleware/auth.ts, mgmt bearer injected
// server-side, TLS relaxed only for the loopback hop, 401 → 502.
import {
createError,
defineEventHandler,
getRequestHeader,
getRequestURL,
} from "h3";
import { isLoopbackUrl, mgmtToken, mgmtUrl } from "../../../util/auth";
export default defineEventHandler(async (event) => {
const token = mgmtToken();
if (!token) {
throw createError({
statusCode: 503,
statusMessage: "management token not configured",
});
}
const base = mgmtUrl();
const { search } = getRequestURL(event);
const headers: Record<string, string> = {
authorization: `Bearer ${token}`,
accept: "text/event-stream",
// Ask for no compression: a buffering encoder defeats the point of a live stream.
"accept-encoding": "identity",
};
// Forward the SSE resume cursor so a reconnect replays from the host's ring rather than
// silently skipping whatever happened while we were away.
const lastId = getRequestHeader(event, "last-event-id");
if (lastId) headers["last-event-id"] = lastId;
const init: RequestInit = { method: "GET", headers, redirect: "manual" };
if (isLoopbackUrl(base)) {
// Bun.fetch extension — scoped per request, never process-wide (see routes/api/[...].ts).
(init as unknown as { tls: { rejectUnauthorized: boolean } }).tls = {
rejectUnauthorized: false,
};
}
let upstream: Response;
try {
upstream = await fetch(`${base}/api/v1/events${search}`, init);
} catch (cause) {
throw createError({
statusCode: 502,
statusMessage: "management API unreachable",
cause,
});
}
if (upstream.status === 401) {
throw createError({
statusCode: 502,
statusMessage:
"management API rejected the host token (check PUNKTFUNK_MGMT_TOKEN)",
});
}
if (!upstream.ok || !upstream.body) {
throw createError({
statusCode: 502,
statusMessage: `management API refused the event stream (${upstream.status})`,
});
}
// The upstream body, untouched. `no-transform` + `X-Accel-Buffering: no` tell any intermediary
// (and Nitro's own compression) to keep their hands off a live stream.
return new Response(upstream.body, {
status: 200,
headers: {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-cache, no-transform",
connection: "keep-alive",
"x-accel-buffering": "no",
},
});
});
+24
View File
@@ -0,0 +1,24 @@
// PUT /api/v1/hooks — writing a hook means writing a SHELL COMMAND the host will execute on its own
// events, as the host user. That is code execution by any other name, so it joins update/apply and
// raw-spec installs behind the console password (util/confirm.ts): a 7-day session cookie must not
// be enough to leave a persistent command behind on the machine.
//
// Wins over the `/api/**` catch-all by h3 route specificity. GET is not gated — reading the current
// automation is ordinary console business.
import { defineEventHandler, readBody } from "h3";
import { confirmPassword } from "../../../util/confirm";
import { forwardJson } from "../../../util/forward";
interface HooksBody {
hooks?: unknown[];
password?: string;
}
export default defineEventHandler(async (event) => {
const body = await readBody<HooksBody>(event);
confirmPassword(event, body?.password);
// Rebuild from the one field the host takes, so the password cannot leak upstream.
return forwardJson(event, "/api/v1/hooks", "PUT", {
hooks: Array.isArray(body?.hooks) ? body.hooks : [],
});
});