diff --git a/docs/internal/DESIGN.md b/docs/internal/DESIGN.md index e6ba908ab..9306ee840 100644 --- a/docs/internal/DESIGN.md +++ b/docs/internal/DESIGN.md @@ -147,22 +147,22 @@ put together from them and draws nothing of its own that one of them already dra opens the links and the bottom block under it. - **Page.** A page that is not a list, as the overview: its title (`h1`) and its actions on the right, then its content. No subtitle: the title and what is under it say what the page is. -- **List and inspector.** Queue, Attention and Activity (waiting requests, attention items, - events) are each a list on the left, 260–360px wide (wider for events), and the chosen thing in - an inspector filling the rest. The list has a header (the page's title as `h1`, a short count +- **List and inspector.** Attention (attention items) is a list on the left, 260–360px wide, and + the chosen thing in an inspector filling the rest. The list has a header (the page's title as `h1`, a short count in mono beside it, then its filters), its rows, and the pager under them. A row is one or two short lines: a status square, a title, one figure on the right, and at most one muted line or bar under them; the chosen row is `--surface` with a 2px `--accent` bar on its left and - `aria-current="page"`. The address names the chosen thing (`/queue/`). The inspector + `aria-current="page"`. The address names the chosen thing (`/attention/`). The inspector has a breadcrumb, the thing's title (`h2`), one muted line under it, actions on the right, and then cards, facts, tabs and panels. -- **Table and drawer.** Leases and Fleet are each a toolbar (the filter chips on the left, a search box on the - right, at the page title's padding) over a table. Leases' filters are its own; Fleet's are +- **Table and drawer.** Leases, Fleet and Queue are each a table (Leases and Fleet under a toolbar: the filter + chips on the left, a search box on the right, at the page title's padding). Activity has the same toolbar over + an event feed that scrolls inside itself; Queue has no toolbar, only the Wait p95 tile above its table. Leases' filters are its own; Fleet's are All, Issues and Busy over workers, and a row opens the worker's own page (a title, a state line, a banner when the worker is disconnected or drained, cards, then tabs), on which a - device row opens the drawer. Choosing a lease or a device opens a **drawer**: a 480px + device row opens the drawer. Choosing a lease, a device, a request or an event opens a **drawer**: a 480px panel (full width under 768px) at the right edge over the page, with a dim layer over everything - else, the sidebar included. It has a title (a lease's holder, a device's model and runtime), a 40px square close button + else, the sidebar included. It has a title (a lease's holder, a device's model and runtime, a request's requester, an event's name), a 40px square close button (`IconButton`) and, for a lease, tabs. Escape, the close button and the dim layer close it. It slides in once, when it opens, and switching its tabs does not replay that. A lease's drawer uses no status colour of its own; a device's shows the device's state as a status, word and square. diff --git a/e2e/console/activity.spec.ts b/e2e/console/activity.spec.ts new file mode 100644 index 000000000..82b644efc --- /dev/null +++ b/e2e/console/activity.spec.ts @@ -0,0 +1,748 @@ +import type { Locator, Page, Route } from "@playwright/test"; + +import { + disposeFleet, + expect, + type RunningDaemon, + signIn, + startDaemon, + startFleet, + settled, + test, +} from "./fixtures.js"; + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; + +interface Envelope { + readonly id: string; + readonly timestamp: number; + readonly event: string; +} + +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; +} + +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, path = "/activity"): Promise { + await page.goto(new URL(path, daemon.url).href); + await signIn(page, daemon.tokens.operator); + // why: a drawer over the page hides the page's heading from the accessibility tree. + if (new URL(path, daemon.url).pathname === "/activity") { + await expect(page.getByRole("heading", { level: 1, name: "Activity" })).toBeVisible(); + } else await expect(page.getByRole("dialog")).toBeVisible(); +} + +function feed(page: Page): Locator { + return page.getByRole("region", { name: "Event feed" }); +} + +function rows(page: Page): Locator { + return feed(page).getByRole("listitem"); +} + +function title(page: Page): Locator { + return page.getByRole("heading", { level: 2 }).first(); +} + +async function shownEvents(page: Page): Promise { + return feed(page).evaluate(async (box) => { + const frame = () => new Promise((resolve) => requestAnimationFrame(resolve)); + const seen = new Map(); + box.scrollTop = 0; + for (let step = 0; step < 1_000; step += 1) { + await frame(); + for (const item of box.querySelectorAll("li")) { + const link = item.querySelector("a"); + const name = item.querySelector("time + span"); + seen.set( + Math.round(item.getBoundingClientRect().top + box.scrollTop), + [ + item.querySelector("time")?.getAttribute("datetime") ?? "", + name?.textContent ?? "", + link?.getAttribute("href")?.replace("/activity/", "") ?? "", + ].join(" "), + ); + } + if (box.scrollTop + box.clientHeight >= box.scrollHeight - 1) break; + box.scrollTop += box.clientHeight; + } + box.scrollTop = 0; + return [...seen.entries()].sort(([a], [b]) => a - b).map(([, shown]) => shown); + }); +} + +function asShown(event: Envelope): string { + return `${new Date(event.timestamp).toISOString()} ${event.event} ${encodeURIComponent(event.id)}`; +} + +async function openEvent(page: Page, id: string): Promise { + const link = feed(page).locator(`a[href="/activity/${encodeURIComponent(id)}"]`); + await feed(page).evaluate((box) => box.scrollTo({ top: 0 })); + for (let step = 0; step < 200 && (await link.count()) === 0; step += 1) { + await feed(page).evaluate((box) => box.scrollBy({ top: box.clientHeight / 2 })); + await page.waitForTimeout(30); + } + await link.click(); +} + +interface Stubbed { + readonly id: string; + readonly seq: number; + readonly timestamp: number; + readonly event: string; + readonly payload: Record; +} + +function stubbed(n: number, now: number): Stubbed { + return { + event: "lease.renewed", + id: `evt_${String(n).padStart(4, "0")}`, + payload: {}, + seq: 1_000_000 - n, + timestamp: now - n * 60_000, + }; +} + +// why: one clock for every stubbed event, so a time the test names is the time the page shows. +const BASE = Date.now(); + +function stubbedRange(from: number, to: number): Stubbed[] { + return Array.from({ length: to - from + 1 }, (_, index) => stubbed(to - index, BASE)); +} + +function localMinute(timestamp: number): string { + const date = new Date(timestamp); + const part = (value: number) => String(value).padStart(2, "0"); + return `${date.getFullYear()}-${part(date.getMonth() + 1)}-${part(date.getDate())} ${part(date.getHours())}:${part(date.getMinutes())}`; +} + +interface StubbedAnswer { + readonly status?: number; + readonly events?: readonly Stubbed[]; +} + +/** + * why: Answers every `GET /v1/events` with what `answer` returns for its query, and records each + * query, so a test sees which pages the console asked for. + */ +async function stubEvents( + page: Page, + answer: (query: URLSearchParams) => StubbedAnswer, +): Promise { + const queries: string[] = []; + await page.route( + (url) => url.pathname === "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/v1/events", + async (route: Route) => { + const { search } = new URL(route.request().url()); + queries.push(search); + const { events = [], status = 200 } = answer(new URLSearchParams(search)); + if (status === 200) await route.fulfill({ json: { events } }); + else + await route.fulfill({ json: { error: { code: "STUBBED", message: "stubbed" } }, status }); + }, + ); + return queries; +} + +async function firstRowInView(page: Page): Promise<{ href: string | null; top: number }> { + return feed(page).evaluate((box) => { + const edge = box.getBoundingClientRect().top; + const link = [...box.querySelectorAll("li")].find( + (item) => item.getBoundingClientRect().bottom > edge, + ); + return { + href: link?.querySelector("a")?.getAttribute("href") ?? null, + top: Math.round((link?.getBoundingClientRect().top ?? 0) - edge), + }; + }); +} + +// why: the first visit signs in; a later one in the same test finds the session still there. +async function visit( + page: Page, + daemon: RunningDaemon, + path: string, + first: boolean, +): Promise { + if (first) return openEvents(page, daemon, path); + await page.goto(new URL(path, daemon.url).href); + await expect(page.getByRole("heading", { level: 1, name: "Activity" })).toBeVisible(); +} + +function older(queries: readonly string[]): string[] { + return queries.filter((query) => !query.startsWith("?since=")); +} + +// why: the feed draws only the rows in view and prints no count, so its scroll height, one row +// tall per event, is the only measure of how many events it holds. +const ROW_PX = 60; + +async function eventsHeld(page: Page): Promise { + return Math.round((await feed(page).evaluate((box) => box.scrollHeight)) / ROW_PX); +} + +async function rowOffset(page: Page, id: string): Promise { + return feed(page).evaluate((box, wanted) => { + const link = box.querySelector(`a[href^="/activity/${wanted}"]`); + if (link === null) throw new Error(`${wanted} is not drawn`); + return Math.round( + link.closest("li")!.getBoundingClientRect().top - box.getBoundingClientRect().top, + ); + }, id); +} + +async function hasHorizontalScroll(page: Page): Promise { + await settled(page); + return page.evaluate( + () => document.documentElement.scrollWidth > document.documentElement.clientWidth, + ); +} + +test.describe("the Activity page", () => { + test("a lease taken with the CLI appears in the feed within a second, and its page opens from it", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await openEvents(page, host); + await expect(rows(page).first()).toBeVisible(); + const granted = rows(page).filter({ hasText: "lease.granted" }); + await expect(granted).toHaveCount(0); + + const id = await lease(host, "console-e2e-events"); + + await expect(granted).toHaveCount(1, { timeout: 1_000 }); + await granted.click(); + await expect(title(page)).toHaveText("lease.granted"); + await expect(page).toHaveURL(/\/activity\/[^/]+$/); + await expect(page.getByText("leaseId", { exact: true })).toBeVisible(); + await expect(page.locator("dd", { hasText: new RegExp(`^${id}$`) })).toBeVisible(); + + await page.getByRole("link", { name: "Open lease" }).click(); + await expect(page).toHaveURL(new RegExp(`/leases/${id}/?$`)); + } finally { + await host.dispose(); + } + }); + + test("the feed 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"); + + 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("choosing a row puts the event in the URL and its payload whole in the drawer", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await lease(host, "console-e2e-choose"); + await openEvents(page, host); + const started = (await cliEvents(host)).find((event) => event.event === "daemon.started"); + expect(started).toBeDefined(); + + await openEvent(page, (started as Envelope).id); + + await expect(page).toHaveURL(new RegExp(`/activity/${(started as Envelope).id}$`)); + await expect(title(page)).toHaveText("daemon.started"); + await expect(page.getByRole("heading", { level: 3, name: "Payload" })).toBeVisible(); + await page.reload(); + await expect(title(page)).toHaveText("daemon.started"); + } finally { + await host.dispose(); + } + }); + + test("an address for an event not among those loaded opens the drawer and says older events load as the list scrolls", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await openEvents(page, host, "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/activity/evt_not_there"); + + await expect( + page + .getByRole("dialog") + .getByText( + "This event is not among those loaded. Older events load as you scroll the list, or with Load older events.", + ), + ).toBeVisible(); + } finally { + await host.dispose(); + } + }); + + test("loaded directly at an event's address, closing the drawer replaces the address with /activity and focus goes to the heading", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await openEvents(page, host, "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/activity/evt_not_there"); + const drawer = page.getByRole("dialog"); + await expect(drawer).toBeVisible(); + const entries = await page.evaluate(() => window.history.length); + + await page.keyboard.press("Escape"); + + await expect(drawer).toHaveCount(0); + expect(new URL(page.url()).pathname).toBe("/activity"); + expect(await page.evaluate(() => window.history.length)).toBe(entries); + await expect(page.locator("main h1")).toBeFocused(); + } finally { + await host.dispose(); + } + }); + + test("the filter and the search show only the events they match and are kept in the URL", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await lease(host, "console-e2e-filter"); + await openEvents(page, host); + + await page.getByRole("radio", { name: "Leases" }).check({ force: true }); + + await expect(page).toHaveURL(/\?subject=lease$/); + const names = await rows(page).locator("time + span").allTextContents(); + expect(names.length).toBeGreaterThan(0); + expect(names.every((name) => name.startsWith("lease."))).toBe(true); + await page.reload(); + await expect(page.getByRole("radio", { name: "Leases" })).toBeChecked(); + + await page.getByRole("searchbox", { name: "Search events" }).fill("GRANTED"); + + await expect(page).toHaveURL(/\?subject=lease&q=GRANTED$/); + await expect(rows(page)).not.toHaveCount(0); + expect( + (await rows(page).locator("time + span").allTextContents()).every( + (name) => name === "lease.granted", + ), + ).toBe(true); + await page.reload(); + await expect(page.getByRole("searchbox", { name: "Search events" })).toHaveValue("GRANTED"); + } finally { + await host.dispose(); + } + }); + + test("the feed scrolls inside itself with the keyboard, and counts the events that came in while scrolled down", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + for (let index = 0; index < 6; index += 1) await lease(host, `console-e2e-scroll-${index}`); + await openEvents(page, host); + await expect.poll(() => rows(page).count()).toBeGreaterThan(5); + + await feed(page).focus(); + await page.keyboard.press("End"); + await expect.poll(() => feed(page).evaluate((box) => box.scrollTop)).toBeGreaterThan(0); + + await expect + .poll(() => + feed(page).evaluate((box) => box.scrollHeight - box.scrollTop - box.clientHeight), + ) + .toBeLessThan(2); + const inView = await firstRowInView(page); + await lease(host, "console-e2e-scroll-new"); + const more = page.getByRole("button", { name: /^\d+ new events?$/ }); + await expect(more).toBeVisible(); + expect(await firstRowInView(page)).toEqual(inView); + await more.click(); + await expect.poll(() => feed(page).evaluate((box) => box.scrollTop)).toBe(0); + await expect(more).toHaveCount(0); + } finally { + await host.dispose(); + } + }); + + test("scrolling within 20 rows of the end loads the 100 events before the oldest held and appends them without moving the rows in view", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + const queries = await stubEvents(page, (query) => { + const before = query.get("before"); + if (before === null) return { events: stubbedRange(1, 30) }; + if (before === "evt_0030") return { events: stubbedRange(31, 130) }; + if (before === "evt_0130") return { events: stubbedRange(131, 230) }; + return {}; + }); + await openEvents(page, host); + + await expect.poll(() => eventsHeld(page)).toBe(130); + expect(older(queries)).toEqual(["?before=evt_0030&limit=100"]); + + // why: 30 rows from the end is farther than 20, so the list asks for nothing yet. + await feed(page).evaluate((box, top) => box.scrollTo({ top }), 85 * ROW_PX); + await expect.poll(() => rowOffset(page, "evt_0090").catch(() => undefined)).toBeDefined(); + await page.waitForTimeout(300); + expect(older(queries)).toEqual(["?before=evt_0030&limit=100"]); + + await feed(page).evaluate((box, top) => box.scrollTo({ top }), 100 * ROW_PX); + await expect.poll(() => rowOffset(page, "evt_0101").catch(() => undefined)).toBeDefined(); + const inView = await rowOffset(page, "evt_0101"); + await expect.poll(() => eventsHeld(page)).toBe(230); + + expect(older(queries)).toEqual(["?before=evt_0030&limit=100", "?before=evt_0130&limit=100"]); + expect(await rowOffset(page, "evt_0101")).toBe(inView); + expect(await feed(page).evaluate((box) => box.scrollTop)).toBe(100 * ROW_PX); + } finally { + await host.dispose(); + } + }); + + test("each end row shows its wording: the history's start, the 10,000 cap, a 422, a 503 and a 500 with Try again, and a page of events already held", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + let queries = await stubEvents(page, (query) => { + if (query.get("before") === null) return { events: stubbedRange(1, 30) }; + return query.get("before") === "evt_0030" ? { events: stubbedRange(31, 70) } : {}; + }); + await openEvents(page, host); + await expect( + page.getByText(`Start of the history (${localMinute(BASE - 70 * 60_000)})`), + ).toBeVisible(); + await expect.poll(() => eventsHeld(page)).toBe(70); + expect(older(queries)).toEqual(["?before=evt_0030&limit=100"]); + + queries = await stubEvents(page, () => ({ events: stubbedRange(1, 10_000) })); + await page.reload(); + await expect(page.getByText("Showing the newest 10,000 events.")).toBeVisible(); + await feed(page).focus(); + await page.keyboard.press("End"); + await page.waitForTimeout(300); + expect(older(queries)).toEqual([]); + + queries = await stubEvents(page, (query) => + query.get("before") === null ? { events: stubbedRange(1, 30) } : { status: 422 }, + ); + await page.reload(); + await expect(page.getByText("Older events are no longer kept.")).toBeVisible(); + expect(older(queries)).toHaveLength(1); + + for (const status of [503, 500]) { + let failing = true; + queries = await stubEvents(page, (query) => { + if (query.get("before") === null) return { events: stubbedRange(1, 30) }; + return failing ? { status } : { events: stubbedRange(31, 40) }; + }); + await page.reload(); + await expect(page.getByText("Older events are not available right now.")).toBeVisible(); + expect(older(queries)).toHaveLength(1); + failing = false; + await page.getByRole("button", { name: "Try again" }).click(); + await expect(page.getByText("Start of the history (", { exact: false })).toBeVisible(); + expect(older(queries)).toHaveLength(2); + } + + queries = await stubEvents(page, () => ({ events: stubbedRange(1, 100) })); + await page.reload(); + await expect.poll(() => eventsHeld(page)).toBe(100); + await feed(page).focus(); + await page.keyboard.press("End"); + await expect(page.getByText("Start of the history (", { exact: false })).toBeVisible(); + expect(older(queries)).toEqual(["?before=evt_0100&limit=100"]); + expect(await eventsHeld(page)).toBe(100); + } finally { + await host.dispose(); + } + }); + + test("the real daemon answers the older page: the events before the oldest held join the list once, and the history starts", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await lease(host, "console-e2e-older-a"); + await lease(host, "console-e2e-older-b"); + const queries: string[] = []; + let all: Array = []; + await page.route( + (url) => url.pathname === "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/v1/events", + async (route: Route) => { + const { search } = new URL(route.request().url()); + if (!search.startsWith("?since=")) { + queries.push(search); + await route.fallback(); + return; + } + // why: the page holds only the newest two events, so the rest must come from the daemon's older page. + const body = (await (await route.fetch()).json()) as { + events: Array; + }; + all = body.events.toSorted((a, b) => b.seq - a.seq); + await route.fulfill({ json: { events: all.slice(0, 2) } }); + }, + ); + await openEvents(page, host); + await expect(page.getByText("Start of the history (", { exact: false })).toBeVisible(); + expect(all.length).toBeGreaterThan(3); + expect(queries).toEqual([`?before=${encodeURIComponent(all[1]!.id)}&limit=100`]); + await expect.poll(() => eventsHeld(page)).toBe(all.length); + const oldest = all.at(-1)!; + await expect( + page.getByText(`Start of the history (${localMinute(oldest.timestamp)})`), + ).toBeVisible(); + } finally { + await host.dispose(); + } + }); + + test("a daemon with no events in the last hour but older history shows them at once, and an empty history says No events yet", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + let queries = await stubEvents(page, (query) => + query.has("since") ? {} : { events: stubbedRange(1, 40) }, + ); + await openEvents(page, host); + await expect.poll(() => eventsHeld(page)).toBe(40); + await expect(rows(page).first()).toBeVisible(); + expect(older(queries)).toEqual(["?limit=100"]); + + queries = await stubEvents(page, () => ({})); + await page.reload(); + await expect(page.getByText("No events yet.")).toBeVisible(); + expect(older(queries)).toEqual(["?limit=100"]); + } finally { + await host.dispose(); + } + }); + + test("with a chip or a search on, nothing loads by itself, and Load older events loads one page per press", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + for (const [turn, address] of ["/activity?subject=lease", "/activity?q=RENEWED"].entries()) { + const queries = await stubEvents(page, (query) => { + if (query.get("before") === null) return { events: stubbedRange(1, 30) }; + if (query.get("before") === "evt_0030") return { events: stubbedRange(31, 130) }; + return query.get("before") === "evt_0130" ? { events: stubbedRange(131, 230) } : {}; + }); + await visit(page, host, address, turn === 0); + await expect.poll(() => eventsHeld(page)).toBe(30); + const more = page.getByRole("button", { name: "Load older events" }); + await expect(more).toBeVisible(); + await page.waitForTimeout(500); + expect(older(queries)).toEqual([]); + + await more.click(); + await expect.poll(() => eventsHeld(page)).toBe(130); + expect(older(queries)).toEqual(["?before=evt_0030&limit=100"]); + await page.waitForTimeout(500); + expect(older(queries)).toHaveLength(1); + + await more.click(); + await expect.poll(() => eventsHeld(page)).toBe(230); + expect(older(queries)).toHaveLength(2); + } + } finally { + await host.dispose(); + } + }); + + test("a chip or a search that matches no held event says so and offers Load older events, which loads one page", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + const queries = await stubEvents(page, (query) => + query.get("before") === null + ? { events: stubbedRange(1, 30) } + : { events: stubbedRange(31, 70) }, + ); + const cases = [ + ["/activity?subject=worker", "No worker events among those loaded."], + ["/activity?q=zzz", "No events match zzz among those loaded."], + ] as const; + for (const [turn, [address, said]] of cases.entries()) { + queries.length = 0; + await visit(page, host, address, turn === 0); + await expect(page.getByText(said)).toBeVisible(); + const more = page.getByRole("button", { name: "Load older events" }); + await expect(more).toBeVisible(); + + await more.click(); + + await expect(page.getByText("Start of the history (", { exact: false })).toBeVisible(); + expect(older(queries)).toEqual(["?before=evt_0030&limit=100"]); + await expect(page.getByText(said)).toBeVisible(); + await expect(more).toHaveCount(0); + } + } 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); + + await lease(worker, "console-e2e-label"); + + const granted = rows(page).filter({ hasText: "lease.granted" }); + await expect(granted).toHaveCount(1); + await expect(granted).toContainText("worker-a"); + await granted.click(); + await expect(page.getByText("workerId", { exact: true })).toBeVisible(); + } finally { + await disposeFleet(fleet); + } + }); + + test("a worker joining a gateway shows no join token anywhere in the events page", 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); + const wanted = daemon === worker ? "daemon.started" : "worker.connected"; + await expect(rows(page).filter({ hasText: wanted }), name).not.toHaveCount(0); + const events = await cliEvents(daemon); + await expect.poll(async () => (await shownEvents(page)).length, name).toBe(events.length); + + const seen: string[] = []; + for (const event of events) { + await openEvent(page, event.id); + await expect(title(page)).toHaveText(event.event); + seen.push(await page.getByRole("dialog").innerText()); + await page.keyboard.press("Escape"); + await expect(page.getByRole("dialog")).toHaveCount(0); + } + expect(seen.join("\n"), name).not.toContain(joinToken); + expect(await page.content(), name).not.toContain(joinToken); + + await page.getByRole("button", { name: "Sign out" }).click(); + } + } finally { + await disposeFleet(fleet); + } + }); + + test("the events page has no horizontal scroll at 360px wide, even with the longest payload", 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); + expect(await hasHorizontalScroll(page)).toBe(false); + + const started = (await cliEvents(host)).find((event) => event.event === "daemon.started"); + await openEvent(page, (started as Envelope).id); + await expect(title(page)).toHaveText("daemon.started"); + + expect(await hasHorizontalScroll(page)).toBe(false); + } finally { + await host.dispose(); + } + }); + + test("the events page is usable with the keyboard alone", async ({ browserName, page }) => { + 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(); + } + }); +}); + +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("navigation").first()).toBeVisible(); + + const nav = page.getByRole("link", { name: "Activity", exact: true }); + for (let step = 0; step < 30 && !(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: "Activity" })).toBeVisible(); + await expect(rows(page).filter({ hasText: "lease.granted" })).not.toHaveCount(0); + + const all = page.getByRole("radio", { name: "All" }); + for (let step = 0; step < 30 && !(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("time + span").allTextContents(); + expect(names.length).toBeGreaterThan(0); + expect(names.every((name) => name.startsWith("lease."))).toBe(true); + + for (let step = 0; step < 10 && !(await isFocused(feed(page))); step += 1) { + await page.keyboard.press(tab); + } + await expect(feed(page)).toBeFocused(); + await page.keyboard.press(tab); + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(/\/activity\/[^/?]+\?subject=lease$/); +} + +async function isFocused(locator: Locator): Promise { + return locator.evaluate((element) => element === document.activeElement); +} diff --git a/e2e/console/events.spec.ts b/e2e/console/events.spec.ts deleted file mode 100644 index 752402d19..000000000 --- a/e2e/console/events.spec.ts +++ /dev/null @@ -1,366 +0,0 @@ -import type { Locator, Page } from "@playwright/test"; - -import { - disposeFleet, - expect, - type RunningDaemon, - signIn, - startDaemon, - startFleet, - settled, - test, -} from "./fixtures.js"; - -const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; - -interface Envelope { - readonly id: string; - readonly timestamp: number; - readonly event: string; -} - -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; -} - -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, path = "/activity"): Promise { - await page.goto(new URL(path, daemon.url).href); - await signIn(page, daemon.tokens.operator); - await expect(page.getByRole("heading", { level: 1, name: "Activity" })).toBeVisible(); -} - -function feed(page: Page): Locator { - return page.getByRole("region", { name: "Event feed" }); -} - -function rows(page: Page): Locator { - return feed(page).getByRole("listitem"); -} - -function title(page: Page): Locator { - return page.getByRole("heading", { level: 2 }).first(); -} - -async function shownEvents(page: Page): Promise { - return feed(page).evaluate(async (box) => { - const frame = () => new Promise((resolve) => requestAnimationFrame(resolve)); - const seen = new Map(); - box.scrollTop = 0; - for (let step = 0; step < 1_000; step += 1) { - await frame(); - for (const item of box.querySelectorAll("li")) { - const link = item.querySelector("a"); - const name = item.querySelector("time + span"); - seen.set( - Math.round(item.getBoundingClientRect().top + box.scrollTop), - [ - item.querySelector("time")?.getAttribute("datetime") ?? "", - name?.textContent ?? "", - link?.getAttribute("href")?.replace("/activity/", "") ?? "", - ].join(" "), - ); - } - if (box.scrollTop + box.clientHeight >= box.scrollHeight - 1) break; - box.scrollTop += box.clientHeight; - } - box.scrollTop = 0; - return [...seen.entries()].sort(([a], [b]) => a - b).map(([, shown]) => shown); - }); -} - -function asShown(event: Envelope): string { - return `${new Date(event.timestamp).toISOString()} ${event.event} ${encodeURIComponent(event.id)}`; -} - -async function openEvent(page: Page, id: string): Promise { - const link = feed(page).locator(`a[href="/activity/${encodeURIComponent(id)}"]`); - await feed(page).evaluate((box) => box.scrollTo({ top: 0 })); - for (let step = 0; step < 200 && (await link.count()) === 0; step += 1) { - await feed(page).evaluate((box) => box.scrollBy({ top: box.clientHeight / 2 })); - await page.waitForTimeout(30); - } - await link.click(); -} - -async function hasHorizontalScroll(page: Page): Promise { - await settled(page); - return page.evaluate( - () => document.documentElement.scrollWidth > document.documentElement.clientWidth, - ); -} - -test.describe("the events page", () => { - test("a lease taken with the CLI appears in the feed within a second, and its page opens from it", async ({ - page, - }) => { - const host = await startDaemon("worker", { driverScript: { ios: IOS } }); - try { - await openEvents(page, host); - await expect(rows(page).first()).toBeVisible(); - const granted = rows(page).filter({ hasText: "lease.granted" }); - await expect(granted).toHaveCount(0); - - const id = await lease(host, "console-e2e-events"); - - await expect(granted).toHaveCount(1, { timeout: 1_000 }); - await granted.click(); - await expect(title(page)).toHaveText("lease.granted"); - await expect(page).toHaveURL(/\/activity\/[^/]+$/); - await expect(page.getByText("leaseId", { exact: true })).toBeVisible(); - await expect(page.locator("dd", { hasText: new RegExp(`^${id}$`) })).toBeVisible(); - - await page.getByRole("link", { name: "Open lease" }).click(); - await expect(page).toHaveURL(new RegExp(`/leases/${id}/?$`)); - } finally { - await host.dispose(); - } - }); - - test("the feed 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"); - - 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("choosing a row puts the event in the URL and its payload whole in the inspector", async ({ - page, - }) => { - const host = await startDaemon("worker", { driverScript: { ios: IOS } }); - try { - await lease(host, "console-e2e-choose"); - await openEvents(page, host); - const started = (await cliEvents(host)).find((event) => event.event === "daemon.started"); - expect(started).toBeDefined(); - - await openEvent(page, (started as Envelope).id); - - await expect(page).toHaveURL(new RegExp(`/activity/${(started as Envelope).id}$`)); - await expect(title(page)).toHaveText("daemon.started"); - await expect(page.getByRole("heading", { level: 2, name: "Payload" })).toBeVisible(); - await page.reload(); - await expect(title(page)).toHaveText("daemon.started"); - } finally { - await host.dispose(); - } - }); - - test("an event the feed does not hold says so and links back", async ({ page }) => { - const host = await startDaemon("worker", { driverScript: { ios: IOS } }); - try { - await openEvents(page, host, "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/activity/evt_not_there"); - - await expect(page.getByText("Event not in the last hour.")).toBeVisible(); - await page.getByRole("link", { name: "Back to Activity" }).click(); - await expect(page).toHaveURL(/\/activity$/); - } finally { - await host.dispose(); - } - }); - - test("the filter shows only one subject's events and is kept in the URL", async ({ page }) => { - const host = await startDaemon("worker", { driverScript: { ios: IOS } }); - try { - await lease(host, "console-e2e-filter"); - await openEvents(page, host); - - await page.getByRole("radio", { name: "Leases" }).check({ force: true }); - - await expect(page).toHaveURL(/\?subject=lease$/); - const names = await rows(page).locator("time + span").allTextContents(); - expect(names.length).toBeGreaterThan(0); - expect(names.every((name) => name.startsWith("lease."))).toBe(true); - await page.reload(); - await expect(page.getByRole("radio", { name: "Leases" })).toBeChecked(); - } finally { - await host.dispose(); - } - }); - - test("the feed scrolls inside itself with the keyboard, and counts the events that came in while scrolled down", async ({ - page, - }) => { - const host = await startDaemon("worker", { driverScript: { ios: IOS } }); - try { - for (let index = 0; index < 6; index += 1) await lease(host, `console-e2e-scroll-${index}`); - await openEvents(page, host); - await expect.poll(() => rows(page).count()).toBeGreaterThan(5); - - await feed(page).focus(); - await page.keyboard.press("End"); - await expect.poll(() => feed(page).evaluate((box) => box.scrollTop)).toBeGreaterThan(0); - - await lease(host, "console-e2e-scroll-new"); - const more = page.getByRole("button", { name: /^\d+ new events?$/ }); - await expect(more).toBeVisible(); - await more.click(); - await expect.poll(() => feed(page).evaluate((box) => box.scrollTop)).toBe(0); - await expect(more).toHaveCount(0); - } 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); - - await lease(worker, "console-e2e-label"); - - const granted = rows(page).filter({ hasText: "lease.granted" }); - await expect(granted).toHaveCount(1); - await expect(granted).toContainText("worker-a"); - await granted.click(); - await expect(page.getByText("workerId", { exact: true })).toBeVisible(); - } finally { - await disposeFleet(fleet); - } - }); - - test("a worker joining a gateway shows no join token anywhere in the events page", 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); - const wanted = daemon === worker ? "daemon.started" : "worker.connected"; - await expect(rows(page).filter({ hasText: wanted }), name).not.toHaveCount(0); - const events = await cliEvents(daemon); - await expect.poll(async () => (await shownEvents(page)).length, name).toBe(events.length); - - const seen: string[] = []; - for (const event of events) { - await openEvent(page, event.id); - await expect(title(page)).toHaveText(event.event); - seen.push(await page.locator("#main").innerText()); - } - expect(seen.join("\n"), name).not.toContain(joinToken); - expect(await page.content(), name).not.toContain(joinToken); - - await page.getByRole("button", { name: "Sign out" }).click(); - } - } finally { - await disposeFleet(fleet); - } - }); - - test("the events page has no horizontal scroll at 360px wide, even with the longest payload", 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); - expect(await hasHorizontalScroll(page)).toBe(false); - - const started = (await cliEvents(host)).find((event) => event.event === "daemon.started"); - await openEvent(page, (started as Envelope).id); - await expect(title(page)).toHaveText("daemon.started"); - - expect(await hasHorizontalScroll(page)).toBe(false); - } finally { - await host.dispose(); - } - }); - - test("the events page is usable with the keyboard alone", async ({ browserName, page }) => { - 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(); - } - }); -}); - -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("navigation").first()).toBeVisible(); - - const nav = page.getByRole("link", { name: "Activity", exact: true }); - for (let step = 0; step < 30 && !(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: "Activity" })).toBeVisible(); - await expect(rows(page).filter({ hasText: "lease.granted" })).not.toHaveCount(0); - - const all = page.getByRole("radio", { name: "All" }); - for (let step = 0; step < 30 && !(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("time + span").allTextContents(); - expect(names.length).toBeGreaterThan(0); - expect(names.every((name) => name.startsWith("lease."))).toBe(true); - - for (let step = 0; step < 10 && !(await isFocused(feed(page))); step += 1) { - await page.keyboard.press(tab); - } - await expect(feed(page)).toBeFocused(); - await page.keyboard.press(tab); - await page.keyboard.press("Enter"); - await expect(page).toHaveURL(/\/activity\/[^/?]+\?subject=lease$/); -} - -async function isFocused(locator: Locator): Promise { - return locator.evaluate((element) => element === document.activeElement); -} diff --git a/e2e/console/long-lists.spec.ts b/e2e/console/long-lists.spec.ts index c17de2787..e992ae1de 100644 --- a/e2e/console/long-lists.spec.ts +++ b/e2e/console/long-lists.spec.ts @@ -126,6 +126,18 @@ async function answer(page: Page, pathname: string, body: () => unknown): Promis ); } +// why: a page before the last hour answers with no events, so the stubbed list ends where it did +// before Activity scrolled back. +async function answerEvents(page: Page, replay: readonly unknown[]): Promise { + await page.route( + (url) => url.pathname === "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/v1/events", + async (route: Route) => { + const since = new URL(route.request().url()).searchParams.has("since"); + await route.fulfill({ json: { events: since ? replay : [] } }); + }, + ); +} + /** `count` leases on the one host, `lse_0001` granted first. */ function leases(count: number): unknown[] { const now = Date.now(); @@ -515,7 +527,7 @@ test.describe("the events feed", () => { page, }) => { const replay = events(10_000); - await answer(page, "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/v1/events", () => ({ events: replay })); + await answerEvents(page, replay); await open(page, daemon, "/activity"); await expect.poll(() => eventsHeld(page)).toBe(10_000); @@ -544,7 +556,7 @@ test.describe("the events feed", () => { platform: "ios", }); const replay = events(1_000); - await answer(page, "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/v1/events", () => ({ events: replay })); + await answerEvents(page, replay); await open(page, host, "/activity"); await expect.poll(() => eventsHeld(page)).toBe(1_000); @@ -577,7 +589,7 @@ test.describe("the events feed", () => { platform: "ios", }); const replay = events(1_000); - await answer(page, "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/v1/events", () => ({ events: replay })); + await answerEvents(page, replay); await open(page, host, "/activity"); await expect.poll(() => eventsHeld(page)).toBe(1_000); await scrollDown(page); @@ -616,7 +628,7 @@ test.describe("the events feed", () => { test("choosing another filter starts the feed again at the top", async ({ daemon, page }) => { const replay = events(1_000); - await answer(page, "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/v1/events", () => ({ events: replay })); + await answerEvents(page, replay); await open(page, daemon, "/activity"); await expect.poll(() => eventsHeld(page)).toBe(1_000); await scrollDown(page); diff --git a/e2e/console/waiting.spec.ts b/e2e/console/queue.spec.ts similarity index 67% rename from e2e/console/waiting.spec.ts rename to e2e/console/queue.spec.ts index 7a91b9af5..8990152d0 100644 --- a/e2e/console/waiting.spec.ts +++ b/e2e/console/queue.spec.ts @@ -3,7 +3,6 @@ import type { Locator, Page } from "@playwright/test"; import { waitFor } from "../helpers/wait.js"; import { expect, type RunningDaemon, settled, signIn, startDaemon, test } from "./fixtures.js"; -/** What `GET /v1/lease-requests` answers, as far as these tests read. */ interface WaitingRequest { readonly id: string; readonly requesterId: string; @@ -12,18 +11,15 @@ interface WaitingRequest { } const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; -/** One iOS device and no more, so a second request waits. */ const ONE_DEVICE = { limits: { ios: { maxDevices: 1, maxRunning: 1 }, maxRunning: 1 } }; const LEASE = ["lease", "--platform", "ios", "--device", "iPhone 16", "--os", "18.4"] as const; -/** Leases the host's one device for `agent`, and answers the lease id. */ async function holdTheDevice(daemon: RunningDaemon, agent: string): Promise { const granted = await daemon.cli([...LEASE, "--agent-id", agent, "--detach"]); expect(granted.code, granted.stderr).toBe(0); return (granted.json as { lease: { id: string } }).lease.id; } -/** The daemon's own `GET /v1/lease-requests`, asked as an operator. */ async function waiting(daemon: RunningDaemon): Promise { const response = await fetch(new URL("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/v1/lease-requests", daemon.url), { headers: { Authorization: `Bearer ${daemon.tokens.operator}` }, @@ -33,7 +29,7 @@ async function waiting(daemon: RunningDaemon): Promise { await page.goto(new URL(path, daemon.url).toString()); await signIn(page, daemon.tokens.operator); - await expect(page.getByRole("heading", { level: 1, name: "Queue" })).toBeVisible(); + // why: a drawer over the page hides the page's heading from the accessibility tree. + if (new URL(path, daemon.url).pathname === "/queue") { + await expect(page.getByRole("heading", { level: 1, name: "Queue" })).toBeVisible(); + } else await expect(page.getByRole("dialog")).toBeVisible(); } function row(page: Page, requester: string): Locator { - return page - .getByRole("list", { name: "Waiting requests" }) - .getByRole("link") - .filter({ hasText: requester }); + return page.locator("main tbody tr").filter({ hasText: requester }); } -function inspectorOf(page: Page, requester: string): Locator { - return page.getByRole("region", { name: requester, exact: true }); +function drawerOf(page: Page, requester: string): Locator { + return page.getByRole("dialog", { name: requester, exact: true }); } -/** Whether the page itself scrolls sideways. */ async function hasHorizontalScroll(page: Page): Promise { return page.evaluate( () => document.documentElement.scrollWidth > document.documentElement.clientWidth, ); } -test.describe("the Waiting page", () => { - test("a request waiting for a device appears in the list with its place, device and stage, and opens with its time waited", async ({ +test.describe("the Queue page", () => { + test("Queue lists each waiting request with place, requester, device, stage, why and wait, and a row opens its drawer with the inspector's facts", async ({ page, }) => { const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); @@ -92,19 +87,21 @@ test.describe("the Waiting page", () => { await expect(row(page, "agent-c")).toContainText("iOS iPhone 16, runtime 18.4, mode slim"); await expect(page.getByText("2 waiting")).toBeVisible(); - // why: With no request named, the first row is the one shown, and the URL stays as it was. - await expect(page.getByRole("heading", { level: 2, name: "agent-b" })).toBeVisible(); + await expect(row(page, "agent-b")).toContainText("Full: device limit"); + await expect(row(page, "agent-b").locator("td").last()).toHaveText(/^\d+ s|\d+ min/); + await expect(page.getByRole("dialog")).toHaveCount(0); expect(new URL(page.url()).pathname).toBe("/queue"); - await row(page, "agent-c").click(); - await expect(page.getByRole("heading", { level: 2, name: "agent-c" })).toBeVisible(); + await row(page, "agent-c").getByRole("link", { name: "agent-c" }).click(); + const drawer = drawerOf(page, "agent-c"); + await expect(drawer).toBeVisible(); expect(new URL(page.url()).pathname).toMatch(/^\/queue\/.+/); - const inspector = inspectorOf(page, "agent-c"); - await expect(inspector).toContainText("wants iOS iPhone 16, runtime 18.4, mode slim"); - await expect(inspector).toContainText("2 of 2"); - await expect(inspector.getByRole("navigation", { name: "Breadcrumb" })).toBeVisible(); - // The time waited counts on in the browser, with no reload. - const waited = inspector.locator(".waiting-card-value").first(); + for (const label of ["Waiting", "Place", "Stage", "Device", "Queue", "Why"]) { + await expect(drawer.locator("dt", { hasText: new RegExp(`^${label}$`) })).toHaveCount(1); + } + await expect(drawer).toContainText("2 of 2"); + await expect(drawer).toContainText("iOS iPhone 16, runtime 18.4, mode slim"); + const waited = drawer.locator("dd").first(); const before = await waited.textContent(); await expect(waited).not.toHaveText(before ?? "", { timeout: 3_000 }); } finally { @@ -129,7 +126,7 @@ test.describe("the Waiting page", () => { }, driverScript: { ios: IOS }, }); - // A local agent on the worker takes the fleet's one device, and a second one waits in the + // why: A local agent on the worker takes the fleet's one device, and a second one waits in the // worker's own queue. A further lease through the gateway then waits in the gateway's. await holdTheDevice(worker, "local-a"); worker.cliBackground([...LEASE, "--agent-id", "local-b"]); @@ -143,13 +140,14 @@ test.describe("the Waiting page", () => { await openWaiting(page, gateway); - await row(page, "local-b").click(); - const local = inspectorOf(page, "local-b"); + await row(page, "local-b").getByRole("link").click(); + const local = drawerOf(page, "local-b"); await expect(local.getByRole("link", { name: "worker-a" })).toBeVisible(); await expect(local).toContainText("1 of 1"); + await page.keyboard.press("Escape"); - await row(page, "fleet-c").click(); - const fleet = inspectorOf(page, "fleet-c"); + await row(page, "fleet-c").getByRole("link").click(); + const fleet = drawerOf(page, "fleet-c"); await expect(fleet).toContainText("the gateway's queue"); await expect(fleet).toContainText("iOS iPhone 16, runtime 18.4"); await expect(fleet).toContainText("queued"); @@ -160,7 +158,7 @@ test.describe("the Waiting page", () => { } }); - test("a waiting request leaves the list within a second of being granted, and its own page says it is not waiting", async ({ + test("a request that is granted while its drawer is open leaves the list within a second, and the drawer says Request not waiting", async ({ page, }) => { const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); @@ -169,8 +167,8 @@ test.describe("the Waiting page", () => { const waiter = host.cliBackground([...LEASE, "--agent-id", "agent-b"]); await untilTheDaemonSays(host, (requests) => requests.length === 1); await openWaiting(page, host); - await row(page, "agent-b").click(); - await expect(page.getByRole("heading", { level: 2, name: "agent-b" })).toBeVisible(); + await row(page, "agent-b").getByRole("link").click(); + await expect(drawerOf(page, "agent-b")).toBeVisible(); expect((await host.cli(["release", held])).code).toBe(0); const grant = JSON.parse(await waiter.firstStdoutLine(10_000)) as { @@ -179,14 +177,12 @@ test.describe("the Waiting page", () => { expect(grant.lease.requesterId).toBe("agent-b"); await untilTheDaemonSays(host, (requests) => requests.length === 0); - await expect(row(page, "agent-b")).toHaveCount(0, { timeout: 1_000 }); - await expect(page.getByText("No requests are waiting.")).toBeVisible(); - await expect(page.getByText("Request not waiting.")).toBeVisible(); - - await page.getByRole("link", { name: "Back to Queue" }).click(); + await expect(page.getByText("Request not waiting.")).toBeVisible({ timeout: 1_000 }); + await page.keyboard.press("Escape"); expect(new URL(page.url()).pathname).toBe("/queue"); - await expect(page.getByText("Request not waiting.")).toHaveCount(0); - await expect(page.getByRole("heading", { level: 2 })).toHaveCount(0); + await expect(row(page, "agent-b")).toHaveCount(0); + await expect(page.getByText("No requests are waiting.")).toBeVisible(); + await expect(page.getByRole("dialog")).toHaveCount(0); } finally { await host.dispose(); } @@ -197,14 +193,33 @@ test.describe("the Waiting page", () => { try { await openWaiting(page, host, "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/queue/req_none"); - await expect(page.getByText("Request not waiting.")).toBeVisible(); - await expect(page.getByRole("link", { name: "Back to Queue" })).toBeVisible(); + await expect(page.getByRole("dialog").getByText("Request not waiting.")).toBeVisible(); + } finally { + await host.dispose(); + } + }); + + test("loaded directly at a request's address, closing the drawer replaces the address with /queue", async ({ + page, + }) => { + const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); + try { + await openWaiting(page, host, "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/queue/req_none"); + const drawer = page.getByRole("dialog"); + await expect(drawer).toBeVisible(); + const entries = await page.evaluate(() => window.history.length); + + await page.keyboard.press("Escape"); + + await expect(drawer).toHaveCount(0); + expect(new URL(page.url()).pathname).toBe("/queue"); + expect(await page.evaluate(() => window.history.length)).toBe(entries); } finally { await host.dispose(); } }); - test("the Waiting page has no horizontal scroll at 360px wide", async ({ page }) => { + test("the Queue page has no horizontal scroll at 360px wide", async ({ page }) => { const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); try { await holdTheDevice(host, "holder"); @@ -220,12 +235,10 @@ test.describe("the Waiting page", () => { await openWaiting(page, host); - await expect( - page.getByRole("list", { name: "Waiting requests" }).getByRole("link"), - ).toHaveCount(1); + await expect(page.locator("main tbody tr")).toHaveCount(1); expect(await hasHorizontalScroll(page)).toBe(false); - await page.getByRole("list", { name: "Waiting requests" }).getByRole("link").click(); - await expect(page.getByRole("heading", { level: 2 })).toBeVisible(); + await page.locator("main tbody tr").getByRole("link").click(); + await expect(page.getByRole("dialog")).toBeVisible(); await settled(page); expect(await hasHorizontalScroll(page)).toBe(false); } finally { @@ -233,8 +246,8 @@ test.describe("the Waiting page", () => { } }); - test("the Waiting page is usable with the keyboard alone", async ({ browserName, page }) => { - // Safari moves focus to links with Option-Tab; plain Tab reaches only form controls there. + test("the Queue page is usable with the keyboard alone", async ({ browserName, page }) => { + // why: 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", { config: ONE_DEVICE, driverScript: { ios: IOS } }); try { @@ -255,12 +268,12 @@ test.describe("the Waiting page", () => { await page.keyboard.press("Enter"); await expect(page.getByRole("heading", { level: 1, name: "Queue" })).toBeVisible(); - await follow(row(page, "agent-b")); - await expect(page.getByRole("heading", { level: 2, name: "agent-b" })).toBeVisible(); + await follow(row(page, "agent-b").getByRole("link")); + await expect(drawerOf(page, "agent-b")).toBeVisible(); expect(new URL(page.url()).pathname).toMatch(/^\/queue\/.+/); - // The request's worker opens that worker's page. - await follow(inspectorOf(page, "agent-b").getByRole("link").last()); + // why: The request's worker opens that worker's page. + await follow(drawerOf(page, "agent-b").getByRole("link").last()); expect(new URL(page.url()).pathname).toMatch(/^\/fleet\/.+/); } finally { await host.dispose(); diff --git a/e2e/console/views.spec.ts b/e2e/console/views.spec.ts index 073655265..6d7591ae7 100644 --- a/e2e/console/views.spec.ts +++ b/e2e/console/views.spec.ts @@ -21,6 +21,8 @@ interface Pages { readonly worker: string; readonly device: string; readonly lease: string; + readonly request: string; + readonly event: string; } async function takeLease(host: RunningDaemon, agent: string): Promise { @@ -36,11 +38,19 @@ async function hostWithLease(): Promise<{ readonly host: RunningDaemon; readonly const [worker] = (listed.json as { workers: { id: string; leases: { deviceId: string }[] }[] }) .workers; const workerPath = `/fleet/${encodeURIComponent(worker?.id ?? "")}`; + const replay = await fetch(new URL("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/v1/events?since=1h", host.url), { + headers: { Authorization: `Bearer ${host.tokens.operator}` }, + }); + const granted = ( + (await replay.json()) as { events: { event: string; id: string }[] } + ).events.find((entry) => entry.event === "lease.granted"); return { host, pages: { device: `${workerPath}/${encodeURIComponent(worker?.leases[0]?.deviceId ?? "")}?tab=devices`, + event: `/activity/${encodeURIComponent(granted?.id ?? "")}`, lease: `/leases/${encodeURIComponent(lease)}/`, + request: "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/queue/req_none", views: NAV.map((entry) => ({ label: entry.label, path: entry.path })), worker: workerPath, }, @@ -48,7 +58,14 @@ async function hostWithLease(): Promise<{ readonly host: RunningDaemon; readonly } function every(pages: Pages): readonly string[] { - return [...pages.views.map((view) => view.path), pages.worker, pages.device, pages.lease]; + return [ + ...pages.views.map((view) => view.path), + pages.worker, + pages.device, + pages.lease, + pages.request, + pages.event, + ]; } async function openSignedIn(page: Page, host: RunningDaemon): Promise { @@ -59,7 +76,7 @@ async function openSignedIn(page: Page, host: RunningDaemon): Promise { // why: an open drawer hides the page behind it from assistive technology. function opensDrawer(path: string): boolean { - return /^\/leases\/./.test(path) || /^\/fleet\/[^/?]+\/./.test(path); + return /^\/(leases|queue|activity)\/./.test(path) || /^\/fleet\/[^/?]+\/./.test(path); } async function visit(page: Page, host: RunningDaemon, path: string): Promise { @@ -92,7 +109,10 @@ test.describe("every view", () => { for (const path of every(pages)) { await visit(page, host, path); - for (const summary of await page.locator("#main summary").all()) await summary.click(); + // why: a drawer makes the page behind it inert, so its disclosures cannot be opened. + if (!opensDrawer(path)) { + for (const summary of await page.locator("#main summary").all()) await summary.click(); + } expect(await hasHorizontalScroll(page), path).toBe(false); } } finally { @@ -256,7 +276,7 @@ test.describe("every view", () => { await visit(page, host, path); if (opensDrawer(path)) await expect(page.getByRole("dialog")).toBeVisible(); const chart = page.locator(".chart svg").first(); - if ((await chart.count()) > 0) { + if (!opensDrawer(path) && (await chart.count()) > 0) { await chart.hover(); await expect(page.locator(".chart-tip")).toBeVisible(); await page.locator("#main summary").first().click(); @@ -274,14 +294,22 @@ test.describe("every view", () => { }); for (const colorScheme of ["light", "dark"] as const) { - test(`Fleet, a worker page and a device drawer pass an automated WCAG AA check (${colorScheme})`, async ({ + test(`Fleet, a worker page, a device drawer, and Queue and Activity with a drawer open pass an automated WCAG AA check (${colorScheme})`, async ({ page, }) => { const { host, pages } = await hostWithLease(); try { await page.emulateMedia({ colorScheme }); await openSignedIn(page, host); - for (const path of ["/fleet", pages.worker, pages.device]) { + for (const path of [ + "/fleet", + pages.worker, + pages.device, + "/queue", + pages.request, + "/activity", + pages.event, + ]) { await visit(page, host, path); if (opensDrawer(path)) await expect(page.getByRole("dialog")).toBeVisible(); const results = await new AxeBuilder({ page }) diff --git a/ui/AGENTS.md b/ui/AGENTS.md index 49d25482b..2d5bb18a1 100644 --- a/ui/AGENTS.md +++ b/ui/AGENTS.md @@ -59,16 +59,22 @@ fails leaves none. `useDaemonMode` (`state/live.tsx`) gives it to state (ADR 003 | `/` | Overview | stat tiles, range picker, three charts, capacity, workers table, attention, activity | | `/fleet[/[/]]` | Fleet | table; a worker opens as its own page (load, capacity, leases, tabs Devices, Warm pool, Host, Events in `?tab=`); a device opens in a `Drawer` | | `/leases[/]` | Leases | toolbar (filters, search) + table; the lease opens in a `Drawer` (Details, Screen, Events) | -| `/queue[/]` | Queue | Wait p95 tile, list + inspector | +| `/queue[/]` | Queue | Wait p95 tile + table; a request opens in a `Drawer` | | `/attention[/]` | Attention | list + inspector | -| `/activity[/]` | Activity | list + inspector with the payload | +| `/activity[/]` | Activity | chart, toolbar (type chips, search) + event feed that scrolls back through the history; an event opens in a `Drawer` with the payload | | `/usage` | Usage | range picker, stat tiles, panels of tables (workers, requesters page in the URL) | The sidebar groups the pages: Overview and Attention, then Operate (Fleet, Leases, Queue), then Observe (Activity, Usage); a route's `group` in `routes.ts` puts it in one. -On a list page (Queue, Attention, Activity) the URL names the chosen item; with none, the first item shows on a wide screen -and the list alone on a phone (Leases shows the list alone, and a lease opens in a drawer over it). +On a list page (Attention) the URL names the chosen item; with none, the first item shows on a wide screen +and the list alone on a phone. Leases, Queue and Activity show the list alone, and the chosen item opens in a drawer over it +(`state/drawer.ts`: closing steps back when the drawer was opened from the list). + +Activity's `EventFeed` (`data/event-feed.ts`) holds the events: the stream, the last hour and the gap after a reconnect add +newer ones, and `loadOlder` adds the 100 before the oldest held (`GET /v1/events?before=&limit=100`, or `?limit=100` with +none held). It reports how the history stands (`HistoryState`: more, start, gone, failed); `ds/feed.tsx` calls `onNearEnd` +within 20 rows of the end and draws the end row. Lists page in the URL (`state/paging.ts`, `model/paging.ts`). ## Design system diff --git a/ui/src/app/routes.ts b/ui/src/app/routes.ts index a890a08a4..5b2d47cfa 100644 --- a/ui/src/app/routes.ts +++ b/ui/src/app/routes.ts @@ -2,11 +2,11 @@ import type { ComponentType } from "react"; import type { IconName } from "../ds"; import { AttentionScreen } from "../screens/attention"; -import { EventsScreen } from "../screens/events"; +import { ActivityScreen } from "../screens/activity"; import { LeasesScreen } from "../screens/leases"; import { OverviewScreen } from "../screens/overview"; import { UsageScreen } from "../screens/usage"; -import { WaitingScreen } from "../screens/waiting"; +import { QueueScreen } from "../screens/queue"; import { FleetScreen } from "../screens/fleet"; export type NavGroup = "Operate" | "Observe"; @@ -24,8 +24,14 @@ export const ROUTES: readonly Route[] = [ { Screen: AttentionScreen, icon: "attention", label: "Attention", path: "/attention" }, { Screen: FleetScreen, group: "Operate", icon: "workers", label: "Fleet", path: "/fleet" }, { Screen: LeasesScreen, group: "Operate", icon: "leases", label: "Leases", path: "/leases" }, - { Screen: WaitingScreen, group: "Operate", icon: "waiting", label: "Queue", path: "/queue" }, - { Screen: EventsScreen, group: "Observe", icon: "events", label: "Activity", path: "/activity" }, + { Screen: QueueScreen, group: "Operate", icon: "waiting", label: "Queue", path: "/queue" }, + { + Screen: ActivityScreen, + group: "Observe", + icon: "events", + label: "Activity", + path: "/activity", + }, { Screen: UsageScreen, group: "Observe", icon: "usage", label: "Usage", path: "/usage" }, ]; diff --git a/ui/src/data/event-feed.test.ts b/ui/src/data/event-feed.test.ts index a9bc675b9..b133371db 100644 --- a/ui/src/data/event-feed.test.ts +++ b/ui/src/data/event-feed.test.ts @@ -41,23 +41,36 @@ function eventLog( }; } -function openView(first: Replay = []) { +function openView(first: Replay = [], showsHistory = false) { const live = connect(); const replays: ApiPath[] = []; + const olderReads: ApiPath[] = []; let replay: Replay = first; live.daemon.reads = async (path) => { if (!path.startsWith("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/v1/events?")) return { body: {}, date: null }; + if (!path.includes("since=")) { + olderReads.push(path); + return { + body: typeof replay === "function" ? await replay(path) : { events: [] }, + 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); + const feed = new EventFeed( + async (path) => (await live.daemon.get(path)).body, + fakeClock, + showsHistory, + ); live.connection.onEvent(feed.streamEvent); live.connection.onStreamOpened(feed.streamOpened); const stop = feed.start(); return { ...live, feed, + olderReads, replays, stop, replayWith(next: Replay) { @@ -474,4 +487,48 @@ describe("the event feed's loads", () => { expect(view.replays.slice(3)).toEqual(["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/v1/events?since=5s"]); expect(view.shown()).toEqual([`1@${T0}`]); }); + + it("an event the stream brings while an older page loads shows once, at the top, and a second signal before the answer asks for nothing", async () => { + const older = envelope(1, T0 - 10_000); + let release: () => void = () => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + const view = openView((path) => + path.includes("before=") + ? gate.then(() => ({ events: [older] })) + : Promise.resolve({ events: [envelope(5, T0)] }), + ); + await settle(); + + view.feed.loadOlder(); + view.feed.loadOlder(); + view.daemon.openStream()?.send(frame(envelope(6, T0 + 1_000))); + view.daemon.openStream()?.send(frame(envelope(6, T0 + 1_000))); + await settle(); + release(); + await settle(); + + expect(view.shown()).toEqual([`6@${T0 + 1_000}`, `5@${T0}`, `1@${T0 - 10_000}`]); + expect(view.olderReads).toEqual([`/v1/events?before=evt_5_${T0}&limit=100`]); + }); + + it("asks for the newest page of older events at once when the last hour is empty, only on a feed that shows the history", async () => { + const history = openView([], true); + const recent = openView([]); + await settle(); + + expect(history.olderReads).toEqual(["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/v1/events?limit=100"]); + expect(recent.olderReads).toEqual([]); + }); + + it("a refused first read on a feed that shows the history asks for the newest page of older events", async () => { + const view = openView( + () => Promise.reject(new ApiError(500, "INTERNAL", "Internal error")), + true, + ); + await settle(); + + expect(view.olderReads).toEqual(["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/v1/events?limit=100"]); + }); }); diff --git a/ui/src/data/event-feed.ts b/ui/src/data/event-feed.ts index 634010161..5b441268b 100644 --- a/ui/src/data/event-feed.ts +++ b/ui/src/data/event-feed.ts @@ -1,4 +1,4 @@ -import type { ApiPath } from "./api"; +import { ApiError, type ApiPath } from "./api"; import { type Clock, isRefusal, @@ -8,8 +8,12 @@ import { } from "./live/connection"; import { type ConsoleEvent, + type HistoryState, + MAX_EVENTS, mergeEvents, + OLDER_PAGE as PAGE, readEvent, + readOlder, readReplay, RECENT, sinceFor, @@ -28,15 +32,22 @@ export class EventFeed { #needRecent = true; #gapFrom: number | undefined; #loading = false; + #loadingOlder = false; + #history: HistoryState = "more"; // why: counts the stream's opens, so a load knows whether one happened while it was out. #opens = 0; #retryTimer: unknown; #retryAttempt = 0; #active = false; - constructor(get: (path: ApiPath) => Promise, clock: Clock) { + readonly #showsHistory: boolean; + + // why: only a screen that scrolls back through the history asks for it; the others read the last + // hour and nothing older, so a quiet hour does not fill their lists with older events. + constructor(get: (path: ApiPath) => Promise, clock: Clock, showsHistory = false) { this.#get = get; this.#clock = clock; + this.#showsHistory = showsHistory; } start(): () => void { @@ -101,6 +112,8 @@ export class EventFeed { this.#events = mergeEvents(this.#events, events); this.#publish({ data: this.#events }); this.#loadMissing(); + // why: a quiet last hour still shows the older history, so the newest page is asked for at once. + if (this.#showsHistory && this.#events.length === 0) this.loadOlder(); }, (error: unknown) => { this.#loading = false; @@ -111,10 +124,48 @@ export class EventFeed { } this.#settled = true; this.#publish({ data: this.#events, error }); + // why: a refused last hour still leaves the older history to show, so it is asked for as for an empty one. + if (this.#showsHistory && this.#events.length === 0) this.loadOlder(); }, ); } + readonly history = (): HistoryState => this.#history; + + // why: one page at a time, none once the history has ended, and none at the cap: a second signal + // before the answer is dropped. + readonly loadOlder = (): void => { + if (!this.#active || this.#loadingOlder || this.#events.length >= MAX_EVENTS) return; + if (this.#history !== "more" && this.#history !== "failed") return; + const oldest = this.#events.at(-1); + const query = + oldest === undefined + ? `limit=${PAGE}` + : `before=${encodeURIComponent(oldest.id)}&limit=${PAGE}`; + this.#loadingOlder = true; + this.#get(`/v1/events?${query}`) + .then(readOlder) + .then( + (page) => { + this.#loadingOlder = false; + if (!this.#active) return; + const current = this.#events; + this.#events = mergeEvents(current, page.events); + this.#setHistory(page.full && this.#events !== current ? "more" : "start"); + }, + (error: unknown) => { + this.#loadingOlder = false; + if (!this.#active) return; + this.#setHistory(error instanceof ApiError && error.status === 422 ? "gone" : "failed"); + }, + ); + }; + + #setHistory(history: HistoryState): void { + this.#history = history; + this.#publish({ ...this.#state, data: this.#events }); + } + #retryLater(): void { const delay = RETRY_BACKOFF_MS[this.#retryAttempt] ?? RETRY_INTERVAL_MS; this.#retryAttempt += 1; diff --git a/ui/src/ds/feed.css b/ui/src/ds/feed.css index b7f8455fc..2834435bb 100644 --- a/ui/src/ds/feed.css +++ b/ui/src/ds/feed.css @@ -39,3 +39,15 @@ background: var(--bg); transform: translateX(-50%); } + +/* The last row: why the list stops, below the scrolling box and outside the list. */ +.feed-end { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); + margin: 0; + padding: var(--space-3) var(--space-4); + border-top: 1px solid var(--border); + font-size: var(--text-sm); +} diff --git a/ui/src/ds/feed.tsx b/ui/src/ds/feed.tsx index 402390d58..775913a58 100644 --- a/ui/src/ds/feed.tsx +++ b/ui/src/ds/feed.tsx @@ -10,6 +10,9 @@ const BOX_HEIGHT_PX = 640; // why: rows drawn past each edge of the box, so a short scroll shows rows already there. const OVERSCAN = 5; +// why: how close to the last row the last drawn row must be before the list asks for more. +const NEAR_END_ROWS = 20; + // why: only the rows in view, and a few past each edge, are in the page; the space of the rest is // padding, so the scroll bar is as long as every row. New rows come in at the top: while the box // is at the top they push the rows down, so the newest is always in view; once the reader scrolls @@ -23,9 +26,23 @@ export function Feed(props: { readonly keyAt: (index: number) => string; readonly newText: (count: number) => string; readonly startAt?: number; + readonly onNearEnd?: (() => void) | undefined; + // why: below the scrolling box, outside the list, so it never counts as a row. + readonly footer?: ReactNode; readonly renderRow: (index: number) => ReactNode; }) { - const { count, keyAt, label, listLabel, newText, renderRow, rowHeight, startAt = 0 } = props; + const { + count, + footer, + keyAt, + label, + listLabel, + newText, + onNearEnd, + renderRow, + rowHeight, + startAt = 0, + } = props; const box = useRef(null); const [atTop, setAtTop] = useState(true); const unseen = useUnseen(count, keyAt, atTop); @@ -44,6 +61,7 @@ export function Feed(props: { box.current?.focus(); }; const items = virtualizer.getVirtualItems(); + useNearEnd(items.at(-1)?.index, count, onNearEnd); const before = items[0]?.start ?? 0; const after = Math.max(0, virtualizer.getTotalSize() - (items.at(-1)?.end ?? 0)); return ( @@ -71,10 +89,21 @@ export function Feed(props: { ))} + {footer} ); } +// why: the callback is read through a ref, so a new function on each render does not ask again; +// only a change in the last drawn row or in the count does. +function useNearEnd(last: number | undefined, count: number, onNearEnd: (() => void) | undefined) { + const callback = useRef(onNearEnd); + callback.current = onNearEnd; + useEffect(() => { + if (last !== undefined && last >= count - NEAR_END_ROWS) callback.current?.(); + }, [last, count]); +} + function useUnseen(count: number, keyAt: (index: number) => string, atTop: boolean): number { const newest = count === 0 ? undefined : keyAt(0); // why: the newest row the reader saw at the top of the box: every row above it is new to them. diff --git a/ui/src/ds/focus-after-drawer.ts b/ui/src/ds/focus-after-drawer.ts new file mode 100644 index 000000000..26fab80cc --- /dev/null +++ b/ui/src/ds/focus-after-drawer.ts @@ -0,0 +1,16 @@ +// why: focus goes back to the row that opened the drawer, or to the page's heading when that row is +// gone or the drawer was loaded directly. A row's link is found by its path alone, trailing slash +// and query set aside, so `evt_1` does not match `evt_10`. +export function focusAfterClosing(options: { + readonly fromList: boolean; + readonly path: string; + readonly links: string; +}): HTMLElement | null { + const { fromList, links, path } = options; + const row = fromList + ? [...document.querySelectorAll(links)].find( + (link) => link.getAttribute("href")?.split("?", 1)[0]?.replace(/\/$/, "") === path, + ) + : undefined; + return row ?? document.querySelector("main h1"); +} diff --git a/ui/src/ds/index.ts b/ui/src/ds/index.ts index 6a6de3431..fcfdeb65e 100644 --- a/ui/src/ds/index.ts +++ b/ui/src/ds/index.ts @@ -21,3 +21,4 @@ export { StatRow, StatTile } from "./stat"; export { Status, StatusDot } from "./status"; export { type Column, DataTable } from "./table"; export { Toolbar } from "./toolbar"; +export { focusAfterClosing } from "./focus-after-drawer"; diff --git a/ui/src/model/event-list.test.ts b/ui/src/model/event-list.test.ts index c8a3ea22c..13e280244 100644 --- a/ui/src/model/event-list.test.ts +++ b/ui/src/model/event-list.test.ts @@ -120,6 +120,29 @@ describe("a list row", () => { }); }); +describe("a search of the list", () => { + const events = [ + event("lease.granted", { requester: "claude-1", token: "Marker-Value" }, 1), + event("worker.connected", { workerId: "wrk_1" }, 2), + event("device.ready", { deviceId: "dev_1" }, 3), + ]; + const found = (query: string) => + eventRows(events, [worker("wrk_1", "Mac Studio")], "all", query).map((row) => row.name); + + it("matches part of the event name or the summary line, ignoring case, and no other payload value", () => { + expect(found("")).toEqual(["lease.granted", "worker.connected", "device.ready"]); + expect(found("GRANT")).toEqual(["lease.granted"]); + expect(found("ice.rea")).toEqual(["device.ready"]); + expect(found("mac stu")).toEqual(["worker.connected"]); + expect(found("CLAUDE")).toEqual(["lease.granted"]); + expect(found("marker-value")).toEqual([]); + expect(found("dev_1")).toEqual([]); + expect(eventRows(events, [], "lease", "grant")[0]?.to).toBe( + "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/activity/evt_1?subject=lease&q=grant", + ); + }); +}); + describe("an event's day", () => { const noon = new Date(2026, 9, 2, 12, 0, 0).getTime(); @@ -263,32 +286,19 @@ describe("the events chart", () => { describe("the event chosen", () => { const events = [event("lease.granted", {}, 2), event("device.ready", {}, 1)]; - const rows = eventRows(events, [], "all"); - const choose = (id: string | undefined, shown = rows) => - chosenEvent(events, shown, id, NO_PLACES, T0); + const choose = (id: string | undefined) => chosenEvent(events, id, NO_PLACES, T0); - it("is the one the URL names", () => { + it("is the one the URL names, even one a filter or a search hides", () => { const chosen = choose("evt_1"); expect(chosen.kind === "event" && chosen.detail.name).toBe("device.ready"); }); - it("is the first row when the URL names none", () => { - const chosen = choose(undefined); - - expect(chosen.kind === "event" && chosen.detail.id).toBe("evt_2"); - }); - - it("opens an event the filter hides", () => { - const filtered = eventRows(events, [], "lease"); - - const chosen = choose("evt_1", filtered); - - expect(chosen.kind === "event" && chosen.detail.id).toBe("evt_1"); + it("is none when the URL names none, so the drawer stays shut", () => { + expect(choose(undefined)).toEqual({ kind: "none" }); }); - it("is missing for an id the feed does not hold, and none for an empty feed", () => { + it("is missing for an id the feed does not hold", () => { expect(choose("evt_gone")).toEqual({ id: "evt_gone", kind: "missing" }); - expect(chosenEvent([], [], undefined, NO_PLACES, T0)).toEqual({ kind: "none" }); }); }); diff --git a/ui/src/model/event-list.ts b/ui/src/model/event-list.ts index 357744d78..b4fb50685 100644 --- a/ui/src/model/event-list.ts +++ b/ui/src/model/event-list.ts @@ -11,7 +11,7 @@ import { } from "./events"; import { eventsPerMinute, extremes, type MinuteCount } from "./history"; import { type LeaseRecord, leasePath } from "./leases"; -import { formatCount } from "./paging"; +import { formatCount, writeQuery } from "./paging"; import { itemPath } from "./paths"; import type { Tone } from "./tones"; import type { WaitingRequest } from "./waiting"; @@ -60,7 +60,7 @@ function startOfDay(timestamp: number): number { return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); } -// why: the feed holds an hour, so an event can be from before midnight, and "today" would then be +// why: the feed holds days of history, so an event can be from before midnight, and "today" would then be // false. export function dayWord(timestamp: number, now: number): string { const days = Math.round((startOfDay(now) - startOfDay(timestamp)) / DAY); @@ -79,14 +79,16 @@ export interface EventRow { readonly summary: string; } -// why: a row keeps the filter in its link, so choosing an event does not undo the filter. +// why: a row keeps the filter and the search in its link, so choosing an event does not undo them. export function eventRows( events: readonly ConsoleEvent[], workers: readonly WorkerView[], subject: SubjectFilter, + search = "", ): readonly EventRow[] { - const query = writeSubject("", subject); - return shownEvents(events, subject).map((event) => { + const query = writeQuery(writeSubject("", subject), search); + const wanted = search.toLowerCase(); + const rows = shownEvents(events, subject).map((event) => { const tone = eventTone(event.event); return { id: event.id, @@ -98,6 +100,14 @@ export function eventRows( ...(tone === undefined ? {} : { tone }), }; }); + // why: the match is over what a row shows, its name and its summary line, and over no other + // part of the payload. + return wanted === "" + ? rows + : rows.filter( + (row) => + row.name.toLowerCase().includes(wanted) || row.summary.toLowerCase().includes(wanted), + ); } export interface EventAction { @@ -196,19 +206,17 @@ export type Chosen = | { readonly kind: "missing"; readonly id: string } | { readonly kind: "event"; readonly detail: EventDetail }; -// why: with no id in the URL the first row shows, so a wide screen is never half empty; an id the -// feed does not hold (older than the hour, or not loaded yet) is said so, not guessed at. An id is -// looked up among every event held, so an event the filter hides still opens. +// why: the drawer opens only for an id in the URL; an id the console does not hold (older than +// what has loaded) is said so, not guessed at. An id is looked up among every event held, so an +// event the filter or the search hides still opens. export function chosenEvent( events: readonly ConsoleEvent[], - rows: readonly EventRow[], id: string | undefined, places: EventPlaces, now: number, ): Chosen { - const wanted = id ?? rows[0]?.id; - if (wanted === undefined) return { kind: "none" }; - const event = events.find((entry) => entry.id === wanted); - if (event === undefined) return { id: wanted, kind: "missing" }; + if (id === undefined) return { kind: "none" }; + const event = events.find((entry) => entry.id === id); + if (event === undefined) return { id, kind: "missing" }; return { detail: eventDetail(event, places, now), kind: "event" }; } diff --git a/ui/src/model/events.test.ts b/ui/src/model/events.test.ts index becbebabc..ecc0cdf2e 100644 --- a/ui/src/model/events.test.ts +++ b/ui/src/model/events.test.ts @@ -3,9 +3,11 @@ import { describe, expect, it } from "vitest"; import { type ConsoleEvent, eventsOfWorker, + MAX_EVENTS, mergeEvents, payloadPairs, readEvent, + readOlder, readReplay, sinceFor, subjectOf, @@ -67,6 +69,40 @@ describe("the events the console holds", () => { }); }); +describe("the events an older page adds", () => { + const at = (seq: number): ConsoleEvent => ({ + ...event("lease.renewed", {}, seq), + timestamp: T0 + seq, + }); + + it("go below the newer ones in order, show once an event the stream also brought, and give way to the newer ones past the cap", () => { + const held = [at(9), at(8), at(7)]; + const page = [at(4), at(5), at(6), at(7)]; + + const merged = mergeEvents(held, page); + + expect(merged.map((entry) => entry.seq)).toEqual([9, 8, 7, 6, 5, 4]); + const full = Array.from({ length: MAX_EVENTS }, (_, index) => at(1_000 + MAX_EVENTS - index)); + const capped = mergeEvents(full.slice(0, MAX_EVENTS - 2), [at(3), at(2), at(1)]); + expect(capped).toHaveLength(MAX_EVENTS); + expect(capped.at(-1)?.seq).toBe(2); + }); +}); + +describe("a page of older events", () => { + it("is full when the reply held 100 events, even if some were malformed, and not full with 99", () => { + const body = (count: number) => ({ + events: Array.from({ length: count }, (_, index) => + index === 0 ? { malformed: true } : event("lease.renewed", {}, index), + ), + }); + + expect(readOlder(body(100)).full).toBe(true); + expect(readOlder(body(100)).events).toHaveLength(99); + expect(readOlder(body(99)).full).toBe(false); + }); +}); + describe("the gap to load after the stream was closed", () => { it("is rounded up to whole seconds, so its first event is inside the window", () => { expect(sinceFor(1_300)).toBe("2s"); diff --git a/ui/src/model/events.ts b/ui/src/model/events.ts index 1376c0adf..17c26a5ca 100644 --- a/ui/src/model/events.ts +++ b/ui/src/model/events.ts @@ -9,6 +9,9 @@ export interface ConsoleEvent { export const MAX_EVENTS = 10_000; +// why: the size of one page of older events the console asks for. +export const OLDER_PAGE = 100; + // why: the same window as `simlock events --since 1h`, so the two show the same events. export const RECENT = "1h"; @@ -37,6 +40,62 @@ export function readReplay(body: unknown): readonly ConsoleEvent[] { return events.flatMap((data: unknown) => readEvent(data) ?? []); } +export interface OlderPage { + readonly events: readonly ConsoleEvent[]; + // why: counted on the raw reply, before malformed events are dropped, so a page that was full on + // the wire is not taken for the history's end. + readonly full: boolean; +} + +export function readOlder(body: unknown): OlderPage { + const events = readReplay(body); + const raw = (body as { readonly events: readonly unknown[] }).events.length; + return { events, full: raw >= OLDER_PAGE }; +} + +// why: where the older events stand: more may come, the history has started, the daemon no longer +// keeps older events, or the last ask failed and may be repeated. +export type HistoryState = "more" | "start" | "gone" | "failed"; + +export interface HistoryEnd { + readonly text: string; + readonly retry: boolean; +} + +function localMinute(timestamp: number): string { + const date = new Date(timestamp); + const part = (value: number) => String(value).padStart(2, "0"); + return `${date.getFullYear()}-${part(date.getMonth() + 1)}-${part(date.getDate())} ${part(date.getHours())}:${part(date.getMinutes())}`; +} + +// why: the last row says why the list stops; nothing is said while more may still load. +export function historyEnd( + state: HistoryState, + held: readonly ConsoleEvent[], +): HistoryEnd | undefined { + if (held.length >= MAX_EVENTS) { + return { + retry: false, + text: `Showing the newest ${MAX_EVENTS.toLocaleString("en-US")} events.`, + }; + } + const oldest = held.at(-1); + if (state === "start") { + return { + retry: false, + text: + oldest === undefined + ? "No events yet." + : `Start of the history (${localMinute(oldest.timestamp)})`, + }; + } + if (state === "gone") return { retry: false, text: "Older events are no longer kept." }; + if (state === "failed") { + return { retry: true, text: "Older events are not available right now." }; + } + return undefined; +} + // why: identity is the `id` alone, so an event seen twice, by the stream and by the `since` window, // is shown once. function keyOf(event: ConsoleEvent): string { diff --git a/ui/src/model/waiting.test.ts b/ui/src/model/waiting.test.ts index c050d2438..1158bd690 100644 --- a/ui/src/model/waiting.test.ts +++ b/ui/src/model/waiting.test.ts @@ -161,16 +161,16 @@ describe("the waiting table", () => { describe("choosing a waiting request", () => { const rows = waitingTable([request({ id: "a" }), request({ id: "b" })], [], NOW).rows; - it("chooses the first row of the page when the URL names none", () => { - expect(chooseWaiting(rows, undefined, rows.slice(1))).toEqual({ chosen: rows[1], gone: false }); + it("chooses nothing when the URL names none, so the drawer stays shut", () => { + expect(chooseWaiting(rows, undefined)).toEqual({ chosen: undefined, gone: false }); }); - it("chooses the request the URL names, even from another page", () => { - expect(chooseWaiting(rows, "a", rows.slice(1))).toEqual({ chosen: rows[0], gone: false }); + it("chooses the request the URL names, whatever page it is on", () => { + expect(chooseWaiting(rows, "a")).toEqual({ chosen: rows[0], gone: false }); }); it("calls a named request that is no longer waiting gone, and chooses nothing", () => { - expect(chooseWaiting(rows, "granted", rows)).toEqual({ chosen: undefined, gone: true }); + expect(chooseWaiting(rows, "granted")).toEqual({ chosen: undefined, gone: true }); }); }); diff --git a/ui/src/model/waiting.ts b/ui/src/model/waiting.ts index 3bfbd78c3..da49bdb00 100644 --- a/ui/src/model/waiting.ts +++ b/ui/src/model/waiting.ts @@ -213,14 +213,10 @@ export interface WaitingChoice { readonly gone: boolean; } -// why: with no id in the URL a wide screen shows the first row of the page; an id that matches no -// waiting request is "gone", whatever page it would have been on. -export function chooseWaiting( - all: readonly WaitingRow[], - id: string | undefined, - pageRows: readonly WaitingRow[], -): WaitingChoice { - if (id === undefined) return { chosen: pageRows[0], gone: false }; +// why: the drawer opens only for an id in the URL; an id that matches no waiting request is +// "gone", whatever page it would have been on. +export function chooseWaiting(all: readonly WaitingRow[], id: string | undefined): WaitingChoice { + if (id === undefined) return { chosen: undefined, gone: false }; const chosen = all.find((row) => row.id === id); return { chosen, gone: chosen === undefined }; } diff --git a/ui/src/screens/events/events.css b/ui/src/screens/activity/activity.css similarity index 50% rename from ui/src/screens/events/events.css rename to ui/src/screens/activity/activity.css index eb717478f..1f55b2116 100644 --- a/ui/src/screens/events/events.css +++ b/ui/src/screens/activity/activity.css @@ -23,3 +23,25 @@ .event-error { color: var(--status-error); } + +.event-drawer-body { + display: flex; + flex-direction: column; + gap: var(--space-4); + padding: var(--space-4) var(--space-6); +} + +.event-line { + margin: 0; + color: var(--text-muted); +} + +.event-payload-title { + margin: 0; + color: var(--text-muted); + font-family: var(--font-mono); + font-size: var(--text-xs); + font-weight: 500; + letter-spacing: var(--label-tracking); + text-transform: uppercase; +} diff --git a/ui/src/screens/events/events.test.tsx b/ui/src/screens/activity/activity.test.tsx similarity index 78% rename from ui/src/screens/events/events.test.tsx rename to ui/src/screens/activity/activity.test.tsx index 3bad6e101..155325aef 100644 --- a/ui/src/screens/events/events.test.tsx +++ b/ui/src/screens/activity/activity.test.tsx @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import type { LoadView } from "../../ds"; import type { EventDetail, EventRow, EventsPage } from "../../state/events"; -import { EventsContent } from "."; +import { ActivityContent, EventDrawerBody } from "."; function text(html: string): string { return html @@ -47,16 +47,31 @@ function page(over: Partial = {}): EventsPage { }, chosen: { detail: DETAIL, kind: "event" }, chosenIndex: 0, + end: undefined, held: 1, - named: false, + loadOlder: () => {}, + query: "", rows: [row(1)], subject: "all", + urlId: "evt_1", ...over, }; } function render(view: LoadView): string { - return renderToStaticMarkup( {}} />); + return renderToStaticMarkup( + {}} + onSearch={() => {}} + onClose={() => {}} + finalFocus={() => null} + />, + ); +} + +function drawer(over: Partial = {}): string { + return renderToStaticMarkup(); } function ready(over: Partial = {}): string { @@ -126,12 +141,20 @@ describe("the events page", () => { }); it("says why an empty list is empty", () => { - expect(text(ready({ chosen: { kind: "none" }, held: 0, rows: [] }))).toContain( - "No events in the last hour.", - ); + expect(text(ready({ chosen: { kind: "none" }, held: 0, rows: [] }))).toContain("Loading…"); + expect( + text( + ready({ + chosen: { kind: "none" }, + end: { retry: false, text: "No events yet." }, + held: 0, + rows: [], + }), + ), + ).toContain("No events yet."); expect( text(ready({ chosen: { kind: "none" }, held: 5, rows: [], subject: "device" })), - ).toContain("No events of this kind."); + ).toContain("No device events among those loaded."); }); it("says it is loading, or why it could not load", () => { @@ -144,41 +167,33 @@ describe("the events page", () => { it("shows a refusal above the events it keeps", () => { const html = render({ data: page(), kind: "ready", refusal: "Internal error" }); - expect(html).toMatch(/^'); expect(text(html)).toContain("lease.granted"); }); - - it("opens on the phone at the inspector only when the URL names an event", () => { - expect(ready({ named: true })).toContain("focus-detail"); - expect(ready({ named: false })).toContain("focus-list"); - }); }); -describe("the events page's inspector", () => { - it("is titled with the event's name and says when and what", () => { - const html = ready(); +describe("the events page's drawer", () => { + it("says when and what the event was", () => { + const html = drawer(); - expect(html).toMatch( - /

]*class="inspector-title mono"[^>]*>lease\.granted<\/span><\/h2>/, - ); expect(text(html)).toContain("11:30:00 today · claude-1 · mac-1"); }); it("shows the payload whole, keys as the daemon spelled them", () => { - const html = ready(); + const html = drawer(); expect(html).toContain('
'); expect(text(html)).toContain('leaseId lse_1 nested {"deep":true}'); }); it("says when there is no payload", () => { - expect(text(ready({ chosen: { detail: { ...DETAIL, pairs: [] }, kind: "event" } }))).toContain( + expect(text(drawer({ chosen: { detail: { ...DETAIL, pairs: [] }, kind: "event" } }))).toContain( "No payload.", ); }); it("links to what the event is about when the console has a page for it", () => { - const withAction = ready({ + const withAction = drawer({ chosen: { detail: { ...DETAIL, action: { label: "Open lease", to: "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/leases/lse_1/" } }, kind: "event", @@ -188,13 +203,14 @@ describe("the events page's inspector", () => { expect(withAction).toContain( 'Open lease', ); - expect(ready()).not.toContain("Open lease"); + expect(drawer()).not.toContain("Open lease"); }); - it("says an event older than the hour is not there, and links back to the list", () => { - const html = ready({ chosen: { id: "evt_old", kind: "missing" }, named: true }); + it("says an event that is not among those loaded is not, and where older ones come from", () => { + const html = drawer({ chosen: { id: "evt_old", kind: "missing" } }); - expect(text(html)).toContain("Event not in the last hour."); - expect(html).toContain('Back to Activity'); + expect(text(html)).toContain( + "This event is not among those loaded. Older events load as you scroll the list, or with Load older events.", + ); }); }); diff --git a/ui/src/screens/activity/index.tsx b/ui/src/screens/activity/index.tsx new file mode 100644 index 000000000..7182c650f --- /dev/null +++ b/ui/src/screens/activity/index.tsx @@ -0,0 +1,252 @@ +import "./activity.css"; + +import { + Button, + ButtonLink, + ChoiceChips, + Drawer, + Empty, + Facts, + Feed, + focusAfterClosing, + ListRow, + Loaded, + type LoadView, + MinuteChart, + MinuteTable, + Page, + SearchField, + Toolbar, +} from "../../ds"; +import { useItemId, useListDrawer } from "../../state/drawer"; +import { + type EventDetail, + type EventRow, + type EventsChart, + type EventsPage, + type HistoryEnd, + SUBJECT_CHOICES, + setQuery, + setSubject, + type SubjectFilter, + useEvents, +} from "../../state/events"; + +// why: a row is two lines of fixed height, so the feed can place the rows it draws by arithmetic. +const ROW_PX = 60; + +export function ActivityScreen() { + const view = useEvents(); + const urlId = useItemId("/activity"); + const { close, fromList } = useListDrawer("/activity", urlId); + return ( + + urlId === undefined + ? null + : focusAfterClosing({ + fromList, + links: ".feed-list a", + path: `/activity/${encodeURIComponent(urlId)}`, + }) + } + /> + ); +} + +export function ActivityContent(props: { + readonly view: LoadView; + readonly onSubject: (subject: SubjectFilter) => void; + readonly onSearch: (query: string) => void; + readonly onClose: () => void; + readonly finalFocus: () => HTMLElement | null; +}) { + const { finalFocus, onClose, onSearch, onSubject, view } = props; + return ( + live}> + + {(page) => ( + <> + + + } + end={} + /> + + {page.urlId === undefined ? null : ( + } + onClose={onClose} + finalFocus={finalFocus} + > + + + )} + + )} + + + ); +} + +function EventList({ page }: { readonly page: EventsPage }) { + const { rows } = page; + const chosenId = page.chosen.kind === "event" ? page.chosen.detail.id : undefined; + // why: a chip or a search shows few of the events held, so scrolling would not tell how many + // more are worth loading; the reader asks for each page. + const narrowed = page.subject !== "all" || page.query !== ""; + if (page.held === 0) { + return page.end === undefined ? ( +

Loading…

+ ) : ( + + ); + } + if (rows.length === 0) { + return ( + <> + + {page.query === "" + ? `No ${page.subject} events among those loaded.` + : `No events match ${page.query} among those loaded.`} + +