Skip to content

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

16.9 KB
Raw Blame
/**
 * 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 and
 * E2E-ASKTOOL-draft-survives-session-switch. It also pins the compact
 * question block: a multi-paragraph question body stays one stacked text
 * column rather than lining its blocks up in a row.
 */
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 { MAX_ASK_TOOL_QUESTION_CHARS } from "../../packages/shared/src/types/agent";
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" }],
  },
];

// A question body with several markdown blocks must render as stacked
// paragraphs. The compact header row once made every block a flex item, so
// the blocks lined up side by side and every sentence wrapped inside a column.
const MULTI_BLOCK_QUESTION: FixtureQuestion = {
  question:
    "The old host 124.71.12.42 is unreachable and the new database is empty, so nothing has been restored yet.\n\nThe S3 bucket still holds every page file, so a rebuild can recover the HTML body plus its title.",
  options: [{ label: "delta", description: "Fourth choice" }],
};

const LONG_QUESTIONS: FixtureQuestion[] = [
  {
    question: `First long question\n\n${Array.from(
      { length: 24 },
      (_, index) => `First prompt paragraph ${index + 1} keeps enough text in the card to require its own scroll area.`,
    ).join("\n\n")}`,
    options: [{ label: "Continue", description: "Move to the next question" }],
  },
  {
    question: `Second long question\n\n${Array.from(
      { length: 24 },
      (_, index) => `Second prompt paragraph ${index + 1} keeps enough text in the card to require its own scroll area.`,
    ).join("\n\n")}`,
    options: [{ label: "Submit", description: "Finish the request" }],
  },
];

const MAX_LENGTH_QUESTION: FixtureQuestion = {
  question: "q".repeat(MAX_ASK_TOOL_QUESTION_CHARS),
  options: [{ label: "continue", description: "Proceed with the selected 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, questions: FixtureQuestion[] = QUESTIONS) => {
    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)}`,
    );

    // Flow E: a multi-block question body keeps its blocks stacked in the
    // card's text column instead of lining them up as flex items.
    mount("ask-layout", [MULTI_BLOCK_QUESTION]);
    await until(() => options().length > 0, "layout flow mounts");
    const paragraphs = [
      ...host.querySelectorAll<HTMLElement>(
        ".asktool-question .asktool-rich-paragraph",
      ),
    ];
    assert(
      paragraphs.length === 2,
      `the multi-block question renders one paragraph per block, saw ${paragraphs.length}`,
    );
    const cardWidth = element(".asktool-card").getBoundingClientRect().width;
    const boxes = paragraphs.map((node) => node.getBoundingClientRect());
    assert(
      boxes[1]!.top >= boxes[0]!.bottom - 1,
      `question blocks stack vertically (tops ${boxes[0]!.top}, ${boxes[1]!.top})`,
    );
    assert(
      Math.abs(boxes[1]!.left - boxes[0]!.left) < 1,
      `question blocks share a left edge (${boxes[0]!.left}, ${boxes[1]!.left})`,
    );
    assert(
      boxes[0]!.width > cardWidth / 2,
      `a question block spans the text column (${boxes[0]!.width} of ${cardWidth})`,
    );
    const numberBox = element(
      ".asktool-question-number",
    ).getBoundingClientRect();
    assert(
      numberBox.right <= boxes[0]!.left + 1,
      `the question number sits left of the text column (${numberBox.right}, ${boxes[0]!.left})`,
    );
    assert(
      numberBox.top >= boxes[0]!.top - 1 &&
        numberBox.bottom <= boxes[0]!.top + 26,
      `the question number shares the first line with the question text (${numberBox.top}, ${boxes[0]!.top})`,
    );

    // Flow F: a long prompt scrolls inside the card, keeps header actions in
    // view, and resets to the top when Next replaces the current question.
    mount("ask-overflow", LONG_QUESTIONS);
    await until(() => {
      const body = host.querySelector<HTMLElement>(".asktool-question-body");
      return Boolean(body && body.clientHeight > 0 && body.scrollHeight > body.clientHeight);
    }, "long question has an internal scroll range");
    const firstBody = element<HTMLElement>(".asktool-question-body");
    assert(firstBody.tabIndex === 0, "the question scroller is keyboard reachable");
    const tabOrder = [
      ...host.querySelectorAll<HTMLElement>("button, input, [tabindex='0']"),
    ];
    const bodyTabIndex = tabOrder.indexOf(firstBody);
    assert(
      tabOrder.indexOf(headerButtons().primary) < bodyTabIndex &&
        bodyTabIndex < tabOrder.indexOf(options()[0]!),
      "Tab reaches the question scroller between header actions and answers",
    );
    assert(
      getComputedStyle(firstBody).overflowY === "auto",
      "the long question scrolls inside its own body",
    );
    const actionRects = Object.values(headerButtons()).map((button) => {
      const rect = button.getBoundingClientRect();
      return { top: rect.top, bottom: rect.bottom };
    });
    assert(
      actionRects.every(({ top, bottom }) => top >= 0 && bottom <= window.innerHeight),
      "header actions stay inside the visible window",
    );
    firstBody.scrollTop = firstBody.scrollHeight;
    await frame();
    assert(firstBody.scrollTop > 0, "the question body accepts scrolling");
    assert(
      Object.values(headerButtons()).every((button, index) => {
        const rect = button.getBoundingClientRect();
        return Math.abs(rect.top - actionRects[index]!.top) < 1 &&
          Math.abs(rect.bottom - actionRects[index]!.bottom) < 1;
      }),
      "scrolling the prompt does not move its header actions",
    );
    flushSync(() => headerButtons().primary.click());
    await until(
      () => questionText().includes("Second long question"),
      "Next advances from the scrolled prompt",
    );
    assert(
      element<HTMLElement>(".asktool-question-body").scrollTop === 0,
      "the next long question starts at the top",
    );

    // Flow G: the maximum permitted prompt remains visible and answerable.
    mount("ask-max-length", [MAX_LENGTH_QUESTION]);
    await until(() => options().length === 1, "maximum-length question mounts");
    const maxLengthQuestion = "q".repeat(MAX_ASK_TOOL_QUESTION_CHARS);
    assert(
      questionText().endsWith(maxLengthQuestion),
      "the card displays the complete 300-character question",
    );
    flushSync(() => options()[0]!.click());
    flushSync(() => headerButtons().primary.click());
    await until(() => resolutions.length === 5, "maximum-length question resolves");
    assert(
      JSON.stringify(resolutions[4]!.answers) === JSON.stringify([["continue"]]),
      "the maximum-length question remains answerable",
    );

    // Flow H: the draft survives an unmount/remount with the same requestId —
    // switching sessions in the real app unmounts the card the same way.
    const persisted = mount("ask-persist");
    await until(() => options().length > 0, "persist flow mounts");
    flushSync(() => options()[1]!.click()); // select "beta" on question 1
    flushSync(() => headerButtons().primary.click()); // next -> question 2
    await until(
      () => questionText().includes("Allow rollback?"),
      "persist flow advances to question 2",
    );
    flushSync(() => root.render(null)); // unmount (session switched away)
    flushSync(() =>
      root.render(
        <I18nextProvider i18n={i18n}>
          <AskToolCard key={persisted.requestId} request={persisted} />
        </I18nextProvider>,
      ),
    );
    await until(() => options().length > 0, "persist flow remounts");
    assert(
      questionText().includes("Allow rollback?"),
      "the remounted card resumes on the question the user left",
    );
    const indicators = [
      ...host.querySelectorAll<HTMLButtonElement>(".asktool-indicator"),
    ];
    flushSync(() => indicators[0]!.click());
    await until(
      () => questionText().includes("Which upgrade path?"),
      "the indicator returns to question 1",
    );
    assert(
      options()[1]!.classList.contains("selected"),
      "the answer selected before the remount is still selected",
    );

    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;