fix(p2): the page never goes blank; old client state and arrangements cannot hide or break views

- AppBoundary around the React root: a failure shows itself with Reload and a
  reset of what the device saved for the session (its layout and panels, keys
  naming it, cached conversations, the tab's navigation and draft, the service
  worker's kept page). Render failures, uncaught errors and rejections and view
  panes' failures are reported to POST /client-error (logs plugin): a notice for
  the owner's pages, a log line for guests'.
- The session panels' stored entries are checked field by field.
- An agent arrangement whose views are all gone (the removed custom kind) no
  longer hides every view.
- The service worker stays alive until the network's page is kept, so a slow
  start does not pin the app to an older kept page.
Chromium test ui-recovery: md and html artifact views at phone width; a
session with an older version's views document and layout; a failing page with
Reset and the owner's notice.
This commit is contained in:
Mario Zechner 2026-11-12 08:17:59 +00:00
parent 749d88d700
commit ad335fec19
14 changed files with 562 additions and 20 deletions

View file

@ -607,6 +607,15 @@ the session) and answers with the outcome: once the worker runs, or rejecting `w
start, so the button shows pending and then the result; drafts and attachments stay intact. Creating a session
navigates to its view before awaiting the worker, so a failed first start also has a visible recovery screen.
**The page never goes blank** (`src/web/app-boundary.tsx`): the React root renders inside `AppBoundary`, which shows
a failure with **Reload** and **Reset this device's saved state for this session** (localStorage keys naming the
session, its panels, its cached conversations, the tab's navigation and draft, the service worker's kept page).
Render failures, uncaught errors and rejections, and failures a view pane's boundary catches are reported to
`POST /client-error` (logs plugin; same-origin, owner or guest, a bounded body; at most 20 per page load and 60 a
minute on the server): an owner's page becomes a notice of source `web`, a guest's only a log line. Persisted client
state is device data an older page may have written: the layout (`parseLayout`) and the session panels (each field
checked) drop what does not fit. Test: `ui-recovery.test.ts`.
Host `onError`, refused reloads and worker failures publish bounded, redacted owner notices (`LogNotices`), with
Show logs and Dismiss. Notices keep the latest error per source (at most 50 sources); normal shutdown/abort
messages do not become worker-failure notices. Archived-session admission refusals are not cached as crashes,

View file

@ -1,11 +1,37 @@
import { readFile, stat } from "node:fs/promises";
import type { IncomingMessage } from "node:http";
import { join } from "node:path";
import { arr, compile, obj, str } from "@earendil-works/pi-schema";
import { contribute, defineFacet, deriveTyped, followNative, forbidden, isOwner } from "@p2/app/v1";
import { contribute, defineFacet, deriveTyped, followNative, forbidden, isGuest, isOwner } from "@p2/app/v1";
import { captureProcessLogs, type LogSnapshot, processLogs } from "@p2/app/v1/node";
import { Server } from "@p2/app/v1/server";
import { fromOrigin, Routes, Server } from "@p2/app/v1/server";
import { LogLineSchema, LogNotices, Logs } from "./contract.ts";
/** A page's report of its own failure (src/web/app-boundary.tsx), as the route takes it: wire input. */
const ClientReportSchema = obj({
where: str({ maxLength: 40 }),
message: str({ maxLength: 2000 }),
stack: str({ maxLength: 4000 }),
path: str({ maxLength: 400 }),
version: str({ maxLength: 80 }),
});
const isClientReport = compile(ClientReportSchema).check;
/** The largest report body read, and how many reports a minute the server keeps (the rest are dropped). */
const CLIENT_REPORT_BYTES = 16 * 1024;
const CLIENT_REPORTS = 60;
/** A request's body as text, or undefined past `limit` bytes. */
async function bodyText(request: IncomingMessage, limit: number): Promise<string | undefined> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of request) {
size += (chunk as Buffer).length;
if (size > limit) return undefined;
chunks.push(chunk as Buffer);
}
return Buffer.concat(chunks).toString("utf8");
}
const SnapshotSchema = obj({ source: str(), lines: arr(LogLineSchema, { maxItems: 1000 }) }, { open: true });
const isSnapshot = compile(SnapshotSchema).check;
@ -69,6 +95,42 @@ export default defineFacet((host) => {
);
});
// What pages report about themselves (src/web/app-boundary.tsx): a failure the owner's page saw is a notice; a
// guest's is only logged (a guest must not fill the owner's notices). Bounded: a page sends at most a few, the
// server keeps at most `CLIENT_REPORTS` a minute.
contribute(host, "p2.client-errors", (self) => {
let minute = { start: 0, count: 0 };
self.contribute(Routes, {
"POST /client-error": async (request, response, { principal, origin }) => {
if (!fromOrigin(request, origin) || (!isOwner(principal) && !isGuest(principal))) {
response.writeHead(403);
response.end();
return;
}
const body = await bodyText(request, CLIENT_REPORT_BYTES);
let report: unknown;
try {
report = body === undefined ? undefined : JSON.parse(body);
} catch {}
if (!isClientReport(report)) {
response.writeHead(400);
response.end();
return;
}
const now = Date.now();
if (now - minute.start > 60_000) minute = { start: now, count: 0 };
if (++minute.count <= CLIENT_REPORTS) {
const who = isOwner(principal) ? "owner" : "guest";
const text = `Page error (${report.where}, ${who}, ${report.path}, version ${report.version}): ${report.message}${report.stack ? `\n${report.stack}` : ""}`;
if (isOwner(principal)) processLogs.notice("web", text);
else processLogs.append("web", "error", text);
}
response.writeHead(204);
response.end();
},
});
});
host.serve(LogNotices, (_params, principal, self) => {
if (!isOwner(principal)) throw forbidden("Notices are only available to owners");
// The process's notices as it keeps them: a dismissal tells this source before `dismiss` returns.

View file

@ -5,6 +5,7 @@
import { BACKGROUND_CONTEXT, liveIn } from "@p2/app/v1";
import {
CloseIcon,
reportClientError,
useComposerState,
useObject,
useReadable,
@ -368,6 +369,10 @@ class PaneBoundary extends Component<{ children: ReactNode }, { error?: string }
return { error: error instanceof Error ? error.message : String(error) };
}
override componentDidCatch(error: unknown): void {
reportClientError(error, "view pane");
}
override render() {
return this.state.error === undefined ? (
this.props.children

View file

@ -287,6 +287,15 @@ export function arrangedTree(value: unknown, known: ReadonlySet<string>): Layout
return viewsIn(tree).includes(CHAT) ? tree : normalize(split("row", [area([CHAT]), tree], [0.4, 0.6]));
}
/** The view IDs an arrangement names, as stored (any version may have written it). */
function namedViews(value: unknown, depth = 0): string[] {
if (depth > 8) return [];
if (typeof value === "string") return [value];
if (!isRecord(value)) return [];
const children = [value.tabs, value.row, value.column].find(Array.isArray) ?? [];
return children.flatMap((child) => namedViews(child, depth + 1));
}
/**
* `layout` with an agent's arrangement adopted: its tree, the session's other views hidden here (the Views sheet shows
* them again), and its stamp, so a device adopts each arrangement once and the person may change it afterwards.
@ -296,8 +305,13 @@ export function adopt(
arrangement: { layout: unknown; stamp: number },
views: readonly string[],
): Layout {
const tree = arrangedTree(arrangement.layout, new Set([CHAT, ...views]));
if (!tree) return { ...layout, arranged: arrangement.stamp };
const known = new Set([CHAT, ...views]);
const tree = arrangedTree(arrangement.layout, known);
// An arrangement whose views are all gone (closed since, or of a removed kind) arranges nothing: it does not hide
// the views the session has now.
const named = namedViews(arrangement.layout).filter((id) => id !== CHAT);
if (!tree || (named.length > 0 && !named.some((id) => known.has(id))))
return { ...layout, arranged: arrangement.stamp };
const placed = new Set(viewsIn(tree));
return {
...layout,

View file

@ -55,11 +55,15 @@ async function keepPage(response) {
const isAppPage = (response) =>
response.ok && response.type === "basic" && (response.headers.get("Content-Type") ?? "").startsWith("text/html");
async function page(request) {
async function page(event) {
const request = event.request;
const network = fetch(request).then(async (response) => {
if (isAppPage(response)) await keepPage(response).catch(() => {});
return response;
});
// When the kept page answers first, the worker stays alive until the network's page is kept too: the next start
// gets the current version, instead of the kept one again whenever the network is slower than PAGE_WAIT.
event.waitUntil(network.catch(() => {}));
const kept = () => caches.open(SHELL).then((cache) => cache.match("/"));
const waited = new Promise((resolve) => setTimeout(resolve, PAGE_WAIT, "waited"));
try {
@ -101,6 +105,6 @@ self.addEventListener("fetch", (event) => {
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (request.mode === "navigate" && request.destination === "document" && isPage(url.pathname))
event.respondWith(page(request));
event.respondWith(page(event));
else if (url.pathname.startsWith(BUNDLE)) event.respondWith(bundleFile(request));
});

View file

@ -3,6 +3,7 @@
export * from "../../runtime/web.tsx";
export * from "../../web/AppLayout.tsx";
export * from "../../web/activity/api.ts";
export { reportClientError } from "../../web/app-boundary.tsx";
export * from "../../web/artifact-kinds.ts";
export * from "../../web/Chat.tsx";
export * from "../../web/Code.tsx";

View file

@ -10,6 +10,7 @@ import { createHost, type Facet, hostErrorText, newerPeerProtocol } from "../../
import { SERVER } from "../../runtime/principals.ts";
import { whenLive } from "../../runtime/refs.ts";
import { getNavigation, HostContext, Slot, setConnected, setShareEnded, webCoreFacet } from "../../runtime/web.tsx";
import { AppBoundary, startErrorReports } from "../../web/app-boundary.tsx";
import { browserEnvironment, keepConnected } from "../../web/reconnect.ts";
import { startShellBridge } from "../../web/shell-bridge.ts";
import { startTheme } from "../../web/theme.ts";
@ -131,9 +132,12 @@ export function startWeb(facets: readonly (readonly [string, Facet])[]): void {
startShellBridge(getNavigation());
const element = document.getElementById("root");
if (!element) throw new Error("Missing application root");
startErrorReports();
createRoot(element).render(
<HostContext.Provider value={host}>
<Slot name="app" fallback={<div className="hero">Loading…</div>} />
</HostContext.Provider>,
<AppBoundary>
<HostContext.Provider value={host}>
<Slot name="app" fallback={<div className="hero">Loading…</div>} />
</HostContext.Provider>
</AppBoundary>,
);
}

View file

@ -0,0 +1,120 @@
// The page never goes blank: the app's root error boundary shows what failed, with a reload and a reset of what this
// device saved for the open session (state an older version of the page may have written), and every failure the page
// sees (a render, an uncaught error or rejection, a pane's boundary) is reported to the server, which logs it and, for
// the owner, shows it among the owner's notices.
import { Component, type ErrorInfo, type ReactNode } from "react";
import { forgetSession } from "./conversation-cache.ts";
/** How many reports one page load sends at most: a failing loop must not flood the server. */
const MAX_REPORTS = 20;
const reported = new Set<string>();
/** Reports a failure of the page to the server (deduplicated, bounded, never throwing). */
export function reportClientError(error: unknown, where: string): void {
const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
const key = `${where}\n${message}`;
if (reported.has(key) || reported.size >= MAX_REPORTS) return;
reported.add(key);
const stack = error instanceof Error ? (error.stack ?? "") : "";
try {
void fetch("/client-error", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
keepalive: true,
body: JSON.stringify({
where,
message: message.slice(0, 2000),
stack: stack.slice(0, 4000),
path: location.pathname,
version: document.documentElement.dataset.webVersion ?? "",
}),
}).catch(() => {});
} catch {
// Reporting is best effort: the page's own recovery does not depend on it.
}
}
/** Reports errors and rejections nothing caught, for the page's whole life. */
export function startErrorReports(): void {
addEventListener("error", (event) => reportClientError(event.error ?? event.message, "window"));
addEventListener("unhandledrejection", (event) => reportClientError(event.reason, "promise"));
}
/** The session the page's address names, if any. */
const sessionOfPage = (): string | undefined => /^\/s\/([0-9a-f-]+)/.exec(location.pathname)?.[1];
/**
* Forgets what this device saved for `session` (its layout and panels, any key naming it, its cached conversations,
* the tab's navigation and draft) and the service worker's kept page, so the next load starts from the server's state
* with the current code.
*/
export async function resetSessionState(session: string): Promise<void> {
try {
for (const key of Object.keys(localStorage)) if (key.includes(session)) localStorage.removeItem(key);
const panels: unknown = JSON.parse(localStorage.getItem("p2-session-panels") ?? "[]");
if (Array.isArray(panels))
localStorage.setItem(
"p2-session-panels",
JSON.stringify(panels.filter((entry) => !(Array.isArray(entry) && entry[0] === session))),
);
sessionStorage.removeItem("p2-navigation");
sessionStorage.removeItem("p2-draft");
} catch {}
await forgetSession(session).catch(() => {});
try {
await caches?.delete("p2-app-shell");
} catch {}
}
/** The app's root boundary: a failure anywhere shows itself with a way out, instead of an empty page. */
export class AppBoundary extends Component<{ children: ReactNode }, { error?: unknown }> {
override state: { error?: unknown } = {};
static getDerivedStateFromError(error: unknown): { error: unknown } {
return { error };
}
override componentDidCatch(error: unknown, info: ErrorInfo): void {
reportClientError(
error instanceof Error && info.componentStack ? withComponents(error, info.componentStack) : error,
"render",
);
}
override render() {
if (this.state.error === undefined) return this.props.children;
return <PageFailed error={this.state.error} />;
}
}
/** `error` with the component stack React gives (where in the page it failed) added to its stack. */
function withComponents(error: Error, components: string): Error {
const copy = new Error(error.message);
copy.name = error.name;
copy.stack = `${error.stack ?? ""}\nComponents:${components}`;
return copy;
}
/** What the person sees when the page failed: the error, Reload, and a reset of the open session's saved state. */
function PageFailed({ error }: { error: unknown }) {
const session = sessionOfPage();
const message = error instanceof Error ? error.message : String(error);
return (
<div className="hero page-failed" role="alert" data-testid="page-failed">
<h2>This page failed</h2>
<p className="muted">{message}</p>
<p className="muted">The error was reported to the server.</p>
<p>
<button type="button" className="primary" onClick={() => location.reload()}>
Reload
</button>{" "}
{session && (
<button type="button" onClick={() => void resetSessionState(session).finally(() => location.reload())}>
Reset this device's saved state for this session
</button>
)}
</p>
</div>
);
}

View file

@ -1,6 +1,6 @@
// The right-hand panels each session had open on this device (the workspace, the terminal, the side panel), so a
// session opens with its own panels instead of the ones the previous session had open.
import type { Route } from "./navigation.ts";
import type { Route, WorkspaceTab } from "./navigation.ts";
/** The parts of a route that are a session's panels. */
export type SessionPanels = Pick<Route, "workspace" | "terminal" | "panel" | "activity">;
@ -75,25 +75,50 @@ function panelsOf(from: SessionPanels, conversation: number, shown: number): Ses
};
}
// The stored list is device data any version of the page may have written: entries that are not as expected are
// dropped, not trusted.
// The stored list is device data any version of the page may have written: entries and fields that are not as this
// version expects are dropped, not trusted.
function read(): [string, Kept][] {
try {
const value: unknown = JSON.parse(localStorage.getItem(STORAGE) ?? "[]");
if (!Array.isArray(value)) return [];
return value.filter(
(entry): entry is [string, Kept] =>
Array.isArray(entry) &&
typeof entry[0] === "string" &&
typeof entry[1] === "object" &&
entry[1] !== null &&
typeof entry[1].conversation === "number",
);
return value.flatMap((entry): [string, Kept][] => {
if (!Array.isArray(entry) || typeof entry[0] !== "string") return [];
const kept = keptOf(entry[1]);
return kept ? [[entry[0], kept]] : [];
});
} catch {
return [];
}
}
const TABS: readonly string[] = ["files", "changes", "search", "comments", "terminal"];
/** A stored entry's panels, each field kept only when it has this version's shape. */
function keptOf(value: unknown): Kept | undefined {
if (typeof value !== "object" || value === null) return undefined;
const { conversation, workspace, terminal, panel, activity } = value as Record<string, unknown>;
if (typeof conversation !== "number") return undefined;
const tab = (workspace as { tab?: unknown } | null | undefined)?.tab;
const shell = (workspace as { terminal?: unknown } | null | undefined)?.terminal;
const row = (activity as { row?: unknown } | null | undefined)?.row;
const step = (activity as { step?: unknown } | null | undefined)?.step;
return {
conversation,
...(typeof tab === "string" && TABS.includes(tab)
? {
workspace: {
tab: tab as WorkspaceTab,
directory: "",
...(typeof shell === "string" ? { terminal: shell } : {}),
},
}
: {}),
...(typeof terminal === "string" ? { terminal } : {}),
...(typeof panel === "string" ? { panel } : {}),
...(typeof row === "string" ? { activity: { row, ...(typeof step === "string" ? { step } : {}) } } : {}),
};
}
function write(entries: [string, Kept][]): void {
try {
localStorage.setItem(STORAGE, JSON.stringify(entries));

View file

@ -0,0 +1,5 @@
{
"name": "recovery",
"private": true,
"type": "module"
}

View file

@ -0,0 +1,17 @@
// Test only (ui-recovery.test.ts): a composer slot that throws while `p2-test-crash:<session>` is set on the device, so
// the page's root boundary has something to catch outside every pane's boundary.
import { contribute, defineFacet } from "@p2/app/v1";
import { Slots, useRoute } from "@p2/app/v1/web";
function Crash() {
const session = useRoute().session;
if (session && localStorage.getItem(`p2-test-crash:${session}`) === "1")
throw new Error("The test's crash: state an older page left");
return null;
}
export default defineFacet((host) => {
contribute(host, "recovery.web", (self) => {
self.contribute(Slots, { "composer:recovery-crash": Crash });
});
});

View file

@ -0,0 +1,89 @@
// Test only (ui-recovery.test.ts): writes the views document as p2 before 2026-11-12 wrote it (custom views, `path`,
// view errors, an arrangement naming a custom view), and a composer slot that can fail (web.tsx).
import { defineDoc, defineExtension } from "@earendil-works/pi-durable";
import { obj } from "@earendil-works/pi-schema";
import { contribute, defineFacet, type JsonValue } from "@p2/app/v1";
import { defineP2Tool, Extensions, harnessOf, type P2Tool } from "@p2/app/v1/worker";
/** The document as any version wrote it: plain JSON. */
type OldState = { [key: string]: JsonValue };
const OldViews = defineDoc<OldState>({
kind: "p2.views",
version: 1,
scope: "session",
initial: () => ({ views: [], annotations: [] }),
checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 32,
});
export default defineFacet((host) => {
contribute(host, "seed.tools", (self) => {
const harness = harnessOf(self);
const extension = defineExtension<P2Tool>({
name: "seed",
tools: [
defineP2Tool({
name: "seed_old_views",
description: "Writes old-shaped views.",
parameters: obj({}),
replay: "unsafe",
callers: ["tools"],
execute: async (_args, _api, context) => {
const now = Date.now();
await harness().durable.commit(async (tx) => {
const draft = await tx.doc(OldViews);
draft.views = [
{
id: "glyph",
kind: "custom",
title: "Glyph editor",
source: 3,
errors: ["TypeError: x"],
selection: { summary: "point 1", data: { point: 1 }, sent: true },
focus: now - 5000,
created: now - 9000,
},
{
id: "notes",
kind: "markdown",
title: "Notes",
path: "notes.md",
focus: now - 4000,
created: now - 8000,
},
{ id: "diff", kind: "changes", title: "Changes", focus: now - 3000, created: now - 7000 },
...((draft.views as JsonValue[] | undefined) ?? []),
];
draft.arrangement = { layout: { row: ["transcript", "glyph"] }, stamp: now - 1000 };
draft.annotations = [
{
id: "a1",
kind: "comment",
view: "glyph",
quote: "point",
note: "bigger",
author: "Owner",
created: now - 2000,
sent: true,
},
{
id: "a2",
kind: "ink",
view: "glyph",
strokes: [[0.1, 0.1, 0.5, 0.5]],
aspect: 1,
under: "x",
author: "Owner",
created: now - 1000,
sent: true,
},
];
}, context);
return { output: [{ type: "text" as const, text: "seeded" }] };
},
}),
],
});
self.contribute(Extensions, { [extension.name]: extension });
});
});

View file

@ -0,0 +1,177 @@
// Browser: the page recovers instead of going blank, and state from before 2026-11-12 opens. At phone width an md and
// an html artifact view show on their own; a session whose views document an older version wrote (custom views, `path`,
// an arrangement naming a removed view) with an older page's layout opens an md artifact view; a page that fails
// outside every pane shows the error with Reload and a reset of the session's saved state, and the owner's notices get
// it. The fixture plugin (test/fixtures/recovery-plugin) writes the old document and can fail on purpose. Fake
// provider, disposable data.
import assert from "node:assert/strict";
import { cpSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import type { ToolResultMessage } from "@earendil-works/pi-ai";
import type { ConversationView } from "@earendil-works/pi-durable";
import { BACKGROUND_CONTEXT } from "@p2/app/v1";
import { Chat } from "../../plugins/chat/contract.ts";
import { LogNotices } from "../../plugins/logs/contract.ts";
import { Sessions } from "../../plugins/sessions/contract.ts";
import type { Host, RefIn } from "../../src/runtime/chord.ts";
import { Browser, browserTests } from "./browser.ts";
import { type Fixture, holdIn, startFixture, until } from "./helpers.ts";
/** The owner's artifact of the night it happened (a table, inline code). */
const NOTES = [
"# Artifacts, as of tonight",
"",
"- **Owned by plugins**, stored on the server, keyed by the session: export, import and delete carry them.",
"- **Tools** are code-mode only, grouped in the `artifact` namespace.",
"- **Views** only show things: `view_open({ kind, item })`.",
"",
"| Tool | Does |",
"| --- | --- |",
"| artifact_write | a new artifact or a new version |",
"| artifact_open | beside the chat |",
"",
].join("\n");
/** Collects what the page throws or logs as an error, from its first script on. */
const CAPTURE = `window.__errors = [];
addEventListener('error', (e) => window.__errors.push(String(e.message)));
addEventListener('unhandledrejection', (e) => window.__errors.push('rejection ' + String(e.reason?.message ?? e.reason)));`;
/** The md artifact's view: its ID made from its title. */
const MD = "artifacts-what-changed-tonight";
const results = (view: ConversationView | null | undefined): ToolResultMessage[] =>
(view?.entries ?? []).flatMap((entry) =>
(entry.model ?? []).filter((message): message is ToolResultMessage => message.role === "toolResult"),
);
describe("page recovery and old state", { skip: !browserTests }, () => {
let fixture: Fixture;
let browser: Browser;
let owner: Host;
let sessions: RefIn<typeof Sessions, "owner">;
let sent = 0;
/** Has `session`'s agent run `text` (a fake-provider prompt) to the end of its turn; that turn's result. */
const run = async (session: string, text: string): Promise<ToolResultMessage | undefined> => {
const chat = await holdIn(owner, Chat, { session, conversation: 1 }, "participant");
const before = results(chat.view.value).length;
await chat.send({ text, requestId: `run-${++sent}` }, BACKGROUND_CONTEXT);
const view = await until(
chat.view,
(value) => results(value).length > before && !(value?.docs["pi.live"] as { run?: unknown })?.run,
);
chat.release();
const result = results(view).at(-1);
assert.equal(result?.isError, false, JSON.stringify(result?.content));
return result;
};
const newSession = async (title: string): Promise<string> =>
(await sessions.create({ cwd: fixture.workspace, title }, BACKGROUND_CONTEXT)).id;
/** The owner's md artifact and an html one, opened as views (the md one last: in front). */
const openArtifacts = (id: string) =>
run(
id,
`codemode ${[
`await tools.artifact_write({ id: "counter", kind: "html", title: "Counter", content: "<button id=add>+1</button>" });`,
`await tools.artifact_write({ id: "notes", kind: "md", title: "Artifacts: what changed tonight", content: ${JSON.stringify(NOTES)} });`,
`await tools.artifact_open({ id: "counter" });`,
`await tools.artifact_open({ id: "notes" });`,
].join("\n")}`,
);
const errors = () => browser.evaluate<string[]>("window.__errors");
const shown = "[...document.querySelectorAll('.views-pane:not([hidden])')].map((pane) => pane.dataset.viewPane)";
before(async () => {
fixture = await startFixture({ web: true });
writeFileSync(join(fixture.workspace, "notes.md"), "# Notes\n");
cpSync(new URL("../fixtures/recovery-plugin", import.meta.url), join(fixture.dataDir, "plugins", "recovery"), {
recursive: true,
});
owner = fixture.browser();
sessions = await holdIn(owner, Sessions, {}, "owner");
const setup = (await sessions.create({ cwd: fixture.workspace, title: "Setup" }, BACKGROUND_CONTEXT)).id;
await run(setup, "reload_plugins {}");
browser = await Browser.start();
await browser.call("Page.addScriptToEvaluateOnNewDocument", { source: CAPTURE });
await browser.signIn(fixture.owner);
});
after(async () => {
await browser?.close();
await fixture?.close();
});
it("shows an md and an html artifact view on their own at phone width", async () => {
const id = await newSession("Phone views");
await openArtifacts(id);
await browser.metrics(390, 844);
await browser.open(`http://127.0.0.1:${fixture.server.port}/s/${id}`);
// The agent showed the md view last: the phone shows it, alone.
await browser.wait(`${shown}.join() === '${MD}' && document.querySelector('[data-view-pane=${MD}] table')`);
assert.match(
await browser.evaluate<string>(`document.querySelector('[data-view-pane=${MD}]').textContent`),
/Artifacts, as of tonight/,
);
await browser.evaluate(
"[...document.querySelectorAll('.views-tabs.phone .views-tab')].find((tab) => tab.textContent === 'Counter').click()",
);
await browser.wait(`${shown}.join() === 'counter' && document.querySelector('[data-view-pane=counter] iframe')`);
assert.deepEqual(await errors(), []);
});
it("opens an md artifact view at phone width in a session whose views and layout an older version wrote", async () => {
const id = await newSession("Old state");
await run(id, "codemode await tools.seed_old_views({});");
await openArtifacts(id);
await browser.metrics(390, 844);
// The layout an older page kept: the custom view placed and in front on the phone.
await browser.open(`http://127.0.0.1:${fixture.server.port}/`);
await browser.evaluate(
`localStorage.setItem('p2.views.layout:${id}', JSON.stringify({ tree: { kind: 'split', id: 's1', dir: 'row', children: [{ kind: 'area', id: 'a1', views: ['transcript'], active: 'transcript' }, { kind: 'area', id: 'a2', views: ['glyph', 'notes'], active: 'glyph' }], sizes: [0.5, 0.5] }, hidden: [], focus: { glyph: 1 }, phone: 'glyph', arranged: 0 }))`,
);
await browser.open(`http://127.0.0.1:${fixture.server.port}/s/${id}`);
// The old arrangement names only the removed custom view: it hides nothing.
await browser.wait(`${shown}.join() === '${MD}' && document.querySelector('[data-view-pane=${MD}] table')`);
const tabs = await browser.evaluate<string[]>(
"[...document.querySelectorAll('.views-tabs.phone .views-tab')].map((tab) => tab.textContent)",
);
assert.deepEqual(tabs, ["Chat", "Notes", "Changes", "Counter", "Artifacts: what changed tonight"]);
assert.deepEqual(await errors(), []);
});
it("shows a failure outside every pane with Reload and a reset of the session's saved state, and reports it", async () => {
const id = await newSession("Failing page");
await browser.metrics(1280, 900);
await browser.open(`http://127.0.0.1:${fixture.server.port}/`);
await browser.evaluate(
`localStorage.setItem('p2-test-crash:${id}', '1'); localStorage.setItem('p2.views.layout:${id}', 'kept by an older page')`,
);
await browser.open(`http://127.0.0.1:${fixture.server.port}/s/${id}`);
await browser.wait("document.querySelector('[data-testid=page-failed]')");
assert.match(
await browser.evaluate<string>("document.querySelector('[data-testid=page-failed]').textContent"),
/The test's crash/,
);
// The owner's notices tell of it.
const notices = await holdIn(owner, LogNotices, {}, "owner");
await until(notices.notices, (value) =>
value.some((notice) => notice.source === "web" && notice.message.includes("The test's crash")),
);
// Reset forgets what the device kept for the session (the failure's flag among it); the page loads.
await browser.evaluate(
"[...document.querySelectorAll('[data-testid=page-failed] button')].find((button) => button.textContent.startsWith('Reset')).click()",
);
await browser.wait(
"!document.querySelector('[data-testid=page-failed]') && document.querySelector('.composer textarea')",
);
assert.deepEqual(
await browser.evaluate<(string | null)[]>(
`[localStorage.getItem('p2-test-crash:${id}'), localStorage.getItem('p2.views.layout:${id}')]`,
),
[null, null],
);
});
});

View file

@ -141,6 +141,16 @@ describe("arrangements", () => {
// Seen views stay where the arrangement put them.
assert.equal(shape(settle(layout, views(["plan", 1], ["glyph", 2])).tree), "row([*transcript] [*glyph])");
});
it("ignores an arrangement whose views are all gone (e.g. of the removed custom kind), hiding nothing", () => {
const before = settle(initialLayout(), views(["plan", 1], ["notes", 2]));
const layout = adopt(before, { layout: { row: [CHAT, "glyph"] }, stamp: 9 }, ["plan", "notes"]);
assert.equal(shape(layout.tree), shape(before.tree));
assert.deepEqual([layout.hidden, layout.arranged], [[], 9]);
// The transcript alone, named on purpose, still hides the rest.
const alone = adopt(before, { layout: CHAT, stamp: 10 }, ["plan", "notes"]);
assert.deepEqual(alone.hidden, ["plan", "notes"]);
});
});
describe("parseLayout", () => {