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
4 changes: 2 additions & 2 deletions desktop/e2e/desktop.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ test("attach: the app starts hided, shows the shell, and runs the native chords
await expect(page.locator("[data-pane-view] .xterm").first()).toBeVisible();
await screenshot(page, "desktop-attached");

// B11: no Node API in the page; the bridge is the host kind and the menu channel.
// B11: no Node API in the page; the bridge is the host kind, the menu channel and the pane-chord report.
expect(
await page.evaluate(() => ({
require: typeof (globalThis as { require?: unknown }).require,
process: typeof (globalThis as { process?: unknown }).process,
bridge: Object.keys(window.hideHost ?? {}).sort(),
kind: window.hideHost?.kind,
})),
).toEqual({ require: "undefined", process: "undefined", bridge: ["kind", "onCommand"], kind: "electron" });
).toEqual({ require: "undefined", process: "undefined", bridge: ["kind", "onCommand", "reportBindings"], kind: "electron" });

// B9: ⌘T is one create_tab here; the browser's ⌥T is not a chord in the app.
const tabs = await page.locator("[role=tab]").count();
Expand Down
198 changes: 198 additions & 0 deletions desktop/e2e/keys.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// The desktop app's keys end to end: the operator's macOS pane chords, which
// hided brings across from the Swift app's state once, and the held-modifier
// cycles, whose commit waits for the modifier's release. A private Herdr
// server for this file, a private hided and Electron app per test.

import { expect, test, type ElectronApplication, type Page } from "@playwright/test";
import fs from "node:fs";
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, screenshot, type Isolated } from "./fixture";

let herdr: HerdrFixture;
let run: Isolated;
let app: ElectronApplication | null = null;

test.beforeAll(async () => {
herdr = await startHerdr();
});

test.afterAll(() => {
herdr?.stop();
});

test.beforeEach(() => {
run = isolate(herdr, test.info().title.split(":")[0]!);
});

test.afterEach(async () => {
const info = test.info();
if (info.status !== info.expectedStatus) console.log(hostLog(run.env).map((line) => JSON.stringify(line)).join("\n"));
await app?.close().catch(() => undefined);
app = null;
run.cleanup();
});

/** A menu item's accelerator as the app menu holds it now. */
function accelerator(id: string): Promise<string | null> {
return app!.evaluate(({ Menu }, itemId) => Menu.getApplicationMenu()?.getMenuItemById(itemId)?.accelerator ?? null, id);
}

/** After the one expected event, a quiet moment in which no second one arrives. */
async function exactlyOnce(sent: Map<string, number>, kind: string, expected: number, page: Page): Promise<void> {
await expect.poll(() => sent.get(kind) ?? 0).toBe(expected);
await page.waitForTimeout(600);
expect(sent.get(kind) ?? 0).toBe(expected);
}

test("pane chords: the macOS app's set comes across, runs once, and Settings edits it", async () => {
// The operator's Swift state on the day of the decision, with the fields
// the Swift shell keeps around the one hided reads.
const swiftState = path.join(run.env.HOME!, "Library", "Application Support", "hide", "state.json");
fs.mkdirSync(path.dirname(swiftState), { recursive: true });
fs.writeFileSync(
swiftState,
JSON.stringify({
schema_version: 1,
expanded_paths: [],
selected_path: null,
selected_pane_id: null,
pet_visible: false,
shortcut_bindings: {
close_pane: "command+shift+w",
split_down: "command+shift+d",
split_right: "command+d",
toggle_zoom: "command+shift+return",
increase_text_size: "command+=",
decrease_text_size: "command+-",
reset_text_size: "command+0",
},
}),
);
({ app } = await launch(run.env));
const page = await app.firstWindow();
const lastSent = new Map<string, Record<string, unknown>>();
const sent = countSent(page, lastSent);
await enterWorkspace(page);
await expect(page.locator("[data-pane-view]")).toHaveCount(2);

// The menu shows the imported chord once the shell reports the set.
await expect.poll(() => accelerator("toggle_zoom")).toBe("Shift+Command+Return");
expect(await accelerator("split_right")).toBe("Command+D");

// ⇧⌘↩ zooms exactly once; the default ⌥⌘↩ is no longer a chord here.
await page.locator("[data-pane-view] .xterm-helper-textarea").first().focus();
await page.keyboard.press("Meta+Alt+Enter");
await page.keyboard.press("Meta+Shift+Enter");
await expect(page.locator("[data-canvas]").first()).toHaveAttribute("data-zoomed", "true");
await exactlyOnce(sent, "toggle_zoom", 1, page);

// The ⌘/ sheet lists it.
await page.keyboard.press("Meta+Slash");
const sheet = page.locator("[data-shortcut-sheet]");
await expect(sheet.locator('[data-shortcut="toggle_zoom"] kbd')).toHaveText("⇧⌘↩");
await page.keyboard.press("Escape");
await expect(sheet).toHaveCount(0);

// Settings > Shortcuts edits the same set, in the Swift app's form.
await page.locator("[data-open-settings]").click();
await page.locator('[data-settings-tab="shortcuts"]').click();
await expect(page.locator('[data-shortcut-effective="toggle_zoom"]')).toHaveText("⇧⌘↩");
await page.locator('[data-shortcut-record="split_right"]').click();
await page.keyboard.press("Meta+Alt+KeyR");
await expect(page.locator('[data-shortcut-draft="split_right"]')).toHaveText("⌥⌘R");
await page.locator('[data-shortcut-apply="split_right"]').click();
await expect(page.locator('[data-shortcut-effective="split_right"]')).toHaveText("⌥⌘R");
const saved = lastSent.get("ui_state_update")?.shortcut_bindings as Record<string, string> | undefined;
expect(saved).toMatchObject({ split_right: "command+option+r", toggle_zoom: "command+shift+return" });
expect(lastSent.get("ui_state_update")?.browser_shortcut_bindings ?? {}).toEqual({});
await expect.poll(() => accelerator("split_right")).toBe("Alt+Command+R");
await screenshot(page, "desktop-shortcut-settings");
});

test("cycles: ⌃Tab and ⌥Tab commit once, on releasing the held modifier", async () => {
// Two more tabs in the fixture Workspace and two more Projects.
const tabs = [herdr.tab];
for (const label of ["second", "third"]) {
const made = herdr.run([
"tab", "create", "--workspace", herdr.workspace, "--cwd", path.join(herdr.root, "fixture"), "--label", label, "--env", `PATH=${herdr.fixturePath}`, "--no-focus",
]) as { result: { tab: { tab_id: string } } };
tabs.push(made.result.tab.tab_id);
}
const extraWorkspaces: string[] = [];
for (const name of ["beta", "gamma"]) {
fs.mkdirSync(path.join(herdr.root, name), { recursive: true });
const made = herdr.run([
"workspace", "create", "--cwd", path.join(herdr.root, name), "--label", name, "--env", `PATH=${herdr.fixturePath}`, "--no-focus",
]) as { result: { workspace: { workspace_id: string } } };
extraWorkspaces.push(made.result.workspace.workspace_id);
}
try {
({ app } = await launch(run.env));
const page = await app.firstWindow();
const sent = countSent(page);
await enterWorkspace(page, "fixture");
const canvas = page.locator("[data-canvas]").first();
const cycleRow = (kind: string) => page.locator(`[data-cycle=${kind}] [aria-selected=true]`);

// Recent order third, second, first: the first tab is current.
for (const tab of [tabs[2]!, tabs[1]!, tabs[0]!]) {
await page.locator(`[data-tab="${tab}"]`).click();
await expect(canvas).toHaveAttribute("data-canvas", tab);
}

// ⌃Tab twice with ⌃ held walks two back; releasing ⌃ commits one focus_tab.
let focused = sent.get("focus_tab") ?? 0;
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
await page.keyboard.press("Tab");
await expect(cycleRow("tabs")).toHaveAttribute("data-cycle-row", tabs[2]!);
expect(sent.get("focus_tab") ?? 0).toBe(focused);
await page.keyboard.up("Control");
await expect(page.locator("[data-cycle]")).toHaveCount(0);
await expect(canvas).toHaveAttribute("data-canvas", tabs[2]!);
await exactlyOnce(sent, "focus_tab", focused + 1, page);

// ⌃⇧Tab walks backward: from third, one back past the end is second.
focused = sent.get("focus_tab") ?? 0;
await page.keyboard.down("Control");
await page.keyboard.press("Shift+Tab");
await expect(cycleRow("tabs")).toHaveAttribute("data-cycle-row", tabs[1]!);
await page.keyboard.up("Control");
await expect(canvas).toHaveAttribute("data-canvas", tabs[1]!);
await exactlyOnce(sent, "focus_tab", focused + 1, page);

// Recent Projects gamma, beta, fixture: fixture is current.
await page.locator('[data-sidebar-mode="projects"]').click();
const checkout = (name: string) => page.locator("[data-project]", { hasText: name }).locator("[data-checkout]").first();
for (const name of ["gamma", "beta", "fixture"]) {
await checkout(name).click();
await expect(checkout(name)).toHaveAttribute("aria-current", "true");
}

// ⌥Tab twice walks to gamma; releasing ⌥ commits one focus_checkout.
focused = sent.get("focus_checkout") ?? 0;
await page.keyboard.down("Alt");
await page.keyboard.press("Tab");
await page.keyboard.press("Tab");
await expect(cycleRow("projects")).toBeVisible();
expect(sent.get("focus_checkout") ?? 0).toBe(focused);
await page.keyboard.up("Alt");
await expect(page.locator("[data-cycle]")).toHaveCount(0);
await expect(checkout("gamma")).toHaveAttribute("aria-current", "true");
await exactlyOnce(sent, "focus_checkout", focused + 1, page);

// ⌥⇧Tab walks backward: from gamma, one back past the end is beta.
focused = sent.get("focus_checkout") ?? 0;
await page.keyboard.down("Alt");
await page.keyboard.press("Shift+Tab");
await page.keyboard.up("Alt");
await expect(checkout("beta")).toHaveAttribute("aria-current", "true");
await exactlyOnce(sent, "focus_checkout", focused + 1, page);
} finally {
for (const id of extraWorkspaces) herdr.run(["workspace", "close", id]);
for (const id of tabs.slice(1)) herdr.run(["tab", "close", id]);
}
});
5 changes: 4 additions & 1 deletion desktop/src/channel.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
/** The one IPC channel between host and shell: app-menu command ids, main -> renderer (B11). */
/** App-menu command ids, main -> renderer (B11). */
export const COMMAND_CHANNEL = "hide:command";

/** The stored macOS pane chords the menu is built from, renderer -> main. */
export const BINDINGS_CHANNEL = "hide:bindings";
20 changes: 18 additions & 2 deletions desktop/src/main/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { app, BrowserWindow, screen, session, shell } from "electron";
import { app, BrowserWindow, ipcMain, screen, session, shell, type IpcMainEvent } from "electron";
import type { CommandId } from "../../../web/src/shortcuts";
import { COMMAND_CHANNEL } from "../channel";
import { BINDINGS_CHANNEL, COMMAND_CHANNEL } from "../channel";
import {
LOGIN_PATH_ARGS,
parseConnect,
Expand Down Expand Up @@ -111,6 +111,22 @@ export class DesktopHost {
this.log.event("host.quit", { state: this.state.kind });
}

/**
* The stored macOS pane chords the shell reports, for the menu. Only this
* window's page on the daemon origin is heard; anything else is logged and
* dropped.
*/
listenBindings(apply: (reported: unknown) => void): void {
ipcMain.on(BINDINGS_CHANNEL, (event: IpcMainEvent, reported: unknown) => {
const frame = event.senderFrame;
if (!this.window || event.sender !== this.window.webContents || !frame || !this.isDaemonUrl(frame.url)) {
this.log.event("bindings.refused", { reason: "sender" });
return;
}
apply(reported);
});
}

/** An app-menu click, delivered to the shell only while it is loaded. */
sendCommand(id: CommandId): void {
if (!this.window || (this.state.kind !== "attached" && this.state.kind !== "lost")) return;
Expand Down
27 changes: 23 additions & 4 deletions desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { app, Menu } from "electron";
import { loadEnv } from "./env";
import { DesktopHost } from "./host";
import { HostLog } from "./log";
import { menuTemplate } from "./menu";
import { REGISTRY, type Command } from "../../../web/src/shortcuts";
import { menuBindings, menuTemplate } from "./menu";

const env = loadEnv(process.env);
// Pinned before anything reads it: the single-instance lock, web storage and
Expand All @@ -29,11 +30,29 @@ if (!app.requestSingleInstanceLock()) {
});
app.on("before-quit", () => host.quit());

// The menu is rebuilt only when the chords it shows change.
let shown: string | null = null;
const showMenu = (registry: readonly Command[]) => {
const chords = JSON.stringify(registry.map((command) => command.electron));
if (chords === shown) return;
shown = chords;
Menu.setApplicationMenu(
Menu.buildFromTemplate(menuTemplate({ appName: app.getName(), send: (id) => host.sendCommand(id), developer: !app.isPackaged, registry })),
);
};
host.listenBindings((reported) => {
const resolved = menuBindings(reported);
if ("refused" in resolved) {
log.event("bindings.refused", { reason: resolved.refused });
return;
}
if (resolved.diagnostic) log.event("bindings.defaults", { detail: resolved.diagnostic });
showMenu(resolved.registry);
});

app.whenReady().then(
() => {
Menu.setApplicationMenu(
Menu.buildFromTemplate(menuTemplate({ appName: app.getName(), send: (id) => host.sendCommand(id), developer: !app.isPackaged })),
);
showMenu(REGISTRY);
host.start();
},
(error: unknown) => {
Expand Down
21 changes: 20 additions & 1 deletion desktop/src/main/menu.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { REGISTRY } from "../../../web/src/shortcuts";
import { accelerator, KEYBOARD_ONLY, MENU_LAYOUT, menuTemplate } from "./menu";
import { accelerator, KEYBOARD_ONLY, MENU_LAYOUT, menuBindings, menuTemplate } from "./menu";

describe("the app menu (B9)", () => {
it("writes registry chords as Electron accelerators", () => {
Expand Down Expand Up @@ -34,4 +34,23 @@ describe("the app menu (B9)", () => {
expect(roles).not.toContain("close");
expect(roles).not.toContain("reload");
});

it("shows the operator's macOS pane chords once the shell reports them", () => {
const resolved = menuBindings({ toggle_zoom: "command+shift+return", toggle_conversation: "command+option+c" });
if ("refused" in resolved) throw new Error(resolved.refused);
expect(resolved.diagnostic).toBeNull();
const template = menuTemplate({ appName: "hide", send: () => undefined, developer: false, registry: resolved.registry });
const items = template.flatMap((menu) => (Array.isArray(menu.submenu) ? menu.submenu : []));
expect(items.find((item) => item.id === "toggle_zoom")?.accelerator).toBe("Shift+Command+Return");
expect(items.find((item) => item.id === "split_right")?.accelerator).toBe("Command+D");
});

it("refuses a report that is not a short string map, and runs the defaults for an unusable set", () => {
expect(menuBindings(null)).toEqual({ refused: "not a map" });
expect(menuBindings(["command+d"])).toEqual({ refused: "not a map" });
expect(menuBindings({ split_right: 4 })).toEqual({ refused: "not short strings" });
expect(menuBindings(Object.fromEntries(Array.from({ length: 17 }, (_, index) => [`k${index}`, "command+d"])))).toEqual({ refused: "too many entries" });
const unusable = menuBindings({ split_right: "command+t" });
expect("refused" in unusable ? null : unusable.registry).toBe(REGISTRY);
});
});
Loading
Loading