diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 4e0db7e6b..34130b31d 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -8,10 +8,8 @@ internet. The console is for people who operate Simlock. It needs an operator token. Coding agents keep using the CLI, the MCP server, the client and the HTTP API. -This version has sign-in, the console's navigation (Workers, Leases, Waiting, -Attention and Events), the Workers and Leases pages, the Waiting page and -the Attention page. The other pages say "Coming soon" until their views are -built. +This version has sign-in and a page for each entry in the console's +navigation: Workers, Leases, Waiting, Attention and Events. ## Turn it on @@ -222,6 +220,37 @@ device is the exception on a gateway: a device becomes stalled when its time runs out, not by anything happening, so the gateway sees it the next time it reads that worker, which it does at least every 30 seconds. +## Events + +**Events** lists recent events, newest first: the same events as +`simlock events --since 1h`. New events appear at the top as they happen. + +Each event shows: + +- its time, on your computer's clock face +- its name, such as `lease.granted` +- on a gateway, the worker it came from, by its label, or by its id if the + worker has no label or the gateway no longer knows it. A `worker.rejected` + event names no worker here: its id is only what the refused worker claimed, + and it shows in the payload. +- its payload, as each key and its value, exactly as the daemon sent it + +An event this version of the console does not know still shows, with its +whole payload. + +**Show** picks which events to list: all of them, or only those about leases, +devices, workers or components. **Other** lists the rest, such as +`daemon.started`. + +The page keeps the newest 1000 events. Older ones drop off the end. + +When the console loses the daemon, or the tab was hidden, it loads the events +it missed as soon as it is back, so the list has no gap. An event the console +already shows is never shown twice, also after the daemon restarts. + +The console shows what the daemon sends. The daemon keeps secrets, such as a +worker's join token, out of its events. + ## Live updates Every page keeps itself current. A change on the daemon, such as a lease diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 058d3cb34..093c04817 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -67,7 +67,11 @@ modes](#gateway-and-worker-modes-adr-0005) below for that topology. marks a route as one the screen reads, and `LiveConnection` refetches every such route on each event from `GET /v1/events/stream` and every second, one request per route at a time; it also owns the disconnect, backoff and - recovery rules and the clock offset behind `useNow()`. See + recovery rules and the clock offset behind `useNow()`. The one exception + is the events view, whose list is not a route's latest answer: its feed + (`ui/src/views/event-feed.ts`) takes each event off the stream through the + live layer and loads `GET /v1/events` itself, for the last hour and for + each gap the stream left. See [CONSOLE.md](../CONSOLE.md) for the user's side and [DESIGN.md](DESIGN.md) for the style. - **CLI**: by default it acquires a lease, prints one JSON result line on diff --git a/e2e/console/events.spec.ts b/e2e/console/events.spec.ts new file mode 100644 index 000000000..da9b3b27c --- /dev/null +++ b/e2e/console/events.spec.ts @@ -0,0 +1,260 @@ +import type { Locator, Page } from "@playwright/test"; + +import { + disposeFleet, + expect, + type RunningDaemon, + signIn, + startDaemon, + startFleet, + test, +} from "./fixtures.js"; + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; + +/** One line of `simlock events`, as far as these tests read it. */ +interface Envelope { + readonly seq: number; + readonly timestamp: number; + readonly event: string; + readonly payload: Record; +} + +/** Takes a lease with the CLI, detached, and returns its id. */ +async function lease(daemon: RunningDaemon, agent: string): Promise { + const granted = await daemon.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + "--agent-id", + agent, + ]); + expect(granted.code, granted.stderr).toBe(0); + const id = (granted.json as { lease?: { id?: unknown } }).lease?.id; + expect(typeof id).toBe("string"); + return id as string; +} + +/** What `simlock events --since 1h` prints. */ +async function cliEvents(daemon: RunningDaemon): Promise { + const result = await daemon.cli(["events", "--since", "1h"]); + expect(result.code, result.stderr).toBe(0); + return result.stdout + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as Envelope); +} + +async function openEvents(page: Page, daemon: RunningDaemon): Promise { + await page.goto(new URL("/events", daemon.url).href); + await signIn(page, daemon.tokens.operator); + await expect(page.getByRole("heading", { level: 1, name: "Events" })).toBeVisible(); +} + +/** Every event the view shows. */ +function rows(page: Page): Locator { + return page.locator("#main li.event"); +} + +/** The events the view shows with this name and this payload value somewhere in it. */ +function row(page: Page, name: string, value: string): Locator { + return rows(page) + .filter({ has: page.locator(".event-name", { hasText: new RegExp(`^${name}$`) }) }) + .filter({ has: page.locator("dd", { hasText: new RegExp(`^${value}$`) }) }); +} + +/** Each event the view shows, as its time, name and payload, in the order shown. */ +async function shownEvents(page: Page): Promise { + return rows(page).evaluateAll((items) => + items.map((item) => + [ + item.querySelector("time")?.getAttribute("datetime") ?? "", + item.querySelector(".event-name")?.textContent ?? "", + ...[...item.querySelectorAll(".event-payload > div")].map( + (pair) => + `${pair.querySelector("dt")?.textContent ?? ""}=${pair.querySelector("dd")?.textContent ?? ""}`, + ), + ].join(" "), + ), + ); +} + +/** An event from the CLI, written as {@link shownEvents} reads the view: strings as themselves. */ +function asShown(event: Envelope): string { + return [ + new Date(event.timestamp).toISOString(), + event.event, + ...Object.entries(event.payload).map( + ([key, value]) => `${key}=${typeof value === "string" ? value : JSON.stringify(value)}`, + ), + ].join(" "); +} + +/** Whether the page itself scrolls sideways. */ +async function hasHorizontalScroll(page: Page): Promise { + return page.evaluate( + () => document.documentElement.scrollWidth > document.documentElement.clientWidth, + ); +} + +test.describe("the events view", () => { + test("a lease taken with the CLI appears in the events view within a second", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await openEvents(page, host); + await expect(rows(page).first()).toBeVisible(); + + const id = await lease(host, "console-e2e-events"); + + await expect(row(page, "lease.granted", id)).toHaveCount(1, { timeout: 1_000 }); + } finally { + await host.dispose(); + } + }); + + test("the events view matches simlock events --since 1h, and a restart leaves no gap and no duplicate", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await lease(host, "console-e2e-before"); + await openEvents(page, host); + const before = (await cliEvents(host)).map(asShown); + await expect.poll(() => shownEvents(page)).toEqual(before.toReversed()); + + await host.stop(); + await expect(page.locator(".connection")).toHaveText(/^Reconnecting/); + await host.start(); + await expect(page.locator(".connection")).toHaveText("Connected", { timeout: 30_000 }); + await lease(host, "console-e2e-after"); + + // Every event once, newest first, the ones sent while the console was away included. + const after = await cliEvents(host); + expect(after.length).toBeGreaterThan(before.length); + await expect.poll(() => shownEvents(page)).toEqual(after.map(asShown).toReversed()); + } finally { + await host.dispose(); + } + }); + + test("on a gateway, a worker's event shows that worker's label", async ({ page }) => { + const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); + try { + const worker = fleet.workers[0] as RunningDaemon; + await openEvents(page, fleet.gateway); + + const id = await lease(worker, "console-e2e-label"); + + const granted = row(page, "lease.granted", id); + await expect(granted).toHaveCount(1); + // The payload names the worker by id only; the label comes from the worker list. + await expect(granted.locator("dt", { hasText: /^workerId$/ })).toHaveCount(1); + await expect(granted.locator(".event-worker")).toHaveText("worker-a"); + } finally { + await disposeFleet(fleet); + } + }); + + test("a worker joining a gateway shows no join token anywhere in the events view", async ({ + page, + }) => { + const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); + try { + const worker = fleet.workers[0] as RunningDaemon; + const joinToken = fleet.gateway.tokens.worker; + for (const daemon of [fleet.gateway, worker]) { + const name = daemon === worker ? "the worker" : "the gateway"; + await openEvents(page, daemon); + // The events that would carry the join token if anything did: the worker's own start, + // with its config, and the gateway's word that the worker joined. + const wanted = daemon === worker ? "daemon.started" : "worker.connected"; + await expect( + rows(page).filter({ has: page.locator(".event-name", { hasText: wanted }) }), + name, + ).not.toHaveCount(0); + const started = await cliEvents(daemon); + await expect.poll(async () => (await shownEvents(page)).length, name).toBe(started.length); + + expect(await page.content(), name).not.toContain(joinToken); + expect(await page.locator("body").innerText(), name).not.toContain(joinToken); + + await page.getByRole("button", { name: "Sign out" }).click(); + } + } finally { + await disposeFleet(fleet); + } + }); + + test("the Events view has no horizontal scroll at 360px wide", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await lease(host, "console-e2e-narrow"); + await page.setViewportSize({ height: 740, width: 360 }); + await openEvents(page, host); + // `daemon.started` carries the whole config: the longest payload there is. + await expect( + rows(page).filter({ has: page.locator(".event-name", { hasText: "daemon.started" }) }), + ).not.toHaveCount(0); + await expect(rows(page).filter({ hasText: "lease.granted" })).not.toHaveCount(0); + + expect(await hasHorizontalScroll(page)).toBe(false); + } finally { + await host.dispose(); + } + }); + + test("the Events view is usable with the keyboard alone", async ({ browserName, page }) => { + // Safari moves focus to links with Option-Tab; plain Tab reaches only form controls there. + const tab = browserName === "webkit" ? "Alt+Tab" : "Tab"; + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await lease(host, "console-e2e-keyboard"); + await keyboardOnly(page, host, tab); + } finally { + await host.dispose(); + } + }); +}); + +/** Signs in, opens the Events view and filters it, with the keyboard alone. */ +async function keyboardOnly(page: Page, host: RunningDaemon, tab: string): Promise { + await page.goto(host.url); + await page.keyboard.press(tab); + await page.keyboard.type(host.tokens.operator); + await page.keyboard.press("Enter"); + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); + + const nav = page.getByRole("link", { name: "Events", exact: true }); + for (let step = 0; step < 20 && !(await isFocused(nav)); step += 1) { + await page.keyboard.press(tab); + } + await expect(nav).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.getByRole("heading", { level: 1, name: "Events" })).toBeVisible(); + await expect(rows(page).filter({ hasText: "daemon.started" })).not.toHaveCount(0); + + // Into the filter: Tab reaches the checked choice, and the arrow keys move along them. + const all = page.getByRole("radio", { name: "All" }); + for (let step = 0; step < 20 && !(await isFocused(all)); step += 1) { + await page.keyboard.press(tab); + } + await expect(all).toBeFocused(); + await expect(all).toBeChecked(); + await page.keyboard.press("ArrowRight"); + await expect(page.getByRole("radio", { name: "Leases" })).toBeChecked(); + + const names = await rows(page).locator(".event-name").allTextContents(); + expect(names.length).toBeGreaterThan(0); + expect(names.every((name) => name.startsWith("lease."))).toBe(true); +} + +async function isFocused(locator: Locator): Promise { + return locator.evaluate((element) => element === document.activeElement); +} diff --git a/ui/src/live/connection.test.ts b/ui/src/live/connection.test.ts index 7eddbd111..b0fe9cdb7 100644 --- a/ui/src/live/connection.test.ts +++ b/ui/src/live/connection.test.ts @@ -517,3 +517,22 @@ describe("LiveConnection", () => { expect(connection.serverNow() - Date.now()).toBe(-30_000); }); }); + +describe("StreamOpened", () => { + it("a stream that died without closing counts as closed from the last thing it sent", async () => { + const { connection, daemon } = connect(); + await settle(); + await vi.advanceTimersByTimeAsync(10_000); + // The daemon's keepalive, then nothing: the stream is dead and the console does not know yet. + daemon.openStream()?.send(": keepalive\n\n"); + await settle(); + const opened: (number | undefined)[] = []; + connection.onStreamOpened((event) => opened.push(event.closedForMs)); + + // 40 seconds of silence mark the console disconnected; /v1/healthz answers 1 second later. + await vi.advanceTimersByTimeAsync(41_000); + + expect(connection.state().phase).toBe("connected"); + expect(opened).toEqual([41_000]); + }); +}); diff --git a/ui/src/live/connection.ts b/ui/src/live/connection.ts index df2350eb2..68a825fd7 100644 --- a/ui/src/live/connection.ts +++ b/ui/src/live/connection.ts @@ -79,8 +79,14 @@ export interface StreamEvent { readonly data: unknown; } -/** The stream opened. `closedForMs` is how long it was closed, absent the first time it opens. */ +/** The stream opened. */ export interface StreamOpened { + /** + * How long the console has not heard from a stream: since the last message or keepalive the + * previous stream sent, or since it opened if it sent none. A stream that died without closing + * counts from its last sign of life, not from when the console noticed. Absent the first time + * a stream opens. + */ readonly closedForMs?: number; } @@ -97,6 +103,15 @@ export interface LiveConnectionOptions { readonly visibility: Visibility; } +/** + * Whether a failed request means the daemon answered and refused it: an error status, or a body + * that is not what was asked for. Anything else means the request did not reach the daemon or + * did not come back. + */ +export function isRefusal(error: unknown): boolean { + return error instanceof ApiError || error instanceof SyntaxError; +} + export class LiveConnection { readonly #api: LiveApi; readonly #clock: Clock; @@ -118,7 +133,9 @@ export class LiveConnection { /** The current stream's controller; aborting it closes the stream. */ #stream: AbortController | undefined; #streamIsOpen = false; - /** When an open stream last closed; `undefined` until one has been open. */ + /** When the open stream last sent anything, or opened. */ + #streamHeardAt: number | undefined; + /** When the closed stream last sent anything; `undefined` until one has been open. */ #streamClosedAt: number | undefined; constructor(options: LiveConnectionOptions) { @@ -272,7 +289,7 @@ export class LiveConnection { * reached it or never came back. */ #classify(error: unknown): "refused" | "retry" | "lost" { - if (error instanceof ApiError || error instanceof SyntaxError) return "refused"; + if (isRefusal(error)) return "refused"; if (error instanceof RequestTimeoutError && this.#state.phase === "starting") return "retry"; return "lost"; } @@ -336,7 +353,7 @@ export class LiveConnection { if (stream === undefined) return; this.#stream = undefined; stream.abort(); - if (this.#streamIsOpen) this.#streamClosedAt = this.#clock.now(); + if (this.#streamIsOpen) this.#streamClosedAt = this.#streamHeardAt; this.#streamIsOpen = false; } @@ -394,6 +411,7 @@ export class LiveConnection { const { done, value } = await reader.read(); if (this.#stream !== controller) return false; if (done) return true; + this.#streamHeardAt = this.#clock.now(); this.#watchSilence(controller); for (const message of parser.push(value)) this.#deliver(message); } @@ -404,6 +422,7 @@ export class LiveConnection { #streamOpened(): void { this.#streamIsOpen = true; + this.#streamHeardAt = this.#clock.now(); const closedAt = this.#streamClosedAt; this.#streamClosedAt = undefined; const opened: StreamOpened = diff --git a/ui/src/live/live-context.tsx b/ui/src/live/live-context.tsx index 199b3114a..a166e85da 100644 --- a/ui/src/live/live-context.tsx +++ b/ui/src/live/live-context.tsx @@ -93,7 +93,6 @@ export function useNow(): Now { } /** Calls `listener` for every event the stream delivers while the calling view is on screen. */ -// fallow-ignore-next-line unused-export -- the events view (#276) reads the stream through this. export function useLiveEvents(listener: (event: StreamEvent) => void): void { const { connection } = useLive(); useEffect(() => connection.onEvent(listener), [connection, listener]); @@ -103,7 +102,6 @@ export function useLiveEvents(listener: (event: StreamEvent) => void): void { * Calls `listener` each time the stream opens, with how long it was closed, so a view can load * what it missed (ADR 0013 §2, §5). */ -// fallow-ignore-next-line unused-export -- the events view (#276) fills its list through this. export function useStreamOpened(listener: (opened: StreamOpened) => void): void { const { connection } = useLive(); useEffect(() => connection.onStreamOpened(listener), [connection, listener]); diff --git a/ui/src/styles.css b/ui/src/styles.css index 99ccbad3a..bac3aa9e7 100644 --- a/ui/src/styles.css +++ b/ui/src/styles.css @@ -505,6 +505,93 @@ input[aria-invalid="true"] { margin: 0; } +/* Events: a filter by subject, then one block per event, newest first. */ + +.filter { + display: flex; + flex-wrap: wrap; + gap: var(--space-1) var(--space-4); + margin: var(--space-4) 0; + padding: 0; + border: 0; + font-size: var(--text-sm); +} + +.filter legend { + margin-bottom: var(--space-1); + padding: 0; + color: var(--text-muted); + font-weight: 500; +} + +.filter label { + display: inline-flex; + align-items: center; + gap: var(--space-2); + min-height: 32px; + cursor: pointer; +} + +.filter input { + width: auto; + min-height: 0; + margin: 0; + padding: 0; + accent-color: var(--accent); +} + +.events { + margin: 0; + padding: 0; + list-style: none; +} + +.event { + min-width: 0; + padding: var(--space-3) 0; + border-bottom: 1px solid var(--border); +} + +.event-head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: var(--space-1) var(--space-3); + margin: 0; + font-size: var(--text-sm); +} + +.event-head time, +.event-worker { + color: var(--text-muted); +} + +.event-name { + font-weight: 500; +} + +.event-payload { + display: grid; + gap: var(--space-1); + margin: var(--space-2) 0 0; + font-size: var(--text-sm); +} + +.event-payload > div { + display: grid; + grid-template-columns: minmax(0, 9rem) minmax(0, 1fr); + gap: var(--space-3); +} + +.event-payload dt { + color: var(--text-muted); +} + +.event-payload dd { + margin: 0; + min-width: 0; +} + /* Tables: a row per item. Under 768px each row stacks into labelled lines, so the page never * scrolls sideways. */ diff --git a/ui/src/views/coming-soon.tsx b/ui/src/views/coming-soon.tsx deleted file mode 100644 index b6c508e52..000000000 --- a/ui/src/views/coming-soon.tsx +++ /dev/null @@ -1,9 +0,0 @@ -/** A view whose data has not been built yet. */ -export function ComingSoon({ title }: { readonly title: string }) { - return ( -
-

{title}

-

Coming soon.

-
- ); -} diff --git a/ui/src/views/event-feed.ts b/ui/src/views/event-feed.ts new file mode 100644 index 000000000..a8ca4e864 --- /dev/null +++ b/ui/src/views/event-feed.ts @@ -0,0 +1,173 @@ +/** + * The events view's list, filled as ADR 0013 §2 and §5 say: the stream's events as they come, + * and `GET /v1/events` for what came before, each event once. Plain TypeScript, so the fill is + * tested against the real live connection on a scripted daemon; `events.tsx` wires it to the + * stream with `useLiveEvents` and `useStreamOpened`. + * + * The feed keeps track of what may be missing, and loads until nothing is: + * + * - The last hour, as `simlock events --since 1h` shows, until a load of it answers. The view + * opening asks for it, and so does the stream's first open: a view opened before the stream + * loads once more after it, so nothing sent between the two is lost. + * - A gap: each time the stream opens again, after a lost daemon or a hidden tab, everything + * since the console last heard from the stream. It is asked for as `since` that long, in whole + * seconds, rounded up. Gaps not yet loaded add up: the load covers from the earliest. + * + * A load clears what was missing only if the stream did not open again while it was out: what + * the stream missed meanwhile may be newer than the load's answer, so the feed loads again. + * + * One load at a time. A load that does not reach the daemon is sent again after 1, 2, 4 and 8 + * seconds, then every 10, and shows nothing of its own: the connection banner says when the + * daemon is lost. A load the daemon refuses shows why, above the events already shown, and is + * asked for again when the stream next opens. + */ +import type { ApiPath } from "../api"; +import { + type Clock, + isRefusal, + type ResourceState, + type StreamEvent, + type StreamOpened, +} from "../live/connection"; +import { + type ConsoleEvent, + mergeEvents, + readEvent, + readReplay, + RECENT, + sinceFor, +} from "./events-model"; + +const RETRY_BACKOFF_MS = [1_000, 2_000, 4_000, 8_000] as const; +const RETRY_INTERVAL_MS = 10_000; + +export class EventFeed { + readonly #get: (path: ApiPath) => Promise; + readonly #clock: Clock; + readonly #listeners = new Set<() => void>(); + #events: readonly ConsoleEvent[] = []; + #state: ResourceState = {}; + /** Whether a load has answered or been refused; until then the view says it is loading. */ + #settled = false; + /** Whether the last hour still has to be loaded. */ + #needRecent = true; + /** The browser time from which events may be missing; `undefined` when none are. */ + #gapFrom: number | undefined; + #loading = false; + /** Counts the stream's opens, so a load knows whether one happened while it was out. */ + #opens = 0; + #retryTimer: unknown; + #retryAttempt = 0; + #active = false; + + /** `get` reads a route and resolves its JSON body. */ + constructor(get: (path: ApiPath) => Promise, clock: Clock) { + this.#get = get; + this.#clock = clock; + } + + /** The view opened: load the recent events. Returns the function that stops the feed. */ + start(): () => void { + this.#active = true; + this.#loadMissing(); + return () => { + this.#active = false; + }; + } + + /** An event off the stream. Not an event envelope: ignored. */ + readonly streamEvent = (message: StreamEvent): void => { + if (!this.#active) return; + const event = readEvent(message.data); + if (event !== undefined) this.#add([event]); + }; + + /** The stream opened: load what it may have missed. */ + readonly streamOpened = (opened: StreamOpened): void => { + const gap = opened.closedForMs; + if (gap === undefined) this.#needRecent = true; + else { + const from = this.#clock.now() - gap; + this.#gapFrom = Math.min(this.#gapFrom ?? from, from); + } + this.#opens += 1; + this.#retryAttempt = 0; + this.#loadMissing(); + }; + + /** + * The events, newest first, once a load has settled. `error` is why the latest load was + * refused, cleared by the next that answers. The same object until it changes. + */ + readonly snapshot = (): ResourceState => this.#state; + + readonly subscribe = (listener: () => void): (() => void) => { + this.#listeners.add(listener); + return () => { + this.#listeners.delete(listener); + }; + }; + + /** The `since` that covers everything missing now, or `undefined` when nothing is. */ + #since(): string | undefined { + if (this.#needRecent) return RECENT; + return this.#gapFrom === undefined ? undefined : sinceFor(this.#clock.now() - this.#gapFrom); + } + + #loadMissing(): void { + const since = this.#since(); + if (!this.#active || this.#loading || since === undefined) return; + this.#clock.clearTimeout(this.#retryTimer); + this.#retryTimer = undefined; + this.#loading = true; + const opens = this.#opens; + this.#get(`/v1/events?since=${since}`) + .then(readReplay) + .then( + (events) => { + this.#loading = false; + if (!this.#active) return; + if (opens === this.#opens) { + this.#needRecent = false; + this.#gapFrom = undefined; + } + this.#retryAttempt = 0; + this.#settled = true; + this.#events = mergeEvents(this.#events, events); + this.#publish({ data: this.#events }); + this.#loadMissing(); + }, + (error: unknown) => { + this.#loading = false; + if (!this.#active) return; + if (!isRefusal(error)) { + this.#retryLater(); + return; + } + this.#settled = true; + this.#publish({ data: this.#events, error }); + }, + ); + } + + #retryLater(): void { + const delay = RETRY_BACKOFF_MS[this.#retryAttempt] ?? RETRY_INTERVAL_MS; + this.#retryAttempt += 1; + this.#retryTimer = this.#clock.setTimeout(() => { + this.#retryTimer = undefined; + this.#loadMissing(); + }, delay); + } + + #add(incoming: readonly ConsoleEvent[]): void { + const merged = mergeEvents(this.#events, incoming); + if (merged === this.#events) return; + this.#events = merged; + if (this.#settled) this.#publish({ ...this.#state, data: merged }); + } + + #publish(state: ResourceState): void { + this.#state = state; + for (const listener of this.#listeners) listener(); + } +} diff --git a/ui/src/views/events-model.ts b/ui/src/views/events-model.ts new file mode 100644 index 000000000..a1db922c8 --- /dev/null +++ b/ui/src/views/events-model.ts @@ -0,0 +1,144 @@ +/** + * The facts the events view shows, from `GET /v1/events` and the event stream (ADR 0013 §1, + * §2). Pure, so the view stays rendering and these stay tested. Wire input is a claim: an + * envelope is read field by field, and an event name or payload this console has never heard + * of is shown as it came. + */ + +/** One business event, as the daemon sent it. */ +export interface ConsoleEvent { + readonly seq: number; + readonly timestamp: number; + readonly event: string; + /** The payload as sent: any JSON value, or `undefined` when the envelope had none. */ + readonly payload: unknown; +} + +/** How many events the view keeps. Older ones drop off the end. */ +export const MAX_EVENTS = 1000; + +/** + * The window the view loads when it opens, the same as `simlock events --since 1h`, so the two + * show the same events. + */ +export const RECENT = "1h"; + +/** + * An envelope off the wire, or `undefined` when it is not one: without a numeric `seq`, a + * `timestamp` that is a date, and a string `event`, it cannot be placed in time or told apart + * from another. + */ +export function readEvent(data: unknown): ConsoleEvent | undefined { + if (typeof data !== "object" || data === null) return undefined; + const { event, payload, seq, timestamp } = data as Record; + if (typeof seq !== "number" || typeof timestamp !== "number" || typeof event !== "string") { + return undefined; + } + if (Number.isNaN(new Date(timestamp).getTime())) return undefined; + return { event, payload, seq, timestamp }; +} + +/** + * The events in a `GET /v1/events` answer. Throws when the answer has no `events` list, so the + * view says it could not read it rather than showing nothing. + */ +export function readReplay(body: unknown): readonly ConsoleEvent[] { + const events = (body as { readonly events?: unknown } | null)?.events; + if (!Array.isArray(events)) throw new SyntaxError("The answer has no events list"); + return events.flatMap((data: unknown) => readEvent(data) ?? []); +} + +/** + * What makes two events the same: `seq` and `timestamp` both. `seq` alone starts again when the + * daemon restarts (ADR 0013 §2). + */ +function keyOf(event: ConsoleEvent): string { + return `${event.seq}:${event.timestamp}`; +} + +/** Newest first: by time, and by `seq` within the same millisecond. */ +function newestFirst(a: ConsoleEvent, b: ConsoleEvent): number { + return b.timestamp - a.timestamp || b.seq - a.seq; +} + +/** + * `current` with `incoming` added: each event once, newest first, and only the newest + * {@link MAX_EVENTS}. Returns `current` itself when nothing new came. + */ +export function mergeEvents( + current: readonly ConsoleEvent[], + incoming: readonly ConsoleEvent[], +): readonly ConsoleEvent[] { + const seen = new Set(current.map(keyOf)); + const added: ConsoleEvent[] = []; + for (const event of incoming) { + const key = keyOf(event); + if (seen.has(key)) continue; + seen.add(key); + added.push(event); + } + if (added.length === 0) return current; + return [...current, ...added].sort(newestFirst).slice(0, MAX_EVENTS); +} + +/** + * The `since` that covers a gap of `ms` milliseconds, in whole seconds, rounded up, so the gap's + * first event is inside it (ADR 0013 §5). + */ +export function sinceFor(ms: number): string { + return `${Math.ceil(ms / 1_000)}s`; +} + +/** The subjects the filter offers. `other` is every subject not named here. */ +const SUBJECTS = ["lease", "device", "worker", "component"] as const; + +export type Subject = (typeof SUBJECTS)[number] | "other"; + +/** The subject of an event: the part of its name before the first dot (`lease.granted`). */ +export function subjectOf(name: string): Subject { + const subject = name.split(".", 1)[0]; + return SUBJECTS.find((known) => known === subject) ?? "other"; +} + +/** + * The worker an event is about, from the `workerId` a gateway adds to each worker's event, or + * the one a gateway's own `worker.*` events carry. `undefined` on a single host, and for + * `worker.rejected`: its `workerId` is what a refused dial claimed, so it names no worker, and + * shows only in the payload. + */ +export function workerIdOf(event: ConsoleEvent): string | undefined { + const { payload } = event; + if (event.event === "worker.rejected" || typeof payload !== "object" || payload === null) { + return undefined; + } + const workerId = (payload as Record).workerId; + return typeof workerId === "string" ? workerId : undefined; +} + +/** + * The payload as key and value pairs, in the order the daemon sent them. A string shows as + * itself; any other value as its JSON. A payload that is not an object shows as one pair, + * `payload`, so an unknown shape is still shown whole. + */ +export function payloadPairs( + payload: unknown, +): readonly { readonly key: string; readonly value: string }[] { + if (payload === undefined) return []; + if (typeof payload !== "object" || payload === null || Array.isArray(payload)) { + return [{ key: "payload", value: valueText(payload) }]; + } + return Object.entries(payload).map(([key, value]) => ({ key, value: valueText(value) })); +} + +function valueText(value: unknown): string { + if (typeof value === "string") return value; + return JSON.stringify(value) ?? String(value); +} + +/** An event's time of day, `HH:MM:SS` on the browser's clock face. */ +export function timeOfDay(timestamp: number): string { + const date = new Date(timestamp); + return [date.getHours(), date.getMinutes(), date.getSeconds()] + .map((part) => String(part).padStart(2, "0")) + .join(":"); +} diff --git a/ui/src/views/events.test.tsx b/ui/src/views/events.test.tsx new file mode 100644 index 000000000..f42487fd1 --- /dev/null +++ b/ui/src/views/events.test.tsx @@ -0,0 +1,635 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { ApiError, type ApiPath, type ApiResponse } from "../api"; +import type { Clock } from "../live/connection"; +import { Loaded } from "../live/route-state"; +import { connect, settle } from "../live/test-support"; +import { EventFeed } from "./event-feed"; +import { EventList } from "./events"; +import { type ConsoleEvent, MAX_EVENTS } from "./events-model"; +import type { WorkerView } from "./workers-model"; + +const T0 = Date.parse("2026-10-02T11:30:00Z"); + +/** Vitest's fake time and timers, as the live connection's tests use them. */ +const fakeClock: Clock = { + now: () => Date.now(), + setTimeout: (run, ms) => setTimeout(run, ms), + clearTimeout: (handle) => clearTimeout(handle as ReturnType), +}; + +function envelope(seq: number, timestamp: number, event = "lease.granted", payload: unknown = {}) { + return { event, module: "lease", payload, seq, timestamp }; +} + +/** One event as the stream frames it. */ +function frame(event: ReturnType): string { + return `event: ${event.event}\ndata: ${JSON.stringify(event)}\n\n`; +} + +/** The text a screen shows, without markup. */ +function text(html: string): string { + return html + .replace(/<[^>]+>/g, " ") + .replace(/"/g, '"') + .replace(/\s+/g, " ") + .trim(); +} + +/** What `GET /v1/events` answers: these events, or whatever this returns. */ +type Replay = unknown[] | ((path: ApiPath) => Promise); + +/** + * A daemon's event file: answers `GET /v1/events?since=s|1h` with the events newer than that, + * by the fake clock, as the daemon does. + */ +function eventLog( + events: readonly ReturnType[], +): (path: ApiPath) => Promise { + return (path) => { + const match = /since=(\d+)(s|h)$/.exec(path); + if (match === null) throw new Error(`Unexpected path ${path}`); + const ms = Number(match[1]) * (match[2] === "h" ? 3_600_000 : 1_000); + return Promise.resolve({ events: events.filter((event) => event.timestamp > Date.now() - ms) }); + }; +} + +/** + * The events view's feed on a live connection to a scripted daemon. `replay` is what + * `GET /v1/events` answers, whatever its `since`; every other read answers `{}`. + */ +function openView(first: Replay = []) { + const live = connect(); + const replays: ApiPath[] = []; + let replay: Replay = first; + live.daemon.reads = async (path) => { + if (!path.startsWith("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/v1/events?")) return { body: {}, date: null }; + replays.push(path); + const body = typeof replay === "function" ? await replay(path) : { events: replay }; + return { body, date: null } satisfies ApiResponse; + }; + const feed = new EventFeed(async (path) => (await live.daemon.get(path)).body, fakeClock); + live.connection.onEvent(feed.streamEvent); + live.connection.onStreamOpened(feed.streamOpened); + const stop = feed.start(); + return { + ...live, + feed, + replays, + stop, + /** Sets what `GET /v1/events` answers from now on. */ + replayWith(next: Replay) { + replay = next; + }, + /** The events the view shows, as `seq@timestamp`, newest first. */ + shown(): string[] { + return (feed.snapshot().data ?? []).map((event) => `${event.seq}@${event.timestamp}`); + }, + }; +} + +/** What the view's page shows for the feed now, as `EventsView` renders it, as markup. */ +function screen(feed: EventFeed): string { + return renderToStaticMarkup( + + {(events) => } + , + ); +} + +/** A worker the daemon lists, with a label or without one. */ +function worker(id: string, label?: string): WorkerView { + return { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id, + lastSeenAt: T0, + leases: [], + ...(label === undefined ? {} : { label }), + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("the events view", () => { + it("the events view lists events from the stream and from the replay once each", async () => { + const view = openView(); + view.replayWith([envelope(1, T0), envelope(2, T0 + 1_000)]); + await settle(); + + view.daemon.openStream()?.send(frame(envelope(3, T0 + 2_000))); + view.daemon.openStream()?.send(frame(envelope(4, T0 + 3_000))); + await settle(); + + expect(view.shown()).toEqual([ + `4@${T0 + 3_000}`, + `3@${T0 + 2_000}`, + `2@${T0 + 1_000}`, + `1@${T0}`, + ]); + }); + + it("an event in both the replay and the stream is shown once", async () => { + const view = openView(); + const both = envelope(7, T0); + // The stream sends it before the replay answers, and the replay holds it too. + view.daemon.openStream()?.send(frame(both)); + view.replayWith([envelope(6, T0 - 1_000), both]); + await settle(); + expect(view.shown()).toEqual([`7@${T0}`, `6@${T0 - 1_000}`]); + + // And the other way round: replayed first, then streamed. + view.daemon.openStream()?.send(frame(both)); + await settle(); + + expect(view.shown()).toEqual([`7@${T0}`, `6@${T0 - 1_000}`]); + }); + + it("events with the same seq from before and after a daemon restart are both shown", async () => { + const view = openView(); + await settle(); + const before = envelope(1, T0, "daemon.started"); + view.daemon.openStream()?.send(frame(before)); + await settle(); + + // The daemon stops, and starts again with its seq counting from 1. + view.daemon.openStream()?.end(); + await settle(); + const after = envelope(1, T0 + 5_000, "daemon.started"); + view.replayWith([before, after]); + await vi.advanceTimersByTimeAsync(1_000); + view.daemon.openStream()?.send(frame(after)); + await settle(); + + expect(view.shown()).toEqual([`1@${T0 + 5_000}`, `1@${T0}`]); + }); + + it("after a reconnect the gap is filled from GET /v1/events with since rounded up to whole seconds", async () => { + const view = openView(); + await settle(); + expect(view.replays).toEqual(["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/v1/events?since=1h", "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/v1/events?since=1h"]); + + // The daemon goes away. `/v1/healthz` answers after 1 s; the new stream's headers take 0.3 s + // more, so the stream was closed for 1.3 s. + view.daemon.holdStreams = true; + view.daemon.openStream()?.end(); + await settle(); + const missed = envelope(1, Date.now() + 500, "daemon.started"); + view.replayWith([missed]); + await vi.advanceTimersByTimeAsync(1_300); + expect(view.replays).toHaveLength(2); + view.daemon.openHeldStreams(); + await settle(); + + expect(view.replays.slice(2)).toEqual(["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/v1/events?since=2s"]); + expect(view.shown()).toEqual([`1@${missed.timestamp}`]); + }); + + it("after a hidden tab is shown again the gap is filled the same way", async () => { + const view = openView(); + await settle(); + + view.visibility.set(true); + await vi.advanceTimersByTimeAsync(4_001); + const missed = envelope(5, Date.now() - 2_000); + view.replayWith([missed]); + view.visibility.set(false); + await settle(); + + expect(view.replays.slice(2)).toEqual(["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/v1/events?since=5s"]); + expect(view.shown()).toEqual([`5@${missed.timestamp}`]); + }); + + it("a view opened before the stream loads the recent events again once the stream opens", async () => { + const view = openView(); + // The first load answers before the stream's headers arrive. + expect(view.replays).toEqual(["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/v1/events?since=1h"]); + const sentBetween = envelope(9, T0); + view.replayWith([sentBetween]); + await settle(); + + expect(view.replays).toEqual(["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/v1/events?since=1h", "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/v1/events?since=1h"]); + expect(view.shown()).toEqual([`9@${T0}`]); + }); + + it("a stream that first opens after the last hour loaded loads it again", async () => { + const view = openView([]); + await settle(); + const sent = view.replays.length; + view.replayWith([envelope(1, T0)]); + + // The stream's headers took longer than the load: its first open comes after. + view.feed.streamOpened({}); + await settle(); + + expect(view.replays.slice(sent)).toEqual(["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/v1/events?since=1h"]); + expect(view.shown()).toEqual([`1@${T0}`]); + }); + + it("the view keeps the newest 1000 events", async () => { + const view = openView(); + view.replayWith( + Array.from({ length: MAX_EVENTS }, (_, index) => envelope(index + 1, T0 + index * 1_000)), + ); + await settle(); + expect(view.shown()).toHaveLength(MAX_EVENTS); + + view.daemon.openStream()?.send(frame(envelope(MAX_EVENTS + 1, T0 + MAX_EVENTS * 1_000))); + // An event older than every one kept arrives late: it does not push a newer one out. + view.daemon.openStream()?.send(frame(envelope(0, T0 - 1_000))); + await settle(); + + const shown = view.shown(); + expect(shown).toHaveLength(MAX_EVENTS); + expect(shown[0]).toBe(`${MAX_EVENTS + 1}@${T0 + MAX_EVENTS * 1_000}`); + // The oldest one dropped off the end. + expect(shown.at(-1)).toBe(`2@${T0 + 1_000}`); + }); + + it("an unknown event name renders with its payload", () => { + const events: ConsoleEvent[] = [ + { + event: "gizmo.frobnicated", + payload: { count: 3, nested: { deep: true }, reason: "because", workerId: "wrk_1" }, + seq: 3, + timestamp: T0, + }, + // A payload that is not an object at all. + { event: "gizmo.listed", payload: ["a", 1], seq: 2, timestamp: T0 - 1_000 }, + // No payload at all. + { event: "gizmo.pinged", payload: undefined, seq: 1, timestamp: T0 - 2_000 }, + ]; + + const html = renderToStaticMarkup( + , + ); + const shown = text(html); + + expect(shown).toContain( + 'gizmo.frobnicated mac-1 count 3 nested {"deep":true} reason because workerId wrk_1', + ); + expect(shown).toContain('gizmo.listed payload ["a",1]'); + expect(shown).toMatch(/gizmo\.pinged$/); + expect(html.match(/
{ + const zone = process.env.TZ; + // Five and a half hours ahead of UTC, so neither the hour nor the minute matches UTC's. + process.env.TZ = "Asia/Kolkata"; + try { + const event: ConsoleEvent = { event: "lease.granted", payload: {}, seq: 1, timestamp: T0 }; + + const html = renderToStaticMarkup(); + + expect(html).toContain( + '', + ); + } finally { + if (zone === undefined) delete process.env.TZ; + else process.env.TZ = zone; + } + }); + + it("an empty list says why it is empty", () => { + const leases: ConsoleEvent[] = [{ event: "lease.granted", payload: {}, seq: 1, timestamp: T0 }]; + const render = (events: ConsoleEvent[], filter: "all" | "device") => + text(renderToStaticMarkup()); + + expect(render([], "all")).toBe("No events in the last hour."); + expect(render([], "device")).toBe("No events in the last hour."); + expect(render(leases, "device")).toBe("No events of this kind."); + }); + + it("the filter shows only the events about the subject it names", () => { + const events: ConsoleEvent[] = [ + "lease.granted", + "device.ready", + "worker.connected", + "component.installed", + "daemon.started", + "gizmo.frobnicated", + ].map((event, index) => ({ event, payload: {}, seq: index, timestamp: T0 - index })); + const names = (filter: "all" | "lease" | "device" | "worker" | "component" | "other") => + [ + ...renderToStaticMarkup( + , + ).matchAll(/([^<]*)<\/span>/g), + ].map((match) => match[1]); + + expect(names("all")).toHaveLength(6); + expect(names("lease")).toEqual(["lease.granted"]); + expect(names("device")).toEqual(["device.ready"]); + expect(names("worker")).toEqual(["worker.connected"]); + expect(names("component")).toEqual(["component.installed"]); + expect(names("other")).toEqual(["daemon.started", "gizmo.frobnicated"]); + }); + + it("a worker the console does not know, or that has no label, shows as its id", () => { + const about = (workerId: string, seq: number): ConsoleEvent => ({ + event: "lease.granted", + payload: { workerId }, + seq, + timestamp: T0 - seq, + }); + const events = [about("wrk_1", 1), about("wrk_2", 2), about("wrk_gone", 3)]; + const workers = [worker("wrk_1", "mac-1"), worker("wrk_2")]; + const names = (listed: readonly WorkerView[] | undefined) => + [ + ...renderToStaticMarkup().matchAll( + /([^<]*)<\/span>/g, + ), + ].map((match) => match[1]); + + // Newest first: wrk_1, then wrk_2, then wrk_gone. + expect(names(workers)).toEqual(["mac-1", "wrk_2", "wrk_gone"]); + // Before the worker list is read, every worker shows as its id. + expect(names(undefined)).toEqual(["wrk_1", "wrk_2", "wrk_gone"]); + }); + it("a worker.rejected event names no worker, even one the console knows", () => { + const rejected: ConsoleEvent = { + event: "worker.rejected", + payload: { reason: "unauthenticated", workerId: "wrk_1" }, + seq: 1, + timestamp: T0, + }; + + const html = renderToStaticMarkup( + , + ); + + expect(html).not.toContain("event-worker"); + expect(text(html)).not.toContain("mac-1"); + // The claim is still shown, as the payload the daemon sent. + expect(text(html)).toContain("workerId wrk_1"); + }); + + it("an envelope without a numeric seq, a timestamp that is a date, or a name is not shown", async () => { + const view = openView(); + view.replayWith([ + { event: "lease.granted", timestamp: T0 }, + { event: "lease.granted", seq: 1 }, + { seq: 2, timestamp: T0 }, + { event: "lease.granted", seq: 3, timestamp: 1e300 }, + // A date, but as a string: not a timestamp. + { event: "lease.granted", seq: 5, timestamp: "2026-10-02T11:30:00Z" }, + { event: "lease.granted", seq: "6", timestamp: T0 }, + envelope(4, T0), + ]); + await settle(); + + expect(view.shown()).toEqual([`4@${T0}`]); + }); + + it("until the first load answers, the view says it is loading", async () => { + let answer: (body: unknown) => void = () => {}; + const view = openView( + () => + new Promise((resolve) => { + answer = resolve; + }), + ); + // The stream opens and sends an event; both loads of the last hour are still out. + await settle(); + view.daemon.openStream()?.send(frame(envelope(2, T0))); + await settle(); + expect(text(screen(view.feed))).toBe("Loading…"); + + answer({ events: [envelope(1, T0 - 1_000)] }); + await settle(); + + expect(view.shown()).toEqual([`2@${T0}`, `1@${T0 - 1_000}`]); + }); + + it("a load the daemon refuses shows why, and keeps the events already shown", async () => { + const view = openView(); + view.replayWith([envelope(1, T0)]); + await settle(); + expect(view.feed.snapshot().error).toBeUndefined(); + + // The stream is closed and opens again; the daemon refuses the load that fills the gap. + const refusal = new ApiError(500, "INTERNAL", "Internal error"); + view.replayWith(() => Promise.reject(refusal)); + view.visibility.set(true); + view.visibility.set(false); + await settle(); + + expect(view.feed.snapshot().error).toBe(refusal); + expect(view.shown()).toEqual([`1@${T0}`]); + const shown = screen(view.feed); + expect(shown).toContain( + '
    ', + ); + expect(text(shown)).toMatch(/^Internal error \d\d:\d\d:\d\d lease\.granted$/); + + // The next load that answers clears it. + view.replayWith([envelope(2, T0 + 1_000)]); + view.visibility.set(true); + view.visibility.set(false); + await settle(); + + expect(view.feed.snapshot().error).toBeUndefined(); + expect(view.shown()).toEqual([`2@${T0 + 1_000}`, `1@${T0}`]); + }); + + it("an answer with no events list is refused as unreadable", async () => { + const view = openView(() => Promise.resolve({ items: [envelope(1, T0)] })); + await settle(); + + const { data, error } = view.feed.snapshot(); + expect(error).toBeInstanceOf(SyntaxError); + expect(data).toEqual([]); + }); + + it("a view opened while the daemon is away loads the last hour once it is back", async () => { + // The daemon is gone: the view's first loads fail at the network level. + const view = openView(() => Promise.reject(new TypeError("Failed to fetch"))); + view.daemon.health = "unreachable"; + await settle(); + view.daemon.openStream()?.end(); + await vi.advanceTimersByTimeAsync(7_000); + expect(view.connection.state().phase).toBe("disconnected"); + // Nothing of its own: the connection says the daemon is lost. + expect(view.feed.snapshot()).toEqual({}); + + // Back, with an event from half an hour ago in its log: only the last hour holds it. + const earlier = envelope(1, Date.now() - 30 * 60_000); + view.replayWith(eventLog([earlier])); + view.daemon.health = "up"; + await vi.advanceTimersByTimeAsync(8_000); + expect(view.connection.state().phase).toBe("connected"); + + expect(view.shown()).toEqual([`1@${earlier.timestamp}`]); + }); + + it("a closed view ignores what arrives after", async () => { + let answer: (body: unknown) => void = () => {}; + let loads = 0; + // The first load answers at once; the one the stream's opening asks for is held. + const view = openView(() => { + loads += 1; + if (loads === 1) return Promise.resolve({ events: [envelope(1, T0 - 1_000)] }); + return new Promise((resolve) => { + answer = resolve; + }); + }); + await settle(); + const before = view.feed.snapshot(); + expect(view.shown()).toEqual([`1@${T0 - 1_000}`]); + + view.stop(); + view.daemon.openStream()?.send(frame(envelope(2, T0))); + answer({ events: [envelope(3, T0 + 1_000)] }); + await settle(); + view.visibility.set(true); + view.visibility.set(false); + await settle(); + + expect(view.feed.snapshot()).toBe(before); + // The stream opening again asked for nothing. + expect(view.replays).toHaveLength(2); + }); +}); + +describe("the events view's loads", () => { + it("a closed view shows no refusal and sends no retry that would arrive after", async () => { + const refused = openView(() => Promise.reject(new ApiError(500, "INTERNAL", "Internal error"))); + refused.stop(); + await settle(); + expect(refused.feed.snapshot()).toEqual({}); + + const lost = openView(() => Promise.reject(new TypeError("Failed to fetch"))); + await settle(); + const sent = lost.replays.length; + lost.stop(); + await vi.advanceTimersByTimeAsync(30_000); + expect(lost.replays).toHaveLength(sent); + }); + + it("a replay that holds the same event twice shows it once", async () => { + const view = openView([envelope(1, T0), envelope(1, T0), envelope(2, T0 + 1)]); + await settle(); + + expect(view.shown()).toEqual([`2@${T0 + 1}`, `1@${T0}`]); + }); + + it("an event already shown changes nothing", async () => { + const view = openView([envelope(1, T0)]); + await settle(); + const before = view.feed.snapshot(); + let changes = 0; + view.feed.subscribe(() => { + changes += 1; + }); + + view.daemon.openStream()?.send(frame(envelope(1, T0))); + await settle(); + + expect(view.feed.snapshot()).toBe(before); + expect(changes).toBe(0); + }); + + it("a refusal stays shown while the stream adds events, and those events show", async () => { + const refusal = new ApiError(500, "INTERNAL", "Internal error"); + const view = openView(() => Promise.reject(refusal)); + await settle(); + expect(view.feed.snapshot()).toEqual({ data: [], error: refusal }); + + view.daemon.openStream()?.send(frame(envelope(1, T0))); + await settle(); + + expect(view.feed.snapshot().error).toBe(refusal); + expect(view.shown()).toEqual([`1@${T0}`]); + }); + + it("a load that fails at the network level is sent again while the stream stays open", async () => { + let failures = 2; + const view = openView(() => { + if (failures > 0) { + failures -= 1; + return Promise.reject(new TypeError("Failed to fetch")); + } + return Promise.resolve({ events: [envelope(1, T0)] }); + }); + await settle(); + expect(view.replays).toEqual(["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/v1/events?since=1h"]); + expect(view.feed.snapshot()).toEqual({}); + + // After 1 second, and after 2 more. + await vi.advanceTimersByTimeAsync(1_000); + expect(view.replays).toHaveLength(2); + expect(view.feed.snapshot()).toEqual({}); + await vi.advanceTimersByTimeAsync(2_000); + + expect(view.replays).toEqual( + ["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/v1/events?since=1h", "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/v1/events?since=1h"].concat(["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/v1/events?since=1h"]), + ); + expect(view.connection.state().phase).toBe("connected"); + expect(view.shown()).toEqual([`1@${T0}`]); + }); + + it("a gap not loaded before the daemon goes away again is loaded with the next one", async () => { + const view = openView([]); + await settle(); + view.daemon.health = "up"; + + // The first outage: the stream ends, with an event sent just after, and the daemon is back + // after 1 s; the load of that gap does not reach it. + view.daemon.openStream()?.end(); + await settle(); + const missed = envelope(1, Date.now() + 200); + view.replayWith(() => Promise.reject(new TypeError("Failed to fetch"))); + await vi.advanceTimersByTimeAsync(1_000); + expect(view.replays.at(-1)).toBe("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/v1/events?since=1s"); + + // The second outage, before that load is sent again, then 30 s more of failed loads. + view.daemon.openStream()?.end(); + await vi.advanceTimersByTimeAsync(30_000); + expect(view.shown()).toEqual([]); + + // The daemon answers again. The load reaches back to the first gap, not just the second. + view.replayWith(eventLog([missed])); + await vi.advanceTimersByTimeAsync(10_000); + + expect(view.connection.state().phase).toBe("connected"); + expect(view.shown()).toEqual([`1@${missed.timestamp}`]); + }); + + it("a stream that opens while a load is out is loaded again after it", async () => { + let answer: (body: unknown) => void = () => {}; + const view = openView([]); + await settle(); + expect(view.replays).toHaveLength(2); + view.replayWith( + () => + new Promise((resolve) => { + answer = resolve; + }), + ); + + // A gap load goes out; the stream closes and opens again before it answers. + view.visibility.set(true); + await vi.advanceTimersByTimeAsync(2_000); + view.visibility.set(false); + await settle(); + expect(view.replays.at(-1)).toBe("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/v1/events?since=2s"); + view.visibility.set(true); + await vi.advanceTimersByTimeAsync(3_000); + view.visibility.set(false); + await settle(); + expect(view.replays).toHaveLength(3); + + view.replayWith([envelope(1, T0)]); + answer({ events: [] }); + await settle(); + + // Again, from the first gap's start: the answer may be older than what the second missed. + expect(view.replays.slice(3)).toEqual(["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/v1/events?since=5s"]); + expect(view.shown()).toEqual([`1@${T0}`]); + }); +}); diff --git a/ui/src/views/events.tsx b/ui/src/views/events.tsx new file mode 100644 index 000000000..dd3146b3a --- /dev/null +++ b/ui/src/views/events.tsx @@ -0,0 +1,121 @@ +import { useEffect, useState, useSyncExternalStore } from "react"; + +import { useApi } from "../console-context"; +import { browserClock } from "../live/browser"; +import { useLiveEvents, useLiveResource, useStreamOpened } from "../live/live-context"; +import { Loaded } from "../live/route-state"; +import { EventFeed } from "./event-feed"; +import { + type ConsoleEvent, + payloadPairs, + type Subject, + subjectOf, + timeOfDay, + workerIdOf, +} from "./events-model"; +import { type WorkerList, type WorkerView, workerName } from "./workers-model"; + +const FILTERS: readonly { readonly value: Subject | "all"; readonly label: string }[] = [ + { label: "All", value: "all" }, + { label: "Leases", value: "lease" }, + { label: "Devices", value: "device" }, + { label: "Workers", value: "worker" }, + { label: "Components", value: "component" }, + { label: "Other", value: "other" }, +]; + +/** + * Recent events, newest first, with new ones added as the stream sends them (ADR 0013 §1, §2). + * Each shows the payload as the daemon sent it: keeping secrets out of events is the daemon's + * job, not the console's. + */ +export function EventsView() { + const api = useApi(); + const [feed] = useState(() => new EventFeed((path) => api.getJson(path), browserClock)); + useLiveEvents(feed.streamEvent); + useStreamOpened(feed.streamOpened); + useEffect(() => feed.start(), [feed]); + const state = useSyncExternalStore(feed.subscribe, feed.snapshot); + const workers = useLiveResource("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/v1/workers").data?.workers; + const [filter, setFilter] = useState("all"); + return ( +
    +

    Events

    +
    + Show + {FILTERS.map((option) => ( + + ))} +
    + + {(events) => } + +
    + ); +} + +/** The events, newest first. Each one's payload is a list of its keys and values. */ +export function EventList(props: { + readonly events: readonly ConsoleEvent[]; + /** The workers the daemon lists, to name an event's worker; `undefined` until read. */ + readonly workers: readonly WorkerView[] | undefined; + /** Only the events about this subject; all of them when absent. */ + readonly filter?: Subject | "all"; +}) { + const { filter = "all", workers } = props; + if (props.events.length === 0) return

    No events in the last hour.

    ; + const events = + filter === "all" + ? props.events + : props.events.filter((event) => subjectOf(event.event) === filter); + if (events.length === 0) return

    No events of this kind.

    ; + return ( +
      + {events.map((event) => { + const workerId = workerIdOf(event); + const pairs = payloadPairs(event.payload); + return ( +
    1. +

      + + {event.event} + {workerId === undefined ? null : ( + {eventWorkerName(workerId, workers)} + )} +

      + {pairs.length === 0 ? null : ( +
      + {pairs.map((pair) => ( +
      +
      {pair.key}
      +
      {pair.value}
      +
      + ))} +
      + )} +
    2. + ); + })} +
    + ); +} + +/** + * The name to show for the worker an event is about: its label when the daemon lists it, its + * id when the worker has no label or is not listed (yet, or any more). + */ +function eventWorkerName(id: string, workers: readonly WorkerView[] | undefined): string { + const worker = workers?.find((candidate) => candidate.id === id); + return worker === undefined ? id : workerName(worker); +} diff --git a/ui/src/views/index.tsx b/ui/src/views/index.tsx index 4c1158d07..8d8dc3aa9 100644 --- a/ui/src/views/index.tsx +++ b/ui/src/views/index.tsx @@ -1,7 +1,7 @@ import type { ComponentType } from "react"; import { AttentionCount, AttentionView } from "./attention"; -import { ComingSoon } from "./coming-soon"; +import { EventsView } from "./events"; import { LeasesView } from "./leases"; import { WaitingView } from "./waiting"; import { WorkersView } from "./workers"; @@ -25,7 +25,7 @@ export const VIEWS: readonly View[] = [ { path: "/leases", label: "Leases", Component: LeasesView }, { path: "/waiting", label: "Waiting", Component: WaitingView }, { path: "/attention", label: "Attention", Component: AttentionView, Badge: AttentionCount }, - { path: "/events", label: "Events", Component: () => }, + { path: "/events", label: "Events", Component: EventsView }, ]; /**