diff --git a/docs/internal/DESIGN.md b/docs/internal/DESIGN.md index 0310aa250..977275eef 100644 --- a/docs/internal/DESIGN.md +++ b/docs/internal/DESIGN.md @@ -141,7 +141,7 @@ own that one of them draws. Named sizes and colours are above. then the links (icon 16px, label 500, muted; current one `--accent-text` on `--nav-current`, `aria-current="page"`) in a fixed order: Overview, Inbox, then **Operate**: Fleet, Leases, Queue, Baselines; then - **Observe**: Activity, Usage; then **Settings**: Settings (a gear icon), each + **Observe**: Screens, Activity, Usage; then **Settings**: Settings (a gear icon), each group under a label. Inbox carries its problem count in a red round badge, none at zero. At the bottom an account box on `--bg`: a 26px avatar chip, the token label or id (mono, cut), the diff --git a/docs/internal/console-redesign/PLAN.md b/docs/internal/console-redesign/PLAN.md index 9251e3793..3fe5b8dec 100644 --- a/docs/internal/console-redesign/PLAN.md +++ b/docs/internal/console-redesign/PLAN.md @@ -87,7 +87,7 @@ One agent; everything else waits for it. of DESIGN.md. Rename or add tokens; delete `--chip` and `--field` (an input's fill is `--bg`). Foundation also owns mechanical substitutions in `ui/src/screens/sign-in.css`, `inbox/inbox.css`, - `overview/overview.css` and `fleet/screen-panel.css`; no other changes to + `overview/overview.css` and `screen-view.css` (then `fleet/screen-panel.css`); no other changes to those screens before their page stages. Verify no retired-token consumers remain and existing pages render in both themes. (decided in delivery, pending the maintainer) - Restyle the `ds` primitives every page shares, to the renders' sidebar, diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 28d9e4a73..814394692 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -779,6 +779,7 @@ export const NAV = [ { label: "Leases", path: "/leases" }, { label: "Queue", path: "/queue" }, { label: "Baselines", path: "/baselines" }, + { label: "Screens", path: "/screens" }, { label: "Activity", path: "/activity" }, { label: "Usage", path: "/usage" }, { label: "Settings", path: "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/settings" }, diff --git a/e2e/console/screens-http1.spec.ts b/e2e/console/screens-http1.spec.ts new file mode 100644 index 000000000..56c161f5b --- /dev/null +++ b/e2e/console/screens-http1.spec.ts @@ -0,0 +1,252 @@ +import { createServer, type ServerResponse } from "node:http"; +import { readFile, writeFile } from "node:fs/promises"; +import { extname, resolve } from "node:path"; + +import { expect, test } from "@playwright/test"; + +test("keeps HTTP/1 reads moving while four watched screens capture, and closes them on removal, hiding, navigation and sign-out", async ({ + page, +}, testInfo) => { + const devices = new Map([ + ["a", ["one", "two", "three"]], + ["b", ["one", "two", "three"]], + ]); + const captures = new Map(); + const held = new Set(); + const history: { kind: string; key: string; active: number }[] = []; + let events: ServerResponse | undefined; + let workerReads = 0; + const versions = new Set(); + let duplicates = 0; + let unauthorized = false; + const packet = (tag: number, value: Buffer) => { + const out = Buffer.alloc(value.length + 5); + out.writeUInt32BE(value.length + 1); + out[4] = tag; + value.copy(out, 5); + return out; + }; + const jpeg = Buffer.from( + await page.evaluate(() => { + const canvas = document.createElement("canvas"); + canvas.width = 180; + canvas.height = 390; + const context = canvas.getContext("2d")!; + context.fillStyle = "#192c3b"; + context.fillRect(0, 0, 180, 390); + context.fillStyle = "white"; + context.fillText("Synthetic HTTP/1 fixture", 8, 100); + return canvas.toDataURL("image/jpeg").split(",")[1]!; + }), + "base64", + ); + const emit = () => + events!.write( + `event: device.ready\ndata: ${JSON.stringify({ id: "synthetic-change", seq: workerReads, timestamp: Date.now(), event: "device.ready", payload: { deviceId: "four" } })}\n\n`, + ); + // fallow-ignore-next-line complexity -- the fake daemon's router: one branch per route it answers. + const server = createServer(async (req, res) => { + versions.add(req.httpVersion); + const path = req.url!; + const json = (value: unknown, status = 200) => + res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(value)); + if (path.startsWith("/v1/") && unauthorized) { + json({ error: { code: "UNAUTHORIZED", message: "Synthetic signed out" } }, 401); + return; + } + if (path === "/v1/events/stream") { + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.write(": connected\n\n"); + events = res; + held.add(res); + res.on("close", () => held.delete(res)); + return; + } + if (path.startsWith("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/v1/stream/")) { + const [, worker, device] = /workers\/([^/]+)\/devices\/([^/]+)/.exec(path)!; + const key = `${worker}/${device}`; + if (captures.has(key)) duplicates++; + captures.set(key, res); + held.add(res); + history.push({ kind: "open", key, active: captures.size }); + res.on("close", () => { + if (captures.get(key) === res) captures.delete(key); + held.delete(res); + history.push({ kind: "close", key, active: captures.size }); + }); + res.writeHead(200, { "Content-Type": "application/octet-stream" }); + res.write( + packet(5, Buffer.from(JSON.stringify({ codec: "mjpeg", width: 180, height: 390, fps: 5 }))), + ); + res.write(packet(3, jpeg)); + return; + } + if (path === "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/v1/workers") { + workerReads++; + json({ + workers: [...devices].map(([id, ids]) => ({ + id, + label: "Synthetic worker", + connection: "connected", + drained: false, + lastSeenAt: 0, + capabilities: [{ name: "stream", state: "available" }], + devices: ids.map((id) => ({ + id, + state: "ready", + physical: false, + spec: { platform: "ios", model: "iPhone", osVersion: "18.4" }, + })), + })), + }); + return; + } + const answers: Record = { + "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/v1/identity": { name: "Synthetic operator", via: "token" }, + "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/v1/healthz": { ok: true }, + "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/v1/status": { daemon: { mode: "worker", version: "0.5.0" } }, + "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/v1/inbox": { items: [], now: Date.now() }, + }; + if (Object.hasOwn(answers, path)) { + json(answers[path]); + return; + } + if (path.startsWith("/v1/")) { + json({}); + return; + } + try { + const file = resolve("dist/ui", "." + (path.startsWith("/assets/") ? path : "/index.html")); + const bytes = await readFile(file); + res.setHeader( + "Content-Type", + ( + { ".js": "text/javascript", ".css": "text/css", ".html": "text/html" } as Record< + string, + string + > + )[extname(file)] ?? "application/octet-stream", + ); + res.end(bytes); + } catch { + res.writeHead(404).end(); + } + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; + try { + await page.addInitScript(() => + sessionStorage.setItem("simlock.operatorToken", "synthetic-test-token"), + ); + await page.setViewportSize({ width: 1900, height: 1900 }); + await page.clock.install(); + const watch = new URLSearchParams(); + for (const key of [ + ["a", "one"], + ["a", "two"], + ["b", "one"], + ["b", "two"], + ]) + watch.append("watch", JSON.stringify(key)); + const screens = `${origin}/screens?${watch}`; + await page.goto(screens); + await expect(page.locator(".screens-slot")).toHaveCount(4); + await expect.poll(() => captures.size).toBe(4); + const beforePoll = workerReads; + await page.clock.runFor(15_001); + await expect.poll(() => workerReads).toBeGreaterThan(beforePoll); + expect([...versions]).toEqual(["1.1"]); + expect(await page.locator("canvas").count()).toBe(4); + await expect + .poll(() => + page + .locator("canvas") + .evaluateAll((nodes) => + nodes.every( + (node) => + (node as HTMLCanvasElement).getContext("2d")!.getImageData(0, 0, 1, 1).data[3] === + 255, + ), + ), + ) + .toBe(true); + devices.get("a")!.push("four"); + emit(); + await page.clock.runFor(350); + await page.getByRole("radio", { name: "All" }).check({ force: true }); + await expect(page.getByRole("button", { name: /^Watch .*\(four\)$/ })).toBeDisabled(); + expect(await page.evaluate(async () => (await fetch("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/v1/healthz")).status)).toBe(200); + devices.set( + "a", + devices.get("a")!.filter((id) => id !== "one"), + ); + emit(); + await page.clock.runFor(350); + await expect(page.locator(".screens-slot")).toHaveCount(3); + await expect.poll(() => captures.has("a/one")).toBe(false); + await expect.poll(() => captures.size).toBe(3); + await page.getByRole("button", { name: /^Watch .*\(four\)$/ }).click(); + await expect(page.locator(".screens-slot")).toHaveCount(4); + await expect.poll(() => captures.size).toBe(4); + const failed = captures.keys().next().value!; + captures.get(failed)!.write(Buffer.from([255, 255, 255, 255, 1])); + await expect( + page.getByText("The stream is not a frame envelope", { exact: true }), + ).toBeVisible(); + await expect.poll(() => captures.has(failed)).toBe(false); + await expect.poll(() => captures.size).toBe(3); + expect(await page.locator("canvas").count()).toBe(3); + await page.evaluate(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" }); + document.dispatchEvent(new Event("visibilitychange")); + }); + await expect.poll(() => captures.size).toBe(0); + await expect(page.locator("canvas")).toHaveCount(0); + await page.evaluate(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" }); + document.dispatchEvent(new Event("visibilitychange")); + }); + await expect.poll(() => captures.size).toBe(4); + await page.getByRole("link", { name: "Fleet", exact: true }).click(); + await expect.poll(() => captures.size).toBe(0); + await page.getByRole("link", { name: "Screens", exact: true }).click(); + await expect.poll(() => captures.size).toBe(4); + await page.getByRole("button", { name: "Sign out", exact: true }).click(); + await expect.poll(() => captures.size).toBe(0); + // why: the first address named a/one, which is gone, and not a/four. + await page.goto(screens); + await expect.poll(() => captures.size).toBe(3); + unauthorized = true; + emit(); + await page.clock.runFor(350); + await expect(page.getByRole("button", { name: "Sign in", exact: true })).toBeVisible(); + await expect.poll(() => captures.size).toBe(0); + expect(duplicates).toBe(0); + } finally { + try { + const record = testInfo.outputPath("http1-ownership-history.json"); + await writeFile( + record, + JSON.stringify({ versions: [...versions], history, workerReads, duplicates }, null, 2), + ); + await testInfo.attach("http1-ownership-history", { + path: record, + contentType: "application/json", + }); + } finally { + try { + await page.close(); + } finally { + try { + for (const response of held) response.destroy(); + } finally { + try { + server.closeAllConnections(); + } finally { + await new Promise((done) => server.close(() => done())); + } + } + } + } + } +}); diff --git a/e2e/console/screens.spec.ts b/e2e/console/screens.spec.ts new file mode 100644 index 000000000..c63a1cfc9 --- /dev/null +++ b/e2e/console/screens.spec.ts @@ -0,0 +1,525 @@ +import { createServer, type Server } from "node:http"; +import { readFile } from "node:fs/promises"; +import { resolve, extname } from "node:path"; + +import { test, expect, type Page } from "@playwright/test"; + +let server: Server; +let origin: string; + +test.beforeAll(async () => { + server = createServer(async (request, response) => { + try { + const path = request.url?.startsWith("/assets/") ? request.url : "/index.html"; + const file = resolve("dist/ui", `.${path}`); + const content = await readFile(file); + response.setHeader( + "Content-Type", + ( + { ".js": "text/javascript", ".css": "text/css", ".html": "text/html" } as Record< + string, + string + > + )[extname(file)] ?? "application/octet-stream", + ); + response.end(content); + } catch { + response.writeHead(404).end(); + } + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; +}); +test.afterAll(async () => { + await new Promise((done, reject) => + server.close((error) => (error ? reject(error) : done())), + ); +}); + +async function fixture(page: Page) { + page.on("pageerror", (error) => { + throw error; + }); + await page.addInitScript(() => { + sessionStorage.setItem("simlock.operatorToken", "synthetic-test-token"); + const original = window.fetch; + const active = new Map>(); + const counts = { opened: 0, closed: 0, max: 0, duplicates: 0 }; + let mode = sessionStorage.getItem("wallTest.mode") ?? "running"; + let workerIds = ["synthetic"]; + let holdCancel: string | undefined; + let finishCancel: (() => void) | undefined; + let devices = ["one", "two", "three", "four"]; + const encoder = new TextEncoder(); + const packet = (tag: number, bytes: Uint8Array) => { + const frame = new Uint8Array(bytes.length + 5); + new DataView(frame.buffer).setUint32(0, bytes.length + 1); + frame[4] = tag; + frame.set(bytes, 5); + return frame; + }; + const workers = () => ({ + workers: workerIds.map((id) => ({ + id, + label: "Synthetic worker", + connection: mode === "disconnected" ? "disconnected" : "connected", + drained: false, + lastSeenAt: 0, + capabilities: mode === "disabled" ? [] : [{ name: "stream", state: "available" }], + leases: + mode === "empty" || !devices.includes("one") + ? [] + : [ + { + id: "lse_one", + deviceId: "one", + requesterId: "claude-code:alpha", + ownerId: "claude-code:alpha", + grantedAt: Date.now() - 90_000, + ttlMs: 600_000, + ttlDeadline: Date.now() + 600_000, + lastRenewedAt: Date.now(), + idChosenByRequester: false, + }, + ], + devices: (mode === "empty" ? [] : devices).map((id, index) => ({ + id, + state: index === 0 ? "leased" : "ready", + physical: false, + spec: { + platform: index === 3 ? "android" : "ios", + model: index === 3 ? "Pixel 9" : "iPhone 16", + osVersion: index === 3 ? "35" : "18.4", + }, + })), + })), + }); + let events: ReadableStreamDefaultController; + const controls = { + active: () => [...active.keys()], + counts, + hidden(value: boolean) { + Object.defineProperty(document, "visibilityState", { + configurable: true, + value: value ? "hidden" : "visible", + }); + document.dispatchEvent(new Event("visibilitychange")); + }, + fail(id: string) { + active.get(id)?.error(new Error("Synthetic capture failed")); + active.delete(id); + counts.closed++; + }, + end(id: string) { + active.get(id)?.enqueue(packet(7, encoder.encode(JSON.stringify({ reason: "explicit" })))); + }, + add(notify: boolean) { + devices.push("five"); + if (notify) + events.enqueue( + encoder.encode( + `event: device.ready\ndata: ${JSON.stringify({ id: "evt_five", seq: 1, timestamp: Date.now(), event: "device.ready", payload: { deviceId: "five" } })}\n\n`, + ), + ); + }, + remove() { + devices = ["one"]; + events.enqueue(encoder.encode("event: device.deleted\ndata: {}\n\n")); + }, + mode(value: string) { + mode = value; + sessionStorage.setItem("wallTest.mode", value); + events.enqueue(encoder.encode("event: device.changed\ndata: {}\n\n")); + }, + holdCancel(id: string) { + holdCancel = id; + }, + finishCancel() { + holdCancel = undefined; + finishCancel?.(); + }, + duplicateWorkers() { + workerIds = ["synthetic", "other"]; + devices = ["one"]; + mode = "disabled"; + events.enqueue(encoder.encode("event: device.changed\ndata: {}\n\n")); + }, + unauthorized: false, + }; + Object.assign(window, { wallTest: controls }); + async function capture(id: string, signal: AbortSignal | null | undefined) { + counts.opened++; + const canvas = document.createElement("canvas"); + canvas.width = 180; + canvas.height = 390; + const ctx = canvas.getContext("2d")!; + ctx.fillStyle = "#192c3b"; + ctx.fillRect(0, 0, 180, 390); + ctx.fillStyle = "#ffffff"; + ctx.font = "16px sans-serif"; + ctx.fillText("Synthetic fixture", 20, 120); + ctx.fillText(id, 20, 155); + const blob = await new Promise((done) => canvas.toBlob((b) => done(b!), "image/jpeg")); + const jpeg = new Uint8Array(await blob.arrayBuffer()); + let closed = false; + const close = () => { + if (closed) return; + closed = true; + active.delete(id); + counts.closed++; + }; + return new Response( + new ReadableStream({ + start(c) { + if (active.has(id)) counts.duplicates++; + active.set(id, c); + counts.max = Math.max(counts.max, active.size); + c.enqueue( + packet( + 5, + encoder.encode(JSON.stringify({ codec: "mjpeg", width: 180, height: 390, fps: 5 })), + ), + ); + if (mode !== "connecting") c.enqueue(packet(3, jpeg)); + if (signal?.aborted) { + close(); + c.close(); + } else + signal?.addEventListener( + "abort", + () => { + close(); + try { + c.close(); + } catch {} + }, + { once: true }, + ); + }, + cancel: () => { + if (holdCancel !== id) { + close(); + return undefined; + } + return new Promise((resolve) => { + finishCancel = () => { + close(); + resolve(); + }; + }); + }, + }), + { headers: { "Content-Type": "application/octet-stream" } }, + ); + } + // fallow-ignore-next-line complexity -- the fake daemon's router: one branch per route it answers. + window.fetch = async (input, init) => { + const path = String(input); + + if (!path.startsWith("/v1/")) return original(input, init); + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); + if ( + path === "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/v1/identity" && + !controls.unauthorized && + new Headers(init?.headers).has("Authorization") + ) + return json({ name: "Synthetic operator", via: "token" }); + if (path === "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/v1/identity") + return json({ error: { code: "UNAUTHORIZED", message: "Synthetic signed out" } }, 401); + if (controls.unauthorized) + return json({ error: { code: "UNAUTHORIZED", message: "Synthetic signed out" } }, 401); + if (path === "/v1/events/stream") + return new Response( + new ReadableStream({ + start(c) { + events = c; + c.enqueue(encoder.encode(": connected\n\n")); + init?.signal?.addEventListener("abort", () => c.close(), { once: true }); + }, + }), + { headers: { "Content-Type": "text/event-stream" } }, + ); + const answers: Readonly> = { + "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/v1/healthz": { ok: true }, + "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/v1/workers": workers(), + "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/v1/inbox": { items: [], now: Date.now() }, + "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/v1/status": { daemon: { mode: "worker", version: "0.5.0" } }, + }; + if (Object.hasOwn(answers, path)) return json(answers[path]); + if (path.startsWith("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/v1/stream/")) { + if (mode === "unsupported") + return json( + { error: { code: "STREAM_NOT_SUPPORTED", message: "Synthetic unsupported" } }, + 415, + ); + return capture(path.split("/").at(-1)!, init?.signal); + } + return json({}); + }; + }); +} + +type Controls = { + active(): string[]; + counts: { opened: number; closed: number; max: number; duplicates: number }; + mode(value: string): void; + hidden(value: boolean): void; + fail(id: string): void; + end(id: string): void; + add(notify: boolean): void; + remove(): void; + holdCancel(id: string): void; + finishCancel(): void; + duplicateWorkers(): void; + unauthorized: boolean; +}; +async function active(page: Page) { + return page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.active().sort(), + ); +} + +const ALL = ["one", "two", "three", "four"]; + +function watching(ids: readonly string[], worker = "synthetic") { + const params = new URLSearchParams(); + for (const id of ids) params.append("watch", JSON.stringify([worker, id])); + return `${origin}/screens?${params}`; +} + +async function showAll(page: Page) { + await page.getByRole("radio", { name: "All" }).check({ force: true }); +} + +async function duplicates(page: Page) { + return page.evaluate( + () => (window as unknown as { wallTest: Controls }).wallTest.counts.duplicates, + ); +} + +test("lists running devices with their holders, streams only the ones watched, at most four", async ({ + page, +}, testInfo) => { + await fixture(page); + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.clock.install(); + await page.goto(`${origin}/screens`); + await expect(page.getByRole("heading", { name: "Screens", exact: true })).toBeVisible(); + await expect(page.getByText(/Choose Watch on a running device below/)).toBeVisible(); + await expect(page.locator("tbody tr")).toHaveCount(1); + await expect(page.locator("tbody tr").first()).toContainText("claude-code:alpha"); + await expect(page.locator("tbody tr").first()).toContainText(/1 min \d+ s/); + expect(await active(page)).toEqual([]); + await showAll(page); + await expect(page.locator("tbody tr")).toHaveCount(4); + for (const id of ALL) + await page.getByRole("button", { name: new RegExp(`^Watch .*\\(${id}\\)$`) }).click(); + await expect.poll(() => active(page)).toEqual(["four", "one", "three", "two"]); + await expect(page.locator("canvas")).toHaveCount(4); + await expect( + page.getByRole("article", { + name: "Screen: claude-code:alpha, iPhone 16 on Synthetic worker (one)", + exact: true, + }), + ).toBeVisible(); + await expect( + page.getByRole("link", { + name: "Open streaming page: Pixel 9, Pixel 9 on Synthetic worker (four)", + exact: true, + }), + ).toHaveAttribute("href", "/fleet/synthetic/devices/four/"); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.add(true)); + await page.clock.runFor(350); + await expect(page.getByRole("button", { name: /^Watch .*\(five\)$/ })).toBeDisabled(); + await page.screenshot({ path: testInfo.outputPath("screens-desktop.png"), fullPage: true }); + + await page.reload(); + await expect.poll(() => active(page)).toEqual(["four", "one", "three", "two"]); + await page.getByRole("link", { name: "Screens", exact: true }).click(); + await expect(page).toHaveURL(/watch=/); + await expect(page.locator(".screens-slot")).toHaveCount(4); + await expect.poll(() => active(page)).toEqual(["four", "one", "three", "two"]); + await page + .getByRole("button", { name: /^Stop watching .*\(two\)$/ }) + .first() + .click(); + await expect.poll(() => active(page)).toEqual(["four", "one", "three"]); + await expect(page.locator(".screens-slot")).toHaveCount(3); + + await page.setViewportSize({ width: 360, height: 800 }); + await expect + .poll(() => page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + .toBe(true); + await page.screenshot({ path: testInfo.outputPath("screens-narrow.png"), fullPage: true }); + expect(await duplicates(page)).toBe(0); +}); + +test("a hidden tab, removal, navigation and authentication loss close watched captures; failures stay isolated", async ({ + page, +}) => { + await fixture(page); + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto(watching(ALL)); + await expect.poll(() => active(page)).toHaveLength(4); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.hidden(true)); + await expect.poll(() => active(page)).toEqual([]); + await expect(page.locator("canvas")).toHaveCount(0); + await expect(page.getByText("Paused while this tab is hidden.", { exact: true })).toHaveCount(4); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.hidden(false)); + await expect.poll(() => active(page)).toHaveLength(4); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.fail("two")); + await expect(page.getByText("Synthetic capture failed", { exact: true })).toBeVisible(); + await expect.poll(() => active(page)).toHaveLength(3); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.end("three")); + await expect(page.getByText("The lease was released.", { exact: true })).toBeVisible(); + await expect.poll(() => active(page)).toHaveLength(2); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.remove()); + await expect(page.locator(".screens-slot")).toHaveCount(1); + await expect.poll(() => active(page)).toEqual(["one"]); + await page.getByRole("link", { name: "Fleet", exact: true }).click(); + await expect.poll(() => active(page)).toEqual([]); + await page.getByRole("link", { name: "Screens", exact: true }).click(); + await expect.poll(() => active(page)).toEqual(["one"]); + expect(await duplicates(page)).toBe(0); + expect( + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.counts.max), + ).toBe(4); + await page.evaluate(() => { + const c = (window as unknown as { wallTest: Controls }).wallTest; + c.unauthorized = true; + c.remove(); + }); + await expect.poll(() => active(page)).toEqual([]); + await expect(page.getByRole("button", { name: "Sign in", exact: true })).toBeVisible(); +}); + +test("a watched device whose stream cannot start says why in its place", async ({ page }) => { + await fixture(page); + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto(watching(ALL)); + await expect.poll(() => active(page)).toHaveLength(4); + for (const [mode, text] of [ + ["disabled", "Streaming is off on Synthetic worker."], + ["disconnected", "Synthetic worker is disconnected."], + ["unsupported", "This device cannot be streamed."], + ] as const) { + await page.evaluate( + (value) => (window as unknown as { wallTest: Controls }).wallTest.mode(value), + mode, + ); + await expect(page.getByText(text, { exact: true })).toHaveCount(4); + await expect.poll(() => active(page)).toEqual([]); + await expect(page.locator("canvas")).toHaveCount(0); + } + await page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.mode("connecting"), + ); + await page.reload(); + await expect(page.getByText("Waiting for the first frame.", { exact: true })).toHaveCount(4); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.mode("empty")); + await expect(page.getByText("No leased devices.", { exact: true })).toBeVisible(); + await expect(page.locator(".screens-slot")).toHaveCount(0); + await expect.poll(() => active(page)).toEqual([]); +}); + +test("signing out closes every watched capture", async ({ page }) => { + await fixture(page); + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto(watching(ALL)); + await expect.poll(() => active(page)).toHaveLength(4); + await page.getByRole("button", { name: "Sign out", exact: true }).click(); + await expect(page.getByRole("button", { name: "Sign in", exact: true })).toBeVisible(); + await expect.poll(() => active(page)).toEqual([]); + expect( + await page.evaluate(() => { + const { opened, closed } = (window as unknown as { wallTest: Controls }).wallTest.counts; + return opened - closed; + }), + ).toBe(0); +}); + +test("lists a new running device without a reload after an event, a poll, or returning to the tab", async ({ + page, +}) => { + await fixture(page); + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.clock.install(); + for (const source of ["event", "poll", "visible"] as const) { + await page.goto(`${origin}/screens`); + await showAll(page); + await expect(page.locator("tbody tr")).toHaveCount(4); + if (source === "visible") + await page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.hidden(true), + ); + await page.evaluate( + (notify) => (window as unknown as { wallTest: Controls }).wallTest.add(notify), + source === "event", + ); + if (source === "event") await page.clock.runFor(350); + if (source === "poll") await page.clock.runFor(15_001); + if (source === "visible") + await page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.hidden(false), + ); + await expect(page.locator("tbody tr")).toHaveCount(5); + await expect(page.getByRole("button", { name: /^Watch .*\(five\)$/ })).toBeEnabled(); + expect(await active(page)).toEqual([]); + } +}); + +test("a newly watched screen waits until a stopped one has finished closing", async ({ page }) => { + await fixture(page); + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.clock.install(); + for (const outcome of ["start", "hidden", "navigation", "logout"] as const) { + await page.goto(watching(ALL)); + await expect.poll(() => active(page)).toHaveLength(4); + await page.evaluate(() => { + const controls = (window as unknown as { wallTest: Controls }).wallTest; + controls.add(true); + controls.holdCancel("one"); + }); + await page.clock.runFor(350); + await page.evaluate(() => (window as unknown as { wallTest: Controls }).wallTest.end("one")); + await expect(page.getByText("The lease was released.", { exact: true })).toBeVisible(); + await showAll(page); + await page + .getByRole("button", { name: /^Stop watching .*\(one\)$/ }) + .first() + .click(); + await page.getByRole("button", { name: /^Watch .*\(five\)$/ }).click(); + await expect( + page.getByText("Starting once another screen has closed.", { exact: true }), + ).toBeVisible(); + await page.clock.runFor(15_001); + expect(await active(page)).toEqual(["four", "three", "two"]); + if (outcome === "hidden") + await page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.hidden(true), + ); + if (outcome === "navigation") + await page.getByRole("link", { name: "Fleet", exact: true }).click(); + if (outcome === "logout") + await page.getByRole("button", { name: "Sign out", exact: true }).click(); + await page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.finishCancel(), + ); + if (outcome === "start") + await expect.poll(() => active(page)).toEqual(["five", "four", "three", "two"]); + else { + await expect.poll(() => active(page)).toEqual([]); + await page.clock.runFor(15_001); + expect(await active(page)).toEqual([]); + } + expect(await duplicates(page)).toBe(0); + if (outcome === "hidden") + await page.evaluate(() => + (window as unknown as { wallTest: Controls }).wallTest.hidden(false), + ); + } +}); diff --git a/ui/src/app/routes.test.ts b/ui/src/app/routes.test.ts index 9770b1185..c881ede5d 100644 --- a/ui/src/app/routes.test.ts +++ b/ui/src/app/routes.test.ts @@ -9,6 +9,8 @@ describe("the console's routes", () => { expect(routeFor("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/fleet/wrk_1")?.label).toBe("Fleet"); expect(routeFor("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/activity/e1")?.label).toBe("Activity"); expect(routeFor("/usage")?.label).toBe("Usage"); + expect(routeFor("/baselines")).toMatchObject({ label: "Baselines", group: "Operate" }); + expect(routeFor("/screens")).toMatchObject({ label: "Screens", group: "Observe" }); }); it("has no route for a path no section owns, one that only shares a prefix included", () => { @@ -24,6 +26,7 @@ describe("the console's routes", () => { "/leases", "/queue", "/baselines", + "/screens", "/activity", "/usage", "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/settings", diff --git a/ui/src/app/routes.ts b/ui/src/app/routes.ts index 17c0df2e8..1a5c93313 100644 --- a/ui/src/app/routes.ts +++ b/ui/src/app/routes.ts @@ -10,6 +10,7 @@ import { BaselinesScreen } from "../screens/baselines"; import { QueueScreen } from "../screens/queue"; import { FleetScreen } from "../screens/fleet"; import { SettingsScreen } from "../screens/settings"; +import { ScreensScreen } from "../screens/screens"; export type NavGroup = "Operate" | "Observe" | "Settings"; @@ -34,6 +35,13 @@ export const ROUTES: readonly Route[] = [ label: "Baselines", path: "/baselines", }, + { + Screen: ScreensScreen, + group: "Observe", + icon: "device", + label: "Screens", + path: "/screens", + }, { Screen: ActivityScreen, group: "Observe", diff --git a/ui/src/app/shell.dom.test.tsx b/ui/src/app/shell.dom.test.tsx index 24d385b01..44d9bca20 100644 --- a/ui/src/app/shell.dom.test.tsx +++ b/ui/src/app/shell.dom.test.tsx @@ -10,6 +10,7 @@ const PAGES = [ { label: "Leases", path: "/leases" }, { label: "Queue", path: "/queue" }, { label: "Baselines", path: "/baselines" }, + { label: "Screens", path: "/screens" }, { label: "Activity", path: "/activity" }, { label: "Usage", path: "/usage" }, { label: "Settings", path: "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/settings" }, @@ -17,7 +18,7 @@ const PAGES = [ const GROUPS = [ { label: "Operate", links: ["Fleet", "Leases", "Queue", "Baselines"] }, - { label: "Observe", links: ["Activity", "Usage"] }, + { label: "Observe", links: ["Screens", "Activity", "Usage"] }, { label: "Settings", links: ["Settings"] }, ] as const; diff --git a/ui/src/app/sign-in.dom.test.tsx b/ui/src/app/sign-in.dom.test.tsx index 198769604..d2fc67e07 100644 --- a/ui/src/app/sign-in.dom.test.tsx +++ b/ui/src/app/sign-in.dom.test.tsx @@ -11,6 +11,7 @@ const NAV_LABELS = [ "Leases", "Queue", "Baselines", + "Screens", "Activity", "Usage", "Settings", diff --git a/ui/src/data/stream.test.ts b/ui/src/data/stream.test.ts index 11782058a..eb9c37f7e 100644 --- a/ui/src/data/stream.test.ts +++ b/ui/src/data/stream.test.ts @@ -292,10 +292,16 @@ describe("reading the envelope", () => { }); it("refuses a length larger than any frame the tool writes, and lets go of the body", async () => { + vi.useFakeTimers(); + let finishCancel!: () => void; + const cancellation = new Promise((resolve) => { + finishCancel = resolve; + }); const cancelled: unknown[] = []; const body = new ReadableStream({ cancel: (reason) => { cancelled.push(reason); + return cancellation; }, start(controller) { controller.enqueue(Uint8Array.from([0xff, 0xff, 0xff, 0xff, TAG.keyframe, 0, 0, 0])); @@ -303,7 +309,17 @@ describe("reading the envelope", () => { }); const recorded = new Recorded(); - await readStream(body, recorded.sink(), new AbortController().signal); + let finished = false; + const reading = readStream(body, recorded.sink(), new AbortController().signal).then(() => { + finished = true; + }); + await vi.advanceTimersByTimeAsync(0); + const finishedBeforeCancel = finished; + finishCancel(); + await reading; + vi.useRealTimers(); + expect(finishedBeforeCancel).toBe(false); + expect(finished).toBe(true); expect(recorded.ends).toEqual(["The stream is not a frame envelope"]); // why: the request is what keeps the worker capturing, so a reader that gives up has to close it — diff --git a/ui/src/data/stream.ts b/ui/src/data/stream.ts index ec6ac4c11..38ef15432 100644 --- a/ui/src/data/stream.ts +++ b/ui/src/data/stream.ts @@ -86,6 +86,9 @@ export async function readStream( now: () => number = () => performance.now(), ): Promise { const reader = body.getReader(); + let cancellation: Promise | undefined; + const cancel = (reason?: string) => + (cancellation ??= reader.cancel(reason).catch(() => undefined)); const clock = new Stopwatch(now); const paintedRecently = new RecentRate(now); const bytesRecently = new RecentRate(now); @@ -134,12 +137,12 @@ export async function readStream( ended = true; report(); sink.onEnd(endedText(payload)); - void reader.cancel().catch(() => undefined); + void cancel(); }; const fail = (reason: string) => { end(reason); - void reader.cancel(reason).catch(() => undefined); + void cancel(reason); }; const configure = (bytes: Uint8Array): void => { @@ -272,9 +275,11 @@ export async function readStream( // why: closing the reader is what closes the request, and closing the request is the only // off-command this surface has. - signal.addEventListener("abort", () => void reader.cancel().catch(() => undefined), { - once: true, - }); + const abort = () => { + void cancel(); + }; + signal.addEventListener("abort", abort, { once: true }); + if (signal.aborted) abort(); // why: a still screen sends nothing to report on, and the rate it shows must fall to zero while it // is still rather than keep the figure of the last swipe until the next frame arrives. @@ -300,7 +305,9 @@ export async function readStream( // why: a decoder that failed has closed itself, and a browser refuses the second close; nothing // is left running either way. } - if (!ended) void reader.cancel().catch(() => undefined); + signal.removeEventListener("abort", abort); + await cancel(); + reader.releaseLock(); } } diff --git a/ui/src/ds/table.css b/ui/src/ds/table.css index b2382f7c8..f094f15ea 100644 --- a/ui/src/ds/table.css +++ b/ui/src/ds/table.css @@ -164,6 +164,16 @@ border-bottom: 0; } + /* why: a stacked row is a padded card, so its hover covers the row: on its cells it would draw a + * box inside the card, and a tap on a phone leaves the row hovered. */ + .table-wide tbody tr:not(.table-group):hover { + background-image: linear-gradient(var(--row-hover), var(--row-hover)); + } + + .table-wide tbody tr:not(.table-group):hover td { + background-image: none; + } + .table-wide td, .table-wide td:first-child, .table-wide td:last-child { @@ -233,6 +243,14 @@ border-bottom: 0; } + .table tbody tr:not(.table-group):hover { + background-image: linear-gradient(var(--row-hover), var(--row-hover)); + } + + .table tbody tr:not(.table-group):hover td { + background-image: none; + } + .table td, .table td:first-child, .table td:last-child { diff --git a/ui/src/model/screen.test.ts b/ui/src/model/screen.test.ts index 3b62e3027..e68ec1519 100644 --- a/ui/src/model/screen.test.ts +++ b/ui/src/model/screen.test.ts @@ -129,6 +129,21 @@ describe("what a device's Screen tab shows", () => { expect(deviceScreen({ conflict: undefined, offer, state }), state).toEqual(expected); } + const input = { state: "ready", offer: { offered: true }, conflict: undefined, queued: true }; + expect(deviceScreen(input)).toEqual({ + kind: "sentence", + text: "Starting once another screen has closed.", + }); + expect(deviceScreen({ ...input, offer: { offered: false, reason: "Unavailable." } })).toEqual({ + kind: "sentence", + text: "Unavailable.", + }); + expect(deviceScreen({ ...input, state: "shutdown" })).toEqual({ + kind: "sentence", + text: "The device is shut down. Its screen shows while it runs.", + }); + expect(deviceScreen({ ...input, queued: false })).toEqual({ kind: "picture" }); + const conflict = "The device is shutdown; only a ready or leased device streams"; expect(deviceScreen({ conflict, offer, state: "ready" })).toEqual(sentence(conflict)); diff --git a/ui/src/model/screen.ts b/ui/src/model/screen.ts index b79a689e0..911ec2942 100644 --- a/ui/src/model/screen.ts +++ b/ui/src/model/screen.ts @@ -1,6 +1,8 @@ import { type WorkerView, workerName } from "./workers"; import type { Toned } from "./tones"; +export const SCREEN_CAPTURE_LIMIT = 4; + export type ScreenPhase = "idle" | "starting" | "live" | "stopped"; export interface ScreenFact { @@ -155,10 +157,16 @@ export function deviceScreen(input: { readonly state: string; readonly offer: StreamOffer; readonly conflict: string | undefined; + readonly queued?: boolean; }): DeviceScreen { const { conflict, offer, state } = input; if (!offer.offered) return { kind: "sentence", text: plainSentence(offer.reason ?? "") }; if (STREAMING_STATES.has(state)) { + if (input.queued) + return { + kind: "sentence", + text: "Starting once another screen has closed.", + }; return conflict === undefined ? { kind: "picture" } : { kind: "sentence", text: plainSentence(conflict) }; diff --git a/ui/src/model/screens.test.ts b/ui/src/model/screens.test.ts new file mode 100644 index 000000000..a8c6ecb87 --- /dev/null +++ b/ui/src/model/screens.test.ts @@ -0,0 +1,251 @@ +import { expect, it } from "vitest"; + +import { + createCaptureBudget, + filterScreens, + readWatch, + screenNotice, + screensOf, + watchedOf, + writeWatch, +} from "./screens"; +import type { WorkerDevice, WorkerView } from "./workers"; + +function worker( + id: string, + states = ["ready", "leased", "shutdown", "provisioning", "absent"], +): WorkerView { + return { + id, + label: `Host ${id}`, + connection: "connected", + drained: false, + lastSeenAt: 0, + capabilities: [{ name: "stream", state: "available" }], + devices: states.map( + (state, index) => + ({ + id: `dev_${index}`, + physical: false, + spec: { platform: "ios", model: "iPhone", osVersion: "18.4" }, + state, + }) as WorkerDevice, + ), + }; +} + +const NOW = 1_000_000; + +function lease(deviceId: string, requesterId: string, grantedAt: number) { + return { + id: `lse_${deviceId}`, + deviceId, + requesterId, + ownerId: requesterId, + grantedAt, + ttlMs: 60_000, + ttlDeadline: grantedAt + 60_000, + lastRenewedAt: grantedAt, + idChosenByRequester: false, + }; +} + +it("lists running devices with leased ones first by holder, and explains unavailable streams", () => { + const a = { ...worker("a"), leases: [lease("dev_1", "codex:zeta", NOW - 125_000)] }; + const b = { + ...worker("b", ["leased", "ready"]), + leases: [lease("dev_0", "claude-code:alpha", NOW - 5_000)], + }; + const rows = screensOf([b, a], NOW); + expect(rows.map((row) => row.key)).toEqual([ + '["b","dev_0"]', + '["a","dev_1"]', + '["a","dev_0"]', + '["b","dev_1"]', + ]); + expect(screensOf([a, b], NOW)).toEqual(rows); + expect(rows[1]).toMatchObject({ + label: "iPhone", + worker: "Host a", + runtime: "18.4", + platform: "iOS", + state: { word: "leased", tone: "ok" }, + holder: { short: "codex:zeta", full: "codex:zeta" }, + leasedFor: "2 min 5 s", + to: "/fleet/a/devices/dev_1/", + }); + expect(rows[2]?.holder).toBeUndefined(); + expect(rows[2]?.leasedFor).toBeUndefined(); + expect(screensOf([], NOW)).toEqual([]); + expect(screensOf([{ ...a, connection: "disconnected" }], NOW)[0]?.offer).toEqual({ + offered: false, + reason: "Host a is disconnected.", + }); + expect(screensOf([{ ...a, capabilities: [] }], NOW)[0]?.offer).toEqual({ + offered: false, + reason: "Streaming is off on Host a.", + }); +}); + +it("filters by state", () => { + const rows = screensOf([worker("a")], NOW); + expect(filterScreens(rows, "leased").map((row) => row.state.word)).toEqual(["leased"]); + expect(filterScreens(rows, "ready").map((row) => row.state.word)).toEqual(["ready"]); + expect(filterScreens(rows, "all")).toHaveLength(2); +}); + +it("keeps the watched devices in the address and shows at most four that are still running", () => { + const keys = ['["a","dev_0"]', '["a","dev_1"]', '["a","gone"]']; + const search = writeWatch("?page=2", keys); + expect(readWatch(search)).toEqual(keys); + expect(new URLSearchParams(search).get("page")).toBe("2"); + expect(writeWatch(search, [])).toBe("?page=2"); + expect(writeWatch("", [])).toBe(""); + expect(readWatch(writeWatch("", ["1", "2", "3", "4", "5"]))).toEqual(["1", "2", "3", "4"]); + const five = screensOf([worker("a", ["ready", "ready", "ready", "ready", "ready"])], NOW); + expect(watchedOf(five, ['["a","gone"]', ...five.map((row) => row.key)])).toEqual( + five.slice(0, 4), + ); + expect(readWatch("?watch=1&watch=1")).toEqual(["1"]); + const rows = screensOf([worker("a")], NOW); + expect(watchedOf(rows, [keys[1]!, keys[2]!, keys[0]!]).map((row) => row.key)).toEqual([ + keys[1], + keys[0], + ]); +}); + +it("prioritizes daemon loss, unavailable offers and visibility before showing a picture", () => { + const cases = [ + { + connected: false, + offer: { offered: false, reason: "Worker unavailable." }, + active: true, + expected: "Disconnected from the daemon.", + }, + { + connected: false, + offer: { offered: true }, + active: false, + expected: "Disconnected from the daemon.", + }, + { + connected: true, + offer: { offered: false, reason: "Worker unavailable." }, + active: true, + expected: "Worker unavailable.", + }, + { + connected: true, + offer: { offered: false, reason: "Worker unavailable." }, + active: false, + expected: "Worker unavailable.", + }, + { + connected: true, + offer: { offered: false }, + active: true, + expected: "Streaming is unavailable.", + }, + { connected: true, offer: { offered: false, reason: "" }, active: true, expected: "" }, + { + connected: true, + offer: { offered: true, reason: "Ignored for an available offer." }, + active: true, + expected: undefined, + }, + { + connected: true, + offer: { offered: true }, + active: false, + expected: "Paused while this tab is hidden.", + }, + ]; + for (const { expected, ...input } of cases) expect(screenNotice(input)).toBe(expected); +}); + +it("does not give an already aborted request a capture slot", async () => { + const acquire = createCaptureBudget(); + const canceled = new AbortController(); + canceled.abort(); + expect(await acquire(canceled.signal)).toBeUndefined(); + const releases: (() => void)[] = []; + for (let index = 0; index < 4; index++) + void acquire(new AbortController().signal).then((release) => { + if (release !== undefined) releases.push(release); + }); + await Promise.resolve(); + expect(releases).toHaveLength(4); + for (const release of releases) release(); +}); + +it("cancels a waiting request without stealing the next released slot", async () => { + const acquire = createCaptureBudget(); + const owners = await Promise.all( + Array.from({ length: 4 }, () => acquire(new AbortController().signal)), + ); + const canceled = new AbortController(); + let outcome: unknown = "pending"; + void acquire(canceled.signal).then((release) => { + outcome = release; + }); + canceled.abort(); + await Promise.resolve(); + expect(outcome).toBeUndefined(); + let next: (() => void) | undefined; + void acquire(new AbortController().signal).then((release) => { + next = release; + }); + expect(owners.every((release) => typeof release === "function")).toBe(true); + owners[0]!(); + await Promise.resolve(); + expect(typeof next).toBe("function"); + for (const release of owners) release!(); + next!(); +}); + +it("admits waiting capture requests in arrival order", async () => { + const acquire = createCaptureBudget(); + const owners = await Promise.all( + Array.from({ length: 4 }, () => acquire(new AbortController().signal)), + ); + const admitted: string[] = []; + const releases: (() => void)[] = []; + for (const id of ["first", "second"]) + void acquire(new AbortController().signal).then((release) => { + if (release !== undefined) { + admitted.push(id); + releases.push(release); + } + }); + await Promise.resolve(); + expect(admitted).toEqual([]); + owners[0]!(); + await Promise.resolve(); + expect(admitted).toEqual(["first"]); + owners[1]!(); + await Promise.resolve(); + expect(admitted).toEqual(["first", "second"]); + for (const release of owners) release!(); + for (const release of releases) release(); +}); + +it("releasing the same capture twice gives only one waiting request a slot", async () => { + const acquire = createCaptureBudget(); + const owners = await Promise.all( + Array.from({ length: 4 }, () => acquire(new AbortController().signal)), + ); + const releases: (() => void)[] = []; + for (let index = 0; index < 2; index++) + void acquire(new AbortController().signal).then((release) => { + if (release !== undefined) releases.push(release); + }); + owners[0]!(); + owners[0]!(); + await Promise.resolve(); + expect(releases).toHaveLength(1); + owners[1]!(); + await Promise.resolve(); + expect(releases).toHaveLength(2); + for (const release of owners) release!(); + for (const release of releases) release(); +}); diff --git a/ui/src/model/screens.ts b/ui/src/model/screens.ts new file mode 100644 index 000000000..526bd8ec4 --- /dev/null +++ b/ui/src/model/screens.ts @@ -0,0 +1,154 @@ +import { platformName } from "../../../src/contract/inbox"; + +import { shortHolder } from "./holder"; +import { streamPath } from "./paths"; +import { SCREEN_CAPTURE_LIMIT, streamOffer, streamsDevice, type StreamOffer } from "./screen"; +import { formatDuration } from "./time"; +import { deviceStateStatus, type Toned } from "./tones"; +import { type WorkerView, workerName } from "./workers"; + +export interface ScreenTile { + readonly key: string; + readonly workerId: string; + readonly deviceId: string; + readonly worker: string; + readonly label: string; + readonly platform: string; + readonly runtime: string; + readonly state: Toned; + readonly offer: StreamOffer; + readonly to: `/${string}`; + readonly holder?: { readonly short: string; readonly full: string }; + readonly leasedFor?: string; +} + +export type ScreenFilter = "leased" | "ready" | "all"; + +export const SCREEN_FILTERS: readonly { readonly value: ScreenFilter; readonly label: string }[] = [ + { label: "Leased", value: "leased" }, + { label: "Ready", value: "ready" }, + { label: "All", value: "all" }, +]; + +// why: what an operator watches is an agent's work, so leased devices come first, by holder. +export function screensOf(workers: readonly WorkerView[], now: number): ScreenTile[] { + return workers + .flatMap((worker) => { + const leases = new Map((worker.leases ?? []).map((lease) => [lease.deviceId, lease])); + return (worker.devices ?? []) + .filter((device) => streamsDevice(device.state, { offered: true })) + .map((device): ScreenTile => { + const lease = device.state === "leased" ? leases.get(device.id) : undefined; + return { + key: JSON.stringify([worker.id, device.id]), + workerId: worker.id, + deviceId: device.id, + worker: workerName(worker), + label: device.spec.model, + platform: platformName(device.spec.platform), + runtime: device.spec.osVersion, + state: deviceStateStatus(device.state), + offer: + worker.connection === "connected" + ? streamOffer(worker) + : { + offered: false, + reason: `${workerName(worker)} is ${worker.connection}.`, + }, + to: streamPath(worker.id, device.id), + ...(lease === undefined + ? {} + : { + holder: { full: lease.requesterId, short: shortHolder(lease.requesterId) }, + leasedFor: formatDuration(now - lease.grantedAt), + }), + }; + }); + }) + .sort(byLeaseThenHolder); +} + +function byLeaseThenHolder(a: ScreenTile, b: ScreenTile): number { + const rank = (tile: ScreenTile) => (tile.state.word === "leased" ? 0 : 1); + return ( + rank(a) - rank(b) || + compare(a.holder?.full ?? "", b.holder?.full ?? "") || + compare(a.key, b.key) + ); +} + +function compare(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +export function filterScreens(tiles: readonly ScreenTile[], filter: ScreenFilter): ScreenTile[] { + return filter === "all" ? [...tiles] : tiles.filter((tile) => tile.state.word === filter); +} + +// why: the watched devices live in the address, so a reload or Back from a device's page keeps +// them. A key that no longer names a running device is dropped, and never more than the budget. +const WATCH = "watch"; + +export function readWatch(search: string): string[] { + return [...new Set(new URLSearchParams(search).getAll(WATCH))]; +} + +export function writeWatch(search: string, keys: readonly string[]): string { + const params = new URLSearchParams(search); + params.delete(WATCH); + for (const key of keys.slice(0, SCREEN_CAPTURE_LIMIT)) params.append(WATCH, key); + const text = params.toString(); + return text === "" ? "" : `?${text}`; +} + +export function watchedOf(tiles: readonly ScreenTile[], keys: readonly string[]): ScreenTile[] { + const byKey = new Map(tiles.map((tile) => [tile.key, tile])); + return keys.flatMap((key) => byKey.get(key) ?? []).slice(0, SCREEN_CAPTURE_LIMIT); +} + +export function screenNotice(input: { + readonly connected: boolean; + readonly offer: StreamOffer; + readonly active: boolean; +}): string | undefined { + if (!input.connected) return "Disconnected from the daemon."; + if (!input.offer.offered) return input.offer.reason ?? "Streaming is unavailable."; + return input.active ? undefined : "Paused while this tab is hidden."; +} + +export type AcquireCapture = (signal: AbortSignal) => Promise<(() => void) | undefined>; + +// why: the page leaves room for data reads beside its event stream on HTTP/1. Aborting an owner +// removes its picture, but only completion of its reader's cleanup gives its place to another tile. +export function createCaptureBudget(): AcquireCapture { + let owners = 0; + const waiting = new Set<() => void>(); + return (signal) => + new Promise((resolve) => { + if (signal.aborted) { + resolve(undefined); + return; + } + const cancel = () => { + waiting.delete(admit); + signal.removeEventListener("abort", cancel); + resolve(undefined); + }; + const admit = () => { + if (owners >= SCREEN_CAPTURE_LIMIT) return; + waiting.delete(admit); + signal.removeEventListener("abort", cancel); + owners++; + let released = false; + resolve(() => { + if (released) return; + released = true; + owners--; + for (const next of waiting) next(); + }); + }; + waiting.add(admit); + signal.addEventListener("abort", cancel, { once: true }); + admit(); + }); +} diff --git a/ui/src/screens/fleet/screen-panel.tsx b/ui/src/screens/fleet/screen-panel.tsx index 5ab59b859..99dba6464 100644 --- a/ui/src/screens/fleet/screen-panel.tsx +++ b/ui/src/screens/fleet/screen-panel.tsx @@ -1,12 +1,8 @@ -import "./screen-panel.css"; - -import type { CSSProperties } from "react"; - import { type StreamOffer, useDeviceScreen } from "../../state/screen"; +import { ScreenNotice, ScreenView } from "../screen-view"; // why: the hook lives in the panel's own component so that leaving the page ends the capture, and a -// panel that is not drawn never starts one. The picture sits in a phone-shaped frame with two pills -// over it that say what the stream is doing, from the decoder's own figures. +// panel that is not drawn never starts one. export function ScreenPanel(props: { readonly workerId: string; readonly deviceId: string; @@ -15,50 +11,9 @@ export function ScreenPanel(props: { }) { const { deviceId, offer, state, workerId } = props; const shown = useDeviceScreen(workerId, deviceId, state, offer); - if (shown.kind !== "picture") { - return ( -
-
-

{shown.text}

-
-
- ); - } - const { screen } = shown; - const { live, note, readout, waiting } = screen; - const landscape = screen.width > screen.height && screen.height > 0; - return ( -
- {readout.overlay === undefined ? null : ( -
- -