+ )}
+
+ );
+ })}
+
);
}
+
+/**
+ * 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);
+}
From ef9d27c3beb34e3f795254c0894b821fb7c77945 Mon Sep 17 00:00:00 2001
From: Szymon Chmal
Date: Fri, 2 Oct 2026 22:51:25 +0200
Subject: [PATCH 3/5] fix(ui): answer the code review of the events view
Load the last hour again until a load has answered, count a gap from
the last thing the stream sent, leave a lost daemon to the connection
banner, and name no worker for worker.rejected.
---
docs/CONSOLE.md | 4 +-
ui/src/live/connection.test.ts | 19 ++++
ui/src/live/connection.ts | 27 ++++-
ui/src/views/event-feed.ts | 69 ++++++------
ui/src/views/events-model.ts | 8 +-
ui/src/views/events.test.tsx | 191 ++++++++++++++++++++++++++++++---
6 files changed, 264 insertions(+), 54 deletions(-)
diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md
index f63ee3afc..34130b31d 100644
--- a/docs/CONSOLE.md
+++ b/docs/CONSOLE.md
@@ -230,7 +230,9 @@ 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
+ 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
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/views/event-feed.ts b/ui/src/views/event-feed.ts
index 1a926b309..3e22cfff4 100644
--- a/ui/src/views/event-feed.ts
+++ b/ui/src/views/event-feed.ts
@@ -7,13 +7,22 @@
* When it loads:
*
* - The view opens: the last hour, as `simlock events --since 1h` shows.
- * - The stream opens for the first time: the last hour again. A view opened before the stream
- * did loads once more after it, so nothing sent between the first load and the stream is lost.
- * - The stream opens again, after a lost daemon or a hidden tab: `since` how long it was closed,
- * in whole seconds, rounded up.
+ * - The stream opens: what it may have missed. Until the last hour has loaded once, that is the
+ * last hour again: the stream's first open after a view opened before it, or a view opened
+ * while the daemon was away. After that, `since` how long the console had not heard from the
+ * stream, in whole seconds, rounded up.
+ *
+ * A load the daemon refuses shows why, above the events already shown. A load that does not
+ * reach the daemon shows nothing of its own: the connection says the daemon is lost, and the
+ * stream opening again loads what was missed.
*/
import type { ApiPath } from "../api";
-import type { ResourceState, StreamEvent, StreamOpened } from "../live/connection";
+import {
+ isRefusal,
+ type ResourceState,
+ type StreamEvent,
+ type StreamOpened,
+} from "../live/connection";
import {
type ConsoleEvent,
mergeEvents,
@@ -28,8 +37,10 @@ export class EventFeed {
readonly #listeners = new Set<() => void>();
#events: readonly ConsoleEvent[] = [];
#state: ResourceState = {};
- /** Whether any load has answered or failed; until then the view says it is loading. */
+ /** Whether a load has answered or been refused; until then the view says it is loading. */
#settled = false;
+ /** Whether a load has answered. Every load until then is the last hour, so after it only a gap can be missing. */
+ #recentLoaded = false;
#active = false;
/** `get` reads a route and resolves its JSON body. */
@@ -56,12 +67,13 @@ export class EventFeed {
/** The stream opened: load what it may have missed. */
readonly streamOpened = (opened: StreamOpened): void => {
if (!this.#active) return;
- this.#load(opened.closedForMs === undefined ? RECENT : sinceFor(opened.closedForMs));
+ const gap = opened.closedForMs;
+ this.#load(gap === undefined || !this.#recentLoaded ? RECENT : sinceFor(gap));
};
/**
- * The events, newest first, once a load has settled. `error` is why the latest load failed,
- * cleared by the next that answers. The same object until it changes.
+ * 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;
@@ -73,24 +85,22 @@ export class EventFeed {
};
#load(since: string): void {
- this.#get(`/v1/events?since=${since}`).then(
- (body) => {
- if (!this.#active) return;
- let events: readonly ConsoleEvent[];
- try {
- events = readReplay(body);
- } catch (error: unknown) {
- this.#fail(error);
- return;
- }
- this.#settled = true;
- this.#events = mergeEvents(this.#events, events);
- this.#publish({ data: this.#events });
- },
- (error: unknown) => {
- if (this.#active) this.#fail(error);
- },
- );
+ this.#get(`/v1/events?since=${since}`)
+ .then(readReplay)
+ .then(
+ (events) => {
+ if (!this.#active) return;
+ this.#recentLoaded = true;
+ this.#settled = true;
+ this.#events = mergeEvents(this.#events, events);
+ this.#publish({ data: this.#events });
+ },
+ (error: unknown) => {
+ if (!this.#active || !isRefusal(error)) return;
+ this.#settled = true;
+ this.#publish({ data: this.#events, error });
+ },
+ );
}
#add(incoming: readonly ConsoleEvent[]): void {
@@ -100,11 +110,6 @@ export class EventFeed {
if (this.#settled) this.#publish({ ...this.#state, data: merged });
}
- #fail(error: unknown): void {
- this.#settled = true;
- this.#publish({ data: this.#events, error });
- }
-
#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
index dee580986..a1db922c8 100644
--- a/ui/src/views/events-model.ts
+++ b/ui/src/views/events-model.ts
@@ -102,11 +102,15 @@ export function subjectOf(name: string): Subject {
/**
* 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.
+ * 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 (typeof payload !== "object" || payload === null || Array.isArray(payload)) return undefined;
+ if (event.event === "worker.rejected" || typeof payload !== "object" || payload === null) {
+ return undefined;
+ }
const workerId = (payload as Record).workerId;
return typeof workerId === "string" ? workerId : undefined;
}
diff --git a/ui/src/views/events.test.tsx b/ui/src/views/events.test.tsx
index 7494bce88..fb4d67f6f 100644
--- a/ui/src/views/events.test.tsx
+++ b/ui/src/views/events.test.tsx
@@ -1,7 +1,7 @@
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
-import type { ApiPath, ApiResponse } from "../api";
+import { ApiError, type ApiPath, type ApiResponse } from "../api";
import { connect, settle } from "../live/test-support";
import { EventFeed } from "./event-feed";
import { EventList } from "./events";
@@ -28,30 +28,35 @@ function text(html: string): string {
.trim();
}
+/** What `GET /v1/events` answers: these events, or whatever this returns. */
+type Replay = unknown[] | (() => Promise);
+
/**
* 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() {
+function openView(first: Replay = []) {
const live = connect();
const replays: ApiPath[] = [];
- let replay: unknown[] = [];
- live.daemon.reads = (path) => {
- if (path.startsWith("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/v1/events?")) replays.push(path);
- const body = path.startsWith("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/v1/events?") ? { events: replay } : {};
- return Promise.resolve({ body, date: null } satisfies ApiResponse);
+ 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() : { events: replay };
+ return { body, date: null } satisfies ApiResponse;
};
const feed = new EventFeed(async (path) => (await live.daemon.get(path)).body);
live.connection.onEvent(feed.streamEvent);
live.connection.onStreamOpened(feed.streamOpened);
- feed.start();
+ const stop = feed.start();
return {
...live,
feed,
replays,
+ stop,
/** Sets what `GET /v1/events` answers from now on. */
- replayWith(events: unknown[]) {
- replay = events;
+ replayWith(next: Replay) {
+ replay = next;
},
/** The events the view shows, as `seq@timestamp`, newest first. */
shown(): string[] {
@@ -204,21 +209,52 @@ describe("the events view", () => {
{
event: "gizmo.frobnicated",
payload: { count: 3, nested: { deep: true }, reason: "because", workerId: "wrk_1" },
- seq: 2,
+ seq: 3,
timestamp: T0,
},
// A payload that is not an object at all.
- { event: "gizmo.listed", payload: ["a", 1], seq: 1, timestamp: T0 - 1_000 },
+ { 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 shown = text(
- renderToStaticMarkup(),
+ 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 render = (filtered: boolean) =>
+ text(renderToStaticMarkup());
+
+ expect(render(false)).toBe("No events in the last hour.");
+ expect(render(true)).toBe("No events of this kind.");
});
it("a worker the console does not know, or that has no label, shows as its id", () => {
@@ -242,18 +278,143 @@ describe("the events view", () => {
// 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(
+ ,
+ );
- it("an envelope without a seq, a timestamp that is a date, or a name is not shown", async () => {
+ 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(view.feed.snapshot()).toEqual({});
+
+ 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}`]);
+
+ // 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.
+ const earlier = envelope(1, Date.now() - 30 * 60_000);
+ view.replayWith([earlier]);
+ view.daemon.health = "up";
+ await vi.advanceTimersByTimeAsync(8_000);
+ expect(view.connection.state().phase).toBe("connected");
+
+ expect(view.replays.at(-1)).toBe("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/v1/events?since=1h");
+ 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);
+ });
});
From 87235537cbb6cf5d3f2bae3b73f10f3fe5c7dc45 Mon Sep 17 00:00:00 2001
From: Szymon Chmal
Date: Fri, 2 Oct 2026 22:55:30 +0200
Subject: [PATCH 4/5] test(ui): render the loading and refused states the
events view shows
---
ui/src/views/events.test.tsx | 17 ++++++++++++++++-
1 file changed, 16 insertions(+), 1 deletion(-)
diff --git a/ui/src/views/events.test.tsx b/ui/src/views/events.test.tsx
index fb4d67f6f..459f34e67 100644
--- a/ui/src/views/events.test.tsx
+++ b/ui/src/views/events.test.tsx
@@ -2,6 +2,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiError, type ApiPath, type ApiResponse } from "../api";
+import { Loaded } from "../live/route-state";
import { connect, settle } from "../live/test-support";
import { EventFeed } from "./event-feed";
import { EventList } from "./events";
@@ -65,6 +66,15 @@ function openView(first: Replay = []) {
};
}
+/** 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 {
@@ -325,7 +335,7 @@ describe("the events view", () => {
await settle();
view.daemon.openStream()?.send(frame(envelope(2, T0)));
await settle();
- expect(view.feed.snapshot()).toEqual({});
+ expect(text(screen(view.feed))).toBe("Loading…");
answer({ events: [envelope(1, T0 - 1_000)] });
await settle();
@@ -348,6 +358,11 @@ describe("the events view", () => {
expect(view.feed.snapshot().error).toBe(refusal);
expect(view.shown()).toEqual([`1@${T0}`]);
+ const shown = screen(view.feed);
+ expect(shown).toContain(
+ '
Internal error
',
+ );
+ 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)]);
From 1010f52ec8913df4b9dad16899e7ad12b54819a6 Mon Sep 17 00:00:00 2001
From: Szymon Chmal
Date: Fri, 2 Oct 2026 23:13:19 +0200
Subject: [PATCH 5/5] fix(ui,docs): answer the second code review of the events
view
Send a load that does not reach the daemon again with backoff, keep
every gap not yet loaded, and load again when the stream opens while a
load is out. The event list filters itself, and ARCHITECTURE.md names the
events feed as the one view that reads a route outside the live layer.
---
docs/internal/ARCHITECTURE.md | 6 +-
ui/src/views/event-feed.ts | 92 +++++++++++---
ui/src/views/events.test.tsx | 220 ++++++++++++++++++++++++++++++++--
ui/src/views/events.tsx | 33 ++---
4 files changed, 301 insertions(+), 50 deletions(-)
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/ui/src/views/event-feed.ts b/ui/src/views/event-feed.ts
index 3e22cfff4..a8ca4e864 100644
--- a/ui/src/views/event-feed.ts
+++ b/ui/src/views/event-feed.ts
@@ -4,20 +4,26 @@
* tested against the real live connection on a scripted daemon; `events.tsx` wires it to the
* stream with `useLiveEvents` and `useStreamOpened`.
*
- * When it loads:
+ * The feed keeps track of what may be missing, and loads until nothing is:
*
- * - The view opens: the last hour, as `simlock events --since 1h` shows.
- * - The stream opens: what it may have missed. Until the last hour has loaded once, that is the
- * last hour again: the stream's first open after a view opened before it, or a view opened
- * while the daemon was away. After that, `since` how long the console had not heard from the
- * stream, in whole seconds, rounded up.
+ * - 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 the daemon refuses shows why, above the events already shown. A load that does not
- * reach the daemon shows nothing of its own: the connection says the daemon is lost, and the
- * stream opening again loads what was missed.
+ * 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,
@@ -32,26 +38,38 @@ import {
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 a load has answered. Every load until then is the last hour, so after it only a gap can be missing. */
- #recentLoaded = 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) {
+ 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.#load(RECENT);
+ this.#loadMissing();
return () => {
this.#active = false;
};
@@ -66,9 +84,15 @@ export class EventFeed {
/** The stream opened: load what it may have missed. */
readonly streamOpened = (opened: StreamOpened): void => {
- if (!this.#active) return;
const gap = opened.closedForMs;
- this.#load(gap === undefined || !this.#recentLoaded ? RECENT : sinceFor(gap));
+ 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();
};
/**
@@ -84,25 +108,57 @@ export class EventFeed {
};
};
- #load(since: string): void {
+ /** 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;
- this.#recentLoaded = true;
+ 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) => {
- if (!this.#active || !isRefusal(error)) return;
+ 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;
diff --git a/ui/src/views/events.test.tsx b/ui/src/views/events.test.tsx
index 459f34e67..f42487fd1 100644
--- a/ui/src/views/events.test.tsx
+++ b/ui/src/views/events.test.tsx
@@ -2,6 +2,7 @@ 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";
@@ -11,6 +12,13 @@ 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 };
}
@@ -30,7 +38,22 @@ function text(html: string): string {
}
/** What `GET /v1/events` answers: these events, or whatever this returns. */
-type Replay = unknown[] | (() => Promise);
+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
@@ -43,10 +66,10 @@ function openView(first: Replay = []) {
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() : { events: replay };
+ 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);
+ 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();
@@ -194,6 +217,20 @@ describe("the events view", () => {
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(
@@ -260,11 +297,37 @@ describe("the events view", () => {
});
it("an empty list says why it is empty", () => {
- const render = (filtered: boolean) =>
- text(renderToStaticMarkup());
+ 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(render(false)).toBe("No events in the last hour.");
- expect(render(true)).toBe("No events of this kind.");
+ 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", () => {
@@ -394,14 +457,13 @@ describe("the events view", () => {
// 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.
+ // 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([earlier]);
+ view.replayWith(eventLog([earlier]));
view.daemon.health = "up";
await vi.advanceTimersByTimeAsync(8_000);
expect(view.connection.state().phase).toBe("connected");
- expect(view.replays.at(-1)).toBe("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/v1/events?since=1h");
expect(view.shown()).toEqual([`1@${earlier.timestamp}`]);
});
@@ -433,3 +495,141 @@ describe("the events view", () => {
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
index e16b2a302..dd3146b3a 100644
--- a/ui/src/views/events.tsx
+++ b/ui/src/views/events.tsx
@@ -1,6 +1,7 @@
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";
@@ -30,7 +31,7 @@ const FILTERS: readonly { readonly value: Subject | "all"; readonly label: strin
*/
export function EventsView() {
const api = useApi();
- const [feed] = useState(() => new EventFeed((path) => api.getJson(path)));
+ const [feed] = useState(() => new EventFeed((path) => api.getJson(path), browserClock));
useLiveEvents(feed.streamEvent);
useStreamOpened(feed.streamOpened);
useEffect(() => feed.start(), [feed]);
@@ -56,17 +57,7 @@ export function EventsView() {
))}
- {(events) => (
- subjectOf(event.event) === filter)
- }
- workers={workers}
- filtered={filter !== "all"}
- />
- )}
+ {(events) => }
);
@@ -77,16 +68,16 @@ 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;
- readonly filtered?: boolean;
+ /** Only the events about this subject; all of them when absent. */
+ readonly filter?: Subject | "all";
}) {
- const { events, filtered = false, workers } = props;
- if (events.length === 0) {
- return (
-
- {filtered ? "No events of this kind." : "No events in the last hour."}
-