Skip to content
Merged
6 changes: 5 additions & 1 deletion desktop/e2e/desktop.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,15 @@ test("New tab: the native chord and menu each open one terminal directly", { tag
};

// New tab opens a shell in the keyboard's Agent area without a start form.
const selected = area.locator('[data-agent-tab-bar] [role=tab][aria-selected="true"]');
// The new tab is drawn before it is selected, so the tab selected until now
// is what the selection has to leave (with-hide/hide-private#141).
const initial = await selected.getAttribute("data-tab");
await page.locator("[data-pane-view] .xterm-helper-textarea").first().focus();
await page.keyboard.press(chord("new_tab", "electron"));
await expect(tabs).toHaveCount(before + 1);
await expect(start).toHaveCount(0);
const selected = area.locator('[data-agent-tab-bar] [role=tab][aria-selected="true"]');
await expect(selected).not.toHaveAttribute("data-tab", initial!);
await expect(selected).not.toHaveAttribute("data-tab", /^draft:/);
const first = await selected.getAttribute("data-tab");
await expect(page.locator("[data-canvas]")).toHaveAttribute("data-canvas", first!);
Expand Down
42 changes: 35 additions & 7 deletions desktop/e2e/fixture-cleanup.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,17 +152,45 @@ test("a rejected close after confirmed candidate exit still cleans home and repo
expectOpenerCopied(run);
});

test("a successful close must confirm exit before home deletion", async () => {
const child = candidate(async () => {});
const run = privateHome("unconfirmed-exit");
/** The exit Node reports for `child`: its exit code, then the `exit` event. */
function exitLater(child: ChildProcess): void {
setImmediate(() => {
reportExit(child);
child.emit("exit", 0, null);
});
}

// Playwright's close returns once the app's debugging pipe closes, and on
// Windows the recorded process (the cmd.exe Playwright starts the app under)
// exits after that (with-hide/hide-private#244).
test("a close that returns before its candidate exits waits for that exit, then the home goes", async () => {
candidate(async (child) => { exitLater(child); });
const run = privateHome("late-exit");
const error = await teardown(async () => { await launch(run.env); });
expect(error?.errors.some((item: Error) => item.message.includes(run.root))).toBe(true);
expect(fs.existsSync(run.env.HOME!)).toBe(true);
reportExit(child, "SIGTERM");
run.cleanup();
expect(error).toBeUndefined();
expect(fs.existsSync(run.root)).toBe(false);
});

test("a candidate that never exits after a successful close fails the close by its pid and keeps the home", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
const child = candidate(async () => {});
Object.assign(child, { pid: 4242 });
const run = privateHome("unconfirmed-exit");
const ended = teardown(async () => { await launch(run.env); });
await vi.advanceTimersByTimeAsync(10_000);
const error = await ended;
expect(error?.errors.some((item: Error) => item.message === "child 4242 did not exit within 10000 ms after app.close() returned")).toBe(true);
expect(error?.errors.some((item: Error) => item.message.includes(run.root))).toBe(true);
expect(fs.existsSync(run.env.HOME!)).toBe(true);
reportExit(child, "SIGTERM");
run.cleanup();
expect(fs.existsSync(run.root)).toBe(false);
} finally {
vi.useRealTimers();
}
});

test("manual cleanup rejects a live candidate before stopping any private service", async () => {
candidate(async (child) => { reportExit(child); });
const run = privateHome("manual-cleanup");
Expand Down
25 changes: 22 additions & 3 deletions desktop/e2e/fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,23 @@ export function seedKitRecord(home: string): void {
*/
export async function endChild(child: ChildProcess, ms = 10_000): Promise<void> {
if (child.exitCode !== null || child.signalCode !== null) return;
const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
const exited = exitOf(child, ms, "after SIGTERM");
child.kill("SIGTERM");
await exited;
}

/** How long a closed app's process may take to exit before its close fails naming it. */
const CANDIDATE_EXIT_MS = 10_000;

/** Returns once `child` has exited; one that has not within `ms` is a failure that names it and what came `before`. */
async function exitOf(child: ChildProcess, ms: number, before: string): Promise<void> {
if (child.exitCode !== null || child.signalCode !== null) return;
let timer: NodeJS.Timeout | undefined;
const late = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`child ${child.pid} did not exit within ${ms} ms after SIGTERM`)), ms);
timer = setTimeout(() => reject(new Error(`child ${child.pid} did not exit within ${ms} ms ${before}`)), ms);
});
try {
await Promise.race([exited, late]);
await Promise.race([new Promise<void>((resolve) => child.once("exit", () => resolve())), late]);
} finally {
clearTimeout(timer);
}
Expand Down Expand Up @@ -340,6 +349,16 @@ async function start(appDir: string, env: Record<string, string>, executablePath
// retains this handle beyond test teardown if closing the app fails.
const child = app.process();
owner.candidates.add(child);
// Playwright's `close()` returns once the app's debugging pipe closes,
// which can come before this process has exited: on Windows the process is
// the cmd.exe Playwright starts the app under, which exits after it. A
// cleanup right after then found the candidate still running. This close
// returns once the recorded process has exited.
const closeApp = app.close.bind(app);
app.close = async () => {
await closeApp();
await exitOf(child, CANDIDATE_EXIT_MS, "after app.close() returned");
};
focusReports.apps.push({ close: () => app.close(), child });
return app;
} finally {
Expand Down
5 changes: 4 additions & 1 deletion desktop/e2e/global-setup.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// Builds the web fixtures' C programs and the fused Electron copy once, before any test
// (web/e2e/shims/build.ts, fused-electron.ts).
// (web/e2e/shims/build.ts, fused-electron.ts), then prepares a Windows run the
// way the web entry point does (`prepareWindowsRun`).
// This file lives in the desktop package so Playwright loads it, and what it
// imports, the way it loads the desktop specs.
import path from "node:path";
import type { FullConfig } from "@playwright/test";
import { prepareWindowsRun } from "../../web/e2e/platform-fixture";
import { buildFixtureShims } from "../../web/e2e/shims/build";
import { makeFusedElectron } from "./fused-electron";

export default async function globalSetup(config: FullConfig): Promise<void> {
await buildFixtureShims(path.dirname(config.configFile!));
await makeFusedElectron();
if (process.platform === "win32") for (const line of await prepareWindowsRun(path.dirname(config.configFile!))) console.log(line);
}
8 changes: 6 additions & 2 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ When the behavior depends on the order of two events, the test fixes that order;
Automatic teardown closes candidate apps, then each home's cleanup checks its recorded process handles for confirmed exit before stopping the private hided and deleting the home.
An unconfirmed candidate exit, stop or cleanup failure fails teardown and retains the home for recovery; the error names the retained path and recovery action.
When candidate exit is unconfirmed, close only the recorded owned candidate, confirm its exit, then call that fixture's `cleanup()` again.
An app's `close()` returns once its recorded process has exited, within ten seconds, or fails naming the pid: Playwright's own close returns when the app's debugging pipe closes, and on Windows the recorded process is the cmd.exe Playwright starts the app under, which exits after that, so a cleanup right after found the candidate running (with-hide/hide-private#244).
After a confirmed exit, cleanup reads the host log: a `host.uncaught` line the test did not expect with `allowHostUncaught` fails the test with its stack once the home is deleted, so an exception the host caught nothing for names itself instead of passing unseen (issue 675).
`desktop/e2e/fixture-cleanup.unit.ts` injects Electron close failures at the external boundary and checks real home retention, confirmed-exit deletion and recovery without starting native processes.
On Windows `endWindowsProcesses` also ends what the owned processes started, found from their pid and start time after they are gone: an owner killed while it starts a child leaves that child out of the tree listed before the kill, and a child hided started suspended and had not yet put in its job stays suspended, keeping its executable locked.
Expand Down Expand Up @@ -167,7 +168,7 @@ When the behavior depends on the order of two events, the test fixes that order;
On macOS and Linux that is while `pane process-info` says the shell alone holds the terminal; on Windows it is while no process names the shell as its parent, which `pane process-info` does not show, so the fixture lists those processes with the compiled `hide-children.exe`.
A refusal as `agent_pane_busy` typed nothing, so the fixture goes back to waiting within the same ten-second bound; any other answer is the start's.
A pane's shell that never gets there fails with the last process info and, on Windows, the children the shell still has.
On Windows `globalSetup` ends every `vctip.exe` after the run's last compile and prints the pids it ended (`endVctip`): MSVC's compiler and linker leave that telemetry helper running, still naming as its parent a linker whose pid Windows can give a pane's shell, and the pinned Herdr counts a shell's children by parent pid alone, so it would refuse that pane as busy for as long as the helper ran.
On Windows both entry points' `globalSetup` (`web/e2e/global-setup.ts`, `desktop/e2e/global-setup.ts`) prepare the run once after its last compile (`prepareWindowsRun` in `web/e2e/platform-fixture.ts`): they start Windows PowerShell once the way the pinned Herdr starts an agent from a cmd.exe pane (`powershell.exe -NoLogo -NoProfile -EncodedCommand` of `& '<name>'`) and the debug `hided` once (`hided node --version`), each printing how long it took, because a job's first start of each paid its cold cost inside the first test's bounds (a 46 s first `agent start` against 30 s, a 24 s daemon start against `hide connect`'s 10 s a step; with-hide/hide-private#256), and they end every `vctip.exe` and print the pids they ended (`endVctip`): MSVC's compiler and linker leave that telemetry helper running, still naming as its parent a linker whose pid Windows can give a pane's shell, and the pinned Herdr counts a shell's children by parent pid alone, so it would refuse that pane as busy for as long as the helper ran.
A process Windows started at boot can do the same and cannot be ended: `csrss.exe` names as its parent the `smss.exe` that started it and exited, and a pane's shell can be given that pid.
So on Windows every workspace the fixture opens, `startHerdr`'s and each `workspace create` a spec sends through `fixture.run` (`spawnAgent`'s included), is checked, as soon as Herdr answers the create, for processes that started before a pane's shell yet name it as their parent (`hide-children.exe` compares start times; the name does not matter).
When there is one, `unclaimedWorkspace` logs a line, opens the workspace again while the claimed shells still hold their pids, and closes the claimed one; a replacement that is claimed too fails with each process's pid, start time and name.
Expand Down Expand Up @@ -359,7 +360,7 @@ A test whose assertion requires a pipe to have no readers creates and closes tha
8. **Give a test a program that has already started once.**
macOS checks a file the first time it is started, once per file, and the checks of every process on the machine wait in one line: on 2026-10-09 at load 7 a new script's first start took about 90 ms, its second 6 ms, and the last of twenty new scripts started together waited 1.8 s; Linux refuses to start a file another thread's fork still holds open for writing (`ETXTBSY`).
A program a test copies or writes and then runs inside a product deadline therefore pays that line inside the deadline, and under load it outgrew the hook's budget and the kit's 5 s deadlines (issue 813).
In `hide-platform`, `hide-agent-hooks`, `hide-kit` and `hided` a stand-in comes from `hide-platform/tests/it/stand_ins.rs`: `program(at, body)` puts at `at` a hard link to one read-only file per body beside the build's test binaries, started once per process before the test gets it, and `place` does the same for the helper cargo built.
In `hide-platform`, `hide-agent-hooks`, `hide-kit`, `hide-ai` and `hided` a stand-in comes from `hide-platform/tests/it/stand_ins.rs`: `program(at, body)` puts at `at` a hard link to one read-only file per body beside the build's test binaries, started once per process before the test gets it, and `place` does the same for the helper cargo built.
On macOS, `place` instead byte-copies a native executable into the fixture, ad-hoc signs that private file, and starts it before the measured deadline; it never signs a hard link or changes the build output.
A first start killed by a signal fails setup with its exit status instead of being cached as ready; a normal nonzero exit remains valid because some CLIs and interpreters reject `--help`.
A body is fixed text and finds its test's files from `HOME` (`${HOME%/*}` for the folder around it), never from a path written into it, because each distinct body is one more file kept for the build.
Expand All @@ -372,6 +373,9 @@ A test whose assertion requires a pipe to have no readers creates and closes tha
A system program pays the same on Windows: Windows PowerShell's first start in a CI job, beside the other tests starting theirs, took from 2 s to past a 15 s run's hang guard (issue 1497), so a test that bounds a run through it starts it once first with `ready_with_args` (`agy_shell` in `hide-agent-hooks/tests/it/windows_hook_command.rs`).
That first start runs the cmdlets the bounded command calls, not only `exit 0`: Windows PowerShell loads a cmdlet's module on first use and, on a fresh runner, first builds its cache of every installed module, which took four tests paying it together 38 to 48 s (issues 198 and 199); this readies the test, and the installed command's own first use is hide-private issue 318.
Node pays the same: the first `node.exe` a Windows job starts took from 2.5 s to past a 30 s hang guard and the next 0.1 s (issue 202), so `hide-kit`'s Windows process test starts `node --version` first.
Python pays the same: the first `python` a Windows job starts, through `hide-ai`'s `fake-claude.cmd`, took 21 to 30 s where later reads take about a second (issue 230), so the `/usage` tests ready the fake (`stand_ins::ready_with_args`) while they hold `FAKE_ENV`.
A new debug build pays it too: a Windows job's first starts of `hided` took 6 to 18 s before its seat answered, against `hide connect`'s 10 s (issues 264, 265 and 212), so `connect_stop` readies the `hided` beside `hide` with `hided node --version`, and the e2e entry points do the same for theirs (above).
This readies the test for what it measures; when the cold cost is one an operator's first start pays too, the product's own wait is a separate issue, not something the readying settles.
Do not rename a system utility to stand in for an agent: a multicall utility can choose its implementation from the executable name and reject the agent's name.
9. **Retries are a classification.**
CI runs every Rust lane (Linux, macOS, Windows, the OS contract and nightly) with `scripts/verify-cargo.sh nextest --profile ci` (`retries = 1` in `.config/nextest.toml`), so a test that fails once and then passes is reported as flaky and recorded in an issue with an expiry; two failures fail the lane.
Expand Down
15 changes: 14 additions & 1 deletion hide-ai/tests/it/claude_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,8 +472,10 @@ mod usage {
use hide_ai::{USAGE_ENVIRONMENT, UsageError};

/// The fake CLI's working folder, which tells it what to answer and
/// keeps what it received; it goes when the test drops it.
/// keeps what it received; it goes when the test drops it. The fake's
/// interpreter has started once before, so no read's deadline holds it.
fn usage_dir(mode: &str) -> tempfile::TempDir {
interpreter_started();
let dir = tempfile::Builder::new()
.prefix(&format!("hide-ai-usage-{mode}-"))
.tempdir()
Expand All @@ -482,6 +484,17 @@ mod usage {
dir
}

/// The fake CLI started once before a read's deadline (docs/TESTING.md,
/// Writing a Rust test, rule 8): a Windows runner's first `python` of a
/// job took 21-30 s where later ones take about a second, so the first
/// reads in the job timed out before their child had started
/// (with-hide/hide-private#230). The lock keeps another test's `FAKE_*`
/// paths out of that start.
fn interpreter_started() {
let _guard = crate::FAKE_ENV.lock().unwrap_or_else(|e| e.into_inner());
crate::stand_ins::ready_with_args(&fixture(), &["auth", "status", "--json"]);
}

fn usage_backend(cwd: &std::path::Path) -> ClaudeCliBackend {
ClaudeCliBackend::new(ClaudeConfig {
binary: fixture(),
Expand Down
3 changes: 3 additions & 0 deletions hide-ai/tests/it/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ mod codex_app_server;
mod omp_sdk;
mod process_ownership;
mod search_path;
#[allow(dead_code)] // The fakes need readiness only, not stand-in placement.
#[path = "../../../hide-platform/tests/it/stand_ins.rs"]
mod stand_ins;
mod text_clis;
2 changes: 1 addition & 1 deletion hide-platform/tests/it/stand_ins.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Programs a test runs against a product deadline, ready before the
//! deadline starts (issues 813 and 824). Built only into tests: hide-platform's
//! integration tests, and by `#[path]` hided's integration tests,
//! integration tests, and by `#[path]` hided's and hide-ai's integration tests,
//! hide-agent-hooks' unit and integration tests and hide-kit's unit tests, so
//! a change here plans every crate that runs it.
//!
Expand Down
10 changes: 10 additions & 0 deletions hided/tests/it/connect_stop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ use serde_json::Value;
/// `hide` with the account's places moved under `home`; on Windows the home
/// and the folders Herdr's default pipe and the folder locks resolve from.
fn isolated(home: &Path, state: &Path) -> Command {
// The daemon `hide connect` starts is the `hided` beside it, and its start
// has 10 s to show progress. A Windows job's first starts of that new
// debug build took 6 to 18 s before its seat answered, three tests
// starting it together, where a later start takes under a second
// (with-hide/hide-private#264, #265, #212); it starts once first
// (docs/TESTING.md, Writing a Rust test, rule 8).
crate::stand_ins::ready_with_args(
Path::new(env!("CARGO_BIN_EXE_hided")),
&["node", "--version"],
);
let mut command = Command::new(env!("CARGO_BIN_EXE_hide"));
for (key, _) in std::env::vars_os() {
let upper = key.to_string_lossy().to_uppercase();
Expand Down
Loading
Loading