Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

test(asktool): cover compact card header actions with a Chromium probe

mingkun968a6e3b3d6ba52
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 3d05eee2d..7795d3087 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -279,6 +279,21 @@
session, clicks an outline dash while follow is pinned, and asserts the
scroller's distance from the bottom once the exchange has settled.
+### E2E-ASKTOOL-compact-card-interaction
+
+- **Preconditions:** No live provider is required; the fixture stubs
+ `api.resolveAskTool` and seeds one two-question ask through the real store
+ slice.
+- **Steps:** Mount the production `AskToolCard`, assert the header Tab order
+ (decline, skip, next) with no legacy bottom action row, then walk select →
+ next → submit, skip → submit, decline-all, and a custom answer, remounting
+ with a fresh request id between flows.
+- **Expected:** Every flow resolves through the store's `resolveAsk` with the
+ exact answers (skips recorded as `null`), and no render errors are reported.
+- **Status:** Automated in `pnpm test:e2e:asktool-card`, which mounts the
+ production `AskToolCard` in a real Chromium page and clicks through the
+ header actions.
+
### E2E-POWER-keep-awake-setting
- **Preconditions:** An isolated desktop profile with the setting absent; no
diff --git a/package.json b/package.json
index 1b91717a0..9b92f422f 100644
--- a/package.json
+++ b/package.json
@@ -21,6 +21,7 @@
"test": "pnpm build:js && pnpm -r --if-present test && cargo test -p host-core",
"test:host": "cargo test -p host-core",
"test:e2e": "node scripts/e2e-smoke.mjs",
+ "test:e2e:asktool-card": "node scripts/e2e-asktool-card.mjs",
"test:e2e:scheduled": "node scripts/e2e-scheduled.mjs",
"test:e2e:keep-awake": "node scripts/e2e-keep-awake.mjs",
"test:e2e:live-voice": "node scripts/e2e-live-voice.mjs",
diff --git a/scripts/e2e-asktool-card.mjs b/scripts/e2e-asktool-card.mjs
new file mode 100755
index 000000000..d59fe4451
--- /dev/null
+++ b/scripts/e2e-asktool-card.mjs
@@ -0,0 +1,136 @@
+#!/usr/bin/env node
+/**
+ * Real React/Chromium regression for E2E-ASKTOOL-compact-card-interaction:
+ * the compact AskTool card keeps its select / skip / submit paths working
+ * after the header absorbed every confirmation affordance.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(
+ join(root, "packages/agent-runtime/package.json"),
+);
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(tmpdir(), "pi-asktool-card-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/asktool-card.tsx")],
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "iife",
+ jsx: "automatic",
+ define: {
+ "process.env.NODE_ENV": '"production"',
+ "import.meta.env.DEV": "false",
+ },
+ // Styles come from the app's built stylesheet below; the component and its
+ // hook are the real modules under test.
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ // The fixture lives outside the desktop package; use its React instance.
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ plugins: [
+ {
+ name: "local-url-assets",
+ setup(build) {
+ build.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({
+ path: join(resolveDir, path.slice(0, -4)),
+ namespace: "local-url-asset",
+ }));
+ build.onLoad(
+ { filter: /.*/, namespace: "local-url-asset" },
+ async ({ path }) => ({
+ contents: await readFile(path),
+ loader: "file",
+ }),
+ );
+ },
+ },
+ ],
+ });
+ // The card is styled by the app's own stylesheet, so the page has to carry
+ // the built one rather than a bare document.
+ const renderer = join(root, "apps/desktop/out/renderer");
+ const appHtml = await readFile(join(renderer, "index.html"), "utf8");
+ const css = [...appHtml.matchAll(/href="([^" ]+\.css)"/g)].map(
+ (match) => match[1],
+ );
+ assert(css.length, "Build the app with pnpm build:js before running this check");
+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });
+ await writeFile(
+ join(temp, "index.html"),
+ `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:"><title>AskTool card regression</title>${css
+ .map((path) => `<link rel="stylesheet" href="${path}">`)
+ .join("")}<script src="renderer.js"></script>`,
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({ show: false, width: 1000, height: 800, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ window.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ await window.webContents.executeJavaScript("window.addEventListener('error', event => console.error(event.error?.stack ?? event.message)); window.addEventListener('unhandledrejection', event => console.error(event.reason?.stack ?? String(event.reason)));");
+ const result = await window.webContents.executeJavaScript("globalThis.asktoolCardProbe()");
+ console.log("ASKTOOL_CARD_PROBE " + JSON.stringify(result));
+ app.quit();
+ } catch (error) {
+ console.error("ASKTOOL_CARD_PROBE " + JSON.stringify({ ok: false, error: error?.stack ?? String(error) }));
+ app.exit(1);
+ }
+});
+`,
+ );
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr])
+ stream.on("data", (data) => {
+ output += data;
+ });
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+ const line = output
+ .split(/\r?\n/)
+ .find((line) => line.startsWith("ASKTOOL_CARD_PROBE "));
+ assert(
+ line,
+ `renderer returned no probe result (exit=${code}): ${output.slice(-2000)}`,
+ );
+ const result = JSON.parse(line.slice("ASKTOOL_CARD_PROBE ".length));
+ console.log("ASKTOOL_CARD_PROBE " + JSON.stringify(result));
+ assert.equal(code, 0, output.slice(-6000));
+ assert.equal(result.ok, true, result.error ?? "asktool card probe failed");
+ console.log("asktool card: ok");
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/asktool-card.tsx b/scripts/e2e/asktool-card.tsx
new file mode 100644
index 000000000..03f5ef507
--- /dev/null
+++ b/scripts/e2e/asktool-card.tsx
@@ -0,0 +1,271 @@
+/**
+ * Real React/Chromium regression for the compact AskTool card.
+ *
+ * The compact layout moved the skip / next / submit buttons from a bottom
+ * action row into the card header, which changed DOM order and therefore the
+ * keyboard Tab sequence. This probe mounts the production `AskToolCard`
+ * against the real store slice with a stubbed `api.resolveAskTool` and walks
+ * the user-visible paths: the new header action order, select → next →
+ * submit, skip → submit, decline-all, and a custom answer.
+ *
+ * Scenario: E2E-ASKTOOL-compact-card-interaction.
+ */
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import { AskToolCard } from "../../apps/desktop/src/components/AskToolCard";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const SESSION_ID = "asktool-card";
+
+declare global {
+ var asktoolCardProbe: () => Promise<unknown>;
+}
+function assert(value: unknown, label: string): asserts value {
+ if (!value) throw new Error(`AskTool card: ${label}`);
+}
+
+const frame = () =>
+ new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+async function until(predicate: () => boolean, label: string): Promise<void> {
+ for (let attempt = 0; attempt < 240; attempt++) {
+ if (predicate()) return;
+ await frame();
+ }
+ throw new Error(`AskTool card never settled: ${label}`);
+}
+
+type FixtureQuestion = {
+ question: string;
+ options: Array<{ label: string; description: string }>;
+};
+
+function askRequest(requestId: string, questions: FixtureQuestion[]) {
+ return {
+ sessionId: SESSION_ID,
+ requestId,
+ toolCallId: `tool-${requestId}`,
+ questions,
+ };
+}
+
+const QUESTIONS: FixtureQuestion[] = [
+ {
+ question: "Which upgrade path?",
+ options: [
+ { label: "alpha", description: "First choice" },
+ { label: "beta", description: "Second choice" },
+ ],
+ },
+ {
+ question: "Allow rollback?",
+ options: [{ label: "gamma", description: "Third choice" }],
+ },
+];
+
+export async function asktoolCardProbe() {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ const initial = useAppStore.getState();
+ const originalResolve = api.resolveAskTool;
+ const resolutions: Array<{ requestId: string; answers: unknown }> = [];
+ api.resolveAskTool = (async (resolution: {
+ requestId: string;
+ answers: unknown;
+ }) => {
+ resolutions.push(resolution);
+ return { ok: true };
+ }) as typeof api.resolveAskTool;
+ const host = document.createElement("div");
+ host.style.cssText = "position:fixed;inset:0;overflow:auto;background:#141414";
+ document.body.append(host);
+ const errors: unknown[] = [];
+ const root = createRoot(host, {
+ onUncaughtError: (error) => errors.push(error),
+ });
+ const element = <T extends HTMLElement = HTMLElement>(
+ selector: string,
+ ): T => {
+ const found = host.querySelector<T>(selector);
+ assert(found, `missing ${selector}`);
+ return found as T;
+ };
+ const options = () =>
+ [...host.querySelectorAll<HTMLButtonElement>(".asktool-option")].filter(
+ (button) => !button.classList.contains("asktool-custom-option"),
+ );
+ const headerButtons = () => ({
+ decline: element<HTMLButtonElement>(".asktool-decline"),
+ skip: element<HTMLButtonElement>(
+ ".asktool-card-header-actions .btn-ghost",
+ ),
+ primary: element<HTMLButtonElement>(
+ ".asktool-card-header-actions .btn-primary",
+ ),
+ });
+ // Fixture question bodies (not translated strings) identify the current
+ // question independent of the active locale.
+ const questionText = () =>
+ element(".asktool-question").textContent ?? "";
+ const mount = (requestId: string) => {
+ const request = askRequest(requestId, QUESTIONS);
+ useAppStore.setState({
+ pendingAsks: { [SESSION_ID]: [request] },
+ });
+ flushSync(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <AskToolCard key={requestId} request={request} />
+ </I18nextProvider>,
+ ),
+ );
+ return request;
+ };
+ try {
+ mount("ask-dom");
+ await until(
+ () => options().length === QUESTIONS[0]!.options.length,
+ "first question options mount",
+ );
+
+ // The header carries every confirmation affordance now that the bottom
+ // action row is gone, so Tab reaches them in this exact DOM order.
+ assert(
+ host.querySelector(".asktool-card-actions") === null,
+ "the legacy bottom action row is gone",
+ );
+ const tabbables = [...host.querySelectorAll("button")];
+ const orderOf = (selector: string) =>
+ tabbables.findIndex((node) => node.matches(selector));
+ const declineAt = orderOf(".asktool-decline");
+ const skipAt = orderOf(
+ ".asktool-card-header-actions .btn-ghost",
+ );
+ const primaryAt = orderOf(
+ ".asktool-card-header-actions .btn-primary",
+ );
+ const firstOptionAt = orderOf(
+ ".asktool-options .asktool-option",
+ );
+ assert(
+ declineAt !== -1 && skipAt !== -1 && primaryAt !== -1,
+ "header actions mount",
+ );
+ assert(
+ declineAt < skipAt && skipAt < primaryAt,
+ `header Tab order is decline, skip, next (saw ${declineAt}, ${skipAt}, ${primaryAt})`,
+ );
+ assert(
+ primaryAt < firstOptionAt,
+ "header actions tab before the options",
+ );
+
+ // Flow A: select → next → answer → submit.
+ flushSync(() => options()[0]!.click());
+ assert(
+ options()[0]!.classList.contains("selected"),
+ "the clicked option is selected",
+ );
+ assert(
+ questionText().includes("Which upgrade path?"),
+ "the card starts on question 1",
+ );
+ flushSync(() => headerButtons().primary.click());
+ await until(
+ () => questionText().includes("Allow rollback?"),
+ "next advances to question 2",
+ );
+ flushSync(() => options()[0]!.click());
+ flushSync(() => headerButtons().primary.click());
+ await until(() => resolutions.length === 1, "submit resolves the ask");
+ assert(
+ resolutions[0]!.requestId === "ask-dom",
+ "the resolution carries the request id",
+ );
+ assert(
+ JSON.stringify(resolutions[0]!.answers) ===
+ JSON.stringify([["alpha"], ["gamma"]]),
+ `select/next/submit answers survive, saw ${JSON.stringify(resolutions[0]!.answers)}`,
+ );
+
+ // Flow B: skip the first question, answer the second, submit.
+ mount("ask-skip");
+ await until(() => options().length > 0, "skip flow mounts");
+ flushSync(() => headerButtons().skip.click());
+ await until(
+ () => questionText().includes("Allow rollback?"),
+ "skip advances to question 2",
+ );
+ flushSync(() => options()[0]!.click());
+ flushSync(() => headerButtons().primary.click());
+ await until(() => resolutions.length === 2, "skip flow resolves");
+ assert(
+ JSON.stringify(resolutions[1]!.answers) ===
+ JSON.stringify([null, ["gamma"]]),
+ `skip records a null answer, saw ${JSON.stringify(resolutions[1]!.answers)}`,
+ );
+
+ // Flow C: decline everything from the header.
+ mount("ask-decline");
+ await until(() => options().length > 0, "decline flow mounts");
+ flushSync(() => headerButtons().decline.click());
+ await until(() => resolutions.length === 3, "decline resolves");
+ assert(
+ JSON.stringify(resolutions[2]!.answers) ===
+ JSON.stringify([null, null]),
+ `decline-all nulls every answer, saw ${JSON.stringify(resolutions[2]!.answers)}`,
+ );
+
+ // Flow D: a custom answer still flows through the header submit.
+ mount("ask-custom");
+ await until(() => options().length > 0, "custom flow mounts");
+ flushSync(() =>
+ element(".asktool-custom-option").click(),
+ );
+ const input = element<HTMLInputElement>(".asktool-custom-input");
+ // Bypass React's instance value tracker: a plain assignment updates the
+ // tracker too, so the input event would read as unchanged and onChange
+ // would never fire. The prototype setter leaves the tracker behind.
+ const nativeValueSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype,
+ "value",
+ )!.set!;
+ nativeValueSetter.call(input, "my reason");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await frame();
+ flushSync(() => headerButtons().primary.click());
+ await until(
+ () => questionText().includes("Allow rollback?"),
+ "custom answer advances to question 2",
+ );
+ flushSync(() => options()[0]!.click());
+ flushSync(() => headerButtons().primary.click());
+ await until(() => resolutions.length === 4, "custom flow resolves");
+ assert(
+ JSON.stringify(resolutions[3]!.answers) ===
+ JSON.stringify([["my reason"], ["gamma"]]),
+ `custom text survives, saw ${JSON.stringify(resolutions[3]!.answers)}`,
+ );
+
+ assert(errors.length === 0, `render errors: ${errors.map(String)}`);
+ return { ok: true, resolutions: resolutions.length };
+ } catch (error) {
+ return {
+ ok: false,
+ error: error instanceof Error ? (error.stack ?? error.message) : String(error),
+ };
+ } finally {
+ flushSync(() => root.unmount());
+ host.remove();
+ api.resolveAskTool = originalResolve;
+ useAppStore.setState({
+ pendingAsks: initial.pendingAsks,
+ activeSessionId: initial.activeSessionId,
+ });
+ }
+}
+
+globalThis.asktoolCardProbe = asktoolCardProbe;