Skip to content

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

test(file-manager): make the directory journey evidence-first

SeanLiu3266af9adf91076
diff --git a/apps/desktop/test/file-manager-directory-location-user-path.e2e.mjs b/apps/desktop/test/file-manager-directory-location-user-path.e2e.mjs
index d9e5b6892..18439191e 100644
--- a/apps/desktop/test/file-manager-directory-location-user-path.e2e.mjs
+++ b/apps/desktop/test/file-manager-directory-location-user-path.e2e.mjs
@@ -11,14 +11,18 @@ import { resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
* A host location that names a directory must browse it, not fail as a file
* read (issue #2113). The journey runs the production view against the real
* bundled plugin main process over the real bridge shapes: the preload only
- * supplies the `pi` environment the plugin expects and forwards every `fm.*`
- * channel to the actual `onPanelInvoke`.
+ * supplies the `pi` environment the plugin expects, records every channel
+ * call, and forwards the `fm.*` channels to the actual `onPanelInvoke`.
*
* Four host requests are exercised against real files on disk: a directory in
* the primary root (expand, select, list, no read), an ordinary file (the
* preview contract is unchanged), a directory in a sibling root of the same
* project group (root switch, then browse), and a directory outside the
* managed roots (scratch) which keeps its honest localized rejection.
+ *
+ * Evidence-first: a scenario that never reaches its expectation does not
+ * abort the journey with a bare timeout — the probe dumps the page state and
+ * the recorded channel log so the failure carries its own diagnosis.
*/
const root = join(dirname(fileURLToPath(import.meta.url)), "../../..");
@@ -36,18 +40,42 @@ const { pathToFileURL } = require("node:url");
const viewEntry = process.env.PI_FILE_MANAGER_VIEW;
app.setPath("userData", path.join(__dirname, "profile"));
-async function waitFor(window, expression) {
- const timeoutMessage = JSON.stringify("timed out: " + expression);
- await window.webContents.executeJavaScript(
- "new Promise((resolve, reject) => {" +
- "const deadline = Date.now() + 5000;" +
- "const poll = () => {" +
- "if (" + expression + ") resolve();" +
- "else if (Date.now() > deadline) reject(new Error(" + timeoutMessage + "));" +
- "else setTimeout(poll, 50);" +
- "}; poll();" +
- "})",
- );
+const WAIT_MS = 15000;
+
+async function waitForState(window, expression) {
+ const deadline = Date.now() + WAIT_MS;
+ let lastState = null;
+ for (;;) {
+ lastState = await readState(window);
+ let met = false;
+ try {
+ met = await window.webContents.executeJavaScript("Boolean(" + expression + ")");
+ } catch {
+ met = false;
+ }
+ if (met) return { met: true, state: lastState };
+ if (Date.now() > deadline) return { met: false, state: lastState };
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+
+function readState(window) {
+ return window.webContents.executeJavaScript("(() => {" +
+ "const selected = document.querySelector('.tree-row[aria-selected=\"true\"]');" +
+ "const alert = document.querySelector('[role=\"alert\"]');" +
+ "let log = null;" +
+ "try { log = window.__fixtureLog ? window.__fixtureLog() : null; } catch {}" +
+ "return {" +
+ "bridge: Boolean(window.pluginBridge)," +
+ "selectedPath: selected?.getAttribute('data-path') ?? null," +
+ "selectedExpanded: selected?.getAttribute('aria-expanded') ?? null," +
+ "alertText: alert?.textContent ?? null," +
+ "editorOpen: Boolean(document.querySelector('.cm-content'))," +
+ "treeRows: [...document.querySelectorAll('.tree-row')].map((row) => row.getAttribute('data-path'))," +
+ "bodySample: (document.body?.textContent ?? '').slice(0, 300)," +
+ "fixtureLog: log," +
+ "};" +
+ "})()");
}
// One Electron window per scenario; the location rides the entry URL query,
@@ -77,56 +105,42 @@ async function open(fixtures, location) {
return window;
}
-function readState(window) {
- return window.webContents.executeJavaScript("(() => {" +
- "const selected = document.querySelector('.tree-row[aria-selected=\"true\"]');" +
- "const alert = document.querySelector('[role=\"alert\"]');" +
- "return {" +
- "selectedPath: selected?.getAttribute('data-path') ?? null," +
- "selectedExpanded: selected?.getAttribute('aria-expanded') ?? null," +
- "alertText: alert?.textContent ?? null," +
- "editorOpen: Boolean(document.querySelector('.cm-content'))," +
- "treeRows: [...document.querySelectorAll('.tree-row')].map((row) => row.getAttribute('data-path'))," +
- "treeHidden: Boolean(document.querySelector('.tree-row')) === false," +
- "};" +
- "})()");
-}
-
app.whenReady().then(async () => {
const fixtures = {
dir: path.join(__dirname),
workspace: process.env.PI_FIXTURE_WORKSPACE,
scratch: process.env.PI_FIXTURE_SCRATCH,
};
+ const report = {};
try {
- const report = {};
-
// 1. A directory in the primary root: expanded, selected, listed, no read.
const directoryWindow = await open(fixtures, "examples");
- await waitFor(directoryWindow,
+ const directory = await waitForState(directoryWindow,
"document.querySelector('.tree-row[data-path=\"examples/child.txt\"]') !== null");
- report.directory = await readState(directoryWindow);
+ report.directory = directory;
directoryWindow.destroy();
// 2. An ordinary file: the preview contract is unchanged.
const fileWindow = await open(fixtures, "test.ts");
- await waitFor(fileWindow, "document.querySelector('.cm-content')?.textContent.includes('visible')");
- report.file = await readState(fileWindow);
+ const file = await waitForState(fileWindow,
+ "document.querySelector('.cm-content')?.textContent.includes('visible')");
+ report.file = file;
fileWindow.destroy();
// 3. A directory in the sibling root, named by its absolute path: switch
// root, then browse.
const siblingWindow = await open(fixtures, path.join(fixtures.workspace, "sibling", "docs"));
- await waitFor(siblingWindow,
+ const sibling = await waitForState(siblingWindow,
"document.querySelector('.tree-row[data-path=\"docs/guide.md\"]') !== null");
- report.sibling = await readState(siblingWindow);
+ report.sibling = sibling;
siblingWindow.destroy();
// 4. A scratch directory outside the managed roots: honest localized
// rejection, no editor, no crash.
const scratchWindow = await open(fixtures, path.join(fixtures.scratch, "run"));
- await waitFor(scratchWindow, "document.querySelector('[role=\"alert\"]') !== null");
- report.scratch = await readState(scratchWindow);
+ const scratch = await waitForState(scratchWindow,
+ "document.querySelector('[role=\"alert\"]') !== null");
+ report.scratch = scratch;
scratchWindow.destroy();
console.log("FILE_MANAGER_DIRECTORY_PROBE " + JSON.stringify({ ok: true, report }));
@@ -134,7 +148,7 @@ app.whenReady().then(async () => {
} catch (error) {
console.error(
"FILE_MANAGER_DIRECTORY_PROBE " +
- JSON.stringify({ ok: false, error: String(error?.stack ?? error) }),
+ JSON.stringify({ ok: false, error: String(error?.stack ?? error), report }),
);
app.exit(1);
}
@@ -142,36 +156,52 @@ app.whenReady().then(async () => {
`;
function assertDirectoryState(state) {
- assert.equal(state.selectedPath, "examples");
- assert.equal(state.selectedExpanded, "true");
- assert.equal(state.editorOpen, false, "a directory must not dispatch a file read");
- assert.equal(state.alertText, null, "no failure banner for a directory location");
- assert.ok(state.treeRows.includes("examples/child.txt"), JSON.stringify(state.treeRows));
+ assert.equal(state.met, true, "child row never appeared; state: " + describe(state));
+ assert.equal(state.state.selectedPath, "examples");
+ assert.equal(state.state.selectedExpanded, "true");
+ assert.equal(state.state.editorOpen, false, "a directory must not dispatch a file read");
+ assert.equal(state.state.alertText, null, "no failure banner for a directory location");
+ assert.ok(state.state.treeRows.includes("examples/child.txt"), state.state.treeRows.join(","));
}
function assertFileState(state) {
- assert.equal(state.selectedPath, "test.ts");
- assert.equal(state.editorOpen, true, "the file preview contract is unchanged");
- assert.equal(state.alertText, null);
+ assert.equal(state.met, true, "editor content never appeared; state: " + describe(state));
+ assert.equal(state.state.selectedPath, "test.ts");
+ assert.equal(state.state.editorOpen, true, "the file preview contract is unchanged");
+ assert.equal(state.state.alertText, null);
}
function assertSiblingState(state) {
- assert.equal(state.selectedPath, "docs");
- assert.equal(state.selectedExpanded, "true");
- assert.equal(state.editorOpen, false);
- assert.equal(state.alertText, null);
- assert.ok(state.treeRows.includes("docs/guide.md"), JSON.stringify(state.treeRows));
+ assert.equal(state.met, true, "sibling rows never appeared; state: " + describe(state));
+ assert.equal(state.state.selectedPath, "docs");
+ assert.equal(state.state.selectedExpanded, "true");
+ assert.equal(state.state.editorOpen, false);
+ assert.equal(state.state.alertText, null);
+ assert.ok(state.state.treeRows.includes("docs/guide.md"), state.state.treeRows.join(","));
}
function assertScratchState(state) {
- assert.equal(state.editorOpen, false);
+ assert.equal(state.met, true, "rejection banner never appeared; state: " + describe(state));
+ assert.equal(state.state.editorOpen, false);
assert.match(
- state.alertText,
+ state.state.alertText,
/That path is a directory/,
"the scratch rejection must be the localized directory message",
);
}
+function describe(state) {
+ return JSON.stringify({
+ bridge: state.state?.bridge,
+ selectedPath: state.state?.selectedPath,
+ alertText: state.state?.alertText,
+ editorOpen: state.state?.editorOpen,
+ treeRows: state.state?.treeRows,
+ bodySample: state.state?.bodySample,
+ fixtureLog: state.state?.fixtureLog,
+ });
+}
+
test(
"host directory locations browse the File Manager instead of failing as file reads",
{
@@ -211,55 +241,74 @@ test(
const { contextBridge } = require("electron");
const path = require("node:path");
-const workspaceDir = process.argv.find((value) => value.startsWith("--fixture-ws="))?.slice("--fixture-ws=".length);
-const dataDir = path.join(workspaceDir, ".plugin-data");
+const log = [];
+const preloadError = (() => {
+ try {
+ const workspaceDir = process.argv.find((value) => value.startsWith("--fixture-ws="))?.slice("--fixture-ws=".length);
+ const dataDir = path.join(workspaceDir, ".plugin-data");
-const workspace = {
- path: workspaceDir,
- name: "project",
- projectId: "fixture-project",
- roots: [
- { path: workspaceDir, name: "project", primary: true },
- { path: path.join(workspaceDir, "sibling"), name: "sibling", primary: false },
- ],
-};
+ const workspace = {
+ path: workspaceDir,
+ name: "project",
+ projectId: "fixture-project",
+ roots: [
+ { path: workspaceDir, name: "project", primary: true },
+ { path: path.join(workspaceDir, "sibling"), name: "sibling", primary: false },
+ ],
+ };
-const plugin = require(path.join(workspaceDir, "..", "staged", "pi.file-manager", "main.js"));
-globalThis.pi = {
- workspace: { get: async () => workspace },
- plugin: {
- getDataPath: async () => dataDir,
- getSettings: async () => ({}),
- setSettings: async () => ({}),
- },
- // handleHello probes this with a bare typeof; an absent fs would throw and
- // turn the whole hello (root included) into a failure.
- fs: {},
-};
+ const plugin = require(path.join(workspaceDir, "..", "staged", "pi.file-manager", "main.js"));
+ globalThis.pi = {
+ workspace: { get: async () => workspace },
+ plugin: {
+ getDataPath: async () => dataDir,
+ getSettings: async () => ({}),
+ setSettings: async () => ({}),
+ },
+ // handleHello probes this with a bare typeof; an absent fs would throw
+ // and turn the whole hello (root included) into a failure.
+ fs: {},
+ };
-contextBridge.exposeInMainWorld("pluginBridge", {
- async invoke(channel, payload = {}) {
- switch (channel) {
- case "app.getAppearance":
- return { base: "dark", locale: "en" };
- case "workspace.get":
- return workspace;
- default:
- if (!channel.startsWith("fm.")) {
- throw new Error("Unexpected fixture channel: " + channel);
+ contextBridge.exposeInMainWorld("pluginBridge", {
+ async invoke(channel, payload = {}) {
+ try {
+ let result;
+ switch (channel) {
+ case "app.getAppearance":
+ result = { base: "dark", locale: "en" };
+ break;
+ case "workspace.get":
+ result = workspace;
+ break;
+ default:
+ if (!channel.startsWith("fm.")) {
+ throw new Error("Unexpected fixture channel: " + channel);
+ }
+ result = await plugin.onPanelInvoke(channel, { ...payload, workspacePath: workspaceDir });
+ }
+ log.push({ channel, ok: true, result: JSON.stringify(result).slice(0, 200) });
+ return result;
+ } catch (error) {
+ log.push({ channel, ok: false, error: String(error).slice(0, 200) });
+ throw error;
}
- return plugin.onPanelInvoke(channel, { ...payload, workspacePath: workspaceDir });
- }
- },
- on() {
- return () => {};
- },
-});
+ },
+ on() {
+ return () => {};
+ },
+ });
+ contextBridge.exposeInMainWorld("__fixtureLog", () => log);
+ return null;
+ } catch (error) {
+ return String(error?.stack ?? error);
+ }
+})();
+contextBridge.exposeInMainWorld("__preloadError", () => preloadError);
`;
- const main = mainFixture;
await writeFile(join(temp, "preload.cjs"), preload);
- await writeFile(join(temp, "main.cjs"), main);
+ await writeFile(join(temp, "main.cjs"), mainFixture);
const env = {
...process.env,
@@ -279,7 +328,7 @@ contextBridge.exposeInMainWorld("pluginBridge", {
output += chunk;
});
}
- const timeout = setTimeout(() => child.kill("SIGKILL"), 90_000);
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 150_000);
let code;
try {
code = await new Promise((resolve, reject) => {