Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ The plugins every server needs to be usable, `chat` and `acp` today. CI packs th
_Avoid_: Built-in plugins, core plugins, bundled plugins

**Plugin log**:
One file per plugin in the computer's temp folder. It holds what the plugin's newest code printed and the errors it threw, on the server and in the window. A reload of that plugin empties it.
One file per plugin in the computer's temp folder. It holds what the active build printed and the errors it threw, on the server and in the window. A successful reload replaces the log only for plugins whose build changes.
_Avoid_: Server log, console, output

**Skill file**:
Expand Down
87 changes: 70 additions & 17 deletions app/src/plugins/views.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export function createPluginShell(
return createRoot((dispose) => {
stop = dispose;
const host: WebPluginHost = new WebPluginHost(endpoint, () => loader.metadata().plugins);
watchUnhandledPluginErrors(host);
const loader: PluginLoader = createPluginLoader(host, serverAssets(endpoint, source));
const navigation = routerFacade(routing.router);
const views = createMemo(() =>
Expand Down Expand Up @@ -126,27 +127,69 @@ export function createPluginShell(
});
}

function watchUnhandledPluginErrors(host: WebPluginHost) {
const unhandled = (event: ErrorEvent | PromiseRejectionEvent) => {
const cause = "reason" in event ? event.reason : event.error;
const plugin = host.errorOwner("filename" in event ? event.filename : "", cause);
if (plugin)
host.reportError(
plugin,
host.logRevision(plugin),
describe(cause ?? ("message" in event ? event.message : "Unhandled rejection")),
);
};
window.addEventListener("error", unhandled);
window.addEventListener("unhandledrejection", unhandled);
onCleanup(() => {
window.removeEventListener("error", unhandled);
window.removeEventListener("unhandledrejection", unhandled);
});
}

export function PluginViews(props: { shell: PluginShell; view: PluginView }) {
const key = () => `${props.view.plugin}:${props.view.id}:${props.shell.loader.version(props.view.plugin)}`;
return (
<Show keyed when={key()}>
{(_key) => (
<Errored
fallback={(cause) => (
<ViewFailure
view={props.view}
cause={cause()}
reload={() => props.shell.loader.reload(props.view.plugin)}
/>
)}
>
<LoadedView {...props} />
</Errored>
)}
{(_key) => {
const revision = props.shell.host.logRevision(props.view.plugin);
return (
<Errored
fallback={(cause) => (
<ViewFailure
view={props.view}
cause={cause()}
report={(text) => props.shell.host.reportError(props.view.plugin, revision, text)}
reload={() => props.shell.loader.reload(props.view.plugin)}
/>
)}
>
<LoadedView {...props} revision={revision} />
</Errored>
);
}}
</Show>
);
}
function ViewFailure(props: { view: PluginView; cause: unknown; reload(): void }) {
function ViewFailure(props: {
view: PluginView;
cause: unknown;
reload(): void;
report(text: string): void;
}) {
const command = () => `tokamak plugin logs ${props.view.plugin}`;
createEffect(
() => describe(props.cause),
(text) => props.report(text),
);
const [copyStatus, setCopyStatus] = createSignal("");
const copy = async () => {
try {
await navigator.clipboard.writeText(command());
setCopyStatus("Copied plugin log command.");
} catch {
setCopyStatus("Could not copy plugin log command.");
}
};
return (
<div
role="alert"
Expand All @@ -165,13 +208,18 @@ function ViewFailure(props: { view: PluginView; cause: unknown; reload(): void }
<Button variant="primary" onClick={() => props.reload()}>
Reload
</Button>
<div class="flex flex-wrap items-center justify-center gap-2">
<code class="text-data break-all">{command()}</code>
<Button onClick={() => void copy()}>Copy plugin log command</Button>
<span role="status">{copyStatus()}</span>
</div>
</div>
);
}
function describe(cause: unknown): string {
return cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
}
function LoadedView(props: { shell: PluginShell; view: PluginView }) {
function LoadedView(props: { shell: PluginShell; view: PluginView; revision?: string }) {
const [module, setModule] = createSignal<ModuleExports>();
const [failure, setFailure] = createSignal<{ cause: unknown }>();
let alive = true;
Expand Down Expand Up @@ -211,6 +259,7 @@ function LoadedView(props: { shell: PluginShell; view: PluginView }) {
<OwnedView
shell={props.shell}
plugin={props.view.plugin}
revision={props.revision}
component={component as Component<Record<string, unknown>>}
/>
);
Expand All @@ -221,13 +270,17 @@ function LoadedView(props: { shell: PluginShell; view: PluginView }) {
function OwnedView(props: {
shell: PluginShell;
plugin: string;
revision?: string;
component: Component<Record<string, unknown>>;
}) {
let dispose = () => {};
onCleanup(() => dispose());
return createRoot((stop): JSX.Element => {
dispose = stop;
onCleanup(props.shell.host.own(props.plugin, stop));
const revision = props.revision;
const reportCallbackError = (cause: unknown) =>
props.shell.host.reportError(props.plugin, revision, describe(cause));
const shortcuts = new Map<string, Set<() => void>>();
const registerShortcut = (key: string, handler: () => void) => {
const handlers = shortcuts.get(key) ?? new Set();
Expand All @@ -254,9 +307,9 @@ function OwnedView(props: {
event.preventDefault();
for (const handler of handlers) {
try {
handler();
void Promise.resolve(handler()).catch(reportCallbackError);
} catch (cause) {
props.shell.host.notifyError(`@plugins/${props.plugin}/ui`, cause);
reportCallbackError(cause);
}
}
};
Expand Down
37 changes: 37 additions & 0 deletions app/src/plugins/web-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,43 @@ export class WebPluginHost implements PluginModuleHost {
throw cause;
}
}
logRevision(id: string) {
return this.manifests().find((manifest) => manifest.plugin.id === id)?.logRevision;
}
errorOwner(filename: string, cause: unknown): string | undefined {
const pluginForUrl = (url: string) => {
for (const manifest of this.manifests()) {
const id = manifest.plugin.id;
if (this.generations.get(moduleName(id))?.urls.has(url)) return id;
}
};
// Browser stack frames carry the actual blob module URLs. Leave errors
// without a known module unattributed, even if a plugin view is open.
if (cause instanceof Error) {
for (const frame of cause.stack?.split("\n").reverse() ?? []) {
const url = frame.match(/blob:[^\s)]+?(?::\d+:\d+)(?=[\s)]|$)/)?.[0].replace(/:\d+:\d+$/, "");
const owner = url && pluginForUrl(url);
if (owner) return owner;
}
}
return pluginForUrl(filename);
}
reportError(id: string, revision: string | undefined, text: string) {
if (!this.endpoint.token || !revision) return;
const bytes = new Uint8Array(8192);
const { written } = new TextEncoder().encodeInto(text, bytes);
const body = new TextDecoder().decode(bytes.subarray(0, written));
// Use the same signed-in browser access as plugin assets. A text body
// keeps cross-origin desktop requests on the simple-request path.
const url = new URL(assetURL(this.endpoint, `/plugins/${encodeURIComponent(id)}/window-error`));
url.searchParams.set("revision", revision);
void fetch(url.href, {
method: "POST",
body,
}).catch(() => {
// Reporting is best effort if the window has lost its connection.
});
}
notifyError(name: string, cause: unknown) {
const error = new Error(`${name}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
for (const affected of this.affected([name])) {
Expand Down
46 changes: 43 additions & 3 deletions app/tests/plugins.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, test, vi } from "vitest";
import { render } from "@solidjs/web";
import { createRoot, createSignal, flush, onCleanup } from "solid-js";
import { waitFor } from "@testing-library/dom";
import { getByRole, waitFor } from "@testing-library/dom";
import {
type AnyRouter,
createMemoryHistory,
Expand All @@ -11,7 +11,7 @@ import {
Outlet,
RouterProvider,
} from "@tanstack/solid-router";
import { view } from "@tokamak/sdk/client";
import { useShortcuts, view } from "@tokamak/sdk/client";
import { useClient, useQuery } from "@tokamak/sdk/solid";
import type { JsonValue, TokamakClient } from "@tokamak/sdk";
import {
Expand All @@ -35,6 +35,7 @@ export function catalog(revision = "one") {
version: revision,
contributes: { view: [{ id: "View", route: "/", title: "Fixture" }] },
},
logRevision: revision,
entries: {
ui: {
code: `/plugins/fixture/${revision}/assets/ui.js`,
Expand Down Expand Up @@ -138,6 +139,16 @@ test("web host rewrites literal imports, owns CSS and disposers, and invalidates
// jsdom cannot execute native blob modules; the browser harness executes the same graph.
await expect(host.importModule("@plugins/fixture/ui", manifests[0]!)).rejects.toThrow();
expect(blobs.size).toBe(2);
expect(host.errorOwner("blob:test-0", undefined)).toBe("other");
const unhandled = Object.assign(new Error("Rejected view callback"), {
stack: "callback@blob:test-1:4:12",
});
expect(host.errorOwner("", unhandled)).toBe("fixture");
const dependency = Object.assign(new Error("Dependency failure"), {
stack: "dependency@blob:test-0:1:2\nonClick@blob:test-1:4:12",
});
expect(host.errorOwner("blob:test-0", dependency)).toBe("fixture");
expect(host.errorOwner("", new Error("Unattributed"))).toBeUndefined();
expect(host.dependencies("@plugins/fixture/ui")).toEqual(["@plugins/other/ui"]);
expect(host.affected(["@plugins/other/ui"])).toEqual(
new Set(["@plugins/other/ui", "@plugins/fixture/ui"]),
Expand Down Expand Up @@ -186,6 +197,11 @@ test("runtime routes mount, retire query owners, swap revision, contain throws,
sharedSignal: createSignal,
View: view({ route: "/" }, () => {
if (revision === "throws") throw new Error("fixture exploded");
onCleanup(
useShortcuts().registerShortcut("k", async () => {
throw "primitive callback rejection";
}),
);
const query = useQuery(useClient(), "fixture:read" as never, () => ({}));
onCleanup(fixtureCleanup);
return (
Expand All @@ -199,9 +215,12 @@ test("runtime routes mount, retire query owners, swap revision, contain throws,
);
// The mock import still establishes a generation so host retirement can own it.
vi.spyOn(WebPluginHost.prototype, "own").mockImplementation(() => () => {});
const writeText = vi.fn(async () => {});
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
const report = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 204 }));
const shell = createPluginShell(
client,
{ http: "http://localhost", ws: "ws://localhost", token: null },
{ http: "http://localhost", ws: "ws://localhost", token: "fixture-token" },
source,
{ router, root, base: [home] },
);
Expand All @@ -224,6 +243,13 @@ test("runtime routes mount, retire query owners, swap revision, contain throws,
});
await router.navigate({ href: "/p/fixture" });
await waitFor(() => expect(target.textContent).toContain("one: query"));
document.dispatchEvent(new KeyboardEvent("keydown", { key: "k" }));
await waitFor(() =>
expect(report).toHaveBeenCalledWith(
"http://localhost/plugins/fixture/window-error?token=fixture-token&revision=one",
{ method: "POST", body: "primitive callback rejection" },
),
);
publish("two");
await waitFor(() => expect(target.textContent).toContain("two: query"));
expect(stopQuery).toHaveBeenCalledOnce();
Expand All @@ -233,6 +259,19 @@ test("runtime routes mount, retire query owners, swap revision, contain throws,
expect(target.querySelector('[role="alert"]')?.textContent).toContain("fixture exploded"),
);
expect(target.querySelector("button")?.textContent).toBe("Reload");
const alert = getByRole(target, "alert", { name: "Plugin view error" });
expect(alert.textContent).toContain("tokamak plugin logs fixture");
getByRole(alert, "button", { name: "Copy plugin log command" }).click();
expect(writeText).toHaveBeenCalledWith("tokamak plugin logs fixture");
await waitFor(() =>
expect(report).toHaveBeenCalledWith(
"http://localhost/plugins/fixture/window-error?token=fixture-token&revision=throws",
{
method: "POST",
body: "Error: fixture exploded",
},
),
);
await router.navigate({ to: "/" });
await waitFor(() => expect(target.textContent).toContain("Host survived"));
notify({ plugins: ["fixture"], catalog: { revision: "removed", plugins: [] } });
Expand All @@ -242,6 +281,7 @@ test("runtime routes mount, retire query owners, swap revision, contain throws,
} finally {
dispose();
shell.dispose();
Reflect.deleteProperty(navigator, "clipboard");
vi.restoreAllMocks();
}
});
Expand Down
1 change: 1 addition & 0 deletions e2e/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ await mkdir("app/.dev", { recursive: true });
const directory = await mkdtemp(resolve("app/.dev/browser-"));
const env = {
...process.env,
TOKAMAK_PLUGIN_LOG_DIR: resolve(directory, "logs"),
TOKAMAK_PLUGIN_DIR: `${directory}/plugins`,
TOKAMAK_FIXTURE_SOURCE: `${directory}/fixture`,
TOKAMAK_E2E_WEB_ROOT: `${directory}/web`,
Expand Down
22 changes: 22 additions & 0 deletions e2e/browser/app.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { test, expect, type Page } from "@playwright/test";
import { spawnSync } from "node:child_process";
import { join } from "node:path";
import { readFile, writeFile } from "node:fs/promises";

const connected = (page: Page) =>
Expand Down Expand Up @@ -80,6 +81,27 @@ test("live threads, compiler views, regions, per-plugin reload and error contain
await rail(page).getByRole("link", { name: throwingTitle, exact: true }).click();
const failure = page.getByRole("alert", { name: "Plugin view error" });
await expect(failure).toContainText("Deliberate fixture failure");
await expect(failure).toContainText("tokamak plugin logs integration-fixture");
const pluginLog = join(process.env.TOKAMAK_PLUGIN_LOG_DIR!, "integration-fixture.log");
await expect
.poll(async () => {
const log = await readFile(pluginLog, "utf8").catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return "";
throw error;
});
return log
.split("\n")
.slice(0, -1)
.filter(Boolean)
.map((line) => JSON.parse(line));
})
.toContainEqual(
expect.objectContaining({
source: "window",
level: "error",
text: expect.stringContaining("Deliberate fixture failure"),
}),
);
await expect(failure.getByRole("button", { name: "Reload" })).toBeVisible();
await expect(sidebar).toBeHidden();
await expect(header.getByRole("heading", { name: throwingTitle })).toBeVisible();
Expand Down
Loading