Skip to content
Merged
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
39 changes: 29 additions & 10 deletions desktop/e2e/browser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,15 @@ test("browser: a page opens from an agent's pane, follows its area, moves withou
await expect.poll(async () => (await viewOf(`${origin}/a.html`)).visible).toBe(false);

// Two View areas side by side need the Workspace's width: the side panel
// is expanded over it. In this window the panel already covers the body,
// so its Expand is not drawn and the palette stores the state; the tools
// fold into an overlay there, closed until asked for (issue 170).
// is expanded over it (issue 170). The open panel beside the agents leaves
// the View area too narrow to split, and the core stores the expansion, so
// the menu below offers Split right only once the expanded panel is drawn:
// it reads the geometry drawn when it opens.
await page.keyboard.press("Meta+KeyK");
await page.keyboard.type("Expand side panel");
await page.locator('[data-palette-row="command:panel:expanded"]').click();
await expect(page.locator("[data-palette-input]")).toHaveCount(0);
await expect(page.locator("[data-workspace-screen]")).toHaveAttribute("data-panel", "expanded");
const toolsShown = page.locator('[data-tools-toggle="on"]');
if (await toolsShown.count()) await toolsShown.click();
await expect(page.locator("[data-workspace-tools]")).toHaveCount(0);
Expand Down Expand Up @@ -665,6 +667,7 @@ test("area cycle native: page input previews one exact area, releases once and c
await page.keyboard.press("Meta+KeyK");
await page.keyboard.type("Expand side panel");
await page.locator('[data-palette-row="command:panel:expanded"]').click();
await expect(page.locator("[data-workspace-screen]")).toHaveAttribute("data-panel", "expanded");
if (await page.locator('[data-tools-toggle="on"]').count()) await page.locator('[data-tools-toggle="on"]').click();
await tab(page, "Page B").click({ button: "right" });
await page.locator('[role=menu] [data-menu-item=split_right]').click();
Expand All @@ -674,12 +677,14 @@ test("area cycle native: page input previews one exact area, releases once and c
const previousId = await displayIdOf(page, "Page B");
const outsideId = await displayIdOf(page, "Page A");
const pid = app.process().pid!;
const focus = async (url: string) => {
const focus = async (url: string, displayId: string) => {
await app!.evaluate(({ app: electron, BrowserWindow }, url) => {
const window = BrowserWindow.getAllWindows()[0]!;
electron.focus({ steal: true }); window.focus();
const child = window.contentView.children.find(view => (view as { webContents?: Electron.WebContents }).webContents?.getURL() === url) as unknown as { webContents: Electron.WebContents };
child.webContents.focus();
// A page already holding native focus announces nothing when focused
// again, so the shell takes it first and the page enters as an operator's click would.
window.webContents.focus(); child.webContents.focus();
}, url);
// macOS activates the window asynchronously, and an activation still in
// flight can hand the keyboard back to the shell a moment after the page
Expand All @@ -690,16 +695,25 @@ test("area cycle native: page input previews one exact area, releases once and c
const child = window.contentView.children.find(view => (view as { webContents?: Electron.WebContents }).webContents?.getURL() === url) as unknown as { webContents: Electron.WebContents };
return window.isFocused() && child.webContents.isFocused();
}, url);
// Native focus is not yet a hold the shell admits. The host starts one
// only from a page it shows, and the shell only when its keyboard owner
// is that page's area and the core's snapshot selects the page there
// (`web/src/keyboard.ts`). A tab click or a closed sheet just before
// reaches both through a round trip, and the window's own activation can
// hand the owner to the shell element it focuses, so keys posted on
// native focus alone drew nothing.
const admitted = async () => (await viewOf(url)).visible && (await page.evaluate((id) =>
document.querySelector("[data-keyboard-area=true] [data-view-tab-bar] [aria-selected=true]")?.getAttribute("data-display") === id, displayId));
await expect.poll(async () => {
await app!.evaluate(({ app: electron, BrowserWindow }, url) => {
const window = BrowserWindow.getAllWindows()[0]!;
electron.focus({ steal: true }); window.focus();
const child = window.contentView.children.find(view => (view as { webContents?: Electron.WebContents }).webContents?.getURL() === url) as unknown as { webContents: Electron.WebContents };
child.webContents.focus();
window.webContents.focus(); child.webContents.focus();
}, url);
if (!(await holds())) return false;
await new Promise((resolve) => setTimeout(resolve, 250));
return holds();
return (await holds()) && (await admitted());
}).toBe(true);
};
const capture = async (name: string) => {
Expand All @@ -710,7 +724,7 @@ test("area cycle native: page input previews one exact area, releases once and c
expect(result.status, "exact native window capture failed: " + result.stderr).toBe(0);
fs.writeFileSync(path.join(dir, "area-native-identity.json"), JSON.stringify({ pid, window: source, daemonPid: run.daemonPid(), socket: herdr.socket, state: run.env.HIDE_STATE_DIR, userData: run.env.HIDE_DESKTOP_USER_DATA_DIR, pages: await views() }, null, 2));
};
await focus(current);
await focus(current, originalId);
await expect(page.locator('[data-keyboard-area=true]')).toHaveCount(1);
const selections = () => page.locator('[data-view-tab-bar] [aria-selected=true]').evaluateAll(tabs => tabs.map(tab => tab.getAttribute("data-display")));
const before = await selections();
Expand Down Expand Up @@ -739,7 +753,7 @@ test("area cycle native: page input previews one exact area, releases once and c
// Escape from the actual native page preserves both the selection and owner.
await tab(page, "한글 브라우저").click();
await inPage(current, "document.querySelector('input').focus()");
await focus(current);
await focus(current, originalId);
const canceled = sent.get("view_layout") ?? 0;
nativeKeys(pid, ["control down", "tab"]);
await expect(page.locator("[data-cycle=area]")).toBeVisible();
Expand Down Expand Up @@ -774,12 +788,17 @@ test("area cycle native: page input previews one exact area, releases once and c
await page.locator('[data-settings-tab="shortcuts"]').click();
await page.locator('[data-shortcut-record="recent_area_tab"]').click();
await page.keyboard.press("Control+Alt+Tab");
// A native page's hold starts from the host's copy of the chords, which
// the shell reports after the core stores the binding; the host takes it
// and then rebuilds the menu in one call, so a new menu means it has it.
await app.evaluate(({ Menu }) => { (globalThis as { menuBeforeRebind?: unknown }).menuBeforeRebind = Menu.getApplicationMenu(); });
await page.locator('[data-shortcut-apply="recent_area_tab"]').click();
await expect(page.locator('[data-shortcut-effective="recent_area_tab"]')).toHaveText("⌃⌥⇥");
await expect.poll(() => app!.evaluate(({ Menu }) => Menu.getApplicationMenu() !== (globalThis as { menuBeforeRebind?: unknown }).menuBeforeRebind)).toBe(true);
await page.keyboard.press("Escape");
await inPage(previous, "document.getElementById('q').value = ''");
await inPage(current, "document.querySelector('input').focus()");
await focus(current);
await focus(current, originalId);
const rebound = sent.get("view_layout") ?? 0;
const originText = await inPage(current, "document.querySelector('input').value");
nativeKeys(pid, ["option down", "control down", "tab"]);
Expand Down
9 changes: 5 additions & 4 deletions desktop/e2e/digit-shortcuts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import path from "node:path";
import { startHerdr, type HerdrFixture } from "../../web/e2e/herdr-fixture";
import "../../web/src/host";
import { countSent, enterWorkspace } from "../../web/e2e/wire";
import { hostLog, isolate, launch, test, type Isolated } from "./fixture";
import { hostLog, isolate, launchShell, test, type Isolated } from "./fixture";

let herdr: HerdrFixture;
let run: Isolated;
Expand Down Expand Up @@ -92,10 +92,11 @@ test("⌘n selects a tab, ⌥n an agent, and holding ⌘ or ⌥ shows the number
]) as { result: { tab: { tab_id: string } } };
tabs.push(made.result.tab.tab_id);
try {
({ app } = await launch(run.env));
const page = await app.firstWindow();
const launched = await launchShell(run.env);
app = launched.app;
const page = launched.page;
const sent = countSent(page);
// Observe the new live socket before it connects, including with an already-loaded shell.
// Observe the new live socket before it connects, reloading the shell the host has already loaded.
// The exactly-once expectations below still assert the real outgoing events.
await Promise.all([
page.waitForEvent("websocket", { predicate: (socket) => new URL(socket.url()).pathname === "/ws", timeout: 5_000 }),
Expand Down
12 changes: 12 additions & 0 deletions desktop/e2e/fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,18 @@ export async function shellPage(app: ElectronApplication): Promise<Page> {
return shell!;
}

/**
* A launch that returns once the host's own navigation from the status page
* to the shell has landed, for a spec that reloads or navigates the window
* itself. A spec navigation sent while the host's is in flight replaces it:
* the host drops a superseded load as not a failure, so the window stays on
* the status page with no socket, or the spec's reload is the one aborted.
*/
export async function launchShell(env: Record<string, string>): Promise<{ app: ElectronApplication; page: Page }> {
const app = await relaunch(env);
return { app, page: await shellPage(app) };
}

/**
* The built app copied under this run's directory, so an unpackaged launch
* has no worktree `target/` beside it and searches for `hide` the way an
Expand Down
4 changes: 2 additions & 2 deletions desktop/e2e/session-labels.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import path from "node:path";
import { REPO } from "./fixture";
import { startHerdr } from "../../web/e2e/herdr-fixture";
import { enterWorkspace } from "../../web/e2e/wire";
import { isolate, launch, test } from "./fixture";
import { isolate, launchShell, test } from "./fixture";

function owner(id: string, kind = "id"): string {
const hash = crypto.createHash("sha256");
Expand Down Expand Up @@ -39,7 +39,7 @@ test("native session replacement hides stale labels before the watcher publishes
try {
labels(`fixture-${pane}`, "세션 A의 한글 작업");
if (process.env.HIDE_E2E_SCREENSHOT_DIR) fs.writeFileSync(path.join(process.env.HIDE_E2E_SCREENSHOT_DIR, "fixture-agents.json"), JSON.stringify(herdr.run(["agent", "list"])));
const launched = await launch(run.env);
const launched = await launchShell(run.env);
app = launched.app;
const page = launched.page;
const cdp = await page.context().newCDPSession(page);
Expand Down
42 changes: 42 additions & 0 deletions herdr-core/src/executable_fixture.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//! Writes a script a test then runs as a program.
//!
//! Linux refuses to exec a file that any process holds open for writing
//! (`ETXTBSY`, "Text file busy"). A fixture written with `std::fs::write` holds
//! such a descriptor for a moment, and a test on another thread that spawns a
//! child in that moment copies it into the child, where it stays until the
//! child's own exec closes it. Run in that gap, the fixture fails to start: on
//! the ubuntu runner `run_gh` returned an error within milliseconds of the
//! suite starting, while a thousand tests were spawning beside it. macOS has
//! no such refusal, so the suite never showed it there.
//!
//! The file is therefore written by a child process: this process never holds
//! a write descriptor to it, so no spawn can carry one away, and the writer has
//! exited, its descriptor with it, before the fixture is run.

use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};

/// Writes `contents` to `path` as an owner-executable file.
pub(crate) fn write_executable(path: &Path, contents: &str) {
let mut writer = Command::new("/bin/sh")
.args(["-c", "cat > \"$1\" && chmod 700 \"$1\"", "sh"])
.arg(path)
.stdin(Stdio::piped())
.spawn()
.expect("start the executable fixture writer");
writer
.stdin
.take()
.expect("piped stdin")
.write_all(contents.as_bytes())
.expect("send the executable fixture");
let status = writer
.wait()
.expect("wait for the executable fixture writer");
assert!(
status.success(),
"writing {} failed: {status}",
path.display()
);
}
21 changes: 12 additions & 9 deletions herdr-core/src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1488,7 +1488,6 @@ mod tests {
#[cfg(unix)]
impl GhFixture {
fn new(body: &str) -> Self {
use std::os::unix::fs::PermissionsExt;
static SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let root = std::env::temp_dir().join(format!(
"hide-gh-{}-{}-{}",
Expand All @@ -1501,8 +1500,7 @@ mod tests {
));
std::fs::create_dir_all(&root).unwrap();
let binary = root.join("gh");
std::fs::write(&binary, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
crate::executable_fixture::write_executable(&binary, &format!("#!/bin/sh\n{body}\n"));
Self { root, binary }
}
}
Expand Down Expand Up @@ -1676,18 +1674,23 @@ esac"#,
#[cfg(unix)]
fn a_pull_request_takes_only_its_body_write_and_its_two_reads() {
let fixture = GhFixture::new(r#"printf 'ok'"#);
let allowed = |arguments: &[&str]| {
let run = |arguments: &[&str]| {
run_gh(
&fixture.binary,
Some(&fixture.root),
arguments,
Duration::from_secs(5),
)
.is_ok()
};
assert!(allowed(&["pr", "view", "12", "--json", "body"]));
assert!(allowed(&["pr", "view", "12", "--json", PR_FEEDBACK_FIELDS]));
assert!(allowed(&["pr", "edit", "12", "--body", "Closes #7"]));
for allowed in [
&["pr", "view", "12", "--json", "body"][..],
&["pr", "view", "12", "--json", PR_FEEDBACK_FIELDS],
&["pr", "edit", "12", "--body", "Closes #7"],
] {
if let Err(failure) = run(allowed) {
panic!("{allowed:?} must run: {}", failure.reason);
}
}
for refused in [
&["pr", "edit", "12", "--title", "x"][..],
&["pr", "edit", "12", "--add-label", "x"],
Expand All @@ -1699,7 +1702,7 @@ esac"#,
&["pr", "review", "12", "--approve"],
&["pr", "close", "12"],
] {
assert!(!allowed(refused), "{refused:?} must be refused");
assert!(run(refused).is_err(), "{refused:?} must be refused");
}
}

Expand Down
2 changes: 2 additions & 0 deletions herdr-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ mod disk;
mod disk_layers;
pub mod domain;
mod environment;
#[cfg(all(test, unix))]
mod executable_fixture;
#[cfg(test)]
mod fake_herdr;
mod files;
Expand Down
9 changes: 3 additions & 6 deletions herdr-core/src/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3934,16 +3934,13 @@ mod tests {
let directory = tempfile::tempdir().expect("create hcoord fixture directory");
let binary = directory.path().join("hcoord");
let pid_path = directory.path().join("pid");
std::fs::write(
crate::executable_fixture::write_executable(
&binary,
format!(
&format!(
"#!/bin/sh\nprintf '%s' \"$$\" > '{}'\nexec /bin/sleep 300\n",
pid_path.display()
),
)
.expect("write hanging hcoord fixture");
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755))
.expect("make hcoord fixture executable");
);
let herdr = FakeHerdr::start("fork-hcoord-timeout", |method, _| match method {
"pane.split" => json!({"type": "pane_info", "pane": {
"pane_id": "child-pane", "terminal_id": "child-terminal",
Expand Down
2 changes: 1 addition & 1 deletion plugins/hcoord/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"install:remote": "node scripts/install.mjs",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --test \"test/unit/*.test.mjs\"",
"test:e2e": "node --test \"test/e2e/*.test.mjs\""
"test:e2e": "node --test --test-timeout=120000 \"test/e2e/*.test.mjs\""
},
"devDependencies": {
"@types/node": "^22.14.0",
Expand Down
14 changes: 7 additions & 7 deletions plugins/hcoord/test/e2e/hcoord-health.test.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import test from "node:test";
import { createFakeRemote } from "../helpers/fake-remote.mjs";
import { hq } from "../helpers/hcoord-hq.mjs";
import { spawnOwned } from "../helpers/owned-children.mjs";
import { daemonPlist } from "../../dist/hcoord/platform.js";

const CLI = path.resolve(import.meta.dirname, "../../dist/hcoord/cli.js");
Expand All @@ -19,7 +19,7 @@ test("the LaunchAgent restarts only unsuccessful exits", () => {
test("three unexpected exits in ten minutes raise one Herdr notification and a warning on every command", async (t) => {
const fake = createFakeRemote(CLI);
t.after(() => fake.cleanup());
const coordinator = hq(t, fake);
const coordinator = hq(fake);
for (let crash = 0; crash < 3; crash += 1) { await coordinator.start(); await coordinator.stop("SIGKILL"); }
await coordinator.start();
await coordinator.until(() => fake.notifications().length > 0, "the restarted daemon sends a Herdr notification");
Expand All @@ -37,7 +37,7 @@ test("three unexpected exits in ten minutes raise one Herdr notification and a w
test("clean stops never count as instability", async (t) => {
const fake = createFakeRemote(CLI);
t.after(() => fake.cleanup());
const coordinator = hq(t, fake);
const coordinator = hq(fake);
for (let restart = 0; restart < 4; restart += 1) { await coordinator.start(); await coordinator.stop("SIGTERM"); }
await coordinator.start();
assert.equal(coordinator.run("status").stderr, "");
Expand All @@ -49,12 +49,12 @@ test("clean stops never count as instability", async (t) => {
test("a stop signal during startup still ends with a clean mark", async (t) => {
const fake = createFakeRemote(CLI);
t.after(() => fake.cleanup());
const coordinator = hq(t, fake);
const coordinator = hq(fake);
const healthFile = path.join(coordinator.dir, "health.json");
const starts = () => { try { return JSON.parse(fs.readFileSync(healthFile, "utf8")).starts; } catch { return []; } };
for (let attempt = 0; attempt < 5; attempt += 1) {
const before = starts().length;
const daemon = spawn(process.execPath, [CLI, "daemon", "run"], { env: coordinator.env, stdio: "ignore" });
const daemon = spawnOwned(`startup daemon ${attempt}`, process.execPath, [CLI, "daemon", "run"], { env: coordinator.env, stdio: "ignore" });
const exited = new Promise((resolve) => daemon.once("exit", (code, signal) => resolve({ code, signal })));
while (starts().length === before && daemon.exitCode === null) await new Promise((resolve) => setImmediate(resolve));
daemon.kill("SIGTERM");
Expand All @@ -66,7 +66,7 @@ test("a stop signal during startup still ends with a clean mark", async (t) => {
test("a start that never answers for a minute warns even without a request, and ten ready minutes clear it", async (t) => {
const fake = createFakeRemote(CLI);
t.after(() => fake.cleanup());
const coordinator = hq(t, fake);
const coordinator = hq(fake);
fs.mkdirSync(coordinator.dir, { recursive: true });
fs.writeFileSync(path.join(coordinator.dir, "health.json"), JSON.stringify({ starts: [{ pid: 999999, at: minutesAgo(2), readyAt: null, cleanAt: null }] }));
const down = coordinator.run("inbox");
Expand All @@ -86,7 +86,7 @@ test("a start that never answers for a minute warns even without a request, and
test("a corrupt health record is reported, not read as a healthy daemon", async (t) => {
const fake = createFakeRemote(CLI);
t.after(() => fake.cleanup());
const coordinator = hq(t, fake);
const coordinator = hq(fake);
fs.mkdirSync(coordinator.dir, { recursive: true });
fs.writeFileSync(path.join(coordinator.dir, "alert.json"), "{not json");
assert.match(coordinator.run("inbox").stderr, /^hcoord warning: daemon health is unknown: .*alert\.json is unreadable/);
Expand Down
Loading
Loading