Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 282e70bb78 docs(app): record chord timing and Android dev-menu keys for device QA 2026-12-05 15:42:37 +01:00
Mohamed Boudra 117d452637 refactor(app): run core shortcuts on the action and keybinding registries
Every core action and default binding is now registered as `paseo/*` at app
start by CoreActionsProvider. The key pipeline, Command Center, Settings ->
Shortcuts, the shortcuts dialog and every badge read the registries, and an
action id is the only key for dispatch, badges and rows. The legacy binding
table, the keyboard action dispatcher, route-shortcut, workspace-shortcuts and
useKeyboardActionHandler are deleted.

Handler priorities are replaced by action scopes (composer, settings, new-tab,
workspace-pane, new-workspace, sidebar-selection): the innermost active scope
wins. Binding ids are unchanged so stored overrides keep applying.

The legacy table suites are ported to the registries with the same cases.
2026-12-05 14:53:04 +01:00
Mohamed Boudra 3485d8d014 fix(app): bind action handlers to one scope activation, not a scope name
Two panes showing the same panel both activate `inbox/list`. With handlers
matched by name, the earliest pane's handler ran even while only the other
pane was active. `activate()` now returns a `ScopeActivation`, and a
handler binds to the activation of the surface it is mounted in, so it
runs only while that activation is active. Keybinding `when` still
matches scopes by name.
2026-12-05 13:12:02 +01:00
Mohamed Boudra e7285f79f4 fix(app): claim intermediate iOS chord steps for pass-through actions
The resolver suppresses every key that only advances a chord, but the
native claim builder skipped any binding whose action passes its key
through (`preventDefault: false`), at every step. With Interrupt agent
rebound to `Cmd+J Enter K`, the intermediate Return stayed with the iOS
composer and could send the draft. The pass-through policy now applies
only to the step that completes the chord.
2026-12-05 13:06:47 +01:00
Mohamed Boudra 6bc8a857bd refactor(app): reshape Phase 0 action and keybinding registries
@/actions now owns only action definitions, mounted handlers, the scope
stack and opaque owners, and imports nothing from @/keyboard. `when`, the
printable guard, conflicts and the display lookup live in @/keyboard.

- Scopes are an ordered stack: the innermost active scope wins, ties go to
  the earliest registration. Specificity weights, overlay depth, surface
  ids and priorities are gone.
- Keyboard context reaches dispatch with the key event; no store keeps a
  copy and there is no setContext.
- A registration carries an opaque owner. Two owners of one id are one
  action or binding; removing either leaves the other; the same owner
  twice throws. Which owner's `run` fires is an injected rule, wired at
  app start in Phase 1A.
- Handlers decline with `{ handled: false }`; a promise counts as handled
  and its rejection goes to onError. Payloads pass through untouched; a
  Digit binding supplies `index`.
- Removed the legacy-table adapter, the unwired registry builders in the
  native and Electron browser key sources, and module-load singletons.
2026-12-05 13:01:45 +01:00
Mohamed Boudra ed36cec5eb test(e2e): use shared command-center helpers in keyboard shortcut spec 2026-12-05 10:44:14 +01:00
Mohamed Boudra 504217afdf fix(keyboard): address global fallback, key/code conflict, and printable E2E reviews 2026-12-05 10:40:24 +01:00
Mohamed Boudra 168e36e281 fix(keyboard): pass holdRelease when building browser registry prefixes after rebase 2026-12-05 10:33:48 +01:00
Mohamed Boudra e3306ed20f fix(app): isolate iOS plain Enter chord claiming from Android 2026-12-05 10:31:20 +01:00
Mohamed Boudra 5f10d60060 fix(app): address bot review findings on Phase 0 registries 2026-12-05 10:31:20 +01:00
Mohamed Boudra 3ba7e64793 fix(app): address Phase 0 registry review feedback 2026-12-05 10:31:20 +01:00
Mohamed Boudra 99d9d9ec8b feat(app): add Phase 0 action and keybinding registries 2026-12-05 10:31:20 +01:00
119 changed files with 6717 additions and 5601 deletions
+49 -4
View File
@@ -1,6 +1,40 @@
# Keyboard shortcuts
Define shortcuts in [the shared binding table](../packages/app/src/keyboard/keyboard-shortcuts.ts). Platforms contribute key sources, not separate action maps, so matching and user rebinds stay consistent across runtimes. Add a shortcut through a binding; add platform support through a key source.
A shortcut is two registrations. An action in the action registry (`@/actions`) is something the app can run. A binding in the keybinding registry (`@/keyboard`) connects keys to an action. `@/keyboard` imports `@/actions`; `@/actions` knows nothing about keys.
Paseo's own actions and default bindings are in [`core-actions/internal/actions.ts`](../packages/app/src/core-actions/internal/actions.ts) and [`bindings.ts`](../packages/app/src/core-actions/internal/bindings.ts). `CoreActionsProvider` registers them at app start, so Settings, badges and Command Center see every core shortcut before any surface mounts. Add a shortcut by adding a binding; add platform support through a key source.
## Actions and handlers
An action id such as `paseo/workspace.tab.next` is the only key for dispatch, badges (`useShortcutKeys`, `Shortcut`), Command Center rows and Settings rows.
A mounted surface supplies behavior with `useActionHandler(actionId, handler, { enabled, scope })`. Dispatch tries handlers in active action scopes innermost first, then unscoped handlers, with the earliest registration first among equals. When every handler declines, the action's own `run` handles it. The app shell supplies `run` for the core actions no screen owns, through `useCoreActionRuns` in [`app-shell-runs.ts`](../packages/app/src/core-actions/internal/app-shell-runs.ts).
A handler declines only by returning `{ handled: false }` synchronously. Any other return, including a promise, counts as handled. Express which handler wins with `enabled` and scopes, not with mount order.
Finite variants are separate actions: `workspace.tab.next` and `workspace.tab.previous`, one action per `message-input.*` operation. Only a `Digit` binding supplies data, as `index`.
## Action scopes
A surface that should shadow a shortcut while it is active creates a scope with `useActionScope(name, { active })`, and passes it to its handlers as `scope` or wraps its children in `<ActionScope activation>`. The innermost active scope wins. There are no priorities.
Example: the composer activates `paseo/composer` while it takes input, and the New Workspace screen activates `paseo/new-workspace` while it is focused. Shift+Tab on the New Workspace screen reaches its composer, and never the mode control of a backgrounded agent composer that is still mounted.
A handler is bound to one activation, not to a scope name. Two panes that show the same surface activate the same name separately, and a handler in one pane never runs for the other.
An action scope is different from the focus scope in a binding's `when` clause. Action scopes come from mounted surfaces. The focus scope comes from the focused input; see [Focus scopes](#focus-scopes).
## Bindings
A binding has an id, an action id, a combo and a `when` clause. User overrides are keyed by binding id, so never rename a shipped id, even when its combo changes (`agent-new-cmd-shift-o-mac` is bound to Cmd+O).
Among bindings that match the same key in the same context, the earliest registered wins. If its action declines, the registry tries the next matching binding. A chord's first step is reserved only while the chord's action can run.
Badges show the first assigned binding for the platform (`displayKeysFor`). Settings → Shortcuts builds its rows from the registry with `buildShortcutSections`, so it lists every core binding with only Settings mounted.
A surface that reads keys itself while it holds the keyboard, such as the workspace switcher HUD, matches them with `createChordMatcher` against the bindings it picks. A binding whose action finishes when its modifier is released, such as Ctrl+Tab in the switcher, sets `holdRelease`; key sources outside the app, such as the Electron browser pane, forward that key-up.
Tests that drive real keys through the real table use `createRecordingCoreRegistries` from `@/core-actions/testing`.
## Badges and routing
@@ -27,7 +61,9 @@ must be claimed up front. `UIKeyCommand` takes only those keys: composer Return,
top overlay's Enter and arrows, and the Shift or Option shortcuts whose binding is
active in the current focus scope, such as Shift+Tab in the composer.
`sources/native.ts` computes the claims from the published bindings and recomputes
them when the focus scope changes. Cmd and Ctrl combos are never claimed, because
them when the focus scope changes. Claims are computed without the action scope
stack, so a binding whose `when` names an action scope is never claimed. Gate a key
that a text control would type with `focusScope`, as mode cycle does. Cmd and Ctrl combos are never claimed, because
text controls do not type them. Android takes no claims: a focused `EditText`
types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned
press is still observed by the window.
@@ -56,6 +92,15 @@ Verify the iOS absence case on a physical iPhone.
Xcode 27.2 has Device Hub in place of Simulator. AppleScript keystrokes reach the
device only while its view has Mac focus. Give it focus with a real mouse click
(a `CGEvent`); keystrokes sent elsewhere drive Device Hub's own controls.
Send both steps of a chord from one AppleScript `tell` block. A chord expires
after 1.5 s, and separate `osascript` calls with settle delays exceed it, so the
second key types into the focused field.
On Android debug builds, the Expo dev menu reads unmodified R, P and I on key-up
outside text fields: R reloads, P opens the performance monitor (and the overlay
permission page), I toggles the inspector. Before hardware-keyboard QA, set
`keyCommandsEnabled` to `false` in the app's `expo.modules.devmenu.sharedpreferences`
SharedPreferences.
Never register Backspace: it would take deletion away from text fields. Changes
to the native module require a native rebuild; an over-the-air JavaScript update
@@ -110,6 +155,6 @@ leaving active IME composition spans untouched for candidate navigation.
## Keys shared with text editing
A binding on a key the platform already uses for editing, such as Cmd/Ctrl+Z for
workspace archive undo, declares `editable: false` and registers its handler with
`isActive` true only while it has work. An inactive handler leaves the key
workspace archive undo, declares `when: { editable: false }`, and its handler is
`enabled` only while it has work. A disabled or declining handler leaves the key
unhandled, so the pipeline skips `preventDefault` and the platform's own undo runs.
@@ -1,17 +1,22 @@
import type { Page } from "@playwright/test";
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { closeCommandCenter, openCommandCenter } from "../support/helpers/command-center";
// Where Settings → Keyboard shortcuts persists a rebound shortcut.
const OVERRIDE_STORAGE_KEY = "@paseo:keyboard-shortcut-overrides";
const COMMAND_CENTER_BINDING = "command-center-toggle-ctrl-k-non-mac";
const COMMAND_CENTER_BINDINGS = [
"command-center-toggle-cmd-k-mac",
"command-center-toggle-ctrl-k-non-mac",
] as const;
async function rebindCommandCenter(page: Page, combo: string): Promise<void> {
await page.addInitScript(
([key, bindingId, value]) => {
window.localStorage.setItem(key, JSON.stringify({ [bindingId]: value }));
([key, bindingIds, value]) => {
const overrides = Object.fromEntries(bindingIds.map((id) => [id, value]));
window.localStorage.setItem(key, JSON.stringify(overrides));
},
[OVERRIDE_STORAGE_KEY, COMMAND_CENTER_BINDING, combo] as const,
[OVERRIDE_STORAGE_KEY, COMMAND_CENTER_BINDINGS, combo] as const,
);
await gotoAppShell(page);
await expect(page.getByTestId("sidebar-search")).toBeVisible({ timeout: 30_000 });
@@ -21,6 +26,18 @@ async function expectCommandCenterOpen(page: Page): Promise<void> {
await expect(page.getByTestId("command-center-panel")).toBeVisible({ timeout: 10_000 });
}
async function expectCommandCenterSearchAcceptsKey(
page: Page,
panel: Locator,
key: string,
): Promise<void> {
const searchInput = panel.getByTestId("command-center-input");
await expect(searchInput).toBeFocused({ timeout: 10_000 });
await page.keyboard.press(key);
await expect(searchInput).toHaveValue(key);
await expectCommandCenterOpen(page);
}
test.describe("Multi-step shortcut", () => {
test("completes a chord whose second step is a bare key", async ({ page }) => {
await rebindCommandCenter(page, "Ctrl+K J");
@@ -41,4 +58,17 @@ test.describe("Multi-step shortcut", () => {
await expectCommandCenterOpen(page);
});
test("typing a rebound printable shortcut inside Command Center enters text instead of toggling it closed", async ({
page,
}) => {
await rebindCommandCenter(page, "J");
const commandCenter = await openCommandCenter(page);
await expectCommandCenterSearchAcceptsKey(page, commandCenter, "j");
await closeCommandCenter(page);
await page.keyboard.press("j");
await expectCommandCenterOpen(page);
});
});
@@ -97,7 +97,8 @@ test.describe("New Workspace mode cycle safety", () => {
// Regression guard for the P1 safety bug: cycling the execution mode with Shift+Tab in
// the New Workspace composer must never reach a backgrounded, still-mounted agent's mode
// control and silently change that (possibly running) agent's mode — e.g. into a
// permissive/bypass mode. See use-keyboard-action-handler.ts.
// permissive/bypass mode. The New Workspace screen's `paseo/new-workspace` action scope
// must shadow a backgrounded composer's handler.
test("Shift+Tab in New Workspace never changes a backgrounded agent's mode", async ({ page }) => {
const seeded = await seedWorkspace({ repoPrefix: "mode-cycle-safety-" });
await seedCodexDefaultPreferences(page);
@@ -0,0 +1,387 @@
import { describe, expect, it } from "vitest";
import {
createActionRegistry,
createActionScopeStore,
DuplicateActionError,
InvalidActionIdError,
type ActionInvocation,
type OrderOwners,
} from "@/actions";
function createHarness(input: { orderOwners?: OrderOwners } = {}) {
const scopes = createActionScopeStore();
const errors: Array<{ error: unknown; actionId: string; owner: string | null }> = [];
const registry = createActionRegistry({
scopes,
...(input.orderOwners ? { orderOwners: input.orderOwners } : {}),
onError: (error, info) => errors.push({ error, ...info }),
});
return { scopes, registry, errors };
}
function registerRunner(
registry: ReturnType<typeof createHarness>["registry"],
input: { id: string; owner: string | null; context?: "global" | "workspace" | "agent" },
ran: Array<string | null>,
) {
return registry.registerAction({
id: input.id,
title: input.id,
owner: input.owner,
...(input.context ? { context: input.context } : {}),
run: (invocation) => {
ran.push(invocation.owner);
},
});
}
describe("ActionScopeStore", () => {
it("lists active scopes outermost first, with the latest activation innermost", () => {
const scopes = createActionScopeStore();
const list = scopes.activate("inbox/list");
const popover = scopes.activate("inbox/popover");
expect(scopes.getActiveScopes()).toEqual(["inbox/list", "inbox/popover"]);
expect([scopes.depthOf(list), scopes.depthOf(popover)]).toEqual([1, 2]);
popover.release();
expect(scopes.getActiveScopes()).toEqual(["inbox/list"]);
expect(scopes.depthOf(popover)).toBeNull();
list.release();
expect(scopes.getActiveScopes()).toEqual([]);
});
it("keeps a name active until every activation releases, at its innermost position", () => {
const scopes = createActionScopeStore();
const first = scopes.activate("inbox/list");
const popover = scopes.activate("inbox/popover");
const second = scopes.activate("inbox/list");
expect(scopes.getActiveScopes()).toEqual(["inbox/popover", "inbox/list"]);
second.release();
expect(scopes.getActiveScopes()).toEqual(["inbox/list", "inbox/popover"]);
second.release();
expect(scopes.getActiveScopes()).toEqual(["inbox/list", "inbox/popover"]);
first.release();
expect(scopes.getActiveScopes()).toEqual(["inbox/popover"]);
popover.release();
});
it("notifies only when the active scope order changes and keeps snapshots stable", () => {
const scopes = createActionScopeStore();
let notifications = 0;
scopes.subscribe(() => {
notifications += 1;
});
const first = scopes.activate("a/one");
const snapshot = scopes.getActiveScopes();
expect(notifications).toBe(1);
expect(scopes.getActiveScopes()).toBe(snapshot);
const again = scopes.activate("a/one");
expect(notifications).toBe(1);
again.release();
expect(notifications).toBe(1);
first.release();
expect(notifications).toBe(2);
});
it("rejects empty scope names", () => {
const scopes = createActionScopeStore();
expect(() => scopes.activate(" ")).toThrow(/non-empty/);
});
});
describe("ActionRegistry", () => {
it("validates namespaced action ids", () => {
const { registry } = createHarness();
expect(() => registry.registerAction({ id: "no-namespace", title: "Bad" })).toThrow(
InvalidActionIdError,
);
const noop = () => {};
expect(() => registry.registerHandler("inbox/", noop)).toThrow(InvalidActionIdError);
expect(() => registry.registerAction({ id: "inbox/item.next", title: "Next" })).not.toThrow();
});
it("notifies on registration and keeps cleanup idempotent", () => {
const { registry } = createHarness();
let notifications = 0;
registry.subscribe(() => {
notifications += 1;
});
const unregister = registry.registerAction({ id: "inbox/refresh", title: "Refresh" });
expect(notifications).toBe(1);
unregister();
unregister();
expect(notifications).toBe(2);
expect(registry.getAction("inbox/refresh")).toBeNull();
});
it("defaults to the global context and no owner", () => {
const { registry } = createHarness();
registry.registerAction({ id: "paseo/settings.open", title: "Open settings" });
expect(registry.getAction("paseo/settings.open")).toEqual({
id: "paseo/settings.open",
title: "Open settings",
context: "global",
owners: [null],
});
});
});
describe("ActionRegistry owners", () => {
it("merges two owners of one id into one action, and removing either leaves the other", () => {
for (const [removed, remaining] of [
["host-1", "host-2"],
["host-2", "host-1"],
] as const) {
const { registry } = createHarness();
const ran: Array<string | null> = [];
const unregister = {
"host-1": registerRunner(registry, { id: "inbox/refresh", owner: "host-1" }, ran),
"host-2": registerRunner(registry, { id: "inbox/refresh", owner: "host-2" }, ran),
};
expect(registry.listActions()).toHaveLength(1);
expect(registry.getAction("inbox/refresh")?.owners).toEqual(["host-1", "host-2"]);
unregister[removed]();
expect(registry.getAction("inbox/refresh")?.owners).toEqual([remaining]);
expect(registry.dispatch("inbox/refresh")).toBe(true);
expect(ran).toEqual([remaining]);
}
});
it("rejects a second registration of the same id by the same owner", () => {
const { registry } = createHarness();
registry.registerAction({ id: "inbox/refresh", title: "Refresh", owner: "host-1" });
expect(() =>
registry.registerAction({ id: "inbox/refresh", title: "Again", owner: "host-1" }),
).toThrow(DuplicateActionError);
registry.registerAction({ id: "paseo/settings.open", title: "Open settings" });
expect(() => registry.registerAction({ id: "paseo/settings.open", title: "Again" })).toThrow(
DuplicateActionError,
);
expect(registry.getAction("inbox/refresh")?.title).toBe("Refresh");
});
it("runs owners in registration order by default", () => {
const { registry } = createHarness();
const ran: Array<string | null> = [];
registerRunner(registry, { id: "inbox/sync", owner: "host-b" }, ran);
registerRunner(registry, { id: "inbox/sync", owner: "host-a" }, ran);
registry.dispatch("inbox/sync");
expect(ran).toEqual(["host-b"]);
});
it("asks the injected rule which owners run, in which order", () => {
let active = "host-a";
const { registry } = createHarness({
orderOwners: (action) => {
const rest = action.context === "global" ? action.owners : [];
return [active, ...rest.filter((owner) => owner !== active)];
},
});
const ran: Array<string | null> = [];
registerRunner(registry, { id: "inbox/sync", owner: "host-b" }, ran);
registerRunner(registry, { id: "inbox/sync", owner: "host-a" }, ran);
registerRunner(registry, { id: "inbox/open", owner: "host-b", context: "workspace" }, ran);
registry.dispatch("inbox/sync");
expect(ran).toEqual(["host-a"]);
expect(registry.canDispatch("inbox/open")).toBe(false);
expect(registry.dispatch("inbox/open")).toBe(false);
active = "host-b";
expect(registry.dispatch("inbox/open")).toBe(true);
expect(ran).toEqual(["host-a", "host-b"]);
});
});
describe("ActionRegistry mounted handlers", () => {
it("runs the handler in the innermost active scope, whichever registered first", () => {
for (const order of [
["list", "popover"],
["popover", "list"],
] as const) {
const { registry, scopes } = createHarness();
const activations = {
list: scopes.activate("inbox/list"),
popover: scopes.activate("inbox/popover"),
};
const calls: string[] = [];
for (const name of order) {
registry.registerHandler(
"inbox/item.next",
() => {
calls.push(name);
},
{ scope: activations[name] },
);
}
expect(registry.dispatch("inbox/item.next")).toBe(true);
expect(calls).toEqual(["popover"]);
activations.popover.release();
expect(registry.dispatch("inbox/item.next")).toBe(true);
expect(calls).toEqual(["popover", "list"]);
activations.list.release();
}
});
it("does not run a scoped handler once its scope activation is released", () => {
const { registry, scopes } = createHarness();
const calls: string[] = [];
const list = scopes.activate("inbox/list");
registry.registerHandler(
"inbox/item.next",
() => {
calls.push("scoped");
},
{ scope: list },
);
expect(registry.dispatch("inbox/item.next")).toBe(true);
list.release();
expect(registry.canDispatch("inbox/item.next")).toBe(false);
expect(registry.dispatch("inbox/item.next")).toBe(false);
expect(calls).toEqual(["scoped"]);
});
it("runs only the active pane when two panes mount the same scope name", () => {
for (const activePane of ["a", "b"] as const) {
const { registry, scopes } = createHarness();
const panes = { a: scopes.activate("inbox/list"), b: scopes.activate("inbox/list") };
const calls: string[] = [];
for (const pane of ["a", "b"] as const) {
registry.registerHandler(
"inbox/item.next",
() => {
calls.push(pane);
},
{ scope: panes[pane] },
);
}
panes[activePane === "a" ? "b" : "a"].release();
expect(registry.dispatch("inbox/item.next")).toBe(true);
expect(calls).toEqual([activePane]);
expect(scopes.getActiveScopes()).toEqual(["inbox/list"]);
}
});
it("prefers an active scoped handler over an unscoped one", () => {
const { registry, scopes } = createHarness();
const calls: string[] = [];
registry.registerHandler("inbox/item.next", () => {
calls.push("unscoped");
});
registry.dispatch("inbox/item.next");
const list = scopes.activate("inbox/list");
registry.registerHandler(
"inbox/item.next",
() => {
calls.push("scoped");
},
{ scope: list },
);
registry.dispatch("inbox/item.next");
list.release();
expect(calls).toEqual(["unscoped", "scoped"]);
});
it("tries equal handlers earliest first, skips disabled ones and falls through on decline", () => {
const { registry } = createHarness();
const calls: string[] = [];
let declines = true;
let enabled = true;
registry.registerHandler("inbox/item.next", () => {
calls.push("declining");
return declines ? { handled: false } : undefined;
});
registry.registerHandler(
"inbox/item.next",
() => {
calls.push("toggled");
},
{ enabled: () => enabled },
);
registry.registerHandler("inbox/item.next", () => {
calls.push("last");
});
expect(registry.dispatch("inbox/item.next")).toBe(true);
expect(calls).toEqual(["declining", "toggled"]);
enabled = false;
calls.length = 0;
expect(registry.dispatch("inbox/item.next")).toBe(true);
expect(calls).toEqual(["declining", "last"]);
declines = false;
calls.length = 0;
expect(registry.dispatch("inbox/item.next")).toBe(true);
expect(calls).toEqual(["declining"]);
});
it("runs the action's run after every handler declines", () => {
const { registry } = createHarness();
const ran: Array<string | null> = [];
registerRunner(registry, { id: "inbox/refresh", owner: null }, ran);
registry.registerHandler("inbox/refresh", () => ({ handled: false }));
expect(registry.dispatch("inbox/refresh")).toBe(true);
expect(ran).toEqual([null]);
});
it("passes the index through unchanged", () => {
const { registry } = createHarness();
const invocations: ActionInvocation[] = [];
registry.registerHandler("inbox/item.open", (invocation) => {
invocations.push(invocation);
});
registry.dispatch("inbox/item.open", { index: 3 });
expect(invocations).toEqual([{ actionId: "inbox/item.open", owner: null, index: 3 }]);
});
});
describe("ActionRegistry errors", () => {
it("routes sync throws and async rejections from runs and handlers to onError", async () => {
const { registry, errors } = createHarness();
const syncError = new Error("sync");
const asyncError = new Error("async");
const handlerError = new Error("handler async");
registry.registerAction({
id: "inbox/sync.fail",
title: "Sync fail",
run: () => {
throw syncError;
},
});
registry.registerAction({
id: "inbox/async.fail",
title: "Async fail",
owner: "host-a",
run: async () => {
throw asyncError;
},
});
registry.registerHandler("inbox/handler.fail", async () => {
throw handlerError;
});
expect(registry.dispatch("inbox/sync.fail")).toBe(true);
expect(registry.dispatch("inbox/async.fail")).toBe(true);
expect(registry.dispatch("inbox/handler.fail")).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(errors).toEqual([
{ error: syncError, actionId: "inbox/sync.fail", owner: null },
{ error: asyncError, actionId: "inbox/async.fail", owner: "host-a" },
{ error: handlerError, actionId: "inbox/handler.fail", owner: null },
]);
});
});
+33
View File
@@ -0,0 +1,33 @@
export {
createActionRegistry,
DuplicateActionError,
InvalidActionIdError,
} from "./internal/action-registry";
export type {
ActionContext,
ActionDeclined,
ActionDefinitionInput,
ActionDispatchInput,
ActionErrorInfo,
ActionHandler,
ActionHandlerOptions,
ActionInvocation,
ActionRegistry,
ActionRegistryOptions,
OrderOwners,
RegisteredAction,
} from "./internal/action-registry";
export { createActionScopeStore } from "./internal/action-scope-store";
export type {
ActionScopeStore,
ActiveScopes,
ScopeActivation,
} from "./internal/action-scope-store";
export {
ActionRegistryProvider,
ActionScope,
useActionHandler,
useActionRegistry,
useActionScope,
} from "./internal/react";
export type { UseActionHandlerOptions } from "./internal/react";
@@ -0,0 +1,348 @@
import type { ActionScopeStore, ScopeActivation } from "./action-scope-store";
const ACTION_ID_RE = /^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/i;
export class InvalidActionIdError extends Error {
readonly actionId: string;
constructor(actionId: string) {
super(`Invalid action id "${actionId}": expected "<namespace>/<dot.name>"`);
this.name = "InvalidActionIdError";
this.actionId = actionId;
}
}
export class DuplicateActionError extends Error {
readonly actionId: string;
readonly owner: string | null;
constructor(actionId: string, owner: string | null) {
super(`Action "${actionId}" is already registered by owner ${owner ?? "(none)"}`);
this.name = "DuplicateActionError";
this.actionId = actionId;
this.owner = owner;
}
}
function assertValidActionId(actionId: string): void {
if (!ACTION_ID_RE.test(actionId)) {
throw new InvalidActionIdError(actionId);
}
}
/** Where an action runs. Same vocabulary as `addCommandCenterItem`'s `context`. */
export type ActionContext = "global" | "workspace" | "agent";
export interface ActionInvocation {
readonly actionId: string;
/** The owner whose `run` this is; `null` for a mounted handler or an unowned action. */
readonly owner: string | null;
/** A position the caller picked, such as the third item. */
readonly index?: number;
}
/** Return this, synchronously, to pass the action on to the next handler or `run`. */
export interface ActionDeclined {
readonly handled: false;
}
/**
* Returning nothing means handled. A returned promise also counts as handled;
* its rejection goes to `onError` and is never re-dispatched.
*/
export type ActionHandler = (invocation: ActionInvocation) => void | ActionDeclined | Promise<void>;
export interface ActionDefinitionInput {
id: string;
title: string;
icon?: string;
/** Defaults to `"global"`. */
context?: ActionContext;
/** Opaque registrant. Core registers with none (`null`). */
owner?: string | null;
run?: ActionHandler;
}
export interface RegisteredAction {
readonly id: string;
readonly title: string;
readonly icon?: string;
readonly context: ActionContext;
/** Every owner that registered this id, earliest first. */
readonly owners: readonly (string | null)[];
}
export interface ActionHandlerOptions {
/**
* The activation of the surface this handler is mounted in. The handler runs
* only while that activation is active, and the innermost one wins.
*/
scope?: ScopeActivation;
/** Read on every dispatch. A disabled handler is invisible to `canDispatch`. */
enabled?: () => boolean;
}
/**
* Picks which owners' `run` to try, in order, for one dispatch. The app
* supplies it; the registry never learns what an owner is.
*/
export type OrderOwners = (action: RegisteredAction) => readonly (string | null)[];
export interface ActionErrorInfo {
readonly actionId: string;
readonly owner: string | null;
}
export interface ActionRegistryOptions {
scopes: ActionScopeStore;
/** Defaults to every owner, earliest registration first. */
orderOwners?: OrderOwners;
onError?: (error: unknown, info: ActionErrorInfo) => void;
}
export interface ActionDispatchInput {
index?: number;
}
export interface ActionRegistry {
registerAction(definition: ActionDefinitionInput): () => void;
registerHandler(
actionId: string,
handler: ActionHandler,
options?: ActionHandlerOptions,
): () => void;
getAction(actionId: string): RegisteredAction | null;
listActions(): readonly RegisteredAction[];
/** Whether a dispatch now would reach an enabled handler or a `run`. */
canDispatch(actionId: string): boolean;
/**
* Tries mounted handlers, innermost active scope first, then each owner's
* `run` in the injected order. Returns whether one took the action.
*/
dispatch(actionId: string, input?: ActionDispatchInput): boolean;
subscribe(listener: () => void): () => void;
}
interface StoredDefinition {
readonly owner: string | null;
readonly title: string;
readonly icon?: string;
readonly context: ActionContext;
readonly run?: ActionHandler;
}
interface StoredHandler {
readonly handler: ActionHandler;
readonly scope: ScopeActivation | null;
readonly enabled: () => boolean;
}
function everyOwner(action: RegisteredAction): readonly (string | null)[] {
return action.owners;
}
function defaultOnError(error: unknown, info: ActionErrorInfo): void {
console.error(`[actions] "${info.actionId}" failed:`, error);
}
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
return (
typeof value === "object" &&
value !== null &&
"then" in value &&
typeof value.then === "function"
);
}
function isDeclined(value: unknown): value is ActionDeclined {
return typeof value === "object" && value !== null && "handled" in value && !value.handled;
}
function alwaysEnabled(): boolean {
return true;
}
function addToList<T>(map: Map<string, T[]>, key: string, value: T): void {
map.set(key, [...(map.get(key) ?? []), value]);
}
function removeFromList<T>(map: Map<string, T[]>, key: string, value: T): boolean {
const current = map.get(key);
if (!current?.includes(value)) {
return false;
}
const remaining = current.filter((entry) => entry !== value);
if (remaining.length === 0) {
map.delete(key);
} else {
map.set(key, remaining);
}
return true;
}
/** The earliest registration describes the action; later owners add their `run`. */
function toRegisteredAction(
id: string,
definitions: readonly StoredDefinition[],
): RegisteredAction {
const [first] = definitions;
return {
id,
title: first.title,
...(first.icon !== undefined ? { icon: first.icon } : {}),
context: first.context,
owners: definitions.map((entry) => entry.owner),
};
}
/**
* Namespaced actions, the `run` each owner registers for them, and the
* handlers mounted surfaces attach. The same id from two owners is one action.
*/
export function createActionRegistry(options: ActionRegistryOptions): ActionRegistry {
const { scopes } = options;
const orderOwners = options.orderOwners ?? everyOwner;
const onError = options.onError ?? defaultOnError;
const definitionsById = new Map<string, StoredDefinition[]>();
const handlersById = new Map<string, StoredHandler[]>();
const listeners = new Set<() => void>();
function notify(): void {
for (const listener of listeners) {
listener();
}
}
/**
* Enabled handlers whose scope activation is active: innermost first,
* unscoped last, earliest registration first among equals.
*/
function eligibleHandlers(actionId: string): StoredHandler[] {
const ranked: Array<{ entry: StoredHandler; rank: number }> = [];
for (const entry of handlersById.get(actionId) ?? []) {
const rank = entry.scope === null ? 0 : scopes.depthOf(entry.scope);
if (rank === null) continue;
if (!entry.enabled()) continue;
ranked.push({ entry, rank });
}
// Array#sort is stable, so equal ranks keep registration order.
ranked.sort((left, right) => right.rank - left.rank);
return ranked.map(({ entry }) => entry);
}
function eligibleRunners(actionId: string): StoredDefinition[] {
const definitions = definitionsById.get(actionId);
if (!definitions) {
return [];
}
const runners: StoredDefinition[] = [];
for (const owner of orderOwners(toRegisteredAction(actionId, definitions))) {
const entry = definitions.find((candidate) => candidate.owner === owner);
if (entry?.run) runners.push(entry);
}
return runners;
}
/** Runs one handler and reports whether it took the action. */
function invoke(handler: ActionHandler, invocation: ActionInvocation): boolean {
const info = { actionId: invocation.actionId, owner: invocation.owner };
let outcome: ReturnType<ActionHandler>;
try {
outcome = handler(invocation);
} catch (error) {
onError(error, info);
return true;
}
if (isPromiseLike(outcome)) {
outcome.then(undefined, (error: unknown) => onError(error, info));
return true;
}
return !isDeclined(outcome);
}
function invocationFor(
actionId: string,
owner: string | null,
input: ActionDispatchInput | undefined,
): ActionInvocation {
return {
actionId,
owner,
...(input?.index !== undefined ? { index: input.index } : {}),
};
}
return {
registerAction(definition) {
assertValidActionId(definition.id);
const owner = definition.owner ?? null;
if (definitionsById.get(definition.id)?.some((entry) => entry.owner === owner)) {
throw new DuplicateActionError(definition.id, owner);
}
const entry: StoredDefinition = {
owner,
title: definition.title,
...(definition.icon !== undefined ? { icon: definition.icon } : {}),
context: definition.context ?? "global",
...(definition.run !== undefined ? { run: definition.run } : {}),
};
addToList(definitionsById, definition.id, entry);
notify();
return () => {
if (removeFromList(definitionsById, definition.id, entry)) {
notify();
}
};
},
registerHandler(actionId, handler, handlerOptions = {}) {
assertValidActionId(actionId);
const entry: StoredHandler = {
handler,
scope: handlerOptions.scope ?? null,
enabled: handlerOptions.enabled ?? alwaysEnabled,
};
addToList(handlersById, actionId, entry);
notify();
return () => {
if (removeFromList(handlersById, actionId, entry)) {
notify();
}
};
},
getAction(actionId) {
const definitions = definitionsById.get(actionId);
return definitions ? toRegisteredAction(actionId, definitions) : null;
},
listActions() {
return [...definitionsById].map(([id, definitions]) => toRegisteredAction(id, definitions));
},
canDispatch(actionId) {
return eligibleHandlers(actionId).length > 0 || eligibleRunners(actionId).length > 0;
},
dispatch(actionId, input) {
for (const entry of eligibleHandlers(actionId)) {
if (invoke(entry.handler, invocationFor(actionId, null, input))) {
return true;
}
}
for (const entry of eligibleRunners(actionId)) {
if (entry.run && invoke(entry.run, invocationFor(actionId, entry.owner, input))) {
return true;
}
}
return false;
},
subscribe(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
}
@@ -0,0 +1,104 @@
/** Active named scopes, outermost first. The last entry is the innermost scope. */
export type ActiveScopes = readonly string[];
/**
* One mounted surface's activation of a named scope. Two panes showing the
* same panel activate the same name separately, and a handler bound to one
* activation never runs for the other.
*/
export interface ScopeActivation {
readonly scope: string;
/** Idempotent. A released activation stays inactive; activate again for a new one. */
release(): void;
}
/**
* The stack of named action scopes that mounted surfaces activate, such as
* `"inbox/list"` under `"inbox/popover"`. The innermost active scope wins; no
* weights or priorities.
*/
export interface ActionScopeStore {
/** Pushes `scope` as the innermost scope. */
activate(scope: string): ScopeActivation;
/** Stable between changes, so it can back `useSyncExternalStore`. */
getActiveScopes(): ActiveScopes;
/**
* How deep `activation` sits in the stack: 1 for the outermost, higher for
* inner ones, `null` once released.
*/
depthOf(activation: ScopeActivation): number | null;
subscribe(listener: () => void): () => void;
}
function sameScopes(left: ActiveScopes, right: ActiveScopes): boolean {
return left.length === right.length && left.every((scope, index) => scope === right[index]);
}
/**
* A name activated more than once stays active until every activation is
* released, and sits at the position of its innermost activation.
*/
function orderActiveScopes(activations: readonly ScopeActivation[]): ActiveScopes {
const innermostIndex = new Map<string, number>();
for (const [index, { scope }] of activations.entries()) {
innermostIndex.set(scope, index);
}
return [...innermostIndex.entries()]
.sort(([, left], [, right]) => left - right)
.map(([scope]) => scope);
}
export function createActionScopeStore(): ActionScopeStore {
const activations: ScopeActivation[] = [];
const listeners = new Set<() => void>();
let activeScopes: ActiveScopes = [];
function commit(): void {
const next = orderActiveScopes(activations);
if (sameScopes(activeScopes, next)) {
return;
}
activeScopes = next;
for (const listener of listeners) {
listener();
}
}
return {
activate(scope) {
if (scope.trim().length === 0) {
throw new Error("Action scope name must be non-empty");
}
const activation: ScopeActivation = {
scope,
release() {
const index = activations.indexOf(activation);
if (index === -1) {
return;
}
activations.splice(index, 1);
commit();
},
};
activations.push(activation);
commit();
return activation;
},
getActiveScopes() {
return activeScopes;
},
depthOf(activation) {
const index = activations.indexOf(activation);
return index === -1 ? null : index + 1;
},
subscribe(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
}
+122
View File
@@ -0,0 +1,122 @@
import { createContext, type ReactNode, useContext, useEffect, useRef, useState } from "react";
import type { ActionHandler, ActionRegistry } from "./action-registry";
import type { ActionScopeStore, ScopeActivation } from "./action-scope-store";
interface ActionRegistries {
actions: ActionRegistry;
scopes: ActionScopeStore;
}
const ActionRegistriesContext = createContext<ActionRegistries | null>(null);
/**
* The activation the surrounding surface handlers belong to. `undefined` means
* no surface encloses them; `null` means the enclosing surface is inactive, so
* its handlers stay unregistered rather than running unscoped.
*/
const EnclosingScopeContext = createContext<ScopeActivation | null | undefined>(undefined);
export function ActionRegistryProvider({
actions,
scopes,
children,
}: ActionRegistries & { children: ReactNode }) {
const [value] = useState<ActionRegistries>(() => ({ actions, scopes }));
return (
<ActionRegistriesContext.Provider value={value}>{children}</ActionRegistriesContext.Provider>
);
}
function useActionRegistries(): ActionRegistries {
const registries = useContext(ActionRegistriesContext);
if (!registries) {
throw new Error("Action hooks must be used within ActionRegistryProvider");
}
return registries;
}
export function useActionRegistry(): ActionRegistry {
return useActionRegistries().actions;
}
/**
* Activates `name` while `active` holds, as the innermost scope. Returns the
* activation, or `null` while inactive. Pass it to `ActionScope` or to
* `useActionHandler`'s `scope` option.
*/
export function useActionScope(name: string, options: { active: boolean }): ScopeActivation | null {
const { scopes } = useActionRegistries();
const [activation, setActivation] = useState<ScopeActivation | null>(null);
const { active } = options;
useEffect(() => {
if (!active) return;
const next = scopes.activate(name);
setActivation(next);
return () => {
next.release();
setActivation((current) => (current === next ? null : current));
};
}, [scopes, name, active]);
return active ? activation : null;
}
/** Puts every `useActionHandler` below it in `activation`. */
export function ActionScope({
activation,
children,
}: {
activation: ScopeActivation | null;
children: ReactNode;
}) {
return (
<EnclosingScopeContext.Provider value={activation}>{children}</EnclosingScopeContext.Provider>
);
}
export interface UseActionHandlerOptions {
/**
* Read on every dispatch. `false` leaves the action to the next handler, and
* hides this one from badges, Command Center and iOS claims.
*/
enabled?: boolean | (() => boolean);
/** Overrides the enclosing `ActionScope`. `null` keeps the handler unregistered. */
scope?: ScopeActivation | null;
}
/**
* Attaches `handler` to each of `actionIds` for as long as the component is
* mounted. It registers once per scope activation and reads the latest
* `handler` and `enabled` on each dispatch, so re-renders never reorder it.
*/
export function useActionHandler(
actionIds: string | readonly string[],
handler: ActionHandler,
options: UseActionHandlerOptions = {},
): void {
const actions = useActionRegistry();
const enclosingScope = useContext(EnclosingScopeContext);
const scope = options.scope !== undefined ? options.scope : enclosingScope;
const handlerRef = useRef(handler);
handlerRef.current = handler;
const enabledRef = useRef(options.enabled);
enabledRef.current = options.enabled;
const idsKey = typeof actionIds === "string" ? actionIds : actionIds.join(" ");
useEffect(() => {
if (scope === null || idsKey === "") return;
const isEnabled = () => {
const enabled = enabledRef.current;
if (enabled === undefined) return true;
return typeof enabled === "function" ? enabled() : enabled;
};
const disposers = idsKey.split(" ").map((actionId) =>
actions.registerHandler(actionId, (invocation) => handlerRef.current(invocation), {
...(scope ? { scope } : {}),
enabled: isEnabled,
}),
);
return () => {
for (const dispose of disposers) dispose();
};
}, [actions, scope, idsKey]);
}
+4 -24
View File
@@ -109,7 +109,6 @@ import { getDesktopHost } from "@/desktop/host";
import { loadDesktopSettings } from "@/desktop/settings/desktop-settings";
import { RosettaCalloutSource } from "@/desktop/updates/rosetta-callout-source";
import { UpdateCalloutSource } from "@/desktop/updates/update-callout-source";
import { useActiveWorktreeNewAction } from "@/hooks/use-active-worktree-new-action";
import { useGlobalNewWorkspaceAction } from "@/hooks/use-global-new-workspace-action";
import { useLatchedBoolean } from "@/hooks/use-latched-boolean";
import { useFaviconStatus } from "@/hooks/use-favicon-status";
@@ -121,10 +120,7 @@ import { useOpenProject } from "@/hooks/use-open-project";
import { useAppSettings } from "@/hooks/use-settings";
import { useOpenAgentListGesture } from "@/mobile-panels/gestures";
import { MobilePanelsProvider, useIsMobilePanelActive } from "@/mobile-panels/provider";
import {
KeyboardActionDispatcherProvider,
useKeyboardActionDispatcher,
} from "@/keyboard/keyboard-action-dispatcher-context";
import { CoreActionsProvider, useAppShellActions } from "@/core-actions";
import { polyfillCrypto } from "@/polyfills/crypto";
import {
getHostRuntimeStore,
@@ -388,7 +384,6 @@ interface AppContainerProps {
const WINDOW_SIDEBAR_TOGGLE_HORIZONTAL_PADDING = 12;
function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppContainerProps) {
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const daemons = useHosts();
const { settings, updateSettings } = useAppSettings();
const toggleMobileAgentList = usePanelStore((state) => state.toggleMobileAgentList);
@@ -420,34 +415,19 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
const chromeEnabled = chromeEnabledOverride ?? daemons.length > 0;
const hasMountedDesktopSidebar = useLatchedBoolean(chromeEnabled);
const toggleAgentList = isCompactLayout ? toggleMobileAgentList : toggleDesktopAgentList;
const toggleDesktopSidebars = useCallback(() => {
// The focused workspace owns its layout key, its checkout, and therefore the
// only correct answer to "is the explorer open". Let it decide when there is
// one: the pathname alone cannot identify the active workspace, because
// desktop cold-starts at "/" and restores the workspace from route params.
if (keyboardActionDispatcher.dispatch({ id: "sidebar.toggle.both", scope: "sidebar" })) {
return;
}
// Off a workspace route there is no explorer — only the agent list.
toggleAgentList();
}, [keyboardActionDispatcher, toggleAgentList]);
// TODO: stop matching pathname here as a branch. `chromeEnabled` should not
// conflate workspace/project-specific chrome (sidebar, mobile gesture) with
// global concerns like keyboard shortcuts. Split those out so settings (and
// other non-workspace routes) don't need a special-case to keep shortcuts alive.
const keyboardShortcutsEnabled = chromeEnabled || pathname.startsWith("/settings");
useAppShellActions({ isMobile: isCompactLayout, toggleAgentList, cycleTheme });
useKeyboardShortcuts({
enabled: keyboardShortcutsEnabled,
isMobile: isCompactLayout,
isWorkspaceFocusModeEnabled,
toggleAgentList,
toggleBothSidebars: toggleDesktopSidebars,
exitFocusMode,
cycleTheme,
});
useActiveWorktreeNewAction();
useGlobalNewWorkspaceAction();
const activeWorkspace = useActiveWorkspaceSelection();
@@ -1014,7 +994,7 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
function RootProviders({ children }: { children: ReactNode }) {
return (
<KeyboardActionDispatcherProvider>
<CoreActionsProvider>
<WindowLayoutProvider>
<WindowChromeProvider>
<KeyboardProvider>
@@ -1024,7 +1004,7 @@ function RootProviders({ children }: { children: ReactNode }) {
</KeyboardProvider>
</WindowChromeProvider>
</WindowLayoutProvider>
</KeyboardActionDispatcherProvider>
</CoreActionsProvider>
);
}
@@ -70,7 +70,7 @@ import {
navigateToWorkspace,
useActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
import { useActionRegistry } from "@/actions";
import {
clearCommandCenterFocusRestoreElement,
takeCommandCenterFocusRestoreElement,
@@ -363,7 +363,7 @@ function useCommandCenterState(
interaction: CommandCenterInteraction,
getInputHandle: () => EditingTextInputHandle | null,
): CommandCenterState {
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const actionRegistry = useActionRegistry();
const { t } = useTranslation();
const open = useKeyboardShortcutsStore((state) => state.commandCenterOpen);
const requestedTab = useKeyboardShortcutsStore((state) => state.commandCenterTab);
@@ -592,11 +592,10 @@ function useCommandCenterState(
const cancel = focusWithRetries({
focus: () => element.focus(),
isFocused: () => typeof document !== "undefined" && document.activeElement === element,
onTimeout: () =>
keyboardActionDispatcher.dispatch({ id: "message-input.focus", scope: "message-input" }),
onTimeout: () => actionRegistry.dispatch("paseo/message-input.focus"),
});
return cancel;
}, [getInputHandle, keyboardActionDispatcher, open]);
}, [actionRegistry, getInputHandle, open]);
return {
open,
@@ -1,4 +1,3 @@
import { usesDesktopBindings } from "@/keyboard";
import { useMemo } from "react";
import { router, type Href } from "expo-router";
import { useTranslation } from "react-i18next";
@@ -21,12 +20,11 @@ import { withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-context";
import { getDesktopHost } from "@/desktop/host";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { useOpenAddProject } from "@/hooks/use-open-add-project";
import { useImportSession } from "@/hooks/use-import-session";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
import { useActionRegistry } from "@/actions";
import { useHardwareKeyboardPresent } from "@/keyboard";
import { resolveShortcutKeysForAction } from "@/keyboard/keyboard-shortcuts";
import { displayKeysFor, getDisplayPlatform, useKeybindings } from "@/keyboard";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { usePanelStore } from "@/stores/panel-store";
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
@@ -40,7 +38,6 @@ import {
buildSessionsRoute,
buildSettingsRoute,
} from "@/utils/host-routes";
import { getShortcutOs } from "@/utils/shortcut-platform";
import type { CommandCenterContribution, CommandCenterIconProps } from "./contributions";
import { getCommandCenterIcon } from "./icon";
import { useCommandCenterActions } from "./provider";
@@ -125,11 +122,11 @@ function SwitchWorkspaceIcon({ size }: CommandCenterIconProps) {
}
export function CommandCenterRootActions() {
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const actionRegistry = useActionRegistry();
const bindings = useKeybindings();
const { t } = useTranslation();
const toast = useToast();
const browserHostLabel = getDesktopHost()?.browserHostLabel;
const { overrides } = useKeyboardShortcutOverrides();
const shortcutsAvailable = useHardwareKeyboardPresent();
const openAddProject = useOpenAddProject();
const { open: openImportSession, sheet: importSessionSheet } = useImportSession();
@@ -147,11 +144,10 @@ export function CommandCenterRootActions() {
const toggleMobileAgentList = usePanelStore((state) => state.toggleMobileAgentList);
const toggleDesktopAgentList = usePanelStore((state) => state.toggleDesktopAgentList);
const toggleAgentList = isCompact ? toggleMobileAgentList : toggleDesktopAgentList;
const shortcutPlatform = useMemo(
() => ({ isMac: getShortcutOs() === "mac", usesDesktopBindings }),
[],
);
const actions = useMemo<CommandCenterContribution[]>(() => {
const platform = getDisplayPlatform();
const shortcutKeys = (actionId: string) =>
displayKeysFor(bindings, actionId, platform) ?? undefined;
const availableActions: CommandCenterContribution[] = [
{
id: "add-project",
@@ -170,8 +166,7 @@ export function CommandCenterRootActions() {
sectionTitle: t("shell.commandCenter.actions"),
icon: AddProjectIcon,
// The help id remains "new-agent" because user overrides are keyed by its binding id.
shortcutKeys:
resolveShortcutKeysForAction("new-agent", overrides, shortcutPlatform) ?? undefined,
shortcutKeys: shortcutKeys("paseo/project.open"),
},
},
{
@@ -182,15 +177,14 @@ export function CommandCenterRootActions() {
keywords: ["new", "workspace", "worktree", "branch"],
visibility: "always",
run: () => {
keyboardActionDispatcher.dispatch({ id: "workspace.new", scope: "sidebar" });
actionRegistry.dispatch("paseo/workspace.new");
},
presentation: {
kind: "action",
title: t("sidebar.actions.newWorkspace"),
sectionTitle: t("shell.commandCenter.actions"),
icon: PlusIcon,
shortcutKeys:
resolveShortcutKeysForAction("new-workspace", overrides, shortcutPlatform) ?? undefined,
shortcutKeys: shortcutKeys("paseo/workspace.new"),
},
},
{
@@ -209,9 +203,7 @@ export function CommandCenterRootActions() {
title: t("settings.shortcuts.help.switchRecentWorkspace"),
sectionTitle: t("shell.commandCenter.actions"),
icon: SwitchWorkspaceIcon,
shortcutKeys:
resolveShortcutKeysForAction("workspace-switcher-next", overrides, shortcutPlatform) ??
undefined,
shortcutKeys: shortcutKeys("paseo/workspace.switcher.next"),
},
},
{
@@ -302,9 +294,7 @@ export function CommandCenterRootActions() {
title: t("sidebar.actions.settings"),
sectionTitle: t("shell.commandCenter.actions"),
icon: SettingsIcon,
shortcutKeys:
resolveShortcutKeysForAction("toggle-settings", overrides, shortcutPlatform) ??
undefined,
shortcutKeys: shortcutKeys("paseo/settings.toggle"),
},
},
// Toggle left sidebar is global: it calls the panel store directly and works on every route.
@@ -329,9 +319,7 @@ export function CommandCenterRootActions() {
title: t("settings.shortcuts.help.toggleLeftSidebar"),
sectionTitle: t("shell.commandCenter.actions"),
icon: PanelLeftIcon,
shortcutKeys:
resolveShortcutKeysForAction("toggle-left-sidebar", overrides, shortcutPlatform) ??
undefined,
shortcutKeys: shortcutKeys("paseo/sidebar.toggle.left"),
},
},
];
@@ -376,9 +364,7 @@ export function CommandCenterRootActions() {
title: t("sidebar.help.shortcuts"),
sectionTitle: t("shell.commandCenter.actions"),
icon: KeyboardIcon,
shortcutKeys:
resolveShortcutKeysForAction("show-shortcuts", overrides, shortcutPlatform) ??
undefined,
shortcutKeys: shortcutKeys("paseo/shortcuts-dialog.toggle"),
},
});
}
@@ -402,16 +388,15 @@ export function CommandCenterRootActions() {
browserHostLabel,
groupMode,
homeRoute,
keyboardActionDispatcher,
actionRegistry,
bindings,
openAddProject,
openImportSession,
overrides,
schedulesRoute,
sessionsRoute,
setGroupMode,
setShortcutsDialogOpen,
settingsRoute,
shortcutPlatform,
shortcutsAvailable,
t,
toast,
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import type { GitAction, GitActions } from "@/git/policy";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import {
buildWorkspaceCommandCenterContributions,
buildWorkspaceFileSearchContribution,
@@ -23,14 +22,14 @@ function gitAction(id: GitAction["id"], label: string): GitAction {
function source(gitActions: GitActions): {
value: WorkspaceCommandCenterSource;
runGitActions: GitAction[];
dispatched: KeyboardActionDefinition[];
dispatched: string[];
copiedPaths: number;
copiedBranchNames: number;
archivedWorkspaces: number;
toggledLabels: Array<{ name: string; assigned: boolean }>;
} {
const runGitActions: GitAction[] = [];
const dispatched: KeyboardActionDefinition[] = [];
const dispatched: string[] = [];
const toggledLabels: Array<{ name: string; assigned: boolean }> = [];
const counters = { copiedPaths: 0, copiedBranchNames: 0, archivedWorkspaces: 0 };
return {
@@ -82,7 +81,7 @@ function source(gitActions: GitActions): {
labelsGroup: "Labels",
},
icons: {},
shortcuts: {},
shortcutKeys: () => undefined,
capabilities: {
canSplitPanes: true,
canOpenBrowserTabs: true,
@@ -96,7 +95,7 @@ function source(gitActions: GitActions): {
currentBranch: null,
isPinned: false,
labelCatalog: null,
dispatch: (action) => dispatched.push(action),
dispatch: (actionId) => dispatched.push(actionId),
runGitAction: (action) => runGitActions.push(action),
archiveWorkspace: () => {
counters.archivedWorkspaces += 1;
@@ -181,9 +180,7 @@ describe("workspace command center contributions", () => {
.find((item) => item.id === "tab:reveal-in-files")
?.run?.();
expect(fixture.dispatched).toEqual([
{ id: "workspace.tab.reveal-in-files", scope: "workspace" },
]);
expect(fixture.dispatched).toEqual(["paseo/workspace.tab.reveal-in-files"]);
});
it("omits archive while the workspace cannot be archived", () => {
@@ -289,21 +286,15 @@ describe("workspace command center contributions", () => {
expect(contributions.some((item) => item.id === "workspace:copy-path")).toBe(true);
});
it("dispatches every tab and pane command to the workspace scope", () => {
it("dispatches every tab and pane command through the action registry", () => {
const fixture = source({ primary: null, secondary: [], menu: [] });
const contributions = buildWorkspaceCommandCenterContributions(fixture.value);
for (const contribution of contributions) contribution.run?.();
expect(fixture.dispatched.length).toBeGreaterThan(5);
// workspace:rename dispatches to workspace scope
expect(
fixture.dispatched.some((a) => a.id === "workspace.rename" && a.scope === "workspace"),
).toBe(true);
// workspace:toggle-explorer-sidebar intentionally dispatches to sidebar scope
expect(
fixture.dispatched.some((a) => a.id === "sidebar.toggle.right" && a.scope === "sidebar"),
).toBe(true);
expect(fixture.dispatched).toContain("paseo/workspace.rename");
expect(fixture.dispatched).toContain("paseo/sidebar.toggle.right");
});
it("keeps workspace creation commands available outside Git", () => {
@@ -319,7 +310,7 @@ describe("workspace command center contributions", () => {
expect(contributions.some((item) => item.id.startsWith("git:"))).toBe(false);
});
it("dispatches rename to the workspace scope", () => {
it("dispatches rename", () => {
const fixture = source({ primary: null, secondary: [], menu: [] });
const contributions = buildWorkspaceCommandCenterContributions(fixture.value);
@@ -327,7 +318,7 @@ describe("workspace command center contributions", () => {
expect(rename?.presentation).toMatchObject({ title: "Rename workspace" });
rename?.run?.();
expect(fixture.dispatched).toEqual([{ id: "workspace.rename", scope: "workspace" }]);
expect(fixture.dispatched).toEqual(["paseo/workspace.rename"]);
});
it("labels active tab rename by the active tab kind", () => {
@@ -388,7 +379,7 @@ describe("workspace command center contributions", () => {
expect(pinContribution?.presentation).toMatchObject({ title: "Pin to top" });
expect(pinContribution?.visibility).toBe("always");
pinContribution?.run?.();
expect(unpinned.dispatched).toEqual([{ id: "workspace.pin", scope: "sidebar" }]);
expect(unpinned.dispatched).toEqual(["paseo/workspace.pin"]);
const pinned = source({ primary: null, secondary: [], menu: [] });
pinned.value.capabilities.canPin = true;
@@ -421,7 +412,7 @@ describe("workspace command center contributions", () => {
.find((item) => item.id === "workspace:show-setup")
?.run?.();
expect(withSetup.dispatched).toEqual([{ id: "workspace.setup.show", scope: "workspace" }]);
expect(withSetup.dispatched).toEqual(["paseo/workspace.setup.show"]);
});
// Regression guard for the registration split: these two are handled only by workspace-screen.tsx
@@ -436,8 +427,8 @@ describe("workspace command center contributions", () => {
contributions.find((item) => item.id === "workspace:toggle-focus-mode")?.run?.();
expect(fixture.dispatched).toEqual([
{ id: "sidebar.toggle.right", scope: "sidebar" },
{ id: "workspace.focus.toggle", scope: "workspace" },
"paseo/sidebar.toggle.right",
"paseo/workspace.focus.toggle",
]);
for (const contribution of contributions) {
expect(contribution.group).toBe("workspace");
@@ -1,14 +1,12 @@
import { actionsWithoutPrimary, type GitAction, type GitActions } from "@/git/policy";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import type {
WorkspacePanelPlacement,
WorkspacePanelTarget,
} from "@/keyboard/keyboard-action-dispatcher";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { ShortcutKey } from "@/utils/format-shortcut";
import type { CommandCenterContribution, CommandCenterIcon } from "./contributions";
import { COMMAND_CENTER_FILES_SUBLIST_ID } from "./sublist";
type WorkspacePanelTarget = "changes" | "files" | "pull-request";
type WorkspacePanelPlacement = "supporting" | "side-pane" | "focused-pane";
export interface WorkspaceCommandCenterLabelChoice {
name: string;
/** Whether the current workspace already carries this label. */
@@ -134,27 +132,12 @@ export interface WorkspaceCommandCenterIcons {
git?(action: GitAction): CommandCenterIcon | undefined;
}
export interface WorkspaceCommandCenterShortcuts {
newAgent?: ShortcutKey[][];
searchFiles?: ShortcutKey[][];
newTerminal?: ShortcutKey[][];
splitRight?: ShortcutKey[][];
splitDown?: ShortcutKey[][];
archiveWorkspace?: ShortcutKey[][];
previousTab?: ShortcutKey[][];
nextTab?: ShortcutKey[][];
closeCurrentTab?: ShortcutKey[][];
closePane?: ShortcutKey[][];
toggleFocusMode?: ShortcutKey[][];
toggleExplorerSidebar?: ShortcutKey[][];
pinWorkspace?: ShortcutKey[][];
}
export interface WorkspaceCommandCenterSource {
gitActions: GitActions;
labels: WorkspaceCommandCenterLabels;
icons: WorkspaceCommandCenterIcons;
shortcuts: WorkspaceCommandCenterShortcuts;
/** The keys a row's badge shows for `actionId`, if it has any. */
shortcutKeys(actionId: string): ShortcutKey[][] | undefined;
capabilities: {
canSplitPanes: boolean;
canOpenBrowserTabs: boolean;
@@ -175,7 +158,7 @@ export interface WorkspaceCommandCenterSource {
* before the catalog has loaded — omits the whole group rather than showing it empty.
*/
labelCatalog: readonly WorkspaceCommandCenterLabelChoice[] | null;
dispatch(action: KeyboardActionDefinition): void;
dispatch(actionId: string): void;
runGitAction(action: GitAction): void;
/** Null while the workspace cannot be archived. A Git workspace archives through `gitActions`. */
archiveWorkspace: (() => void) | null;
@@ -204,7 +187,9 @@ function buildGitContribution(
sectionTitle: source.labels.section,
icon: source.icons.git?.(action),
shortcutKeys:
action.id === "archive-workspace" ? source.shortcuts.archiveWorkspace : undefined,
action.id === "archive-workspace"
? source.shortcutKeys("paseo/workspace.archive")
: undefined,
},
};
}
@@ -216,8 +201,7 @@ function buildWorkspaceAction(input: {
title: string;
keywords: readonly string[];
icon?: CommandCenterIcon;
shortcutKeys?: ShortcutKey[][];
action: KeyboardActionDefinition;
actionId: string;
visibility: "always" | "query";
}): CommandCenterContribution {
return {
@@ -227,13 +211,13 @@ function buildWorkspaceAction(input: {
rank: input.rank,
keywords: input.keywords,
visibility: input.visibility,
run: () => input.source.dispatch(input.action),
run: () => input.source.dispatch(input.actionId),
presentation: {
kind: "action",
title: input.title,
sectionTitle: input.source.labels.section,
icon: input.icon,
shortcutKeys: input.shortcutKeys,
shortcutKeys: input.source.shortcutKeys(input.actionId),
},
};
}
@@ -273,12 +257,7 @@ function buildPanelContributions(
title: source.labels.openPanel(panel.name, "supporting"),
keywords: ["open", panel.target, "tab", "supporting"],
icon: panel.icon,
action: {
id: "workspace.tab.open",
scope: "workspace",
target: panel.target,
placement: "supporting",
},
actionId: `paseo/workspace.tab.open.${panel.target}`,
}),
);
if (!source.capabilities.canSplitPanes) continue;
@@ -292,12 +271,7 @@ function buildPanelContributions(
title: source.labels.openPanel(panel.name, placement),
keywords: ["open", panel.target, "tab", placement, "pane"],
icon: panel.icon,
action: {
id: "workspace.tab.open",
scope: "workspace",
target: panel.target,
placement,
},
actionId: `paseo/workspace.tab.open.${panel.target}.${placement}`,
}),
);
}
@@ -316,8 +290,7 @@ function buildActiveTabContributions(
title: source.labels.previousTab,
keywords: ["tab", "previous", "switch", "navigate"],
icon: source.icons.previousTab,
shortcutKeys: source.shortcuts.previousTab,
action: { id: "workspace.tab.navigate-relative", scope: "workspace", delta: -1 },
actionId: "paseo/workspace.tab.previous",
}),
buildQueryAction(source, {
id: "tab:next",
@@ -325,8 +298,7 @@ function buildActiveTabContributions(
title: source.labels.nextTab,
keywords: ["tab", "next", "switch", "navigate"],
icon: source.icons.nextTab,
shortcutKeys: source.shortcuts.nextTab,
action: { id: "workspace.tab.navigate-relative", scope: "workspace", delta: 1 },
actionId: "paseo/workspace.tab.next",
}),
buildQueryAction(source, {
id: "tab:close-current",
@@ -334,8 +306,7 @@ function buildActiveTabContributions(
title: source.labels.closeCurrentTab,
keywords: ["tab", "close", "current"],
icon: source.icons.close,
shortcutKeys: source.shortcuts.closeCurrentTab,
action: { id: "workspace.tab.close-current", scope: "workspace" },
actionId: "paseo/workspace.tab.close-current",
}),
];
if (source.activeTabKind === "agent" || source.activeTabKind === "terminal") {
@@ -349,7 +320,7 @@ function buildActiveTabContributions(
: source.labels.renameTerminal,
keywords: ["tab", "rename", "current"],
icon: source.icons.rename,
action: { id: "workspace.tab.rename-current", scope: "workspace" },
actionId: "paseo/workspace.tab.rename-current",
}),
buildQueryAction(source, {
id: "tab:copy-id",
@@ -360,7 +331,7 @@ function buildActiveTabContributions(
: source.labels.copyTerminalId,
keywords: ["tab", "copy", "id"],
icon: source.icons.copy,
action: { id: "workspace.tab.copy-id", scope: "workspace" },
actionId: "paseo/workspace.tab.copy-id",
}),
);
}
@@ -372,7 +343,7 @@ function buildActiveTabContributions(
title: source.labels.reloadAgent,
keywords: ["tab", "agent", "reload"],
icon: source.icons.reload,
action: { id: "workspace.tab.reload-current", scope: "workspace" },
actionId: "paseo/workspace.tab.reload-current",
}),
buildQueryAction(source, {
id: "tab:copy-resume-command",
@@ -380,7 +351,7 @@ function buildActiveTabContributions(
title: source.labels.copyResumeCommand,
keywords: ["tab", "agent", "copy", "resume", "command"],
icon: source.icons.copy,
action: { id: "workspace.tab.copy-resume-command", scope: "workspace" },
actionId: "paseo/workspace.tab.copy-resume-command",
}),
);
}
@@ -392,7 +363,7 @@ function buildActiveTabContributions(
title: source.labels.copyFilePath,
keywords: ["tab", "file", "copy", "path"],
icon: source.icons.copy,
action: { id: "workspace.tab.copy-file-path", scope: "workspace" },
actionId: "paseo/workspace.tab.copy-file-path",
}),
buildQueryAction(source, {
id: "tab:reveal-in-files",
@@ -400,7 +371,7 @@ function buildActiveTabContributions(
title: source.labels.revealInFiles,
keywords: ["tab", "file", "reveal", "files", "explorer"],
icon: source.icons.files,
action: { id: "workspace.tab.reveal-in-files", scope: "workspace" },
actionId: "paseo/workspace.tab.reveal-in-files",
}),
);
}
@@ -412,7 +383,7 @@ function buildActiveTabContributions(
title: source.labels.closeTabsLeft,
keywords: ["tab", "close", "left"],
icon: source.icons.close,
action: { id: "workspace.tab.close-left", scope: "workspace" },
actionId: "paseo/workspace.tab.close-left",
}),
);
}
@@ -424,7 +395,7 @@ function buildActiveTabContributions(
title: source.labels.closeTabsRight,
keywords: ["tab", "close", "right"],
icon: source.icons.close,
action: { id: "workspace.tab.close-right", scope: "workspace" },
actionId: "paseo/workspace.tab.close-right",
}),
);
}
@@ -436,7 +407,7 @@ function buildActiveTabContributions(
title: source.labels.closeOtherTabs,
keywords: ["tab", "close", "others"],
icon: source.icons.close,
action: { id: "workspace.tab.close-others", scope: "workspace" },
actionId: "paseo/workspace.tab.close-others",
}),
);
}
@@ -449,9 +420,8 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
rank: number;
title: string;
keywords: string[];
action: KeyboardActionDefinition;
actionId: string;
icon?: CommandCenterIcon;
shortcutKeys?: ShortcutKey[][];
}> = [
{
id: "pane:split-right",
@@ -459,8 +429,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.splitRight,
keywords: ["split", "pane", "vertical"],
icon: source.icons.splitRight,
shortcutKeys: source.shortcuts.splitRight,
action: { id: "workspace.pane.split.right", scope: "workspace" },
actionId: "paseo/workspace.pane.split.right",
},
{
id: "pane:split-down",
@@ -468,8 +437,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.splitDown,
keywords: ["split", "pane", "horizontal"],
icon: source.icons.splitDown,
shortcutKeys: source.shortcuts.splitDown,
action: { id: "workspace.pane.split.down", scope: "workspace" },
actionId: "paseo/workspace.pane.split.down",
},
{
id: "pane:focus-left",
@@ -477,7 +445,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.focusPaneLeft,
keywords: ["pane", "focus", "left"],
icon: source.icons.focusPane,
action: { id: "workspace.pane.focus.left", scope: "workspace" },
actionId: "paseo/workspace.pane.focus.left",
},
{
id: "pane:focus-right",
@@ -485,7 +453,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.focusPaneRight,
keywords: ["pane", "focus", "right"],
icon: source.icons.focusPane,
action: { id: "workspace.pane.focus.right", scope: "workspace" },
actionId: "paseo/workspace.pane.focus.right",
},
{
id: "pane:focus-up",
@@ -493,7 +461,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.focusPaneUp,
keywords: ["pane", "focus", "up"],
icon: source.icons.focusPane,
action: { id: "workspace.pane.focus.up", scope: "workspace" },
actionId: "paseo/workspace.pane.focus.up",
},
{
id: "pane:focus-down",
@@ -501,7 +469,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.focusPaneDown,
keywords: ["pane", "focus", "down"],
icon: source.icons.focusPane,
action: { id: "workspace.pane.focus.down", scope: "workspace" },
actionId: "paseo/workspace.pane.focus.down",
},
{
id: "pane:move-tab-left",
@@ -509,7 +477,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.moveTabLeft,
keywords: ["pane", "tab", "move", "left"],
icon: source.icons.moveTab,
action: { id: "workspace.pane.move-tab.left", scope: "workspace" },
actionId: "paseo/workspace.pane.move-tab.left",
},
{
id: "pane:move-tab-right",
@@ -517,7 +485,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.moveTabRight,
keywords: ["pane", "tab", "move", "right"],
icon: source.icons.moveTab,
action: { id: "workspace.pane.move-tab.right", scope: "workspace" },
actionId: "paseo/workspace.pane.move-tab.right",
},
{
id: "pane:move-tab-up",
@@ -525,7 +493,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.moveTabUp,
keywords: ["pane", "tab", "move", "up"],
icon: source.icons.moveTab,
action: { id: "workspace.pane.move-tab.up", scope: "workspace" },
actionId: "paseo/workspace.pane.move-tab.up",
},
{
id: "pane:move-tab-down",
@@ -533,7 +501,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.moveTabDown,
keywords: ["pane", "tab", "move", "down"],
icon: source.icons.moveTab,
action: { id: "workspace.pane.move-tab.down", scope: "workspace" },
actionId: "paseo/workspace.pane.move-tab.down",
},
{
id: "pane:close",
@@ -541,8 +509,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.closePane,
keywords: ["pane", "close"],
icon: source.icons.close,
shortcutKeys: source.shortcuts.closePane,
action: { id: "workspace.pane.close", scope: "workspace" },
actionId: "paseo/workspace.pane.close",
},
{
id: "pane:focus-mode-toggle",
@@ -550,8 +517,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
title: source.labels.toggleFocusMode,
keywords: ["pane", "focus", "mode", "toggle"],
icon: source.icons.focusMode,
shortcutKeys: source.shortcuts.toggleFocusMode,
action: { id: "workspace.focus.toggle", scope: "workspace" },
actionId: "paseo/workspace.focus.toggle",
},
];
return paneActions.map((action) => buildQueryAction(source, action));
@@ -597,8 +563,7 @@ function buildCreationContributions(
title: source.labels.newAgent,
keywords: ["tab", "new", "agent", "chat"],
icon: source.icons.newAgent,
shortcutKeys: source.shortcuts.newAgent,
action: { id: "workspace.agent.new", scope: "workspace" },
actionId: "paseo/workspace.tab.target.agent",
visibility: "always",
}),
];
@@ -611,8 +576,7 @@ function buildCreationContributions(
title: source.labels.newTerminal,
keywords: ["terminal", "shell", "console"],
icon: source.icons.newTerminal,
shortcutKeys: source.shortcuts.newTerminal,
action: { id: "workspace.terminal.new", scope: "workspace" },
actionId: "paseo/workspace.terminal.new",
}),
);
if (source.capabilities.canOpenBrowserTabs) {
@@ -623,7 +587,7 @@ function buildCreationContributions(
title: source.labels.newBrowser,
keywords: ["browser", "web", "preview"],
icon: source.icons.newBrowser,
action: { id: "workspace.browser.new", scope: "workspace" },
actionId: "paseo/workspace.tab.target.browser",
}),
);
}
@@ -654,7 +618,7 @@ export function buildWorkspaceCommandCenterContributions(
title: source.labels.archiveWorkspace,
keywords: ["archive", "workspace"],
icon: source.icons.archiveWorkspace,
shortcutKeys: source.shortcuts.archiveWorkspace,
shortcutKeys: source.shortcutKeys("paseo/workspace.archive"),
run: source.archiveWorkspace,
visibility: "query",
}),
@@ -670,8 +634,7 @@ export function buildWorkspaceCommandCenterContributions(
title: source.isPinned ? source.labels.unpin : source.labels.pin,
keywords: ["pin", "unpin", "favorite", "sticky"],
icon: source.isPinned ? source.icons.unpin : source.icons.pin,
shortcutKeys: source.shortcuts.pinWorkspace,
action: { id: "workspace.pin", scope: "sidebar" },
actionId: "paseo/workspace.pin",
visibility: "always",
}),
);
@@ -685,7 +648,7 @@ export function buildWorkspaceCommandCenterContributions(
title: source.labels.rename,
keywords: ["rename", "title", "name", "label"],
icon: source.icons.rename,
action: { id: "workspace.rename", scope: "workspace" },
actionId: "paseo/workspace.rename",
visibility: "query",
}),
buildWorkspaceCallback({
@@ -725,7 +688,7 @@ export function buildWorkspaceCommandCenterContributions(
title: source.labels.showSetup,
keywords: ["setup", "provision", "install", "bootstrap"],
icon: source.icons.showSetup,
action: { id: "workspace.setup.show", scope: "workspace" },
actionId: "paseo/workspace.setup.show",
visibility: "query",
}),
);
@@ -744,8 +707,7 @@ export function buildWorkspaceCommandCenterContributions(
title: source.labels.toggleExplorerSidebar,
keywords: ["toggle", "sidebar", "explorer", "files", "changes"],
icon: source.icons.explorerSidebar,
shortcutKeys: source.shortcuts.toggleExplorerSidebar,
action: { id: "sidebar.toggle.right", scope: "sidebar" },
actionId: "paseo/sidebar.toggle.right",
visibility: "query",
}),
);
@@ -762,8 +724,7 @@ export function buildWorkspaceCommandCenterContributions(
title: source.labels.toggleFocusMode,
keywords: ["toggle", "focus", "zen", "distraction", "fullscreen"],
icon: source.icons.toggleFocusMode,
shortcutKeys: source.shortcuts.toggleFocusMode,
action: { id: "workspace.focus.toggle", scope: "workspace" },
actionId: "paseo/workspace.focus.toggle",
visibility: "query",
}),
);
@@ -1,4 +1,5 @@
import { usesDesktopBindings } from "@/keyboard";
import { displayKeysFor, getDisplayPlatform, useKeybindings } from "@/keyboard";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useCallback, useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -30,11 +31,9 @@ import { getIsElectron } from "@/constants/platform";
import { supportsDesktopPaneSplits, useIsCompactFormFactor } from "@/constants/layout";
import { GIT_ACTION_ICONS } from "@/git/action-icons";
import { useGitActionRunner, useGitActions } from "@/git/use-actions";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { useWorkspaceClipboardActions } from "@/hooks/use-workspace-clipboard-actions";
import { useToast } from "@/contexts/toast-context";
import { type ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
import { useActionRegistry } from "@/actions";
import { useHostFeature } from "@/runtime/host-features";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceDirectory, useWorkspaceFields } from "@/stores/session-store-hooks";
@@ -45,7 +44,6 @@ import {
} from "@/stores/workspace-layout-store";
import { shouldShowWorkspaceSetup } from "@/stores/workspace-setup-store";
import { clearCommandCenterFocusRestoreElement } from "@/utils/command-center-focus-restore";
import { getShortcutOs } from "@/utils/shortcut-platform";
import {
buildWorkspaceLabelPickerRows,
useWorkspaceLabelProjection,
@@ -61,9 +59,7 @@ import {
buildWorkspaceCommandCenterContributions,
buildWorkspaceFileSearchContribution,
type WorkspaceCommandCenterLabelChoice,
type WorkspaceCommandCenterShortcuts,
} from "./workspace-contributions";
import { resolveWorkspaceCommandCenterShortcuts } from "./workspace-shortcuts";
const WORKSPACE_COMMAND_CENTER_ICONS = {
newAgent: getCommandCenterIcon(SquarePen),
@@ -108,11 +104,6 @@ function staticIcon(element: ReactElement | undefined): CommandCenterIcon | unde
return StaticIcon;
}
function resolveWorkspaceShortcuts(overrides: ShortcutOverrides): WorkspaceCommandCenterShortcuts {
const platform = { isMac: getShortcutOs() === "mac", usesDesktopBindings };
return resolveWorkspaceCommandCenterShortcuts({ overrides, platform });
}
/**
* The label catalog and its toggle callback, pulled out of `useWorkspaceCommandCenterActions` to
* keep that hook under the complexity limit. Null while the host's catalog hasn't loaded, so the
@@ -168,7 +159,7 @@ function useWorkspaceLabelCatalog(
function useWorkspaceFileSearchAction(
serverId: string | null,
workspaceId: string | null,
shortcutKeys: WorkspaceCommandCenterShortcuts["searchFiles"],
shortcutKeys: ShortcutKey[][] | undefined,
) {
const { t } = useTranslation();
const actions = useMemo(
@@ -191,7 +182,8 @@ function useWorkspaceFileSearchAction(
}
export function useWorkspaceCommandCenterActions(): void {
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const actionRegistry = useActionRegistry();
const bindings = useKeybindings();
const { t } = useTranslation();
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
@@ -230,7 +222,6 @@ export function useWorkspaceCommandCenterActions(): void {
fields?.setupStatus ?? null,
supportsSetupObservation,
);
const { overrides } = useKeyboardShortcutOverrides();
const { gitActions, isGit, archiveWorkspace } = useGitActions({
serverId: serverId ?? "",
workspaceId,
@@ -259,8 +250,12 @@ export function useWorkspaceCommandCenterActions(): void {
}, [clipboard, fields]);
const { labelCatalog, toggleLabel } = useWorkspaceLabelCatalog(serverId, fields);
const shortcuts = useMemo(() => resolveWorkspaceShortcuts(overrides), [overrides]);
useWorkspaceFileSearchAction(serverId, workspaceId, shortcuts.searchFiles);
const shortcutKeys = useCallback(
(actionId: string) => displayKeysFor(bindings, actionId, getDisplayPlatform()) ?? undefined,
[bindings],
);
const searchFilesKeys = useMemo(() => shortcutKeys("paseo/command-center.files"), [shortcutKeys]);
useWorkspaceFileSearchAction(serverId, workspaceId, searchFilesKeys);
const actions = useMemo(
() =>
@@ -317,7 +312,7 @@ export function useWorkspaceCommandCenterActions(): void {
archiveWorkspace: staticIcon(GIT_ACTION_ICONS.archive),
git: (action) => staticIcon(action.icon),
},
shortcuts,
shortcutKeys,
capabilities: {
canSplitPanes: supportsDesktopPaneSplits() && !isCompact,
canOpenBrowserTabs: getIsElectron(),
@@ -331,9 +326,9 @@ export function useWorkspaceCommandCenterActions(): void {
currentBranch,
isPinned,
labelCatalog,
dispatch: (action) => {
dispatch: (actionId) => {
clearCommandCenterFocusRestoreElement();
keyboardActionDispatcher.dispatch(action);
actionRegistry.dispatch(actionId);
},
runGitAction,
archiveWorkspace,
@@ -355,10 +350,10 @@ export function useWorkspaceCommandCenterActions(): void {
isCompact,
isGit,
isPinned,
keyboardActionDispatcher,
actionRegistry,
labelCatalog,
runGitAction,
shortcuts,
shortcutKeys,
t,
toggleLabel,
],
@@ -1,13 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveWorkspaceCommandCenterShortcuts } from "./workspace-shortcuts";
describe("resolveWorkspaceCommandCenterShortcuts", () => {
it("assigns the New agent and Search files commands their own shortcuts", () => {
const resolved = resolveWorkspaceCommandCenterShortcuts({
overrides: {},
platform: { isMac: true, usesDesktopBindings: true },
});
expect(resolved.newAgent).toEqual([["mod", "shift", "A"]]);
expect(resolved.searchFiles).toEqual([["mod", "P"]]);
});
});
@@ -1,41 +0,0 @@
import {
resolveShortcutKeysForAction,
type ShortcutOverrides,
} from "@/keyboard/keyboard-shortcuts";
import type { WorkspaceCommandCenterShortcuts } from "./workspace-contributions";
interface ResolveWorkspaceCommandCenterShortcutsInput {
overrides: ShortcutOverrides;
platform: { isMac: boolean; usesDesktopBindings: boolean };
}
export function resolveWorkspaceCommandCenterShortcuts({
overrides,
platform,
}: ResolveWorkspaceCommandCenterShortcutsInput): WorkspaceCommandCenterShortcuts {
return {
newAgent:
resolveShortcutKeysForAction("workspace-tab-target-agent", overrides, platform) ?? undefined,
searchFiles: resolveShortcutKeysForAction("search-files", overrides, platform) ?? undefined,
newTerminal:
resolveShortcutKeysForAction("workspace-terminal-new", overrides, platform) ?? undefined,
splitRight:
resolveShortcutKeysForAction("workspace-pane-split-right", overrides, platform) ?? undefined,
splitDown:
resolveShortcutKeysForAction("workspace-pane-split-down", overrides, platform) ?? undefined,
archiveWorkspace:
resolveShortcutKeysForAction("archive-workspace", overrides, platform) ?? undefined,
previousTab:
resolveShortcutKeysForAction("workspace-tab-prev", overrides, platform) ?? undefined,
nextTab: resolveShortcutKeysForAction("workspace-tab-next", overrides, platform) ?? undefined,
closeCurrentTab:
resolveShortcutKeysForAction("workspace-tab-close-current", overrides, platform) ?? undefined,
closePane:
resolveShortcutKeysForAction("workspace-pane-close", overrides, platform) ?? undefined,
toggleFocusMode: resolveShortcutKeysForAction("toggle-focus", overrides, platform) ?? undefined,
toggleExplorerSidebar:
resolveShortcutKeysForAction("toggle-right-sidebar", overrides, platform) ?? undefined,
// Workspace management shortcuts
pinWorkspace: resolveShortcutKeysForAction("pin-workspace", overrides, platform) ?? undefined,
};
}
@@ -1,4 +1,3 @@
import { usesDesktopBindings } from "@/keyboard";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
@@ -7,12 +6,8 @@ import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-moda
import { Shortcut } from "@/components/ui/shortcut";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { getShortcutOs } from "@/utils/shortcut-platform";
import {
buildEffectiveBindings,
buildKeyboardShortcutHelpSections,
} from "@/keyboard/keyboard-shortcuts";
import { filterShortcutHelpSections } from "@/keyboard/shortcut-help-search";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { buildShortcutSections, filterShortcutHelpSections } from "@/core-actions";
import { getDisplayPlatform, useKeybindings } from "@/keyboard";
const SNAP_POINTS: string[] = ["70%", "92%"];
@@ -23,15 +18,10 @@ export function KeyboardShortcutsDialog() {
const [query, setQuery] = useState("");
const shortcutOs = getShortcutOs();
const isMac = shortcutOs === "mac";
const { overrides } = useKeyboardShortcutOverrides();
// Effective bindings, so a shortcut the user unassigned lists no keys here
// instead of advertising a default that no longer fires.
const bindings = useMemo(() => buildEffectiveBindings(overrides), [overrides]);
const sections = useMemo(
() => buildKeyboardShortcutHelpSections({ isMac, usesDesktopBindings }, bindings),
[bindings, isMac],
);
const bindings = useKeybindings();
const sections = useMemo(() => buildShortcutSections(bindings, getDisplayPlatform()), [bindings]);
const visibleSections = useMemo(
() => filterShortcutHelpSections({ sections, query, translate: t, shortcutOs }),
[query, sections, shortcutOs, t],
@@ -65,16 +55,14 @@ export function KeyboardShortcutsDialog() {
>
<View testID="keyboard-shortcuts-dialog-content" style={styles.content}>
{visibleSections.map((section) => (
<View key={section.title} style={styles.section}>
<View key={section.id} style={styles.section}>
<Text style={styles.sectionTitle}>{t(section.titleKey)}</Text>
<View style={styles.rows}>
{section.rows.map((row) => (
<View key={row.id} style={styles.row} testID={`shortcut-help-row-${row.id}`}>
<View style={styles.rowText}>
<Text style={styles.rowLabel}>{t(row.labelKey)}</Text>
{row.note ? (
<Text style={styles.rowNote}>{row.noteKey ? t(row.noteKey) : row.note}</Text>
) : null}
{row.noteKey ? <Text style={styles.rowNote}>{t(row.noteKey)}</Text> : null}
</View>
{row.chord === null ? (
<Text style={styles.rowUnassigned}>{t("settings.shortcuts.unassigned")}</Text>
+3 -3
View File
@@ -82,7 +82,7 @@ import { HEADER_INNER_HEIGHT, useIsCompactFormFactor } from "@/constants/layout"
import { isNative as platformIsNative } from "@/constants/platform";
import { useOpenAddProject } from "@/hooks/use-open-add-project";
import { useImportSession } from "@/hooks/use-import-session";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import {
type SidebarProjectEntry,
type SidebarWorkspaceEntry,
@@ -453,8 +453,8 @@ function SidebarFooter({
handleOpenHostSettings: (serverId: string) => void;
onBeforeNavigate?: () => void;
}) {
const newAgentKeys = useShortcutKeys("new-agent");
const settingsKeys = useShortcutKeys("toggle-settings");
const newAgentKeys = useShortcutKeys("paseo/project.open");
const settingsKeys = useShortcutKeys("paseo/settings.toggle");
const isCompactLayout = useIsCompactFormFactor();
const [rowWidth, setRowWidth] = useState(0);
const handleRowLayout = useCallback((event: LayoutChangeEvent) => {
@@ -135,9 +135,8 @@ import {
import { DensityIcon } from "@/components/ui/density-icon";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Shortcut } from "@/components/ui/shortcut";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
import type { PrHint } from "@/git/use-pr-status-query";
import {
@@ -262,7 +261,6 @@ interface ProjectHeaderRowProps {
chevron: "expand" | "collapse" | null;
onPress: () => void;
worktreeTarget: SidebarProjectHostTarget | null;
isProjectActive?: boolean;
onWorkspacePress?: () => void;
onWorktreeCreated?: (workspaceId: string) => void;
shortcutNumber?: number | null;
@@ -423,7 +421,6 @@ function ProjectRowTrailingActions({
projectPath,
isHovered,
isMobileBreakpoint,
isProjectActive,
onBeginWorkspaceSetup,
onRemoveProject,
removeProjectStatus,
@@ -435,7 +432,6 @@ function ProjectRowTrailingActions({
projectPath: string;
isHovered: boolean;
isMobileBreakpoint: boolean;
isProjectActive: boolean;
onBeginWorkspaceSetup: () => void;
onRemoveProject?: () => void;
removeProjectStatus: "idle" | "pending" | "success";
@@ -448,7 +444,6 @@ function ProjectRowTrailingActions({
displayName={displayName}
onPress={onBeginWorkspaceSetup}
visible={actionsVisible}
showShortcutHint={isProjectActive}
testID={`sidebar-project-new-worktree-${projectViewKey}`}
/>
) : null}
@@ -743,17 +738,14 @@ function NewWorktreeButton({
visible,
loading = false,
testID,
showShortcutHint = false,
}: {
displayName: string;
onPress: () => void;
visible: boolean;
loading?: boolean;
testID: string;
showShortcutHint?: boolean;
}) {
const { t } = useTranslation();
const newWorktreeKeys = useShortcutKeys("new-worktree");
const pressableStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
@@ -805,9 +797,6 @@ function NewWorktreeButton({
<Text style={styles.projectActionTooltipText}>
{t("sidebar.workspace.actions.newWorkspace")}
</Text>
{showShortcutHint && newWorktreeKeys ? (
<Shortcut chord={newWorktreeKeys} style={styles.projectActionTooltipShortcut} />
) : null}
</View>
</TooltipContent>
</Tooltip>
@@ -891,7 +880,6 @@ function ProjectHeaderRow({
chevron,
onPress,
worktreeTarget,
isProjectActive = false,
onWorkspacePress,
onWorktreeCreated: _onWorktreeCreated,
shortcutNumber = null,
@@ -991,7 +979,6 @@ function ProjectHeaderRow({
projectPath={projectPath}
isHovered={isHovered}
isMobileBreakpoint={isMobileBreakpoint}
isProjectActive={isProjectActive}
onBeginWorkspaceSetup={handleBeginWorkspaceSetup}
onRemoveProject={onRemoveProject}
removeProjectStatus={removeProjectStatus}
@@ -1346,7 +1333,7 @@ function WorkspaceRowWithMenu({
}, [onToggleWorkspacePin, workspace]);
const onTogglePin = canPin ? handleTogglePin : undefined;
const archiveShortcutKeys = useShortcutKeys("archive-workspace");
const archiveShortcutKeys = useShortcutKeys("paseo/workspace.archive");
const { hasClearableAttention, canMarkUnread, clearAttention, markUnread } =
useWorkspaceReadState({
serverId: workspace.serverId,
@@ -1669,12 +1656,6 @@ function ProjectBlock({
enabled: collapsed,
});
const active = isProjectSelectedByRoute({
selection: activeWorkspaceSelection,
project,
enabled: selectionEnabled,
});
const renderWorkspaceRow = useCallback(
(
item: SidebarWorkspacePlacement,
@@ -1878,7 +1859,6 @@ function ProjectBlock({
worktreeTarget={
rowModel.trailingAction.kind === "new_workspace" ? rowModel.trailingAction.target : null
}
isProjectActive={active}
onWorkspacePress={onWorkspacePress}
onWorktreeCreated={onWorktreeCreated}
drag={drag}
@@ -2892,7 +2872,6 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
projectActionTooltipShortcut: {},
projectShortcutBadgeOverlay: {
position: "absolute",
top: theme.spacing[2] + 1,
@@ -22,7 +22,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { Shortcut } from "@/components/ui/shortcut";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { useHosts } from "@/runtime/host-runtime";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { orderHostsLocalFirst } from "@/types/host-connection";
@@ -73,8 +73,8 @@ export function SidebarFooterOverflowMenu({
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const openUsage = useOpenSidebarUsage();
const newAgentKeys = useShortcutKeys("new-agent");
const settingsKeys = useShortcutKeys("toggle-settings");
const newAgentKeys = useShortcutKeys("paseo/project.open");
const settingsKeys = useShortcutKeys("paseo/settings.toggle");
const helpLabel = t("sidebar.help.trigger");
const addProjectTrailing = useMemo(
() => (newAgentKeys ? <Shortcut chord={newAgentKeys} /> : null),
@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { PluginSidebarItem } from "@/plugins/sidebar-items";
import { canCreateWorktreeForProjectKind } from "@/projects/host-projects";
import { useHostFeature } from "@/runtime/host-features";
@@ -43,7 +43,7 @@ import { useWorkspaceClipboardActions } from "@/hooks/use-workspace-clipboard-ac
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
import {
SidebarWorkspaceRowFrame,
@@ -770,7 +770,7 @@ function StatusWorkspaceRowWithMenu({
}, [onToggleWorkspacePin, workspace]);
const onTogglePin = canPin ? handleTogglePin : undefined;
const archiveShortcutKeys = useShortcutKeys("archive-workspace");
const archiveShortcutKeys = useShortcutKeys("paseo/workspace.archive");
const { hasClearableAttention, canMarkUnread, clearAttention, markUnread } =
useWorkspaceReadState({
serverId: workspace.serverId,
@@ -785,11 +785,7 @@ const SplitPaneView = memo(function SplitPaneView({
);
const createNewTab = useCallback(() => onCreateNewTab({ paneId }), [onCreateNewTab, paneId]);
useWorkspaceNewTabKeyboardAction({
handlerName: "workspace-chrome-new-tab",
ownsKeyboardShortcuts: isFocused && isWorkspaceFocused,
normalizedServerId,
normalizedWorkspaceId,
paneId,
createNewTab,
});
const compactHeader = useMemo(
@@ -27,7 +27,7 @@ import { Keyframe, runOnJS } from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { FloatingScrollView, FloatingSurface } from "@/components/ui/floating";
import { isWeb } from "@/constants/platform";
import type { KeyboardFocusScope } from "@/keyboard/actions";
import type { KeyboardFocusScope } from "@/keyboard";
import { getOverlayRoot, OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
import {
computePosition,
@@ -61,7 +61,7 @@ import {
resolveSheetCanvasStaticContentHeight,
} from "./menu-sheet-layout";
import type { Alignment, Placement } from "../anchor";
import type { KeyboardFocusScope } from "@/keyboard/actions";
import type { KeyboardFocusScope } from "@/keyboard";
const ThemedChevronLeft = withUnistyles(ChevronLeft);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
@@ -1,12 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { WorkspaceRenameModal } from "@/workspace-rename";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActionHandler } from "@/actions";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
const WORKSPACE_RENAME_ACTIONS: readonly KeyboardActionId[] = ["workspace.rename"];
/**
* The rename dialog used to live only on the sidebar row, so it was unreachable whenever that row
* was not rendered — a collapsed project or status group, a collapsed Pinned section, or focus
@@ -44,13 +41,12 @@ export function WorkspaceRenameHost() {
// lands the dialog behind it, and on web the palette's teardown steals focus back from the
// input. Wait a frame. (The caller has already cleared the focus-restore element.)
const handle = useCallback(() => {
if (!fields) return false;
if (!fields) return { handled: false } as const;
cancelPendingOpen();
openFrameRef.current = requestAnimationFrame(() => {
openFrameRef.current = null;
setIsOpen(true);
});
return true;
}, [cancelPendingOpen, fields]);
const handleClose = useCallback(() => {
@@ -64,12 +60,8 @@ export function WorkspaceRenameHost() {
setIsOpen(false);
}, [cancelPendingOpen, serverId, routeWorkspaceId]);
useKeyboardActionHandler({
handlerId: "workspace-rename-global",
actions: WORKSPACE_RENAME_ACTIONS,
useActionHandler("paseo/workspace.rename", handle, {
enabled: serverId !== null && fields !== null,
priority: 0,
handle,
});
const workspace = useMemo(
@@ -1,4 +1,4 @@
import { useId, useMemo } from "react";
import { useMemo } from "react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { DensityIcon } from "@/components/ui/density-icon";
@@ -19,8 +19,8 @@ import {
import type { ComposerControlPresentation } from "@/composer/agent-controls/layout";
import { getAgentControlHintKey, getFeatureHighlightColor } from "@/composer/agent-controls/utils";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useActionHandler } from "@/actions";
import { useShortcutKeys } from "@/keyboard";
import { useComposerInput } from "@/composer/session";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { resolveNextChoiceId } from "./mode";
@@ -89,33 +89,28 @@ export function useModelPickerShortcut(disabled: boolean) {
const action =
isActiveComposer && !disabled && input
? {
id: "message-input.model-toggle" as const,
id: "paseo/message-input.model-toggle",
canOpen: input.isFocused,
}
: undefined;
const keys = useShortcutKeys(action ? "toggle-model-picker" : null);
const keys = useShortcutKeys(action ? "paseo/message-input.model-toggle" : null);
return { action, keys };
}
export function useEffortCycleShortcut(thinking: ThinkingControl | null, disabled: boolean) {
const { isActiveComposer } = useComposerKeyboardScope();
const input = useComposerInput();
const effortHandlerId = useId();
const nextEffortId = resolveNextChoiceId(thinking?.options ?? [], thinking?.selectedId);
const canCycleEffort = isActiveComposer && !disabled && nextEffortId !== null && input !== null;
useKeyboardActionHandler({
handlerId: effortHandlerId,
actions: ["message-input.effort-cycle"],
enabled: canCycleEffort,
isActive: input?.isFocused,
priority: 200,
handle: () => {
if (!thinking || nextEffortId === null) return false;
useActionHandler(
"paseo/message-input.effort-cycle",
() => {
if (!thinking || nextEffortId === null) return { handled: false };
thinking.onSelect(nextEffortId);
return true;
},
});
return useShortcutKeys(canCycleEffort ? "cycle-effort" : null);
{ enabled: () => canCycleEffort && (input?.isFocused() ?? false) },
);
return useShortcutKeys(canCycleEffort ? "paseo/message-input.effort-cycle" : null);
}
/** The thinking select and the option controls, as the data `ComposerControl` draws. */
@@ -75,7 +75,7 @@ import {
useAgentControlCommandCenterActions,
type AgentControlCommandCenterSource,
} from "@/command-center/agent-control-registration";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import {
composerToolbarGeometry,
@@ -3,10 +3,8 @@ import { act, cleanup, render } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentMode } from "@getpaseo/protocol/agent-types";
import { ComposerKeyboardScopeProvider } from "@/composer/keyboard-scope";
import {
KeyboardActionDispatcherProvider,
useKeyboardActionDispatcher,
} from "@/keyboard/keyboard-action-dispatcher-context";
import { ActionRegistryProvider } from "@/actions";
import { createCoreRegistries, type CoreRegistries } from "@/core-actions";
import { useAgentModeCycleShortcut, type AgentModeControlValue } from "./mode-control";
beforeEach(() => vi.stubGlobal("React", React));
@@ -18,7 +16,7 @@ const MODES: AgentMode[] = [
{ id: "bypass", label: "Bypass" },
];
let dispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
let core: CoreRegistries | null = null;
// A composer's controls with no Mode control mounted, as a compact composer renders them while
// its settings drawer is closed.
@@ -29,7 +27,6 @@ function ComposerControlsProbe({
selectedModeId: string;
onSelectMode: (modeId: string) => void;
}) {
dispatcher = useKeyboardActionDispatcher();
const modeControl = useMemo<AgentModeControlValue>(
() => ({
provider: "claude",
@@ -46,8 +43,9 @@ function ComposerControlsProbe({
function renderComposer(input: { selectedModeId: string; isActiveComposer?: boolean }) {
const onSelectMode = vi.fn();
core = createCoreRegistries();
render(
<KeyboardActionDispatcherProvider>
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
<ComposerKeyboardScopeProvider
isPaneFocused
isActiveComposer={input.isActiveComposer ?? true}
@@ -55,16 +53,17 @@ function renderComposer(input: { selectedModeId: string; isActiveComposer?: bool
>
<ComposerControlsProbe selectedModeId={input.selectedModeId} onSelectMode={onSelectMode} />
</ComposerKeyboardScopeProvider>
</KeyboardActionDispatcherProvider>,
</ActionRegistryProvider>,
);
return onSelectMode;
}
function cycleMode(): boolean {
if (!dispatcher) throw new Error("The dispatcher is not mounted");
const registries = core;
if (!registries) throw new Error("The composer is not rendered");
let handled = false;
act(() => {
handled = dispatcher!.dispatch({ id: "message-input.mode-cycle", scope: "message-input" });
handled = registries.actions.dispatch("paseo/message-input.mode-cycle");
});
return handled;
}
@@ -10,9 +10,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { Shortcut } from "@/components/ui/shortcut";
import { formatAgentModeLabel } from "@/agent-controls/labels";
import { getAgentControlHintKey } from "@/composer/agent-controls/utils";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import { useShortcutKeys } from "@/keyboard";
import { useActionHandler } from "@/actions";
import { resolveNextAgentModeId } from "@/composer/agent-controls/mode";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { useComposerControlLayout } from "@/composer/agent-controls/layout-context";
@@ -89,7 +88,7 @@ export function AgentModeControl({
const { presentation } = useComposerControlLayout();
const { t } = useTranslation();
const { isActiveComposer } = useComposerKeyboardScope();
const cycleShortcutKeys = useShortcutKeys("cycle-agent-mode");
const cycleShortcutKeys = useShortcutKeys("paseo/message-input.mode-cycle");
const anchorRef = useRef<View>(null);
const openRef = useRef(false);
const [open, setOpen] = useState(false);
@@ -221,32 +220,23 @@ const EMPTY_MODES: AgentMode[] = [];
*/
export function useAgentModeCycleShortcut(modeControl: AgentModeControlValue | null | undefined) {
const { isActiveComposer } = useComposerKeyboardScope();
const handlerIdRef = useRef(`mode-cycle:${Math.random().toString(36).slice(2)}`);
const modeOptions = modeControl?.modeOptions ?? EMPTY_MODES;
const enabled =
isActiveComposer && modeControl != null && !modeControl.disabled && modeOptions.length > 1;
const handle = useCallback(
(action: KeyboardActionDefinition): boolean => {
if (action.id !== "message-input.mode-cycle" || !enabled || !modeControl) return false;
useActionHandler(
"paseo/message-input.mode-cycle",
() => {
if (!modeControl) return { handled: false };
const nextModeId = resolveNextAgentModeId({
modeOptions,
selectedMode: modeControl.selectedModeId,
});
if (!nextModeId) return false;
if (!nextModeId) return { handled: false };
modeControl.onSelectMode(nextModeId);
return true;
},
[enabled, modeControl, modeOptions],
{ enabled },
);
useKeyboardActionHandler({
handlerId: handlerIdRef.current,
actions: ["message-input.mode-cycle"],
enabled,
priority: 200,
handle,
});
}
function compareAvailableModes(a: AgentMode[], b: AgentMode[]): boolean {
@@ -29,7 +29,7 @@ import {
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
import { getAgentControlHintKey, shortModelLabel } from "./utils";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { useKeyboardToggle } from "@/hooks/use-keyboard-toggle";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ComposerControls, ControlTooltipHint } from "./composer-control";
+58 -102
View File
@@ -119,7 +119,7 @@ import { useVoiceOptional } from "@/contexts/voice-context";
import { useToast } from "@/contexts/toast-context";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { AutocompletePopover } from "@/components/ui/autocomplete-popover";
import type { AutocompleteOption } from "@/components/ui/autocomplete";
import { useAgentAutocomplete } from "@/hooks/use-agent-autocomplete";
@@ -145,10 +145,15 @@ import {
import { resolveAgentControlsMode } from "@/composer/agent-controls/mode";
import { resolveComposerInputMode, type ComposerInputMode } from "@/composer/input-mode";
import { useIsInputLive } from "./input/use-input-live";
import type { MessageInputKeyboardActionKind } from "./input/state";
import { resolveActiveSendBehavior } from "./input/state";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import {
type ActionDeclined,
type ActionInvocation,
ActionScope,
useActionHandler,
useActionScope,
} from "@/actions";
import { submitAgentInput } from "@/composer/submit";
import { ComposerRecall } from "@/composer/recall";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
@@ -249,10 +254,6 @@ function resolveIsVoiceModeForAgent(
return voice?.isVoiceModeForAgent(serverId, agentId) ?? false;
}
function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
return isMessageInputFocused ? 200 : 100;
}
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
return isWeb && !isMobile;
}
@@ -588,9 +589,18 @@ function focusMessageInputWithPlatformStrategy(messageInputRef: {
});
}
interface DispatchComposerKeyboardActionArgs {
action: KeyboardActionDefinition;
isPaneFocused: boolean;
const DECLINED: ActionDeclined = { handled: false };
const COMPOSER_KEYBOARD_ACTIONS = [
"paseo/agent.interrupt",
"paseo/message-input.focus",
"paseo/message-input.dictation-toggle",
"paseo/message-input.dictation-confirm",
"paseo/message-input.voice-toggle",
"paseo/message-input.voice-mute-toggle",
] as const;
interface ComposerKeyboardActionArgs {
messageInputRef: { current: MessageInputRef | null };
isAgentRunning: boolean;
isCancellingAgent: boolean;
@@ -599,10 +609,11 @@ interface DispatchComposerKeyboardActionArgs {
focusMessageInputForKeyboardAction: () => void;
}
function dispatchComposerKeyboardAction(args: DispatchComposerKeyboardActionArgs): boolean {
function runComposerKeyboardAction(
invocation: ActionInvocation,
args: ComposerKeyboardActionArgs,
): void | ActionDeclined {
const {
action,
isPaneFocused,
messageInputRef,
isAgentRunning,
isCancellingAgent,
@@ -610,83 +621,33 @@ function dispatchComposerKeyboardAction(args: DispatchComposerKeyboardActionArgs
handleCancelAgent,
focusMessageInputForKeyboardAction,
} = args;
if (!isPaneFocused) return false;
if (action.id === "agent.interrupt") {
if (messageInputRef.current?.runKeyboardAction("dictation-cancel")) return true;
if (!isAgentRunning || isCancellingAgent || !isConnected) return false;
if (invocation.actionId === "paseo/agent.interrupt") {
if (messageInputRef.current?.runKeyboardAction("dictation-cancel")) return;
if (!isAgentRunning || isCancellingAgent || !isConnected) return DECLINED;
handleCancelAgent();
return true;
return;
}
if (action.id === "message-input.focus") {
if (invocation.actionId === "paseo/message-input.focus") {
focusMessageInputForKeyboardAction();
return true;
return;
}
const passthroughAction = resolveMessageInputPassthroughAction(action.id);
if (!passthroughAction) return false;
const passthroughAction = resolveMessageInputPassthroughAction(invocation.actionId);
if (!passthroughAction) return DECLINED;
const result = messageInputRef.current?.runKeyboardAction(passthroughAction);
if (passthroughAction === "send" || passthroughAction === "dictation-confirm") {
return result ?? false;
}
return true;
if (passthroughAction === "dictation-confirm" && result !== true) return DECLINED;
}
function ComposerKeyboardRegistration({
messageInputRef,
isAgentRunning,
isCancellingAgent,
isConnected,
handleCancelAgent,
focusMessageInputForKeyboardAction,
isMessageInputFocused,
handlerId,
}: Omit<DispatchComposerKeyboardActionArgs, "action" | "isPaneFocused"> & {
isMessageInputFocused: boolean;
handlerId: string;
}) {
/** Runs the composer's keyboard actions; it sits inside the composer's action scope. */
function ComposerKeyboardRegistration(props: ComposerKeyboardActionArgs) {
const { isActiveComposer } = useComposerKeyboardScope();
const handleKeyboardAction = useCallback(
(action: KeyboardActionDefinition): boolean =>
dispatchComposerKeyboardAction({
action,
isPaneFocused: isActiveComposer,
messageInputRef,
isAgentRunning,
isCancellingAgent,
isConnected,
handleCancelAgent,
focusMessageInputForKeyboardAction,
}),
[
focusMessageInputForKeyboardAction,
handleCancelAgent,
isActiveComposer,
isAgentRunning,
isCancellingAgent,
isConnected,
messageInputRef,
],
useActionHandler(
COMPOSER_KEYBOARD_ACTIONS,
(invocation) => runComposerKeyboardAction(invocation, props),
{ enabled: isActiveComposer },
);
useKeyboardActionHandler({
handlerId,
actions: [
"agent.interrupt",
"message-input.focus",
"message-input.send",
"message-input.dictation-toggle",
"message-input.dictation-cancel",
"message-input.dictation-confirm",
"message-input.voice-toggle",
"message-input.voice-mute-toggle",
],
enabled: isActiveComposer,
priority: resolveKeyboardPriority(isMessageInputFocused),
isActive: () => isActiveComposer,
handle: handleKeyboardAction,
});
return null;
}
@@ -699,17 +660,13 @@ function resolveMessageInputPassthroughAction(
actionId: string,
): MessageInputKeyboardActionKind | null {
switch (actionId) {
case "message-input.send":
return "send";
case "message-input.dictation-confirm":
case "paseo/message-input.dictation-confirm":
return "dictation-confirm";
case "message-input.dictation-toggle":
case "paseo/message-input.dictation-toggle":
return "dictation-toggle";
case "message-input.dictation-cancel":
return "dictation-cancel";
case "message-input.voice-toggle":
case "paseo/message-input.voice-toggle":
return "voice-toggle";
case "message-input.voice-mute-toggle":
case "paseo/message-input.voice-mute-toggle":
return "voice-mute-toggle";
default:
return null;
@@ -1240,17 +1197,23 @@ export function Composer({ isPaneFocused, ...props }: ComposerProps) {
const commandCenterPanel = mobilePanelTarget === "agent-list" ? "agent" : mobilePanelTarget;
const coveredForCommandCenter =
isCompact && isMobilePanelCoveringHost(commandCenterPanel, paneHost);
const isActiveComposer = isPaneFocused && !coveredByOverlayPanel;
// Every active composer activates its own scope. The newest one, such as a
// New workspace draft over a running agent, is innermost and takes the keys.
const actionScope = useActionScope("paseo/composer", { active: isActiveComposer });
return (
<ComposerKeyboardScopeProvider
isPaneFocused={isPaneFocused}
isActiveComposer={isPaneFocused && !coveredByOverlayPanel}
isActiveComposer={isActiveComposer}
isCommandCenterTarget={isPaneFocused && !coveredForCommandCenter}
>
<OverlayDismissalScope>
<RenderProfile id="ComposerContent">
<ComposerContent {...props} />
</RenderProfile>
</OverlayDismissalScope>
<ActionScope activation={actionScope}>
<OverlayDismissalScope>
<RenderProfile id="ComposerContent">
<ComposerContent {...props} />
</RenderProfile>
</OverlayDismissalScope>
</ActionScope>
</ComposerKeyboardScopeProvider>
);
}
@@ -1314,8 +1277,8 @@ function ComposerContentImpl({
const toastErrorRef = useRef(toast.error);
toastErrorRef.current = toast.error;
const voice = useVoiceOptional();
const voiceToggleKeys = useShortcutKeys("voice-toggle");
const agentInterruptKeys = useShortcutKeys("agent-interrupt");
const voiceToggleKeys = useShortcutKeys("paseo/message-input.voice-toggle");
const agentInterruptKeys = useShortcutKeys("paseo/agent.interrupt");
const isDictationReady = useIsDictationReady({
serverId,
isConnected,
@@ -1449,7 +1412,6 @@ function ComposerContentImpl({
const editingSession = useComposerEditingSession(inputMode, providedEditingSession);
const isFullscreen = useComposerFullscreen(editingSession);
const [sendError, setSendError] = useState<string | null>(null);
const [isMessageInputFocused, setIsMessageInputFocused] = useState(false);
const [isGithubPickerOpen, setIsGithubPickerOpen] = useState(false);
const [githubSearchQuery, setGithubSearchQuery] = useState("");
const [lightboxMetadata, setLightboxMetadata] = useState<AttachmentMetadata | null>(null);
@@ -1474,9 +1436,6 @@ function ComposerContentImpl({
? installedPluginClientSlashCommands
: NO_PLUGIN_CLIENT_SLASH_COMMANDS;
const isComposerLocked = resolveIsComposerLocked(submitBehavior, isSubmitLoading);
const keyboardHandlerIdRef = useRef(
`message-input:${serverId}:${agentId}:${Math.random().toString(36).slice(2)}`,
);
const replaceUserInput = useCallback(
(text: string, selection?: { start: number; end: number }) => {
@@ -2477,7 +2436,6 @@ function ComposerContentImpl({
const handleFocusChange = useCallback(
(focused: boolean) => {
setIsMessageInputFocused(focused);
if (focused) {
onAttentionInputFocus?.();
}
@@ -2746,14 +2704,12 @@ function ComposerContentImpl({
return (
<>
<ComposerKeyboardRegistration
handlerId={keyboardHandlerIdRef.current}
messageInputRef={messageInputRef}
isAgentRunning={isAgentRunning}
isCancellingAgent={isCancellingAgent}
isConnected={isConnected}
handleCancelAgent={handleCancelAgent}
focusMessageInputForKeyboardAction={focusMessageInputForKeyboardAction}
isMessageInputFocused={isMessageInputFocused}
/>
<View
style={
+5 -5
View File
@@ -77,11 +77,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { useIosHardwareKeyboardSubmit } from "@/hooks/use-ios-hardware-keyboard-submit";
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -116,6 +115,7 @@ import {
runDefaultSendAction,
runMessageInputKeyboardAction,
stopRealtimeVoice,
type MessageInputKeyboardActionKind,
} from "./state";
const DEFAULT_SEND_KEYS: ShortcutKey[][] = [["Enter"]];
@@ -1386,9 +1386,9 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
const discGlyphSize = TOOLBAR_DISC_GLYPH_SIZES[controlSizing];
const toast = useToast();
const voice = useVoiceOptional();
const voiceMuteToggleKeys = useShortcutKeys("voice-mute-toggle");
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
const focusInputKeys = useShortcutKeys("focus-message-input");
const voiceMuteToggleKeys = useShortcutKeys("paseo/message-input.voice-mute-toggle");
const dictationToggleKeys = useShortcutKeys("paseo/message-input.dictation-toggle");
const focusInputKeys = useShortcutKeys("paseo/message-input.focus");
const [isInputFocused, setIsInputFocused] = useState(false);
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
// Web text is DOM-owned between deferred draft publications. The action button only needs
+13 -1
View File
@@ -2,7 +2,6 @@ import type { SendShortcut } from "@/hooks/use-settings";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type { MessagePayload, TextReplacement } from "@/composer/types";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
export type SendBehavior = ActiveTurnBehavior | "queue";
@@ -98,6 +97,19 @@ export function applyDictationTranscript(text: string, ctx: DictationTranscriptC
});
}
/** What the composer's keyboard actions ask the message input to do. */
export type MessageInputKeyboardActionKind =
| "focus"
| "send"
| "dictation-toggle"
| "dictation-cancel"
| "dictation-confirm"
| "voice-toggle"
| "voice-mute-toggle"
| "mode-cycle"
| "model-toggle"
| "effort-cycle";
interface MessageInputKeyboardActions {
focusInput: () => void;
isDictationRecording: () => boolean;
+11
View File
@@ -0,0 +1,11 @@
export { CoreActionsProvider, createCoreRegistries } from "./internal/provider";
export type { CoreRegistries } from "./internal/provider";
export { useAppShellActions } from "./internal/app-shell-actions";
export { buildShortcutSections } from "./internal/sections";
export { filterShortcutHelpSections } from "./internal/help-search";
export type { ShortcutRow, ShortcutSection } from "./internal/sections";
export {
getWorkspaceIndexJumpModifierKey,
getWorkspaceSwitcherCycleKey,
getWorkspaceSwitcherReleaseModifier,
} from "./internal/workspace-keys";
@@ -0,0 +1,102 @@
import type { ActionContext } from "@/actions";
interface CoreActionDefinition {
id: string;
title: string;
context?: ActionContext;
}
/**
* Every action Paseo itself registers. A shortcut, a Command Center row or a
* button dispatches one of these ids; a mounted surface attaches the handler,
* and the app shell supplies the `run` for the ones no surface owns.
*/
export const CORE_ACTIONS: readonly CoreActionDefinition[] = [
// App shell
{ id: "paseo/project.open", title: "Open project" },
{ id: "paseo/workspace.new", title: "New workspace" },
{ id: "paseo/command-center.toggle", title: "Toggle command center" },
{ id: "paseo/command-center.files", title: "Search files" },
{ id: "paseo/shortcuts-dialog.toggle", title: "Show keyboard shortcuts" },
{ id: "paseo/settings.toggle", title: "Toggle settings" },
{ id: "paseo/theme.cycle", title: "Cycle theme" },
{ id: "paseo/sidebar.toggle.left", title: "Toggle left sidebar" },
{ id: "paseo/sidebar.toggle.right", title: "Toggle right sidebar", context: "workspace" },
{ id: "paseo/sidebar.toggle.both", title: "Toggle both sidebars" },
{ id: "paseo/workspace.navigate.index", title: "Jump to workspace" },
{ id: "paseo/workspace.previous", title: "Previous workspace" },
{ id: "paseo/workspace.next", title: "Next workspace" },
{ id: "paseo/workspace.switcher.next", title: "Switch to recent workspace" },
{ id: "paseo/workspace.switcher.previous", title: "Switch to recent workspace (reverse)" },
{ id: "paseo/workspace.project.pick", title: "Switch project" },
// Workspace
{ id: "paseo/workspace.archive", title: "Archive workspace", context: "workspace" },
{ id: "paseo/workspace.archive.undo", title: "Undo archive workspace" },
{ id: "paseo/workspace.pin", title: "Pin chat", context: "workspace" },
{ id: "paseo/workspace.rename", title: "Rename workspace", context: "workspace" },
{ id: "paseo/workspace.setup.show", title: "Show setup", context: "workspace" },
{ id: "paseo/workspace.focus.toggle", title: "Toggle focus mode", context: "workspace" },
// Tabs
{ id: "paseo/workspace.tab.menu.open", title: "New tab", context: "workspace" },
{ id: "paseo/workspace.tab.target.agent", title: "New agent", context: "workspace" },
{ id: "paseo/workspace.tab.target.browser", title: "New browser", context: "workspace" },
{ id: "paseo/workspace.tab.target.changes", title: "Changes", context: "workspace" },
{ id: "paseo/workspace.tab.target.files", title: "Files", context: "workspace" },
{ id: "paseo/workspace.terminal.new", title: "New terminal", context: "workspace" },
{ id: "paseo/workspace.tab.close-current", title: "Close current tab", context: "workspace" },
{ id: "paseo/workspace.tab.navigate.index", title: "Jump to tab", context: "workspace" },
{ id: "paseo/workspace.tab.previous", title: "Previous tab", context: "workspace" },
{ id: "paseo/workspace.tab.next", title: "Next tab", context: "workspace" },
{ id: "paseo/workspace.tab.open.changes", title: "Open changes", context: "workspace" },
{ id: "paseo/workspace.tab.open.files", title: "Open files", context: "workspace" },
{ id: "paseo/workspace.tab.open.pull-request", title: "Open pull request", context: "workspace" },
{
id: "paseo/workspace.tab.open.pull-request.side-pane",
title: "Open pull request in side pane",
context: "workspace",
},
{
id: "paseo/workspace.tab.open.pull-request.focused-pane",
title: "Open pull request in focused pane",
context: "workspace",
},
{ id: "paseo/workspace.tab.rename-current", title: "Rename tab", context: "workspace" },
{ id: "paseo/workspace.tab.reload-current", title: "Reload agent", context: "workspace" },
{
id: "paseo/workspace.tab.copy-resume-command",
title: "Copy resume command",
context: "workspace",
},
{ id: "paseo/workspace.tab.copy-id", title: "Copy id", context: "workspace" },
{ id: "paseo/workspace.tab.copy-file-path", title: "Copy file path", context: "workspace" },
{ id: "paseo/workspace.tab.reveal-in-files", title: "Reveal in files", context: "workspace" },
{ id: "paseo/workspace.tab.close-left", title: "Close tabs to the left", context: "workspace" },
{ id: "paseo/workspace.tab.close-right", title: "Close tabs to the right", context: "workspace" },
{ id: "paseo/workspace.tab.close-others", title: "Close other tabs", context: "workspace" },
// Panes
{ id: "paseo/workspace.pane.split.right", title: "Split pane right", context: "workspace" },
{ id: "paseo/workspace.pane.split.down", title: "Split pane down", context: "workspace" },
{ id: "paseo/workspace.pane.focus.left", title: "Focus pane left", context: "workspace" },
{ id: "paseo/workspace.pane.focus.right", title: "Focus pane right", context: "workspace" },
{ id: "paseo/workspace.pane.focus.up", title: "Focus pane up", context: "workspace" },
{ id: "paseo/workspace.pane.focus.down", title: "Focus pane down", context: "workspace" },
{ id: "paseo/workspace.pane.move-tab.left", title: "Move tab left", context: "workspace" },
{ id: "paseo/workspace.pane.move-tab.right", title: "Move tab right", context: "workspace" },
{ id: "paseo/workspace.pane.move-tab.up", title: "Move tab up", context: "workspace" },
{ id: "paseo/workspace.pane.move-tab.down", title: "Move tab down", context: "workspace" },
{ id: "paseo/workspace.pane.close", title: "Close pane", context: "workspace" },
// Composer
{ id: "paseo/agent.interrupt", title: "Interrupt agent", context: "agent" },
{ id: "paseo/message-input.focus", title: "Focus message input", context: "agent" },
{ id: "paseo/message-input.model-toggle", title: "Toggle model picker", context: "agent" },
{ id: "paseo/message-input.effort-cycle", title: "Cycle effort", context: "agent" },
{ id: "paseo/message-input.mode-cycle", title: "Cycle agent mode", context: "agent" },
{ id: "paseo/message-input.voice-toggle", title: "Toggle voice mode", context: "agent" },
{ id: "paseo/message-input.voice-mute-toggle", title: "Mute voice mode", context: "agent" },
{ id: "paseo/message-input.dictation-toggle", title: "Start/stop dictation", context: "agent" },
{ id: "paseo/message-input.dictation-confirm", title: "Confirm dictation", context: "agent" },
];
@@ -0,0 +1,90 @@
import { useEffect, useRef } from "react";
import { usePathname, useRouter } from "expo-router";
import { useActionHandler, useActionRegistry, useActionScope } from "@/actions";
import { getDisplayPlatform, useKeybindings } from "@/keyboard";
import { useOpenAddProject } from "@/hooks/use-open-add-project";
import {
type ActiveWorkspaceSelection,
getLastWorkspaceSelection,
navigateToLastWorkspace,
navigateToWorkspace,
useActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { triggerWorkspaceSwitcherCycle } from "@/workspace-switcher";
import { type AppShell, createAppShellRuns, returnFromSettings } from "./app-shell-runs";
import { useCoreActionRuns } from "./provider";
import { getWorkspaceSwitcherReleaseModifier } from "./workspace-keys";
/**
* Supplies the app shell's `run` for the core actions no screen owns, and
* takes Escape on desktop Settings.
*/
export function useAppShellActions({
isMobile,
toggleAgentList,
cycleTheme,
}: {
isMobile: boolean;
toggleAgentList: () => void;
cycleTheme: () => void;
}): void {
const actions = useActionRegistry();
const bindings = useKeybindings();
const pathname = usePathname();
const router = useRouter();
const openProjectPicker = useOpenAddProject();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
// The workspace the last jump went to, ahead of the route catching up, so
// repeated next/previous presses step from it.
const jumpedWorkspaceRef = useRef<ActiveWorkspaceSelection | null>(null);
useEffect(() => {
if (activeWorkspaceSelection) {
jumpedWorkspaceRef.current = activeWorkspaceSelection;
}
}, [activeWorkspaceSelection]);
const shell: AppShell = {
pathname: () => pathname,
isMobile: () => isMobile,
router: {
push: (route) => router.push(route as Parameters<typeof router.push>[0]),
replace: (route) => router.replace(route as Parameters<typeof router.replace>[0]),
back: () => router.back(),
},
selectedWorkspace: () => jumpedWorkspaceRef.current ?? activeWorkspaceSelection,
navigateToWorkspace: (target) => {
jumpedWorkspaceRef.current = target;
navigateToWorkspace(target);
},
navigateToLastWorkspace,
cycleWorkspaceSwitcher: (delta) => {
const currentWorkspace = activeWorkspaceSelection
? (getLastWorkspaceSelection() ?? activeWorkspaceSelection)
: null;
const releaseModifier = getWorkspaceSwitcherReleaseModifier({
delta,
platform: getDisplayPlatform(),
bindings,
});
return triggerWorkspaceSwitcherCycle({ delta, releaseModifier, currentWorkspace });
},
openProjectPicker: () => {
void openProjectPicker();
},
toggleAgentList,
cycleTheme,
dispatch: (actionId) => actions.dispatch(actionId),
};
useCoreActionRuns(createAppShellRuns(shell));
// Escape on desktop Settings goes back to the workspace. The workspace's
// composer stays mounted and active under Settings, so Settings activates
// the innermost scope while it shows.
const isDesktopSettings = pathname.startsWith("/settings") && !isMobile;
const settingsScope = useActionScope("paseo/settings", { active: isDesktopSettings });
useActionHandler("paseo/agent.interrupt", () => returnFromSettings(shell), {
scope: settingsScope,
});
}
@@ -0,0 +1,271 @@
import { beforeEach, describe, expect, it } from "vitest";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import type { SidebarShortcutWorkspaceTarget } from "@/utils/sidebar-shortcuts";
import { createAppShellRuns, type AppShell } from "./app-shell-runs";
import { createCoreRegistries } from "./provider";
const SIDEBAR_TARGETS = [
{ serverId: "srv", workspaceId: "ws-1" },
{ serverId: "srv", workspaceId: "ws-2" },
{ serverId: "srv", workspaceId: "ws-3" },
{ serverId: "srv", workspaceId: "ws-4" },
{ serverId: "srv", workspaceId: "ws-5" },
] as const;
const STATUS_VISUAL_TARGETS = [
{ serverId: "srv", workspaceId: "needs-input" },
{ serverId: "srv", workspaceId: "running-new" },
{ serverId: "srv", workspaceId: "running-old" },
{ serverId: "srv", workspaceId: "done" },
] as const;
interface ShellState {
pathname?: string;
isMobile?: boolean;
selectedWorkspace?: SidebarShortcutWorkspaceTarget | null;
sidebarTargets?: readonly SidebarShortcutWorkspaceTarget[];
hasLastWorkspace?: boolean;
switcherTakesStep?: boolean;
projectPickerHost?: boolean;
}
/** The core registries with the app shell's runs behind them, recording what the shell did. */
function createShell(state: ShellState = {}) {
const did: unknown[] = [];
useKeyboardShortcutsStore.setState({
sidebarShortcutWorkspaceTargets: [...(state.sidebarTargets ?? SIDEBAR_TARGETS)],
});
const shell: AppShell = {
pathname: () => state.pathname ?? "/h/srv/workspace/ws-2",
isMobile: () => state.isMobile ?? false,
router: {
push: (route) => did.push(["router-push", route]),
replace: (route) => did.push(["router-replace", route]),
back: () => did.push(["router-back"]),
},
selectedWorkspace: () => state.selectedWorkspace ?? null,
navigateToWorkspace: (target) => did.push(["navigate-workspace", target]),
navigateToLastWorkspace: () => {
did.push(["navigate-last-workspace"]);
return state.hasLastWorkspace ?? true;
},
cycleWorkspaceSwitcher: (delta) => {
did.push(["workspace-switcher-cycle", delta]);
return state.switcherTakesStep ?? true;
},
openProjectPicker: () => did.push(["open-project-picker"]),
toggleAgentList: () => did.push(["toggle-agent-list"]),
cycleTheme: () => did.push(["cycle-theme"]),
dispatch: (actionId) => core.actions.dispatch(actionId),
};
const core = createCoreRegistries(createAppShellRuns(shell));
if (state.projectPickerHost) {
core.actions.registerHandler("paseo/workspace.project.pick", () => {
did.push(["project-pick"]);
});
}
return { actions: core.actions, did };
}
beforeEach(() => {
useKeyboardShortcutsStore.setState({
commandCenterOpen: false,
shortcutsDialogOpen: false,
sidebarShortcutWorkspaceTargets: [],
});
});
describe("workspace.navigate.index", () => {
it("navigates to the sidebar target at index-1", () => {
const { actions, did } = createShell();
expect(actions.dispatch("paseo/workspace.navigate.index", { index: 4 })).toBe(true);
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-4" }]]);
});
it("declines when the target index is out of range", () => {
const { actions, did } = createShell();
expect(actions.dispatch("paseo/workspace.navigate.index", { index: 99 })).toBe(false);
expect(did).toEqual([]);
});
it("declines when no index arrives", () => {
const { actions, did } = createShell();
expect(actions.dispatch("paseo/workspace.navigate.index")).toBe(false);
expect(did).toEqual([]);
});
it("declines when there are no sidebar targets", () => {
const { actions, did } = createShell({ sidebarTargets: [] });
expect(actions.dispatch("paseo/workspace.navigate.index", { index: 1 })).toBe(false);
expect(did).toEqual([]);
});
});
describe("workspace.next and workspace.previous", () => {
function step(actionId: "paseo/workspace.next" | "paseo/workspace.previous", state: ShellState) {
const { actions, did } = createShell(state);
const handled = actions.dispatch(actionId);
return { handled, did };
}
it("uses the retained navigation workspace selection over a stale pathname", () => {
const { did } = step("paseo/workspace.next", {
pathname: "/h/srv/workspace/ws-2",
selectedWorkspace: { serverId: "srv", workspaceId: "ws-4" },
});
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-5" }]]);
});
it("moves from status row 2 to row 3 using status visual target order", () => {
const { did } = step("paseo/workspace.next", {
pathname: "/h/srv/workspace/ui-expose-archive-worktrees-on-merge",
sidebarTargets: STATUS_VISUAL_TARGETS,
selectedWorkspace: { serverId: "srv", workspaceId: "running-new" },
});
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "running-old" }]]);
});
it("moves backward from status row 2 to row 1 using status visual target order", () => {
const { did } = step("paseo/workspace.previous", {
pathname: "/h/srv/workspace/ui-expose-archive-worktrees-on-merge",
sidebarTargets: STATUS_VISUAL_TARGETS,
selectedWorkspace: { serverId: "srv", workspaceId: "running-new" },
});
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "needs-input" }]]);
});
it("moves backward from status row 3 to row 2 using status visual target order", () => {
const { did } = step("paseo/workspace.previous", {
pathname: "/h/srv/workspace/running-old",
sidebarTargets: STATUS_VISUAL_TARGETS,
selectedWorkspace: { serverId: "srv", workspaceId: "running-old" },
});
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "running-new" }]]);
});
it("falls back to the pathname workspace when no retained selection exists", () => {
const { did } = step("paseo/workspace.previous", { pathname: "/h/srv/workspace/ws-3" });
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-2" }]]);
});
it("wraps from the last target forward to the first", () => {
const { did } = step("paseo/workspace.next", {
selectedWorkspace: { serverId: "srv", workspaceId: "ws-5" },
});
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-1" }]]);
});
it("declines when there are no sidebar targets", () => {
const { handled, did } = step("paseo/workspace.next", { sidebarTargets: [] });
expect(handled).toBe(false);
expect(did).toEqual([]);
});
it("falls back to the first target when the current workspace is not in the sidebar", () => {
const { did } = step("paseo/workspace.next", {
pathname: "/settings/general",
selectedWorkspace: { serverId: "other", workspaceId: "ws-x" },
});
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-1" }]]);
});
});
describe("settings.toggle", () => {
it("pushes to the settings root when not currently in settings", () => {
const { actions, did } = createShell({ pathname: "/h/srv/workspace/ws-2" });
actions.dispatch("paseo/settings.toggle");
expect(did).toEqual([["router-push", "/settings"]]);
});
it("navigates to the last workspace when leaving settings on desktop", () => {
const { actions, did } = createShell({ pathname: "/settings/general", isMobile: false });
actions.dispatch("paseo/settings.toggle");
expect(did).toEqual([["navigate-last-workspace"]]);
});
it("opens the project picker route when there is no workspace to return to", () => {
const { actions, did } = createShell({
pathname: "/settings/general",
hasLastWorkspace: false,
});
actions.dispatch("paseo/settings.toggle");
expect(did).toEqual([["navigate-last-workspace"], ["router-replace", "/open-project"]]);
});
it("falls back to router.back() on mobile", () => {
const { actions, did } = createShell({ pathname: "/settings/general", isMobile: true });
actions.dispatch("paseo/settings.toggle");
expect(did).toEqual([["router-back"]]);
});
});
describe("callbacks and pickers", () => {
it.each([
["paseo/sidebar.toggle.left", "toggle-agent-list"],
["paseo/sidebar.toggle.both", "toggle-agent-list"],
["paseo/theme.cycle", "cycle-theme"],
["paseo/project.open", "open-project-picker"],
] as const)("%s → %s", (actionId, effect) => {
const { actions, did } = createShell();
expect(actions.dispatch(actionId)).toBe(true);
expect(did).toEqual([[effect]]);
});
});
describe("toggle dialogs", () => {
it("opens the command center directly into the files sub-list from a workspace", () => {
const { actions } = createShell();
actions.dispatch("paseo/command-center.files");
const store = useKeyboardShortcutsStore.getState();
expect(store.commandCenterOpen).toBe(true);
expect(store.commandCenterSublist?.id).toBe("files");
});
it("leaves the file-search shortcut to the project-picker host outside a workspace", () => {
const { actions, did } = createShell({ pathname: "/settings", projectPickerHost: true });
expect(actions.dispatch("paseo/command-center.files")).toBe(true);
expect(did).toEqual([["project-pick"]]);
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(false);
});
it("opens the command center when closed and closes it when open", () => {
const { actions } = createShell();
actions.dispatch("paseo/command-center.toggle");
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(true);
actions.dispatch("paseo/command-center.toggle");
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(false);
});
it("toggles the shortcuts dialog", () => {
const { actions } = createShell();
actions.dispatch("paseo/shortcuts-dialog.toggle");
expect(useKeyboardShortcutsStore.getState().shortcutsDialogOpen).toBe(true);
actions.dispatch("paseo/shortcuts-dialog.toggle");
expect(useKeyboardShortcutsStore.getState().shortcutsDialogOpen).toBe(false);
});
});
describe("workspace switcher", () => {
it("steps forward and backward", () => {
const { actions, did } = createShell();
actions.dispatch("paseo/workspace.switcher.next");
actions.dispatch("paseo/workspace.switcher.previous");
expect(did).toEqual([
["workspace-switcher-cycle", 1],
["workspace-switcher-cycle", -1],
]);
});
it("declines when the switcher does not take the step", () => {
const { actions } = createShell({ switcherTakesStep: false });
expect(actions.dispatch("paseo/workspace.switcher.next")).toBe(false);
});
});
describe("unknown actions", () => {
it("dispatches nothing for an id no one registered", () => {
const { actions, did } = createShell();
expect(actions.dispatch("totally.made.up")).toBe(false);
expect(did).toEqual([]);
});
});
@@ -0,0 +1,120 @@
import type { ActionDeclined } from "@/actions";
import { COMMAND_CENTER_FILES_SUBLIST_ID } from "@/command-center/sublist";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import {
buildOpenProjectRoute,
buildSettingsRoute,
parseHostWorkspaceRouteFromPathname,
} from "@/utils/host-routes";
import {
getRelativeSidebarShortcutTarget,
type SidebarShortcutWorkspaceTarget,
} from "@/utils/sidebar-shortcuts";
import type { CoreActionRuns } from "./provider";
const DECLINED: ActionDeclined = { handled: false };
/** What the app shell's actions act on: the route, navigation, and the shell's own toggles. */
export interface AppShell {
pathname(): string;
isMobile(): boolean;
router: {
push(route: string): void;
replace(route: string): void;
back(): void;
};
/** The workspace navigation last selected, which can be ahead of the route. */
selectedWorkspace(): SidebarShortcutWorkspaceTarget | null;
navigateToWorkspace(target: SidebarShortcutWorkspaceTarget): void;
/** Returns whether there was a workspace to go back to. */
navigateToLastWorkspace(): boolean;
/** Returns whether the switcher took the step. */
cycleWorkspaceSwitcher(delta: 1 | -1): boolean;
openProjectPicker(): void;
toggleAgentList(): void;
cycleTheme(): void;
dispatch(actionId: string): boolean;
}
/**
* The app shell's `run` for the core actions no screen owns: navigation,
* global toggles, and the fallbacks a focused workspace declines.
*/
export function createAppShellRuns(shell: AppShell): CoreActionRuns {
function sidebarTargets(): readonly SidebarShortcutWorkspaceTarget[] {
return useKeyboardShortcutsStore.getState().sidebarShortcutWorkspaceTargets;
}
function jumpTo(target: SidebarShortcutWorkspaceTarget | null): void | ActionDeclined {
if (!target) return DECLINED;
shell.navigateToWorkspace({ serverId: target.serverId, workspaceId: target.workspaceId });
}
function jumpRelative(delta: 1 | -1): void | ActionDeclined {
const targets = sidebarTargets();
if (targets.length === 0) return DECLINED;
const current =
shell.selectedWorkspace() ?? parseHostWorkspaceRouteFromPathname(shell.pathname());
return jumpTo(
getRelativeSidebarShortcutTarget({
targets,
currentTarget: current
? { serverId: current.serverId, workspaceId: current.workspaceId }
: null,
delta,
}),
);
}
function cycleSwitcher(delta: 1 | -1): void | ActionDeclined {
return shell.cycleWorkspaceSwitcher(delta) ? undefined : DECLINED;
}
return {
"paseo/project.open": () => shell.openProjectPicker(),
"paseo/settings.toggle": () => {
if (!shell.pathname().startsWith("/settings")) {
shell.router.push(buildSettingsRoute());
} else if (!shell.isMobile()) {
returnFromSettings(shell);
} else {
shell.router.back();
}
},
"paseo/command-center.toggle": () => {
const store = useKeyboardShortcutsStore.getState();
store.setCommandCenterOpen(!store.commandCenterOpen);
},
"paseo/command-center.files": () => {
if (!parseHostWorkspaceRouteFromPathname(shell.pathname())) {
return shell.dispatch("paseo/workspace.project.pick") ? undefined : DECLINED;
}
useKeyboardShortcutsStore
.getState()
.setCommandCenterOpen(true, { sublistId: COMMAND_CENTER_FILES_SUBLIST_ID });
},
"paseo/shortcuts-dialog.toggle": () => {
const store = useKeyboardShortcutsStore.getState();
store.setShortcutsDialogOpen(!store.shortcutsDialogOpen);
},
"paseo/theme.cycle": () => shell.cycleTheme(),
// A focused workspace takes both sidebars first; elsewhere only the agent list exists.
"paseo/sidebar.toggle.left": () => shell.toggleAgentList(),
"paseo/sidebar.toggle.both": () => shell.toggleAgentList(),
"paseo/workspace.navigate.index": ({ index }) => {
if (index === undefined) return DECLINED;
return jumpTo(sidebarTargets()[index - 1] ?? null);
},
"paseo/workspace.previous": () => jumpRelative(-1),
"paseo/workspace.next": () => jumpRelative(1),
"paseo/workspace.switcher.next": () => cycleSwitcher(1),
"paseo/workspace.switcher.previous": () => cycleSwitcher(-1),
};
}
/** Leaves Settings for the workspace it was opened from, or the project picker. */
export function returnFromSettings(shell: Pick<AppShell, "navigateToLastWorkspace" | "router">) {
if (!shell.navigateToLastWorkspace()) {
shell.router.replace(buildOpenProjectRoute());
}
}
@@ -0,0 +1,588 @@
import type { KeybindingInput } from "@/keyboard";
/**
* Paseo's default shortcuts, in resolution order: among bindings that match
* the same key in the same context, the earlier one wins. Binding ids key the
* user's stored overrides, so an id never changes once shipped.
*/
export const CORE_BINDINGS: readonly KeybindingInput[] = [
// --- Open project ---
// Open project moved from Cmd+Shift+O to Cmd+O. The binding ids intentionally
// keep their original "cmd-shift-o" / "ctrl-shift-o" names: user shortcut
// overrides are keyed by binding id, so renaming them would silently drop a
// user's customized Open project shortcut on upgrade.
{
id: "agent-new-cmd-shift-o-mac",
actionId: "paseo/project.open",
combo: "Cmd+O",
when: { mac: true },
},
{
id: "agent-new-ctrl-shift-o-non-mac",
actionId: "paseo/project.open",
combo: "Ctrl+O",
when: { mac: false, terminal: false },
},
// --- New workspace ---
{
id: "workspace-new-cmd-n-mac",
actionId: "paseo/workspace.new",
combo: "Cmd+N",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-new-ctrl-n-non-mac",
actionId: "paseo/workspace.new",
combo: "Ctrl+N",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Search files (switch project on the New Workspace screen) ---
{
id: "workspace-project-pick-cmd-p-mac",
actionId: "paseo/command-center.files",
combo: "Cmd+P",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-project-pick-ctrl-p-non-mac",
actionId: "paseo/command-center.files",
combo: "Ctrl+P",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Archive workspace ---
// COMPAT(workspaceArchiveShortcutOverride): added in v0.1.106; remove after
// 2027-01-11 with a stored-override migration. Keeps existing custom chords.
{
id: "worktree-archive-cmd-shift-backspace-mac",
actionId: "paseo/workspace.archive",
combo: "Cmd+Shift+Backspace",
when: { mac: true, commandCenter: false },
},
// COMPAT(workspaceArchiveShortcutOverride): added in v0.1.106; remove after
// 2027-01-11 with a stored-override migration. Keeps existing custom chords.
{
id: "worktree-archive-ctrl-shift-backspace-non-mac",
actionId: "paseo/workspace.archive",
combo: "Ctrl+Shift+Backspace",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Undo archive workspace ---
// Only claims the key while an archive can be undone; otherwise text undo runs as usual.
{
id: "workspace-archive-undo-cmd-z-mac",
actionId: "paseo/workspace.archive.undo",
combo: "Cmd+Z",
when: { mac: true, commandCenter: false, editable: false, terminal: false },
},
{
id: "workspace-archive-undo-ctrl-z-non-mac",
actionId: "paseo/workspace.archive.undo",
combo: "Ctrl+Z",
when: { mac: false, commandCenter: false, editable: false, terminal: false },
},
// --- Pin workspace ---
{
id: "workspace-pin-cmd-shift-p-mac",
actionId: "paseo/workspace.pin",
combo: "Cmd+Shift+P",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pin-ctrl-shift-p-non-mac",
actionId: "paseo/workspace.pin",
combo: "Ctrl+Shift+P",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Tab management ---
{
id: "workspace-tab-new-cmd-t-mac",
actionId: "paseo/workspace.tab.menu.open",
combo: "Cmd+T",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-tab-new-ctrl-t-non-mac",
actionId: "paseo/workspace.tab.menu.open",
combo: "Ctrl+T",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "workspace-tab-target-agent-cmd-shift-a-mac",
actionId: "paseo/workspace.tab.target.agent",
combo: "Cmd+Shift+A",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-tab-target-agent-ctrl-shift-a-non-mac",
actionId: "paseo/workspace.tab.target.agent",
combo: "Ctrl+Shift+A",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "workspace-tab-target-browser-cmd-shift-b-mac",
actionId: "paseo/workspace.tab.target.browser",
combo: "Cmd+Shift+B",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-tab-target-browser-ctrl-shift-b-non-mac",
actionId: "paseo/workspace.tab.target.browser",
combo: "Ctrl+Shift+B",
when: { mac: false, commandCenter: false, terminal: false },
},
// Keep the binding id stable so saved overrides from the former Cmd+Shift+C default survive.
{
id: "workspace-tab-target-changes-cmd-shift-c-mac",
actionId: "paseo/workspace.tab.target.changes",
combo: "Cmd+Shift+G",
when: { mac: true, commandCenter: false },
},
// Keep the binding id stable so saved overrides from the former Ctrl+Shift+C default survive.
{
id: "workspace-tab-target-changes-ctrl-shift-c-non-mac",
actionId: "paseo/workspace.tab.target.changes",
combo: "Ctrl+Shift+G",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "workspace-tab-target-files-cmd-shift-e-mac",
actionId: "paseo/workspace.tab.target.files",
combo: "Cmd+Shift+E",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-tab-target-files-ctrl-shift-e-non-mac",
actionId: "paseo/workspace.tab.target.files",
combo: "Ctrl+Shift+E",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "workspace-tab-close-current-cmd-w-mac",
actionId: "paseo/workspace.tab.close-current",
combo: "Cmd+W",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-tab-close-current-ctrl-w-non-mac",
actionId: "paseo/workspace.tab.close-current",
combo: "Ctrl+W",
when: { mac: false, desktop: true, commandCenter: false, terminal: false },
},
{
id: "workspace-tab-close-current-alt-shift-w-web",
actionId: "paseo/workspace.tab.close-current",
combo: "Alt+Shift+W",
when: { desktop: false, commandCenter: false },
},
// --- Workspace index jump ---
{
id: "workspace-navigate-index-cmd-digit-mac",
actionId: "paseo/workspace.navigate.index",
combo: "Cmd+Digit",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-navigate-index-ctrl-digit-non-mac",
actionId: "paseo/workspace.navigate.index",
combo: "Ctrl+Digit",
when: { mac: false, desktop: true, commandCenter: false, terminal: false },
},
{
id: "workspace-navigate-index-alt-digit-web",
actionId: "paseo/workspace.navigate.index",
combo: "Alt+Digit",
when: { desktop: false, commandCenter: false },
},
// --- Tab index jump ---
{
id: "workspace-tab-navigate-index-cmd-alt-digit-mac-desktop",
actionId: "paseo/workspace.tab.navigate.index",
combo: "Cmd+Alt+Digit",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-tab-navigate-index-alt-digit-desktop",
actionId: "paseo/workspace.tab.navigate.index",
combo: "Alt+Digit",
when: { mac: false, desktop: true, commandCenter: false },
},
{
id: "workspace-tab-navigate-index-alt-shift-digit-web",
actionId: "paseo/workspace.tab.navigate.index",
combo: "Alt+Shift+Digit",
when: { desktop: false, commandCenter: false },
},
// --- Workspace relative navigation ---
{
id: "workspace-navigate-relative-cmd-left-mac",
actionId: "paseo/workspace.previous",
combo: "Cmd+[",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-navigate-relative-ctrl-left-non-mac",
actionId: "paseo/workspace.previous",
combo: "Ctrl+[",
when: { mac: false, desktop: true, commandCenter: false, terminal: false },
},
{
id: "workspace-navigate-relative-cmd-right-mac",
actionId: "paseo/workspace.next",
combo: "Cmd+]",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-navigate-relative-ctrl-right-non-mac",
actionId: "paseo/workspace.next",
combo: "Ctrl+]",
when: { mac: false, desktop: true, commandCenter: false, terminal: false },
},
{
id: "workspace-navigate-relative-alt-left-web",
actionId: "paseo/workspace.previous",
combo: "Alt+[",
when: { desktop: false, commandCenter: false },
},
{
id: "workspace-navigate-relative-alt-right-web",
actionId: "paseo/workspace.next",
combo: "Alt+]",
when: { desktop: false, commandCenter: false },
},
// --- Fast MRU workspace switcher ---
// Physical Ctrl+Tab / Ctrl+Shift+Tab on all desktop OSes (macOS, Windows, Linux), including
// terminal focus. Web browsers reserve Ctrl+Tab, so web uses Alt+` / Alt+Shift+` in Paseo's
// existing Alt+* workspace namespace.
{
id: "workspace-switcher-next-ctrl-tab-desktop",
actionId: "paseo/workspace.switcher.next",
combo: "Ctrl+Tab",
when: { desktop: true, commandCenter: false },
holdRelease: true,
},
{
id: "workspace-switcher-prev-ctrl-shift-tab-desktop",
actionId: "paseo/workspace.switcher.previous",
combo: "Ctrl+Shift+Tab",
when: { desktop: true, commandCenter: false },
holdRelease: true,
},
{
id: "workspace-switcher-next-alt-backquote-web",
actionId: "paseo/workspace.switcher.next",
combo: "Alt+`",
when: { desktop: false, commandCenter: false },
holdRelease: true,
},
{
id: "workspace-switcher-prev-alt-shift-backquote-web",
actionId: "paseo/workspace.switcher.previous",
combo: "Alt+Shift+`",
when: { desktop: false, commandCenter: false },
holdRelease: true,
},
// --- Tab relative navigation ---
// macOS desktop uses Cmd+Shift+brackets; the browser owns those keys, so
// macOS web keeps Alt+Shift alongside every non-mac platform.
{
id: "workspace-tab-navigate-relative-cmd-shift-left-mac",
actionId: "paseo/workspace.tab.previous",
combo: "Cmd+Shift+[",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-tab-navigate-relative-cmd-shift-right-mac",
actionId: "paseo/workspace.tab.next",
combo: "Cmd+Shift+]",
when: { mac: true, desktop: true, commandCenter: false },
},
{
id: "workspace-tab-navigate-relative-alt-shift-left",
actionId: "paseo/workspace.tab.previous",
combo: "Alt+Shift+[",
when: { mac: false, commandCenter: false },
},
{
id: "workspace-tab-navigate-relative-alt-shift-right",
actionId: "paseo/workspace.tab.next",
combo: "Alt+Shift+]",
when: { mac: false, commandCenter: false },
},
{
id: "workspace-tab-navigate-relative-alt-shift-left-mac-web",
actionId: "paseo/workspace.tab.previous",
combo: "Alt+Shift+[",
when: { mac: true, desktop: false, commandCenter: false },
},
{
id: "workspace-tab-navigate-relative-alt-shift-right-mac-web",
actionId: "paseo/workspace.tab.next",
combo: "Alt+Shift+]",
when: { mac: true, desktop: false, commandCenter: false },
},
// --- Pane management (mac only) ---
{
id: "workspace-pane-split-right-cmd-backslash",
actionId: "paseo/workspace.pane.split.right",
combo: "Cmd+\\",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pane-split-down-cmd-shift-backslash",
actionId: "paseo/workspace.pane.split.down",
combo: "Cmd+Shift+\\",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pane-focus-left-cmd-shift-left",
actionId: "paseo/workspace.pane.focus.left",
combo: "Cmd+Shift+ArrowLeft",
when: { mac: true, commandCenter: false, editable: false },
},
{
id: "workspace-pane-focus-right-cmd-shift-right",
actionId: "paseo/workspace.pane.focus.right",
combo: "Cmd+Shift+ArrowRight",
when: { mac: true, commandCenter: false, editable: false },
},
{
id: "workspace-pane-focus-up-cmd-shift-up",
actionId: "paseo/workspace.pane.focus.up",
combo: "Cmd+Shift+ArrowUp",
when: { mac: true, commandCenter: false, editable: false },
},
{
id: "workspace-pane-focus-down-cmd-shift-down",
actionId: "paseo/workspace.pane.focus.down",
combo: "Cmd+Shift+ArrowDown",
when: { mac: true, commandCenter: false, editable: false },
},
{
id: "workspace-pane-move-tab-left-cmd-shift-alt-left",
actionId: "paseo/workspace.pane.move-tab.left",
combo: "Cmd+Alt+Shift+ArrowLeft",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pane-move-tab-right-cmd-shift-alt-right",
actionId: "paseo/workspace.pane.move-tab.right",
combo: "Cmd+Alt+Shift+ArrowRight",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pane-move-tab-up-cmd-shift-alt-up",
actionId: "paseo/workspace.pane.move-tab.up",
combo: "Cmd+Alt+Shift+ArrowUp",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pane-move-tab-down-cmd-shift-alt-down",
actionId: "paseo/workspace.pane.move-tab.down",
combo: "Cmd+Alt+Shift+ArrowDown",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-pane-close-cmd-shift-w",
actionId: "paseo/workspace.pane.close",
combo: "Cmd+Shift+W",
when: { mac: true, commandCenter: false },
},
// --- New terminal ---
{
id: "workspace-terminal-new-cmd-shift-t-mac",
actionId: "paseo/workspace.terminal.new",
combo: "Cmd+Shift+T",
when: { mac: true, commandCenter: false },
},
{
id: "workspace-terminal-new-ctrl-shift-t-non-mac",
actionId: "paseo/workspace.terminal.new",
combo: "Ctrl+Shift+T",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Command center ---
{
id: "command-center-toggle-cmd-k-mac",
actionId: "paseo/command-center.toggle",
combo: "Cmd+K",
when: { mac: true },
},
{
id: "command-center-toggle-ctrl-k-non-mac",
actionId: "paseo/command-center.toggle",
combo: "Ctrl+K",
when: { mac: false, terminal: false },
},
// --- Keyboard shortcuts dialog ---
{
id: "shortcuts-dialog-toggle-question-mark",
actionId: "paseo/shortcuts-dialog.toggle",
combo: "Shift+?",
repeat: false,
when: { focusScope: "other" },
},
// --- Sidebar toggles ---
{
id: "sidebar-toggle-left-mac-cmd-b",
actionId: "paseo/sidebar.toggle.left",
combo: "Cmd+B",
when: { mac: true },
},
{
id: "sidebar-toggle-left-ctrl-period-non-mac",
actionId: "paseo/sidebar.toggle.left",
combo: "Ctrl+B",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "sidebar-toggle-right-cmd-e-mac",
actionId: "paseo/sidebar.toggle.right",
combo: "Cmd+E",
when: { mac: true, commandCenter: false },
},
{
id: "sidebar-toggle-right-ctrl-e-non-mac",
actionId: "paseo/sidebar.toggle.right",
combo: "Ctrl+E",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "sidebar-toggle-right-ctrl-backquote",
actionId: "paseo/sidebar.toggle.right",
combo: "Ctrl+`",
when: { commandCenter: false },
},
// --- Toggle both sidebars ---
{
id: "sidebar-toggle-both-cmd-period-mac",
actionId: "paseo/sidebar.toggle.both",
combo: "Cmd+.",
when: { mac: true, commandCenter: false },
},
{
id: "sidebar-toggle-both-ctrl-period-non-mac",
actionId: "paseo/sidebar.toggle.both",
combo: "Ctrl+.",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Settings toggle ---
{
id: "settings-toggle-cmd-comma-mac",
actionId: "paseo/settings.toggle",
combo: "Cmd+,",
when: { mac: true, commandCenter: false },
},
{
id: "settings-toggle-ctrl-comma-non-mac",
actionId: "paseo/settings.toggle",
combo: "Ctrl+,",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Focus mode ---
{
id: "view-toggle-focus-cmd-shift-f-mac",
actionId: "paseo/workspace.focus.toggle",
combo: "Cmd+Shift+F",
when: { mac: true, commandCenter: false },
},
{
id: "view-toggle-focus-ctrl-shift-f-non-mac",
actionId: "paseo/workspace.focus.toggle",
combo: "Ctrl+Shift+F",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Theme cycling ---
{
id: "theme-cycle-cmd-shift-t-mac",
actionId: "paseo/theme.cycle",
combo: "Cmd+Alt+T",
when: { mac: true, commandCenter: false },
},
{
id: "theme-cycle-ctrl-alt-t-non-mac",
actionId: "paseo/theme.cycle",
combo: "Ctrl+Alt+T",
when: { mac: false, commandCenter: false, terminal: false },
},
// --- Message input ---
{
id: "message-input-focus-cmd-l-mac",
actionId: "paseo/message-input.focus",
combo: "Cmd+L",
when: { mac: true, commandCenter: false },
},
{
id: "message-input-focus-ctrl-l-non-mac",
actionId: "paseo/message-input.focus",
combo: "Ctrl+L",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "message-input-model-toggle-mod-slash",
actionId: "paseo/message-input.model-toggle",
combo: "Mod+/",
repeat: false,
when: { commandCenter: false, focusScope: ["message-input", "editable", "other"] },
},
{
id: "message-input-effort-cycle-mod-shift-slash",
actionId: "paseo/message-input.effort-cycle",
combo: "Mod+Shift+/",
repeat: false,
when: { commandCenter: false, focusScope: "message-input" },
},
{
id: "message-input-mode-cycle-shift-tab",
actionId: "paseo/message-input.mode-cycle",
combo: "Shift+Tab",
repeat: false,
when: { commandCenter: false, focusScope: "message-input" },
},
{
id: "message-input-voice-toggle-cmd-shift-d-mac",
actionId: "paseo/message-input.voice-toggle",
combo: "Cmd+Shift+D",
repeat: false,
when: { mac: true, commandCenter: false, terminal: false },
},
{
id: "message-input-voice-toggle-ctrl-shift-d-non-mac",
actionId: "paseo/message-input.voice-toggle",
combo: "Ctrl+Shift+D",
repeat: false,
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "message-input-dictation-toggle-cmd-d-mac",
actionId: "paseo/message-input.dictation-toggle",
combo: "Cmd+D",
when: { mac: true, commandCenter: false, terminal: false },
},
{
id: "message-input-dictation-toggle-ctrl-d-non-mac",
actionId: "paseo/message-input.dictation-toggle",
combo: "Ctrl+D",
when: { mac: false, commandCenter: false, terminal: false },
},
{
id: "agent-interrupt",
actionId: "paseo/agent.interrupt",
combo: "Escape",
when: { commandCenter: false, focusScope: ["message-input", "other"] },
preventDefault: false,
stopPropagation: false,
},
{
id: "message-input-dictation-confirm-enter",
actionId: "paseo/message-input.dictation-confirm",
combo: "Enter",
when: { commandCenter: false, terminal: false },
},
{
id: "message-input-voice-mute-toggle",
actionId: "paseo/message-input.voice-mute-toggle",
combo: "Space",
repeat: false,
when: { commandCenter: false, focusScope: "other" },
},
];
@@ -1,14 +1,12 @@
import { describe, expect, it } from "vitest";
import {
buildEffectiveBindings,
buildKeyboardShortcutHelpSections,
UNASSIGNED_COMBO,
type ShortcutOverrides,
} from "./keyboard-shortcuts";
import { filterShortcutHelpSections, shortcutSearchText } from "./shortcut-help-search";
import { UNASSIGNED_COMBO, type ShortcutOverrides } from "@/keyboard/shortcut-override-store";
import { filterShortcutHelpSections, shortcutSearchText } from "./help-search";
import { createCoreRegistries } from "./provider";
import { buildShortcutSections } from "./sections";
const MAC_DESKTOP = { isMac: true, usesDesktopBindings: true };
const NEW_WORKSPACE_BINDING = "workspace-new-cmd-n-mac";
const NEW_WORKSPACE = "paseo/workspace.new";
/**
* The i18n port, filled with the real English strings the rows use. Translation
@@ -16,7 +14,7 @@ const NEW_WORKSPACE_BINDING = "workspace-new-cmd-n-mac";
* than mocked.
*/
const EN: Record<string, string> = {
"settings.shortcuts.sections.projects": "Projects",
"settings.shortcuts.sections.workspaces": "Workspaces",
"settings.shortcuts.help.newWorkspace": "New workspace",
"settings.shortcuts.help.openProject": "Open project",
};
@@ -25,9 +23,15 @@ function translate(key: string): string {
return EN[key] ?? key;
}
function sections(overrides: ShortcutOverrides = {}) {
const { keybindings } = createCoreRegistries();
keybindings.setOverrides(overrides);
return buildShortcutSections(keybindings.getBindings(), MAC_DESKTOP);
}
function filter(query: string, overrides: ShortcutOverrides = {}) {
return filterShortcutHelpSections({
sections: buildKeyboardShortcutHelpSections(MAC_DESKTOP, buildEffectiveBindings(overrides)),
sections: sections(overrides),
query,
translate,
shortcutOs: "mac",
@@ -67,19 +71,19 @@ describe("shortcutSearchText", () => {
describe("filterShortcutHelpSections", () => {
it("returns every section for a blank query", () => {
expect(filter(" ")).toHaveLength(buildKeyboardShortcutHelpSections(MAC_DESKTOP).length);
expect(filter(" ")).toHaveLength(sections().length);
});
it("matches a row by its label", () => {
expect(matchedRowIds("new workspace")).toContain("new-workspace");
expect(matchedRowIds("new workspace")).toContain(NEW_WORKSPACE);
});
it("matches a row by the rendered badge", () => {
expect(matchedRowIds("⌘n")).toContain("new-workspace");
expect(matchedRowIds("⌘n")).toContain(NEW_WORKSPACE);
});
it("matches a row by a spelled-out modifier", () => {
expect(matchedRowIds("command+n")).toContain("new-workspace");
expect(matchedRowIds("command+n")).toContain(NEW_WORKSPACE);
});
// The reported bug, from the search side: the cheat sheet has to stop finding
@@ -87,22 +91,20 @@ describe("filterShortcutHelpSections", () => {
it("finds a rebound row by its new keys and not by the superseded default", () => {
const overrides = { [NEW_WORKSPACE_BINDING]: "Cmd+Shift+K" };
expect(matchedRowIds("cmd+shift+k", overrides)).toContain("new-workspace");
expect(matchedRowIds("cmd+n", overrides)).not.toContain("new-workspace");
expect(matchedRowIds("cmd+shift+k", overrides)).toContain(NEW_WORKSPACE);
expect(matchedRowIds("cmd+n", overrides)).not.toContain(NEW_WORKSPACE);
});
it("still finds an unassigned row by its label", () => {
const overrides = { [NEW_WORKSPACE_BINDING]: UNASSIGNED_COMBO };
expect(matchedRowIds("new workspace", overrides)).toContain("new-workspace");
expect(matchedRowIds("cmd+n", overrides)).not.toContain("new-workspace");
expect(matchedRowIds("new workspace", overrides)).toContain(NEW_WORKSPACE);
expect(matchedRowIds("cmd+n", overrides)).not.toContain(NEW_WORKSPACE);
});
it("keeps every row of a section whose own title matches", () => {
const matched = filter("layout").find((section) => section.id === "layout");
const all = buildKeyboardShortcutHelpSections(MAC_DESKTOP).find(
(section) => section.id === "layout",
);
const all = sections().find((section) => section.id === "layout");
expect(matched?.rows).toHaveLength(all?.rows.length ?? 0);
});
@@ -1,4 +1,4 @@
import type { KeyboardShortcutHelpSection } from "@/keyboard/keyboard-shortcuts";
import type { ShortcutSection } from "./sections";
import { formatShortcut, type ShortcutKey, type ShortcutOs } from "@/utils/format-shortcut";
/** Resolves an i18n key to display text. The caller's `t`, injected. */
@@ -60,11 +60,11 @@ export function filterShortcutHelpSections({
translate,
shortcutOs,
}: {
sections: readonly KeyboardShortcutHelpSection[];
sections: readonly ShortcutSection[];
query: string;
translate: TranslateHelpKey;
shortcutOs: ShortcutOs;
}): KeyboardShortcutHelpSection[] {
}): ShortcutSection[] {
const normalizedQuery = query.trim().toLocaleLowerCase();
if (!normalizedQuery) return [...sections];
@@ -76,7 +76,7 @@ export function filterShortcutHelpSections({
const rows = section.rows.filter((row) => {
const searchText = [
translate(row.labelKey),
row.noteKey ? translate(row.noteKey) : row.note,
row.noteKey ? translate(row.noteKey) : null,
row.chord ? shortcutSearchText(row.chord, shortcutOs) : null,
]
.filter(Boolean)
@@ -0,0 +1,108 @@
import {
createContext,
type ReactNode,
useContext,
useEffect,
useLayoutEffect,
useState,
} from "react";
import {
ActionRegistryProvider,
createActionRegistry,
createActionScopeStore,
type ActionHandler,
type ActionRegistry,
type ActionScopeStore,
} from "@/actions";
import {
createKeybindingRegistry,
KeybindingRegistryProvider,
type KeybindingRegistry,
} from "@/keyboard";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { CORE_ACTIONS } from "./actions";
import { CORE_BINDINGS } from "./bindings";
/** The app shell's implementation of core actions that no mounted surface owns. */
export type CoreActionRuns = Readonly<Partial<Record<string, ActionHandler>>>;
interface RunsSlot {
current: CoreActionRuns;
}
const DECLINED = { handled: false } as const;
const RunsSlotContext = createContext<RunsSlot | null>(null);
export interface CoreRegistries {
scopes: ActionScopeStore;
actions: ActionRegistry;
keybindings: KeybindingRegistry;
}
function registerCore(runs: RunsSlot): CoreRegistries {
const scopes = createActionScopeStore();
const actions = createActionRegistry({ scopes });
const keybindings = createKeybindingRegistry({ actions, scopes });
for (const definition of CORE_ACTIONS) {
actions.registerAction({
...definition,
run: (invocation) => {
const run = runs.current[definition.id];
return run ? run(invocation) : DECLINED;
},
});
}
keybindings.registerBindings(CORE_BINDINGS);
return { scopes, actions, keybindings };
}
/**
* The app's registries with every `paseo/*` action and default binding, for
* code that runs outside `CoreActionsProvider`. A core action with no entry in
* `runs` and no mounted handler is declined.
*/
export function createCoreRegistries(runs: CoreActionRuns = {}): CoreRegistries {
return registerCore({ current: runs });
}
/**
* Creates the app's action and keybinding registries and registers every
* `paseo/*` action and default shortcut, so Settings and badges see them
* before any surface mounts. Mount it once, at the app root.
*/
export function CoreActionsProvider({ children }: { children: ReactNode }) {
const [core] = useState(() => {
const runs: RunsSlot = { current: {} };
return { runs, ...registerCore(runs) };
});
const { overrides } = useKeyboardShortcutOverrides();
useEffect(() => {
core.keybindings.setOverrides(overrides);
}, [core, overrides]);
useEffect(() => () => core.keybindings.dispose(), [core]);
return (
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
<KeybindingRegistryProvider keybindings={core.keybindings}>
<RunsSlotContext.Provider value={core.runs}>{children}</RunsSlotContext.Provider>
</KeybindingRegistryProvider>
</ActionRegistryProvider>
);
}
/**
* Supplies the `run` of core actions from the app shell. Each one runs after
* every mounted handler declines, and reads the latest closure.
*/
export function useCoreActionRuns(runs: CoreActionRuns): void {
const slot = useContext(RunsSlotContext);
if (!slot) {
throw new Error("useCoreActionRuns must be used within CoreActionsProvider");
}
useLayoutEffect(() => {
slot.current = runs;
});
}
@@ -0,0 +1,244 @@
import { whenMatchesPlatform, type DisplayPlatform, type EffectiveKeybinding } from "@/keyboard";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { chordStringToShortcutKeys } from "@/keyboard/shortcut-string";
interface ShortcutRowDefinition {
actionId: string;
labelKey: string;
noteKey?: string;
}
interface ShortcutSectionDefinition {
id: string;
titleKey: string;
rows: readonly ShortcutRowDefinition[];
}
/**
* Settings → Shortcuts and the shortcuts dialog, in display order: sections
* most-reached-for first, and in each section the shortcut someone opens the
* sheet to find at the top.
*/
const SHORTCUT_SECTIONS: readonly ShortcutSectionDefinition[] = [
{
id: "general",
titleKey: "settings.shortcuts.sections.general",
rows: [
{
actionId: "paseo/command-center.toggle",
labelKey: "settings.shortcuts.help.toggleCommandCenter",
},
{ actionId: "paseo/command-center.files", labelKey: "settings.shortcuts.help.searchFiles" },
{
actionId: "paseo/shortcuts-dialog.toggle",
labelKey: "settings.shortcuts.help.showKeyboardShortcuts",
noteKey: "settings.shortcuts.helpNotes.showKeyboardShortcuts",
},
{ actionId: "paseo/settings.toggle", labelKey: "settings.shortcuts.help.toggleSettings" },
{ actionId: "paseo/theme.cycle", labelKey: "settings.shortcuts.help.cycleTheme" },
],
},
{
id: "workspaces",
titleKey: "settings.shortcuts.sections.workspaces",
rows: [
{ actionId: "paseo/project.open", labelKey: "settings.shortcuts.help.openProject" },
{ actionId: "paseo/workspace.new", labelKey: "settings.shortcuts.help.newWorkspace" },
{
actionId: "paseo/workspace.switcher.next",
labelKey: "settings.shortcuts.help.switchRecentWorkspace",
},
{
actionId: "paseo/workspace.switcher.previous",
labelKey: "settings.shortcuts.help.switchRecentWorkspaceReverse",
},
{
actionId: "paseo/workspace.navigate.index",
labelKey: "settings.shortcuts.help.jumpToWorkspace",
},
{
actionId: "paseo/workspace.previous",
labelKey: "settings.shortcuts.help.previousWorkspace",
},
{ actionId: "paseo/workspace.next", labelKey: "settings.shortcuts.help.nextWorkspace" },
{ actionId: "paseo/workspace.pin", labelKey: "Pin chat" },
{ actionId: "paseo/workspace.archive", labelKey: "settings.shortcuts.help.archiveWorkspace" },
{ actionId: "paseo/workspace.archive.undo", labelKey: "Undo archive workspace" },
],
},
{
id: "tabs-panes",
titleKey: "settings.shortcuts.sections.tabsPanes",
rows: [
{ actionId: "paseo/workspace.tab.menu.open", labelKey: "settings.shortcuts.help.newTab" },
{ actionId: "paseo/workspace.tab.target.agent", labelKey: "workspace.tabs.actions.newAgent" },
{ actionId: "paseo/workspace.terminal.new", labelKey: "settings.shortcuts.help.newTerminal" },
{
actionId: "paseo/workspace.tab.target.browser",
labelKey: "workspace.tabs.actions.newBrowser",
},
{
actionId: "paseo/workspace.tab.target.changes",
labelKey: "workspace.tabs.actions.changes",
},
{ actionId: "paseo/workspace.tab.target.files", labelKey: "workspace.tabs.actions.files" },
{
actionId: "paseo/workspace.tab.close-current",
labelKey: "settings.shortcuts.help.closeCurrentTab",
},
{
actionId: "paseo/workspace.tab.navigate.index",
labelKey: "settings.shortcuts.help.jumpToTab",
},
{ actionId: "paseo/workspace.tab.previous", labelKey: "settings.shortcuts.help.previousTab" },
{ actionId: "paseo/workspace.tab.next", labelKey: "settings.shortcuts.help.nextTab" },
{
actionId: "paseo/workspace.pane.split.right",
labelKey: "settings.shortcuts.help.splitPaneRight",
},
{
actionId: "paseo/workspace.pane.split.down",
labelKey: "settings.shortcuts.help.splitPaneDown",
},
{
actionId: "paseo/workspace.pane.focus.left",
labelKey: "settings.shortcuts.help.focusPaneLeft",
},
{
actionId: "paseo/workspace.pane.focus.right",
labelKey: "settings.shortcuts.help.focusPaneRight",
},
{
actionId: "paseo/workspace.pane.focus.up",
labelKey: "settings.shortcuts.help.focusPaneUp",
},
{
actionId: "paseo/workspace.pane.focus.down",
labelKey: "settings.shortcuts.help.focusPaneDown",
},
{
actionId: "paseo/workspace.pane.move-tab.left",
labelKey: "settings.shortcuts.help.moveTabLeft",
},
{
actionId: "paseo/workspace.pane.move-tab.right",
labelKey: "settings.shortcuts.help.moveTabRight",
},
{
actionId: "paseo/workspace.pane.move-tab.up",
labelKey: "settings.shortcuts.help.moveTabUp",
},
{
actionId: "paseo/workspace.pane.move-tab.down",
labelKey: "settings.shortcuts.help.moveTabDown",
},
{ actionId: "paseo/workspace.pane.close", labelKey: "settings.shortcuts.help.closePane" },
],
},
{
id: "layout",
titleKey: "settings.shortcuts.sections.layout",
rows: [
{
actionId: "paseo/sidebar.toggle.left",
labelKey: "settings.shortcuts.help.toggleLeftSidebar",
},
{
actionId: "paseo/sidebar.toggle.right",
labelKey: "settings.shortcuts.help.toggleRightSidebar",
},
{
actionId: "paseo/sidebar.toggle.both",
labelKey: "settings.shortcuts.help.toggleBothSidebars",
},
{
actionId: "paseo/workspace.focus.toggle",
labelKey: "settings.shortcuts.help.toggleFocusMode",
},
],
},
{
id: "agent-input",
titleKey: "settings.shortcuts.sections.agentInput",
rows: [
{
actionId: "paseo/message-input.focus",
labelKey: "settings.shortcuts.help.focusMessageInput",
},
{
actionId: "paseo/message-input.model-toggle",
labelKey: "settings.shortcuts.help.toggleModelPicker",
},
{
actionId: "paseo/message-input.effort-cycle",
labelKey: "settings.shortcuts.help.cycleEffort",
},
{
actionId: "paseo/message-input.mode-cycle",
labelKey: "settings.shortcuts.help.cycleAgentMode",
},
{
actionId: "paseo/message-input.voice-toggle",
labelKey: "settings.shortcuts.help.toggleVoiceMode",
},
{
actionId: "paseo/message-input.dictation-toggle",
labelKey: "settings.shortcuts.help.startStopDictation",
},
{ actionId: "paseo/agent.interrupt", labelKey: "settings.shortcuts.help.interruptAgent" },
{
actionId: "paseo/message-input.voice-mute-toggle",
labelKey: "settings.shortcuts.help.muteUnmuteVoiceMode",
},
],
},
];
export interface ShortcutRow {
/** The action id. */
id: string;
labelKey: string;
noteKey?: string;
/** The binding a rebind edits: the action's first binding on this platform. */
binding: EffectiveKeybinding;
/** The keys that fire it, or `null` when the user unassigned it. */
chord: ShortcutKey[][] | null;
}
export interface ShortcutSection {
id: string;
titleKey: string;
rows: ShortcutRow[];
}
function rowFor(
definition: ShortcutRowDefinition,
bindings: readonly EffectiveKeybinding[],
platform: DisplayPlatform,
): ShortcutRow | null {
const binding = bindings.find(
(candidate) =>
candidate.actionId === definition.actionId && whenMatchesPlatform(candidate.when, platform),
);
if (!binding) {
return null;
}
return {
id: definition.actionId,
labelKey: definition.labelKey,
...(definition.noteKey ? { noteKey: definition.noteKey } : {}),
binding,
chord: binding.parsedChord.length === 0 ? null : chordStringToShortcutKeys(binding.combo),
};
}
/** The shortcut sections for this platform. A row with no binding here is left out. */
export function buildShortcutSections(
bindings: readonly EffectiveKeybinding[],
platform: DisplayPlatform,
): ShortcutSection[] {
return SHORTCUT_SECTIONS.flatMap((section) => {
const rows = section.rows.flatMap((row) => rowFor(row, bindings, platform) ?? []);
return rows.length > 0 ? [{ id: section.id, titleKey: section.titleKey, rows }] : [];
});
}
@@ -0,0 +1,92 @@
import { whenMatchesPlatform, type DisplayPlatform, type EffectiveKeybinding } from "@/keyboard";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { chordStringToShortcutKeys } from "@/keyboard/shortcut-string";
type ModifierKey = "Alt" | "Meta" | "Control";
function firstBinding(
bindings: readonly EffectiveKeybinding[],
actionId: string,
platform: DisplayPlatform,
): EffectiveKeybinding | null {
return (
bindings.find(
(binding) => binding.actionId === actionId && whenMatchesPlatform(binding.when, platform),
) ?? null
);
}
/**
* The `KeyboardEvent.key` whose hold reveals the sidebar's 1-9 workspace
* badges, or `null` when no badges should appear.
*
* It must be the one modifier of the jump binding on this platform. Anything
* else (unassigned, rebound to one digit, a chord, or a second modifier) yields
* `null`, because the badges would advertise more than the shortcut delivers.
*/
export function getWorkspaceIndexJumpModifierKey(
platform: DisplayPlatform,
bindings: readonly EffectiveKeybinding[],
): ModifierKey | null {
const binding = firstBinding(bindings, "paseo/workspace.navigate.index", platform);
if (!binding || binding.parsedChord.length !== 1) {
return null;
}
const combo = binding.parsedChord[0];
if (!combo || combo.code !== "Digit") {
return null;
}
const modifiers = [combo.mod, combo.meta, combo.ctrl, combo.alt, combo.shift];
if (modifiers.filter(Boolean).length !== 1) {
return null;
}
if (combo.mod) return platform.isMac ? "Meta" : "Control";
if (combo.meta) return "Meta";
if (combo.ctrl) return "Control";
if (combo.alt) return "Alt";
return null;
}
function switcherActionId(delta: 1 | -1): string {
return delta === 1 ? "paseo/workspace.switcher.next" : "paseo/workspace.switcher.previous";
}
/**
* The modifier whose release commits the workspace switcher's highlight, or
* `null` (an unmodified key or a chord), which makes the HUD sticky.
*/
export function getWorkspaceSwitcherReleaseModifier(input: {
delta: 1 | -1;
platform: DisplayPlatform;
bindings: readonly EffectiveKeybinding[];
}): ModifierKey | null {
const binding = firstBinding(input.bindings, switcherActionId(input.delta), input.platform);
if (!binding || binding.parsedChord.length !== 1) {
return null;
}
const combo = binding.parsedChord[0];
if (!combo) return null;
const { isMac } = input.platform;
if (combo.ctrl || (combo.mod && !isMac)) return "Control";
if (combo.alt) return "Alt";
if (combo.meta || (combo.mod && isMac)) return "Meta";
return null;
}
const MODIFIER_SHORTCUT_KEYS = new Set<ShortcutKey>(["ctrl", "alt", "shift", "mod", "meta"]);
/**
* The non-modifier key of the forward switcher binding (`Tab` on desktop, `` ` ``
* on web), so the HUD's hints name what actually cycles.
*/
export function getWorkspaceSwitcherCycleKey(input: {
platform: DisplayPlatform;
bindings: readonly EffectiveKeybinding[];
}): ShortcutKey | null {
const binding = firstBinding(input.bindings, switcherActionId(1), input.platform);
if (!binding || binding.parsedChord.length !== 1) {
return null;
}
const keys = chordStringToShortcutKeys(binding.combo)[0];
return keys?.find((token) => !MODIFIER_SHORTCUT_KEYS.has(token)) ?? null;
}
+27
View File
@@ -0,0 +1,27 @@
import type { ShortcutOverrides } from "@/keyboard/shortcut-override-store";
import { createCoreRegistries, type CoreRegistries } from "./internal/provider";
export interface RecordedDispatch {
actionId: string;
index?: number;
}
/**
* The core registries with a handler on every action that records what ran,
* for tests that drive real keys through the real binding table.
*/
export function createRecordingCoreRegistries(overrides: ShortcutOverrides = {}): CoreRegistries & {
ran: RecordedDispatch[];
/** The action ids that ran, in order. */
ranIds(): string[];
} {
const core = createCoreRegistries();
core.keybindings.setOverrides(overrides);
const ran: RecordedDispatch[] = [];
for (const action of core.actions.listActions()) {
core.actions.registerHandler(action.id, ({ actionId, index }) => {
ran.push(index === undefined ? { actionId } : { actionId, index });
});
}
return { ...core, ran, ranIds: () => ran.map((entry) => entry.actionId) };
}
@@ -12,7 +12,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { actionsWithoutPrimary, type GitAction, type GitActions } from "@/git/policy";
@@ -83,7 +83,7 @@ export function GitActionsSplitButton({
const { theme } = useUnistyles();
const { t } = useTranslation();
const runGitAction = useGitActionRunner();
const archiveShortcutKeys = useShortcutKeys("archive-workspace");
const archiveShortcutKeys = useShortcutKeys("paseo/workspace.archive");
const getActionDisplayLabel = useCallback((action: GitAction): string => {
if (action.status === "pending") return action.pendingLabel;
@@ -1,39 +0,0 @@
import { useCallback } from "react";
import { router } from "expo-router";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspace } from "@/stores/session-store-hooks";
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
const WORKTREE_NEW_ACTIONS: readonly KeyboardActionId[] = ["worktree.new"];
export function useActiveWorktreeNewAction() {
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
const workspaceId = selection?.workspaceId ?? null;
const activeWorkspace = useWorkspace(serverId, workspaceId);
const activeGitWorkspace = activeWorkspace?.projectKind === "git" ? activeWorkspace : null;
const handle = useCallback(() => {
if (!serverId || !activeGitWorkspace) {
return false;
}
router.navigate(
buildNewWorkspaceRoute({
serverId,
sourceDirectory: activeGitWorkspace.projectRootPath,
projectId: activeGitWorkspace.projectId,
}) as never,
);
return true;
}, [activeGitWorkspace, serverId]);
useKeyboardActionHandler({
handlerId: "worktree-new-active",
actions: WORKTREE_NEW_ACTIONS,
enabled: serverId !== null && activeGitWorkspace !== null,
priority: 0,
handle,
});
}
@@ -1,7 +1,6 @@
import { useCallback } from "react";
import { router } from "expo-router";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActionHandler } from "@/actions";
import { canCreateWorktreeForProjectKind } from "@/projects/host-projects";
import { useHostFeature } from "@/runtime/host-features";
import { useHosts } from "@/runtime/host-runtime";
@@ -9,8 +8,6 @@ import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspac
import { useWorkspace } from "@/stores/session-store-hooks";
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
const WORKSPACE_NEW_ACTIONS: readonly KeyboardActionId[] = ["workspace.new"];
export function useGlobalNewWorkspaceAction() {
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
@@ -25,7 +22,7 @@ export function useGlobalNewWorkspaceAction() {
const handle = useCallback(() => {
if (hosts.length === 0) {
return false;
return { handled: false } as const;
}
router.navigate(
(serverId
@@ -40,14 +37,7 @@ export function useGlobalNewWorkspaceAction() {
)
: buildNewWorkspaceRoute()) as never,
);
return true;
}, [activeWorkspace, canUseActiveWorkspaceContext, hosts.length, serverId]);
useKeyboardActionHandler({
handlerId: "workspace-new-global",
actions: WORKSPACE_NEW_ACTIONS,
enabled: hosts.length > 0,
priority: 0,
handle,
});
useActionHandler("paseo/workspace.new", handle, { enabled: hosts.length > 0 });
}
@@ -1,8 +1,5 @@
import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
import { useActionHandler } from "@/actions";
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
@@ -11,11 +8,7 @@ const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archi
export function useGlobalWorkspaceArchiveAction() {
const { canArchive, archive } = useActiveWorkspaceArchive();
useKeyboardActionHandler({
handlerId: "workspace-archive-global",
actions: WORKSPACE_ARCHIVE_ACTIONS,
useActionHandler("paseo/workspace.archive", () => (archive() ? undefined : { handled: false }), {
enabled: canArchive,
priority: 0,
handle: archive,
});
}
@@ -1,14 +1,11 @@
import { useCallback } from "react";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useActionHandler } from "@/actions";
import { useSidebarWorkspacePinController } from "@/hooks/use-sidebar-workspace-pin";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useHostFeature } from "@/runtime/host-features";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
const WORKSPACE_PIN_ACTIONS: readonly KeyboardActionId[] = ["workspace.pin"];
// The pin shortcut used to live on the sidebar row, so it disappeared whenever the row was not
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode.
// It belongs here instead: one registration keyed on the active route selection.
@@ -36,14 +33,14 @@ export function useGlobalWorkspacePinAction() {
const handle = useCallback(() => {
if (!serverId || !fields || !canPin) {
return false;
return { handled: false } as const;
}
const workspaceKey = buildWorkspaceTabPersistenceKey({
serverId,
workspaceId: fields.id,
});
if (!workspaceKey) {
return false;
return { handled: false } as const;
}
togglePin({
serverId,
@@ -51,14 +48,9 @@ export function useGlobalWorkspacePinAction() {
workspaceKey,
pinnedAt: fields.pinnedAt,
});
return true;
}, [canPin, fields, serverId, togglePin]);
useKeyboardActionHandler({
handlerId: "workspace-pin-global",
actions: WORKSPACE_PIN_ACTIONS,
useActionHandler("paseo/workspace.pin", handle, {
enabled: serverId !== null && fields !== null && canPin,
priority: 0,
handle,
});
}
@@ -1,63 +0,0 @@
import { useEffect, useRef } from "react";
import type {
KeyboardActionDefinition,
KeyboardActionId,
} from "@/keyboard/keyboard-action-dispatcher";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
interface UseKeyboardActionHandlerInput {
handlerId: string;
actions: readonly KeyboardActionId[];
enabled: boolean;
priority: number;
isActive?: () => boolean;
handle: (action: KeyboardActionDefinition) => boolean;
}
/**
* Registers a keyboard action handler with the global dispatcher.
*
* The dispatcher is driven by a native window keydown listener and calls the
* most-recently-registered matching handler first (see keyboard-action-dispatcher.ts).
* Two properties must hold or handlers bound to the same action step on each other:
*
* 1. Stable registration order. registerHandler bumps a registration counter, so
* re-registering on every render reshuffles which handler the dispatcher reaches
* first. A frequently re-rendering control (e.g. a running agent's mode control)
* would then jump ahead of another (e.g. the New Workspace draft) and consume the
* key, silently acting on the wrong surface. So we register once per
* (handlerId, priority, actions) and never re-register just because handle,
* isActive, or enabled changed.
*
* 2. Fresh callbacks. Because we do not re-register on every render, the registered
* entry must read the latest props at dispatch time. handle and isActive are read
* live from a ref, and enabled is folded into isActive so the dispatcher
* re-evaluates it fresh (the plain enabled field it filters on is captured at
* registration and would otherwise go stale).
*/
export function useKeyboardActionHandler(input: UseKeyboardActionHandlerInput) {
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const inputRef = useRef(input);
inputRef.current = input;
// Only these identity-affecting fields trigger a re-register. actions is compared by
// content, not array identity, so inline literals do not churn the registration.
const actionsKey = input.actions.join(" ");
useEffect(() => {
return keyboardActionDispatcher.registerHandler({
handlerId: inputRef.current.handlerId,
actions: inputRef.current.actions,
// Always-on at the coarse filter; the real enable/active gate is re-checked fresh
// inside isActive below so it can never be stale in the registry entry.
enabled: true,
priority: inputRef.current.priority,
isActive: () => {
const current = inputRef.current;
if (!current.enabled) return false;
return current.isActive ? current.isActive() : true;
},
handle: (action) => inputRef.current.handle(action),
});
}, [actionsKey, input.handlerId, input.priority, keyboardActionDispatcher]);
}
@@ -1,7 +1,7 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { type QueryClient, useQuery, useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import type { ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
import type { ShortcutOverrides } from "@/keyboard/shortcut-override-store";
import {
createShortcutOverrideStore,
type ShortcutOverrideStore,
+7 -16
View File
@@ -1,10 +1,8 @@
import { useId } from "react";
import { useActionHandler } from "@/actions";
import { hasFocusedTextInput } from "@/keyboard";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
export interface KeyboardToggleAction {
id: KeyboardActionId;
id: string;
canOpen: () => boolean;
}
@@ -22,17 +20,10 @@ export function useKeyboardToggle({
searchFocused: boolean;
onToggle: () => void;
}) {
const handlerId = useId();
useKeyboardActionHandler({
handlerId,
actions: action ? [action.id] : [],
enabled: action !== undefined && !disabled,
priority: 200,
isActive: () =>
action?.canOpen() === true || (open && (searchFocused || !hasFocusedTextInput())),
handle: () => {
onToggle();
return true;
},
useActionHandler(action ? action.id : [], onToggle, {
enabled: () =>
action !== undefined &&
!disabled &&
(action.canOpen() || (open && (searchFocused || !hasFocusedTextInput()))),
});
}
@@ -1,20 +0,0 @@
import { usesDesktopBindings } from "@/keyboard";
import { useMemo } from "react";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { resolveShortcutKeysForAction } from "@/keyboard/keyboard-shortcuts";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { getShortcutOs } from "@/utils/shortcut-platform";
/** `null` action ids are accepted so callers can keep the hook unconditional. */
export function useShortcutKeys(actionId: string | null): ShortcutKey[][] | null {
const { overrides } = useKeyboardShortcutOverrides();
const isMac = getShortcutOs() === "mac";
return useMemo(() => {
if (actionId === null) return null;
return resolveShortcutKeysForAction(actionId, overrides, {
isMac,
usesDesktopBindings,
});
}, [actionId, overrides, isMac]);
}
-68
View File
@@ -1,68 +0,0 @@
export type KeyboardFocusScope =
| "terminal"
| "message-input"
| "command-center"
| "editable"
| "browser"
| "other";
export type MessageInputKeyboardActionKind =
| "focus"
| "send"
| "dictation-toggle"
| "dictation-cancel"
| "dictation-confirm"
| "voice-toggle"
| "voice-mute-toggle"
| "mode-cycle"
| "model-toggle"
| "effort-cycle";
export type KeyboardActionId =
| "agent.interrupt"
| "agent.new"
| "workspace.tab.menu.open"
| "workspace.tab.target.agent"
| "workspace.tab.target.browser"
| "workspace.tab.target.changes"
| "workspace.tab.target.files"
| "workspace.tab.close.current"
| "workspace.tab.navigate.index"
| "workspace.tab.navigate.relative"
| "workspace.pane.split.right"
| "workspace.pane.split.down"
| "workspace.pane.focus.left"
| "workspace.pane.focus.right"
| "workspace.pane.focus.up"
| "workspace.pane.focus.down"
| "workspace.pane.move-tab.left"
| "workspace.pane.move-tab.right"
| "workspace.pane.move-tab.up"
| "workspace.pane.move-tab.down"
| "workspace.pane.close"
| "workspace.navigate.index"
| "workspace.navigate.relative"
| "workspace.switcher.cycle"
| "sidebar.toggle.left"
| "sidebar.toggle.right"
| "sidebar.toggle.both"
| "settings.toggle"
| "command-center.toggle"
| "command-center.files"
| "shortcuts.dialog.toggle"
| "workspace.terminal.new"
| "workspace.new"
| "workspace.project.pick"
| "worktree.new"
| "workspace.archive"
| "workspace.archive.undo"
| "workspace.pin"
| "view.toggle.focus"
| "theme.cycle"
| "message-input.action";
export type KeyboardShortcutPayload =
| { index: number }
| { delta: 1 | -1 }
| { kind: MessageInputKeyboardActionKind }
| null;
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { createHardwareKeyboardPresence } from "./internal/hardware-presence";
import { buildEffectiveBindings } from "./keyboard-shortcuts";
import { createRecordingCoreRegistries } from "@/core-actions/testing";
import { createKeyboardPipeline } from "./internal/pipeline";
import { createOverlayRegistry } from "./internal/overlays";
import { nativeKeyboardInput } from "./internal/sources/contract";
@@ -34,15 +34,11 @@ describe("hardware keyboard availability", () => {
it("routes compact Electron input independently of hint availability", () => {
const presence = createHardwareKeyboardPresence({ read: () => false, watch: () => () => {} });
const actions: string[] = [];
const core = createRecordingCoreRegistries();
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac: true, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({}),
keybindings: core.keybindings,
isCapturing: () => false,
dispatch: (match) => {
actions.push(match.action);
return true;
},
overlays: createOverlayRegistry(),
});
pipeline.keyDown(
@@ -62,7 +58,7 @@ describe("hardware keyboard availability", () => {
),
);
expect(presence.getSnapshot()).toBe(false);
expect(actions).toEqual(["command-center.toggle"]);
expect(core.ranIds()).toEqual(["paseo/command-center.toggle"]);
pipeline.dispose();
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
import type { KeyboardFocusScope } from "@/keyboard/actions";
import type { KeyboardFocusScope } from "./internal/key-event";
function isElement(value: unknown): value is Element {
return typeof Element !== "undefined" && value instanceof Element;
@@ -1,62 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildWorkspaceKeyboardHandlerId } from "@/keyboard/handler-id";
describe("buildWorkspaceKeyboardHandlerId", () => {
it("separates workspaces that share a pane id", () => {
// Every workspace's default pane is called "main", and the deck keeps several
// workspaces mounted at once. Dropping the workspace id here left the evicted
// workspace without a keyboard.
const left = buildWorkspaceKeyboardHandlerId({
name: "workspace-new-tab-menu",
serverId: "srv",
workspaceId: "wks_a",
paneId: "main",
});
const right = buildWorkspaceKeyboardHandlerId({
name: "workspace-new-tab-menu",
serverId: "srv",
workspaceId: "wks_b",
paneId: "main",
});
expect(left).not.toBe(right);
});
it("separates panes within a workspace", () => {
const main = buildWorkspaceKeyboardHandlerId({
name: "workspace-new-tab-menu",
serverId: "srv",
workspaceId: "wks_a",
paneId: "main",
});
const explorer = buildWorkspaceKeyboardHandlerId({
name: "workspace-new-tab-menu",
serverId: "srv",
workspaceId: "wks_a",
paneId: "explorer",
});
expect(main).not.toBe(explorer);
});
it("omits the pane segment for workspace-wide surfaces", () => {
expect(
buildWorkspaceKeyboardHandlerId({
name: "workspace-tab-actions",
serverId: "srv",
workspaceId: "wks_a",
}),
).toBe("workspace-tab-actions:srv:wks_a");
});
it("treats a blank pane id as workspace-wide", () => {
expect(
buildWorkspaceKeyboardHandlerId({
name: "workspace-new-tab-menu",
serverId: "srv",
workspaceId: "wks_a",
paneId: " ",
}),
).toBe("workspace-new-tab-menu:srv:wks_a");
});
});
-33
View File
@@ -1,33 +0,0 @@
/**
* A keyboard handler id is an identity, not a label.
*
* The dispatcher keeps one live handler per id and useKeyboardActionHandler
* registers once per id, never re-registering when focus changes. So when two
* mounted surfaces produce the same id, the second one evicts the first and the
* first is left without a keyboard for the rest of its mount — silently, with no
* symptom until someone presses the key.
*
* The workspace deck keeps several workspaces mounted at once, so a workspace
* surface is only identified by its server, its workspace, and its pane. Pane
* ids are namespaced per workspace ("main" is every workspace's default pane),
* which is why they cannot carry the identity on their own.
*/
export interface WorkspaceKeyboardSurface {
/** Stable name for the surface, e.g. "workspace-new-tab-menu". */
name: string;
serverId: string;
workspaceId: string;
/** Omit for surfaces that own the whole workspace rather than one pane. */
paneId?: string | null;
}
export function buildWorkspaceKeyboardHandlerId({
name,
serverId,
workspaceId,
paneId,
}: WorkspaceKeyboardSurface): string {
const trimmedPaneId = paneId?.trim();
const paneSegment = trimmedPaneId ? `:${trimmedPaneId}` : "";
return `${name}:${serverId}:${workspaceId}${paneSegment}`;
}
+28
View File
@@ -16,3 +16,31 @@ export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser"
export { useHardwareKeyboardPresent } from "./availability";
export { readPressModifiers } from "./internal/press-modifiers";
export type { PressModifiers } from "./internal/press-modifiers";
export {
createKeybindingRegistry,
displayKeysFor,
DuplicateKeybindingError,
} from "./internal/keybinding-registry";
export type {
DisplayPlatform,
EffectiveKeybinding,
KeybindingConflict,
KeybindingDispatchResult,
KeybindingInput,
KeybindingRegistry,
KeybindingRegistryOptions,
} from "./internal/keybinding-registry";
export { whenMatchesPlatform } from "./internal/when";
export type { When, WhenClause } from "./internal/when";
export type { KeyboardFocusScope } from "./internal/key-event";
export {
getDisplayPlatform,
KeybindingRegistryProvider,
useKeybindingRegistry,
useKeybindings,
useShortcutKeys,
} from "./internal/react";
export { isCaptureComplete, normalizeCapturedCombo } from "./internal/capture";
export { createChordMatcher } from "./internal/chord-matcher";
export type { ChordMatch, ChordMatcher } from "./internal/chord-matcher";
export type { KeyboardShortcutContext, KeyboardShortcutInput } from "./internal/key-event";
@@ -0,0 +1,22 @@
import type { EffectiveKeybinding } from "./keybinding-registry";
import { parseBindingChord } from "./key-event";
/** A binding shipped on the `Digit` wildcard stands for every digit 1-9. */
function bindsDigitWildcard(binding: EffectiveKeybinding): boolean {
return parseBindingChord(binding.defaultCombo).at(-1)?.code === "Digit";
}
/** Keeps a 1-9 binding on all nine digits when the user records a new modifier for it. */
export function normalizeCapturedCombo(binding: EffectiveKeybinding, combo: string): string {
return bindsDigitWildcard(binding) ? combo.replace(/(^|\+)[1-9]$/, "$1Digit") : combo;
}
/** A 1-9 binding needs a final digit; earlier combos may be any chord prefix. */
export function isCaptureComplete(
binding: EffectiveKeybinding,
combos: readonly string[],
): boolean {
const lastCombo = combos.at(-1);
if (!lastCombo) return false;
return !bindsDigitWildcard(binding) || /(^|\+)(Digit|[1-9])$/.test(lastCombo);
}
@@ -0,0 +1,120 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createActionRegistry, createActionScopeStore } from "@/actions";
import { createChordMatcher } from "./chord-matcher";
import type { KeyboardShortcutInput } from "./key-event";
import { createKeybindingRegistry, type EffectiveKeybinding } from "./keybinding-registry";
function bindings(
entries: ReadonlyArray<{ id: string; combo: string }>,
): readonly EffectiveKeybinding[] {
const scopes = createActionScopeStore();
const actions = createActionRegistry({ scopes });
const registry = createKeybindingRegistry({ actions, scopes });
registry.registerBindings(
entries.map((entry) => ({ id: entry.id, actionId: `test/${entry.id}`, combo: entry.combo })),
);
return registry.getBindings();
}
function key(input: Partial<KeyboardShortcutInput> & { key: string; code: string }) {
return {
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
...input,
};
}
const CTRL_TAB = key({ key: "Tab", code: "Tab", ctrlKey: true });
const CTRL_W = key({ key: "w", code: "KeyW", ctrlKey: true });
const KEY_S = key({ key: "s", code: "KeyS" });
const KEY_X = key({ key: "x", code: "KeyX" });
const CONTROL = key({ key: "Control", code: "ControlLeft", ctrlKey: true });
afterEach(() => {
vi.useRealTimers();
});
describe("createChordMatcher", () => {
it("matches a single-step binding on its key", () => {
const chord = createChordMatcher();
const table = bindings([{ id: "next", combo: "Ctrl+Tab" }]);
expect(chord.keyDown(CTRL_TAB, table, false)).toEqual({
kind: "matched",
binding: table[0],
});
});
it("matches a chord across two presses", () => {
const chord = createChordMatcher();
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
expect(chord.keyDown(CTRL_W, table, false)).toEqual({ kind: "pending" });
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "matched", binding: table[0] });
});
it("reserves a chord's first step over a single-step binding on the same keys", () => {
const chord = createChordMatcher();
const table = bindings([
{ id: "close", combo: "Ctrl+W" },
{ id: "split", combo: "Ctrl+W S" },
]);
expect(chord.keyDown(CTRL_W, table, false)).toEqual({ kind: "pending" });
expect(chord.keyDown(KEY_S, table, false)).toEqual({
kind: "matched",
binding: table.find((binding) => binding.id === "split"),
});
});
it("keeps a chord pending while a modifier goes down between steps", () => {
const chord = createChordMatcher();
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
chord.keyDown(CTRL_W, table, false);
expect(chord.keyDown(CONTROL, table, false)).toEqual({ kind: "pending" });
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "matched", binding: table[0] });
});
it("ignores a lone modifier when no chord is pending", () => {
const chord = createChordMatcher();
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
expect(chord.keyDown(CONTROL, table, false)).toEqual({ kind: "none" });
});
it("drops the chord on a second key that continues nothing", () => {
const chord = createChordMatcher();
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
chord.keyDown(CTRL_W, table, false);
expect(chord.keyDown(KEY_X, table, false)).toEqual({ kind: "none" });
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "none" });
});
it("drops a pending chord once the timeout passes", () => {
vi.useFakeTimers();
const chord = createChordMatcher({ timeoutMs: 100 });
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
chord.keyDown(CTRL_W, table, false);
vi.advanceTimersByTime(100);
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "none" });
});
it("drops a pending chord on reset", () => {
const chord = createChordMatcher();
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
chord.keyDown(CTRL_W, table, false);
chord.reset();
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "none" });
});
});
@@ -0,0 +1,84 @@
import { isModifierKeyCode } from "../shortcut-string";
import { matchesCombo, type KeyboardShortcutInput } from "./key-event";
import type { EffectiveKeybinding } from "./keybinding-registry";
const DEFAULT_CHORD_TIMEOUT_MS = 1500;
export type ChordMatch =
| { kind: "matched"; binding: EffectiveKeybinding }
| { kind: "pending" }
| { kind: "none" };
/**
* Matches key presses against a set of bindings, one step at a time, for a
* surface that reads keys itself while it holds the keyboard. Unlike the
* registry it runs no action and ignores `when`: the caller picks the bindings.
*/
export interface ChordMatcher {
keyDown(
event: KeyboardShortcutInput,
bindings: readonly EffectiveKeybinding[],
isMac: boolean,
): ChordMatch;
/** Drops a pending chord. */
reset(): void;
}
export function createChordMatcher(options: { timeoutMs?: number } = {}): ChordMatcher {
const timeoutMs = options.timeoutMs ?? DEFAULT_CHORD_TIMEOUT_MS;
let step = 0;
let candidates: readonly EffectiveKeybinding[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
function reset(): void {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
step = 0;
candidates = [];
}
function advance(nextStep: number, next: readonly EffectiveKeybinding[]): ChordMatch {
reset();
step = nextStep;
candidates = next;
timer = setTimeout(reset, timeoutMs);
return { kind: "pending" };
}
return {
keyDown(event, bindings, isMac) {
if (isModifierKeyCode(event.code)) {
return step > 0 ? { kind: "pending" } : { kind: "none" };
}
const currentStep = step;
const pool = currentStep === 0 ? bindings : candidates;
let completed: EffectiveKeybinding | null = null;
const advancing: EffectiveKeybinding[] = [];
for (const binding of pool) {
const combo = binding.parsedChord[currentStep];
if (!combo || !matchesCombo(combo, event, isMac)) continue;
if (binding.parsedChord.length === currentStep + 1) {
completed ??= binding;
} else {
advancing.push(binding);
}
}
// A chord start reserves its prefix over a single-key binding on the same keys.
if (currentStep === 0 && advancing.length > 0) {
return advance(1, advancing);
}
if (completed) {
reset();
return { kind: "matched", binding: completed };
}
if (advancing.length > 0) {
return advance(currentStep + 1, advancing);
}
reset();
return { kind: "none" };
},
reset,
};
}
@@ -1,5 +1,5 @@
import { hasFocusedTextInput } from "./focused-text-input";
import type { KeyboardFocusScope } from "../actions";
import type { KeyboardFocusScope } from "./key-event";
export type KeyboardFocusSurface = "message-input" | "terminal";
export function createKeyboardFocusScope(hasEditableFocus: () => boolean = () => false) {
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { parseBindingChord } from "./key-event";
describe("parseBindingChord", () => {
it("yields an empty chord for a binding that ships without a default combo", () => {
expect(parseBindingChord("")).toEqual([]);
});
it("parses a normal combo into one step", () => {
expect(parseBindingChord("Ctrl+T")).toHaveLength(1);
});
it("parses a chord into one step per combo", () => {
expect(parseBindingChord("Ctrl+W S")).toHaveLength(2);
});
it("still throws on an unparseable combo", () => {
expect(() => parseBindingChord("Ctrl+Nonsense")).toThrow();
});
});
@@ -0,0 +1,112 @@
import { parseChordString, type KeyCombo } from "../shortcut-string";
/** What holds keyboard focus when a key is pressed. */
export type KeyboardFocusScope =
| "terminal"
| "message-input"
| "command-center"
| "editable"
| "browser"
| "other";
/** The live focus and platform state a key press arrives with. */
export interface KeyboardShortcutContext {
isMac: boolean;
usesDesktopBindings: boolean;
focusScope: KeyboardFocusScope;
commandCenterOpen: boolean;
}
/** The fields of a key press that matching reads, from any key source. */
export interface KeyboardShortcutInput {
key: string;
code: string;
altKey: boolean;
ctrlKey: boolean;
metaKey: boolean;
shiftKey: boolean;
repeat: boolean;
}
/**
* Parse a binding's combo string into a chord.
*
* An empty combo yields an empty chord, which never matches any event. That is
* how both a user-unassigned shortcut and a binding authored without a default
* combo are represented: one state, not two.
*/
export function parseBindingChord(combo: string): KeyCombo[] {
if (combo === "") {
return [];
}
return parseChordString(combo);
}
/** The 1-9 a `Digit` wildcard press stands for, or `null` for any other key. */
export function parseDigit(event: KeyboardShortcutInput): number | null {
const code = event.code;
if (code.startsWith("Digit")) {
const value = Number(code.slice("Digit".length));
return Number.isFinite(value) && value >= 1 && value <= 9 ? value : null;
}
if (code.startsWith("Numpad")) {
const value = Number(code.slice("Numpad".length));
return Number.isFinite(value) && value >= 1 && value <= 9 ? value : null;
}
const key = event.key;
if (key >= "1" && key <= "9") {
return Number(key);
}
return null;
}
function matchesKeyOrCode(combo: KeyCombo, event: KeyboardShortcutInput): boolean {
if (combo.key === undefined) {
return event.code === combo.code;
}
const eventKey = event.key.toLowerCase();
if (eventKey === combo.key) return true;
if (combo.shift === true && combo.shiftedKey !== undefined && eventKey === combo.shiftedKey) {
return true;
}
// Recording an unsupported letter (for example Cyrillic и on KeyB)
// stores its physical A-Z key. Dispatch must accept that same key without
// giving Latin layouts such as Dvorak a second physical-key binding.
if (/^[a-z]$/.test(combo.key) && /^\p{Letter}$/u.test(event.key) && !/^[a-z]$/.test(eventKey)) {
return event.code === combo.code;
}
// macOS rewrites event.key when Option is held (Option+T -> "†",
// Option+[ -> "“"), so Alt-bound letter / bracket bindings can only
// match by event.code. Stay key-first for non-Alt bindings so Dvorak
// keeps its logical-character matching (e.g. Cmd+V on physical Period
// must paste, not trigger Cmd+.).
if (combo.alt === true && event.code === combo.code) return true;
return combo.codeFallback === true && event.code === combo.code;
}
export function matchesCombo(
combo: KeyCombo,
event: KeyboardShortcutInput,
isMac: boolean,
): boolean {
if (combo.mod) {
if (isMac) {
if (!event.metaKey) return false;
if (!!combo.ctrl !== event.ctrlKey) return false;
} else {
if (!event.ctrlKey) return false;
if (!!combo.meta !== event.metaKey) return false;
}
} else {
if (!!combo.meta !== event.metaKey) return false;
if (!!combo.ctrl !== event.ctrlKey) return false;
}
if (!!combo.alt !== event.altKey) return false;
if (!!combo.shift !== event.shiftKey) return false;
if (combo.repeat === false && event.repeat) return false;
if (combo.code === "Digit") {
return parseDigit(event) !== null;
}
return matchesKeyOrCode(combo, event);
}
@@ -0,0 +1,621 @@
import { describe, expect, it, vi } from "vitest";
import { createActionRegistry, createActionScopeStore, type ActionInvocation } from "@/actions";
import type { KeyboardShortcutContext, KeyboardShortcutInput } from "./key-event";
import {
createShortcutOverrideStore,
UNASSIGNED_COMBO,
type ShortcutOverrides,
} from "@/keyboard/shortcut-override-store";
import { createKeybindingRegistry, DuplicateKeybindingError } from "./keybinding-registry";
function keyEvent(overrides: Partial<KeyboardShortcutInput>): KeyboardShortcutInput {
return {
key: "",
code: "",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
...overrides,
};
}
const MAC_OTHER: KeyboardShortcutContext = {
isMac: true,
usesDesktopBindings: true,
focusScope: "other",
commandCenterOpen: false,
};
function createHarness(input: { chordTimeoutMs?: number } = {}) {
const scopes = createActionScopeStore();
const actions = createActionRegistry({ scopes });
const registry = createKeybindingRegistry({
actions,
scopes,
...(input.chordTimeoutMs !== undefined ? { chordTimeoutMs: input.chordTimeoutMs } : {}),
});
const ran: string[] = [];
function runnable(id: string): void {
actions.registerAction({
id,
title: id,
run: () => {
ran.push(id);
},
});
}
function press(
event: Partial<KeyboardShortcutInput>,
context: Partial<KeyboardShortcutContext> = {},
) {
return registry.dispatchKeyDown(keyEvent(event), { ...MAC_OTHER, ...context });
}
return { scopes, actions, registry, ran, runnable, press };
}
const KEY_J = { key: "j", code: "KeyJ" };
const CMD_K = { key: "k", code: "KeyK", metaKey: true };
describe("KeybindingRegistry", () => {
it("registers and removes bindings at runtime with notifications", () => {
const { registry, runnable, press, ran } = createHarness();
runnable("inbox/item.next");
let notifications = 0;
registry.subscribe(() => {
notifications += 1;
});
const unregister = registry.registerBinding({
id: "inbox-next",
actionId: "inbox/item.next",
combo: "Cmd+J",
});
expect(notifications).toBe(1);
expect(press({ ...KEY_J, metaKey: true }).handled).toBe(true);
expect(ran).toEqual(["inbox/item.next"]);
unregister();
unregister();
expect(notifications).toBe(2);
expect(registry.getBinding("inbox-next")).toBeNull();
expect(press({ ...KEY_J, metaKey: true }).handled).toBe(false);
registry.dispose();
});
it("keeps legacy binding ids so ShortcutOverrideStore overrides apply", async () => {
const { registry, runnable, press, ran } = createHarness();
runnable("paseo/command-center.toggle");
registry.registerBinding({
id: "command-center-toggle-cmd-k-mac",
actionId: "paseo/command-center.toggle",
combo: "Cmd+K",
when: { mac: true },
});
let cache: ShortcutOverrides = {};
const overrideStore = createShortcutOverrideStore({
cache: {
read: () => cache,
write: (next) => {
cache = next;
registry.setOverrides(next);
},
},
storage: { write: async () => {}, remove: async () => {} },
onError: () => {},
});
await overrideStore.set("command-center-toggle-cmd-k-mac", "Cmd+J");
expect(press(CMD_K).handled).toBe(false);
expect(press({ ...KEY_J, metaKey: true }).handled).toBe(true);
await overrideStore.clear("command-center-toggle-cmd-k-mac");
expect(registry.getBinding("command-center-toggle-cmd-k-mac")?.combo).toBe("");
expect(press({ ...KEY_J, metaKey: true }).handled).toBe(false);
await overrideStore.remove("command-center-toggle-cmd-k-mac");
expect(press(CMD_K).handled).toBe(true);
expect(ran).toEqual(["paseo/command-center.toggle", "paseo/command-center.toggle"]);
registry.setOverrides({ "command-center-toggle-cmd-k-mac": UNASSIGNED_COMBO });
expect(registry.getBinding("command-center-toggle-cmd-k-mac")?.parsedChord).toEqual([]);
registry.dispose();
});
});
describe("KeybindingRegistry precedence", () => {
it("fires the binding of the innermost active scope, in either registration order", () => {
for (const order of [
["list", "popover"],
["popover", "list"],
]) {
const { registry, scopes, runnable, press, ran } = createHarness();
runnable("inbox/list.next");
runnable("inbox/popover.next");
for (const name of order) {
registry.registerBinding({
id: `${name}-next`,
actionId: `inbox/${name}.next`,
combo: "J",
when: { scope: `inbox/${name}` },
});
}
const list = scopes.activate("inbox/list");
const popover = scopes.activate("inbox/popover");
expect(press(KEY_J).binding?.id).toBe("popover-next");
popover.release();
expect(press(KEY_J).binding?.id).toBe("list-next");
list.release();
expect(press(KEY_J).handled).toBe(false);
expect(ran).toEqual(["inbox/popover.next", "inbox/list.next"]);
registry.dispose();
}
});
it("lets sibling surfaces share a key through their own scopes", () => {
const { registry, scopes, runnable, press } = createHarness();
runnable("inbox/list.next");
runnable("inbox/preview.next");
registry.registerBindings([
{ id: "list-next", actionId: "inbox/list.next", combo: "J", when: { scope: "inbox/list" } },
{
id: "preview-next",
actionId: "inbox/preview.next",
combo: "J",
when: { scope: "inbox/preview" },
},
]);
const preview = scopes.activate("inbox/preview");
expect(press(KEY_J).binding?.id).toBe("preview-next");
preview.release();
const list = scopes.activate("inbox/list");
expect(press(KEY_J).binding?.id).toBe("list-next");
list.release();
registry.dispose();
});
it("prefers the earliest registered binding at equal rank and falls through when it declines", () => {
const { registry, actions, scopes, runnable, press } = createHarness();
runnable("paseo/fallback");
let declines = true;
registry.registerBindings([
{ id: "core-e", actionId: "paseo/fallback", combo: "Cmd+E" },
{ id: "plugin-e", actionId: "paseo/plugin.e", combo: "Cmd+E" },
{
id: "list-e",
actionId: "inbox/list.archive",
combo: "Cmd+E",
when: { scope: "inbox/list" },
},
]);
runnable("paseo/plugin.e");
const cmdE = { key: "e", code: "KeyE", metaKey: true };
expect(press(cmdE).binding?.id).toBe("core-e");
const list = scopes.activate("inbox/list");
actions.registerHandler(
"inbox/list.archive",
() => (declines ? { handled: false } : undefined),
{ scope: list },
);
expect(press(cmdE).binding?.id).toBe("core-e");
declines = false;
expect(press(cmdE).binding?.id).toBe("list-e");
list.release();
registry.dispose();
});
it("evaluates bindings against the state passed with the key event", () => {
const { registry, runnable, press } = createHarness();
runnable("paseo/pane.focus.left");
registry.registerBinding({
id: "pane-focus-left",
actionId: "paseo/pane.focus.left",
combo: "Cmd+Shift+ArrowLeft",
when: { mac: true, editable: false },
});
const event = { key: "ArrowLeft", code: "ArrowLeft", metaKey: true, shiftKey: true };
expect(press(event, { focusScope: "message-input" }).handled).toBe(false);
expect(press(event, { isMac: false }).handled).toBe(false);
expect(press(event).handled).toBe(true);
registry.dispose();
});
});
describe("KeybindingRegistry printable keys", () => {
it("guards unmodified and Shift-only printable keys from typing surfaces on defaults and rebinds (D522)", () => {
const { registry, runnable, press, ran } = createHarness();
runnable("inbox/archive");
runnable("inbox/help");
runnable("inbox/tab.next");
registry.registerBindings([
{ id: "printable", actionId: "inbox/archive", combo: "J" },
{ id: "shift-printable", actionId: "inbox/help", combo: "Shift+?" },
{
id: "rebound",
actionId: "inbox/tab.next",
combo: "Cmd+Shift+ArrowRight",
when: { mac: true, editable: false },
},
]);
const shiftQuestion = { key: "?", code: "Slash", shiftKey: true };
for (const focusScope of ["editable", "message-input", "terminal"] as const) {
expect(press(KEY_J, { focusScope }).handled).toBe(false);
expect(press(shiftQuestion, { focusScope }).handled).toBe(false);
}
expect(press(KEY_J, { focusScope: "command-center", commandCenterOpen: true }).handled).toBe(
false,
);
registry.setOverrides({ rebound: "Shift+K" });
expect(
press({ key: "K", code: "KeyK", shiftKey: true }, { focusScope: "editable" }).handled,
).toBe(false);
registry.setOverrides({ rebound: "Alt+K" });
expect(
press({ key: "˚", code: "KeyK", altKey: true }, { focusScope: "editable" }).handled,
).toBe(true);
expect(press(KEY_J).handled).toBe(true);
expect(press(shiftQuestion).handled).toBe(true);
expect(ran).toEqual(["inbox/tab.next", "inbox/archive", "inbox/help"]);
registry.setOverrides({ printable: "Mod+1" });
expect(registry.getBinding("printable")?.when).toBeUndefined();
registry.dispose();
});
});
describe("KeybindingRegistry index", () => {
it("passes the pressed digit only for Digit bindings", () => {
const { registry, actions, press } = createHarness();
const invocations: ActionInvocation[] = [];
actions.registerHandler("inbox/folder.open", (invocation) => {
invocations.push(invocation);
});
registry.registerBindings([
{ id: "open-first", actionId: "inbox/folder.open", combo: "Cmd+A" },
{ id: "open-index", actionId: "inbox/folder.open", combo: "Cmd+Digit" },
]);
press({ key: "a", code: "KeyA", metaKey: true });
press({ key: "3", code: "Digit3", metaKey: true });
expect(invocations.map(({ index }) => index)).toEqual([undefined, 3]);
registry.dispose();
});
});
describe("KeybindingRegistry registration identity", () => {
it("merges two owners of one binding id, and removing either leaves the other", () => {
for (const [removed, remaining] of [
["host-1", "host-2"],
["host-2", "host-1"],
] as const) {
const { registry, runnable, press } = createHarness();
runnable("inbox/refresh");
const binding = { id: "inbox-refresh", actionId: "inbox/refresh", combo: "Cmd+R" };
const unregister = {
"host-1": registry.registerBinding({ ...binding, owner: "host-1" }),
"host-2": registry.registerBinding({ ...binding, owner: "host-2" }),
};
expect(registry.getBindings()).toHaveLength(1);
unregister[removed]();
expect(registry.getBinding("inbox-refresh")?.owner).toBe(remaining);
expect(press({ key: "r", code: "KeyR", metaKey: true }).handled).toBe(true);
registry.dispose();
}
});
it("rejects a duplicate binding id from the same owner without touching the first", () => {
const { registry } = createHarness();
registry.registerBinding({ id: "dup", actionId: "inbox/a", combo: "Cmd+1", owner: "h" });
expect(() =>
registry.registerBinding({ id: "dup", actionId: "inbox/b", combo: "Cmd+2", owner: "h" }),
).toThrow(DuplicateKeybindingError);
expect(() =>
registry.registerBindings([
{ id: "x", actionId: "inbox/x", combo: "Cmd+3" },
{ id: "x", actionId: "inbox/x", combo: "Cmd+4" },
]),
).toThrow(DuplicateKeybindingError);
expect(registry.getBinding("dup")?.actionId).toBe("inbox/a");
expect(registry.getBinding("x")).toBeNull();
registry.dispose();
});
it("commits registerBindings atomically and notifies once per batch", () => {
const { registry } = createHarness();
let notifications = 0;
registry.subscribe(() => {
notifications += 1;
});
expect(() =>
registry.registerBindings([
{ id: "valid-first", actionId: "paseo/a1", combo: "Cmd+1" },
{ id: "invalid-second", actionId: "paseo/a2", combo: "Cmd+NotARealKey" },
]),
).toThrow();
expect(registry.getBindings()).toEqual([]);
expect(notifications).toBe(0);
const unregister = registry.registerBindings([
{ id: "b1", actionId: "paseo/a1", combo: "Cmd+1" },
{ id: "b2", actionId: "paseo/a2", combo: "Cmd+2" },
]);
expect(notifications).toBe(1);
unregister();
unregister();
expect(notifications).toBe(2);
expect(registry.getBindings()).toEqual([]);
registry.dispose();
});
});
describe("KeybindingRegistry chords", () => {
it("handles multi-step chords, ignores bare modifiers, and resets on timeout", () => {
vi.useFakeTimers();
try {
const { registry, runnable, press, ran } = createHarness({ chordTimeoutMs: 1000 });
runnable("paseo/chord.test");
registry.registerBinding({
id: "chord",
actionId: "paseo/chord.test",
combo: "Cmd+K Shift+J",
});
const step1 = press(CMD_K);
expect(step1).toMatchObject({ chordPending: true, preventDefault: true });
expect(registry.getChordState()).toEqual({ step: 1, candidateIds: ["chord"] });
expect(press({ key: "Shift", code: "ShiftLeft", shiftKey: true }).chordPending).toBe(true);
expect(press({ key: "J", code: "KeyJ", shiftKey: true }).handled).toBe(true);
expect(ran).toEqual(["paseo/chord.test"]);
expect(registry.getChordState()).toEqual({ step: 0, candidateIds: [] });
press(CMD_K);
vi.advanceTimersByTime(1000);
expect(registry.getChordState()).toEqual({ step: 0, candidateIds: [] });
registry.dispose();
} finally {
vi.useRealTimers();
}
});
it("only reserves a chord prefix while its action can run", () => {
const { registry, actions, runnable, press, ran } = createHarness();
runnable("paseo/command-center.toggle");
registry.registerBindings([
{ id: "single-cmd-k", actionId: "paseo/command-center.toggle", combo: "Cmd+K" },
{ id: "chord-cmd-k-j", actionId: "inbox/chord.panel", combo: "Cmd+K J" },
]);
expect(press(CMD_K)).toMatchObject({ handled: true, chordPending: false });
let enabled = false;
const chordRuns: string[] = [];
actions.registerHandler(
"inbox/chord.panel",
() => {
chordRuns.push("chord");
},
{ enabled: () => enabled },
);
expect(press(CMD_K)).toMatchObject({ handled: true, chordPending: false });
expect(ran).toEqual(["paseo/command-center.toggle", "paseo/command-center.toggle"]);
enabled = true;
expect(press(CMD_K).chordPending).toBe(true);
expect(press(KEY_J).handled).toBe(true);
expect(chordRuns).toEqual(["chord"]);
registry.dispose();
});
it("drops a pending chord when its binding is rebound or replaced", () => {
const { registry, runnable, press, ran } = createHarness();
runnable("inbox/chord.run");
const unregister = registry.registerBinding({
id: "chord-main",
actionId: "inbox/chord.run",
combo: "Cmd+K J",
});
press(CMD_K);
registry.setOverrides({ "chord-main": "Cmd+X L" });
expect(registry.getChordState()).toEqual({ step: 0, candidateIds: [] });
registry.setOverrides({});
press(CMD_K);
expect(registry.getChordState().step).toBe(1);
unregister();
registry.registerBinding({ id: "chord-main", actionId: "inbox/chord.run", combo: "Cmd+K L" });
expect(registry.getChordState()).toEqual({ step: 0, candidateIds: [] });
expect(press({ key: "l", code: "KeyL" }).handled).toBe(false);
expect(ran).toEqual([]);
registry.dispose();
});
});
describe("KeybindingRegistry display keys", () => {
it("resolves the keys to show for an action on a platform", () => {
const { registry } = createHarness();
registry.registerBindings([
{
id: "toggle-mac",
actionId: "paseo/sidebar.toggle",
combo: "Cmd+B",
when: { mac: true },
},
{
id: "toggle-other",
actionId: "paseo/sidebar.toggle",
combo: "Ctrl+B",
when: { mac: false },
},
{ id: "toggle-alt", actionId: "paseo/sidebar.toggle", combo: "Ctrl+Alt+B" },
]);
const mac = { isMac: true, usesDesktopBindings: true };
const other = { isMac: false, usesDesktopBindings: true };
expect(registry.getDisplayKeys("paseo/sidebar.toggle", mac)).toEqual([["mod", "B"]]);
expect(registry.getDisplayKeys("paseo/sidebar.toggle", other)).toEqual([["ctrl", "B"]]);
registry.setOverrides({ "toggle-mac": "Cmd+Shift+B" });
expect(registry.getDisplayKeys("paseo/sidebar.toggle", mac)).toEqual([["mod", "shift", "B"]]);
registry.setOverrides({ "toggle-mac": UNASSIGNED_COMBO });
expect(registry.getDisplayKeys("paseo/sidebar.toggle", mac)).toEqual([["ctrl", "alt", "B"]]);
expect(registry.getDisplayKeys("paseo/missing", mac)).toBeNull();
registry.dispose();
});
});
describe("KeybindingRegistry conflicts", () => {
it("reports overlapping bindings and keeps distinct named scopes apart", () => {
const { registry } = createHarness();
registry.registerBindings([
{
id: "list1-archive",
actionId: "inbox/list1.archive",
combo: "Cmd+E",
when: { scope: "inbox/list1" },
},
{
id: "list2-archive",
actionId: "inbox/list2.archive",
combo: "Cmd+E",
when: { scope: "inbox/list2" },
},
{
id: "list1-duplicate",
actionId: "inbox/list1.edit",
combo: "Cmd+E",
when: { scope: "inbox/list1" },
},
{
id: "global-explorer",
actionId: "paseo/explorer.toggle",
combo: "Cmd+E",
when: { mac: true },
},
{
id: "non-mac-binding",
actionId: "paseo/explorer.win",
combo: "Cmd+E",
when: { mac: false },
},
{ id: "mod-b", actionId: "paseo/sidebar.left", combo: "Mod+B" },
]);
expect(
registry
.findConflictsForBinding("list2-archive")
.map((c) => c.conflictingBinding.id)
.sort(),
).toEqual(["global-explorer", "non-mac-binding"]);
expect(
registry
.findConflictsForBinding("list1-archive", { mac: true })
.map((c) => c.conflictingBinding.id)
.sort(),
).toEqual(["global-explorer", "list1-duplicate"]);
expect(registry.findConflictsForBinding("non-mac-binding", { mac: true })).toEqual([]);
expect(
registry
.findConflictsForBinding({ combo: "Cmd+B", when: { mac: true } }, { mac: true })
.map((c) => c.conflictingBinding.id),
).toEqual(["mod-b"]);
expect(
registry.findConflictsForBinding({ combo: "Cmd+B", when: { mac: false } }, { mac: false }),
).toEqual([]);
expect(registry.getConflicts({ mac: true })).toHaveLength(4);
registry.dispose();
});
it("distinguishes shortcuts that share a physical code but not a key", () => {
const { registry } = createHarness();
registry.registerBindings([
{ id: "cmd-slash", actionId: "paseo/slash", combo: "Cmd+/", when: { mac: true } },
{ id: "cmd-question", actionId: "paseo/question", combo: "Cmd+?", when: { mac: true } },
{
id: "cmd-shift-slash",
actionId: "paseo/shift.slash",
combo: "Cmd+Shift+/",
when: { mac: true },
},
{
id: "cmd-shift-question",
actionId: "paseo/shift.question",
combo: "Cmd+Shift+?",
when: { mac: true },
},
{ id: "cmd-alt-slash", actionId: "paseo/alt.slash", combo: "Cmd+Alt+/", when: { mac: true } },
{
id: "cmd-alt-question",
actionId: "paseo/alt.question",
combo: "Cmd+Alt+?",
when: { mac: true },
},
]);
expect(registry.findConflictsForBinding("cmd-slash", { mac: true })).toEqual([]);
expect(
registry
.findConflictsForBinding("cmd-shift-slash", { mac: true })
.map((c) => c.conflictingBinding.id),
).toEqual(["cmd-shift-question"]);
expect(
registry
.findConflictsForBinding("cmd-alt-slash", { mac: true })
.map((c) => c.conflictingBinding.id),
).toEqual(["cmd-alt-question"]);
expect(registry.getConflicts({ mac: true })).toHaveLength(2);
registry.dispose();
});
it("previews a rebind with the same guards setOverrides would apply", () => {
const { registry } = createHarness();
registry.registerBindings([
{
id: "pane-focus-left",
actionId: "paseo/pane.focus.left",
combo: "Cmd+Shift+ArrowLeft",
when: { mac: true, editable: false },
},
{
id: "editable-digit",
actionId: "inbox/snippet",
combo: "Cmd+1",
when: { mac: true, editable: true },
},
{
id: "other-j",
actionId: "inbox/other.j",
combo: "J",
when: { mac: true, focusScope: "other" },
},
]);
expect(
registry
.findConflictsForBinding({ id: "pane-focus-left", combo: "Mod+1" }, { mac: true })
.map((c) => c.conflictingBinding.id),
).toEqual(["editable-digit"]);
const printable = registry.findConflictsForBinding(
{ id: "pane-focus-left", combo: "J" },
{ mac: true },
);
expect(printable.map((c) => c.conflictingBinding.id)).toEqual(["other-j"]);
expect(printable[0]?.binding.when).toEqual({
mac: true,
editable: false,
terminal: false,
commandCenter: false,
});
registry.dispose();
});
});
@@ -0,0 +1,735 @@
import type { ActionRegistry, ActionScopeStore } from "@/actions";
import { UNASSIGNED_COMBO, type ShortcutOverrides } from "../shortcut-override-store";
import {
chordStringToShortcutKeys,
isModifierKeyCode,
isPrintableKeyCombo,
type KeyCombo,
} from "../shortcut-string";
import type { ShortcutKey } from "@/utils/format-shortcut";
import {
matchesCombo,
parseBindingChord,
parseDigit,
type KeyboardShortcutContext,
type KeyboardShortcutInput,
} from "./key-event";
import {
rankWhen,
toWhenClauses,
whenClausesOverlap,
whenMatchesPlatform,
type When,
type WhenClause,
} from "./when";
import type { DisplayPlatform } from "./when";
export interface KeybindingInput {
/** Stable id. `ShortcutOverrideStore` keys user rebinds by it. */
id: string;
actionId: string;
combo: string;
when?: When;
/** Opaque registrant. Core registers with none (`null`). */
owner?: string | null;
repeat?: false;
preventDefault?: boolean;
stopPropagation?: boolean;
/**
* The action keeps going while the combo's modifier stays held, and
* releasing it finishes the action, as Ctrl+Tab does in the workspace
* switcher. Key sources that sit outside the app, such as the Electron
* browser pane, forward the key-up for it.
*/
holdRelease?: true;
}
export interface EffectiveKeybinding {
readonly id: string;
readonly actionId: string;
readonly owner: string | null;
readonly combo: string;
readonly defaultCombo: string;
readonly parsedChord: readonly KeyCombo[];
readonly when?: When;
readonly preventDefault: boolean;
readonly stopPropagation: boolean;
readonly holdRelease: boolean;
readonly isOverridden: boolean;
readonly registeredAt: number;
}
export interface RegistryChordState {
readonly step: number;
readonly candidateIds: readonly string[];
}
export interface KeybindingDispatchResult {
readonly handled: boolean;
readonly chordPending: boolean;
readonly preventDefault: boolean;
readonly stopPropagation: boolean;
readonly binding: EffectiveKeybinding | null;
}
export interface ConflictQueryOptions {
mac?: boolean;
desktop?: boolean;
}
export interface KeybindingConflictCandidate {
id?: string;
actionId?: string;
combo: string;
when?: When;
isOverride?: boolean;
}
export interface KeybindingConflict {
readonly binding: EffectiveKeybinding;
readonly conflictingBinding: EffectiveKeybinding;
readonly combo: string;
readonly kind: "exact" | "prefix";
}
export type { DisplayPlatform };
export interface KeybindingRegistryOptions {
actions: ActionRegistry;
scopes: ActionScopeStore;
initialOverrides?: ShortcutOverrides;
chordTimeoutMs?: number;
}
export interface KeybindingRegistry {
registerBinding(binding: KeybindingInput): () => void;
/** All or nothing: an invalid combo or duplicate id registers none of them. */
registerBindings(bindings: readonly KeybindingInput[]): () => void;
setOverrides(overrides: ShortcutOverrides): void;
getOverrides(): ShortcutOverrides;
getBindings(): readonly EffectiveKeybinding[];
getBinding(id: string): EffectiveKeybinding | null;
/** The keys a badge or menu shows for `actionId`, or `null` when it has none on this platform. */
getDisplayKeys(actionId: string, platform: DisplayPlatform): ShortcutKey[][] | null;
getChordState(): RegistryChordState;
resetChord(): void;
/** `context` is the live focus and platform state the key event came from. */
dispatchKeyDown(
event: KeyboardShortcutInput,
context: KeyboardShortcutContext,
): KeybindingDispatchResult;
getConflicts(options?: ConflictQueryOptions): readonly KeybindingConflict[];
findConflictsForBinding(
target: string | KeybindingConflictCandidate,
options?: ConflictQueryOptions,
): readonly KeybindingConflict[];
subscribe(listener: () => void): () => void;
dispose(): void;
}
/**
* The keys a badge shows for `actionId`: its first assigned binding on
* `platform`, or `null` when it has none.
*/
export function displayKeysFor(
bindings: readonly EffectiveKeybinding[],
actionId: string,
platform: DisplayPlatform,
): ShortcutKey[][] | null {
const binding = bindings.find(
(candidate) =>
candidate.actionId === actionId &&
candidate.parsedChord.length > 0 &&
whenMatchesPlatform(candidate.when, platform),
);
return binding ? chordStringToShortcutKeys(binding.combo) : null;
}
export class DuplicateKeybindingError extends Error {
readonly bindingId: string;
readonly owner: string | null;
constructor(bindingId: string, owner: string | null) {
super(`Keybinding "${bindingId}" is already registered by owner ${owner ?? "(none)"}`);
this.name = "DuplicateKeybindingError";
this.bindingId = bindingId;
this.owner = owner;
}
}
interface StoredKeybinding {
readonly input: KeybindingInput;
readonly owner: string | null;
readonly defaultChord: readonly KeyCombo[];
readonly registeredAt: number;
}
const DEFAULT_CHORD_TIMEOUT_MS = 1500;
const IDLE_CHORD_STATE: RegistryChordState = { step: 0, candidateIds: [] };
const UNHANDLED: KeybindingDispatchResult = {
handled: false,
chordPending: false,
preventDefault: false,
stopPropagation: false,
binding: null,
};
const CHORD_PENDING: KeybindingDispatchResult = {
handled: false,
chordPending: true,
preventDefault: true,
stopPropagation: true,
binding: null,
};
// --- Printable-key guard (D522) ---
const PRINTABLE_GUARD = { editable: false, terminal: false, commandCenter: false } as const;
function isClauseList(when: When): when is readonly WhenClause[] {
return Array.isArray(when);
}
function mapWhen(when: When, map: (clause: WhenClause) => WhenClause): When {
return isClauseList(when) ? when.map(map) : map(when);
}
/** An unmodified or Shift-only printable first key would type into text, so it never fires there. */
function guardPrintable(when: When | undefined, chord: readonly KeyCombo[]): When | undefined {
const first = chord[0];
if (!first || !isPrintableKeyCombo(first)) {
return when;
}
if (when === undefined) {
return { ...PRINTABLE_GUARD };
}
return mapWhen(when, (clause) => ({ ...clause, ...PRINTABLE_GUARD }));
}
/**
* `editable: false` on a default describes its shipped combo, such as
* Cmd+Shift+Arrow that also selects text. A rebind drops it, unless the new
* combo is printable and the D522 guard applies.
*/
function whenForOverride(when: When | undefined, chord: readonly KeyCombo[]): When | undefined {
if (chord[0] && isPrintableKeyCombo(chord[0])) {
return guardPrintable(when, chord);
}
if (when === undefined) {
return undefined;
}
return mapWhen(when, (clause) => {
if (clause.editable !== false) return clause;
const { editable: _editable, ...rest } = clause;
return rest;
});
}
// --- Effective bindings ---
function parseChord(combo: string, repeat: false | undefined): KeyCombo[] {
const chord = parseBindingChord(combo);
const last = chord.at(-1);
if (repeat === false && last) {
last.repeat = false;
}
return chord;
}
function buildEffective(
stored: StoredKeybinding,
resolved: {
combo: string;
parsedChord: readonly KeyCombo[];
when: When | undefined;
isOverridden: boolean;
},
): EffectiveKeybinding {
const { input } = stored;
return {
id: input.id,
actionId: input.actionId,
owner: stored.owner,
combo: resolved.combo,
defaultCombo: input.combo,
parsedChord: resolved.parsedChord,
...(resolved.when !== undefined ? { when: resolved.when } : {}),
preventDefault: input.preventDefault ?? true,
stopPropagation: input.stopPropagation ?? true,
holdRelease: input.holdRelease === true,
isOverridden: resolved.isOverridden,
registeredAt: stored.registeredAt,
};
}
function resolveEffective(
stored: StoredKeybinding,
overrides: ShortcutOverrides,
): EffectiveKeybinding {
const { input, defaultChord } = stored;
const override = overrides[input.id];
if (override === UNASSIGNED_COMBO || override === "") {
return buildEffective(stored, {
combo: "",
parsedChord: [],
when: input.when,
isOverridden: true,
});
}
if (typeof override === "string") {
try {
const parsedChord = parseChord(override, input.repeat);
return buildEffective(stored, {
combo: override,
parsedChord,
when: whenForOverride(input.when, parsedChord),
isOverridden: true,
});
} catch {
// An unparseable stored override falls back to the default combo.
}
}
return buildEffective(stored, {
combo: input.combo,
parsedChord: defaultChord,
when: guardPrintable(input.when, defaultChord),
isOverridden: false,
});
}
function combosEqual(left: KeyCombo, right: KeyCombo): boolean {
return (
left.code === right.code &&
left.key === right.key &&
left.shiftedKey === right.shiftedKey &&
Boolean(left.codeFallback) === Boolean(right.codeFallback) &&
Boolean(left.meta) === Boolean(right.meta) &&
Boolean(left.ctrl) === Boolean(right.ctrl) &&
Boolean(left.alt) === Boolean(right.alt) &&
Boolean(left.shift) === Boolean(right.shift) &&
Boolean(left.mod) === Boolean(right.mod)
);
}
// --- Static conflicts ---
function acceptedKeys(combo: KeyCombo): Set<string> | null {
if (combo.key === undefined) {
return null;
}
const keys = new Set<string>([combo.key.toLowerCase()]);
if (combo.shift === true && combo.shiftedKey !== undefined) {
keys.add(combo.shiftedKey.toLowerCase());
}
return keys;
}
function usesCodeFallback(combo: KeyCombo): boolean {
return combo.key === undefined || combo.alt === true || combo.codeFallback === true;
}
function modifiersMatchOnPlatform(left: KeyCombo, right: KeyCombo, mac: boolean): boolean {
const leftMeta = Boolean(left.meta || (mac && left.mod));
const rightMeta = Boolean(right.meta || (mac && right.mod));
const leftCtrl = Boolean(left.ctrl || (!mac && left.mod));
const rightCtrl = Boolean(right.ctrl || (!mac && right.mod));
return (
leftMeta === rightMeta &&
leftCtrl === rightCtrl &&
Boolean(left.alt) === Boolean(right.alt) &&
Boolean(left.shift) === Boolean(right.shift)
);
}
function isDigitWildcardOverlap(leftCode: string, rightCode: string): boolean {
if (leftCode === "Digit" && rightCode === "Digit") return true;
if (leftCode === "Digit" && /^Digit[1-9]$/.test(rightCode)) return true;
return rightCode === "Digit" && /^Digit[1-9]$/.test(leftCode);
}
function keysOverlap(left: KeyCombo, right: KeyCombo): boolean {
if (usesCodeFallback(left) || usesCodeFallback(right)) {
return true;
}
const leftKeys = acceptedKeys(left);
const rightKeys = acceptedKeys(right);
if (!leftKeys || !rightKeys) {
return true;
}
return [...leftKeys].some((key) => rightKeys.has(key));
}
function combosOverlap(left: KeyCombo, right: KeyCombo, mac: boolean): boolean {
if (!modifiersMatchOnPlatform(left, right, mac)) return false;
if (isDigitWildcardOverlap(left.code, right.code)) return true;
return left.code === right.code && keysOverlap(left, right);
}
function chordConflictKind(
left: readonly KeyCombo[],
right: readonly KeyCombo[],
mac: boolean,
): "exact" | "prefix" | null {
if (left.length === 0 || right.length === 0) {
return null;
}
const shared = Math.min(left.length, right.length);
for (let index = 0; index < shared; index += 1) {
if (!combosOverlap(left[index], right[index], mac)) {
return null;
}
}
return left.length === right.length ? "exact" : "prefix";
}
function whenOnPlatform(when: When | undefined, mac: boolean, desktop: boolean | undefined): When {
const clauses: WhenClause[] = [];
for (const clause of toWhenClauses(when)) {
if (clause.mac !== undefined && clause.mac !== mac) continue;
if (desktop !== undefined && clause.desktop !== undefined && clause.desktop !== desktop) {
continue;
}
clauses.push({ ...clause, mac, ...(desktop !== undefined ? { desktop } : {}) });
}
return clauses;
}
function detectConflict(
left: EffectiveKeybinding,
right: EffectiveKeybinding,
options: ConflictQueryOptions | undefined,
): KeybindingConflict | null {
if (left.id === right.id) {
return null;
}
for (const mac of options?.mac !== undefined ? [options.mac] : [true, false]) {
const kind = chordConflictKind(left.parsedChord, right.parsedChord, mac);
if (!kind) continue;
const leftWhen = whenOnPlatform(left.when, mac, options?.desktop);
const rightWhen = whenOnPlatform(right.when, mac, options?.desktop);
if (whenClausesOverlap(leftWhen, rightWhen)) {
return { binding: left, conflictingBinding: right, combo: left.combo, kind };
}
}
return null;
}
// --- Registry ---
/**
* Runtime keybindings merged with user overrides. A key press goes to the
* matching bindings by rank: the innermost active scope first, then the
* earliest registered. Each binding dispatches its action through the
* `ActionRegistry`; a binding whose action declines falls through to the next.
*
* The same binding id may be registered once per host, such as one plugin
* loaded from two hosts. The first registration is effective; when it
* unregisters, the next one takes over.
*/
export function createKeybindingRegistry(options: KeybindingRegistryOptions): KeybindingRegistry {
const { actions, scopes } = options;
const chordTimeoutMs = options.chordTimeoutMs ?? DEFAULT_CHORD_TIMEOUT_MS;
const registrationsById = new Map<string, StoredKeybinding[]>();
const effectiveById = new Map<string, EffectiveKeybinding>();
const listeners = new Set<() => void>();
let overrides: ShortcutOverrides = { ...options.initialOverrides };
let effectiveList: readonly EffectiveKeybinding[] = [];
let chordState: RegistryChordState = IDLE_CHORD_STATE;
let chordTimer: ReturnType<typeof setTimeout> | null = null;
let nextOrder = 1;
function notify(): void {
for (const listener of listeners) {
listener();
}
}
function clearChord(): boolean {
if (chordTimer !== null) {
clearTimeout(chordTimer);
chordTimer = null;
}
if (chordState === IDLE_CHORD_STATE) {
return false;
}
chordState = IDLE_CHORD_STATE;
return true;
}
function setChord(step: number, candidates: readonly EffectiveKeybinding[]): void {
clearChord();
chordState = { step, candidateIds: candidates.map((binding) => binding.id) };
chordTimer = setTimeout(() => {
if (clearChord()) notify();
}, chordTimeoutMs);
notify();
}
/** A pending candidate survives a rebuild only if its prefix and registration are unchanged. */
function keepsPendingPrefix(previous: EffectiveKeybinding | undefined, id: string): boolean {
const next = effectiveById.get(id);
if (!previous || !next || previous.registeredAt !== next.registeredAt) return false;
if (next.parsedChord.length <= chordState.step) return false;
for (let index = 0; index < chordState.step; index += 1) {
if (!combosEqual(previous.parsedChord[index], next.parsedChord[index])) return false;
}
return true;
}
function rebuild(): void {
const previousById = new Map(effectiveById);
effectiveById.clear();
const next: EffectiveKeybinding[] = [];
for (const registrations of registrationsById.values()) {
const current = registrations[0];
if (!current) continue;
const effective = resolveEffective(current, overrides);
effectiveById.set(effective.id, effective);
next.push(effective);
}
effectiveList = next.sort((left, right) => left.registeredAt - right.registeredAt);
if (chordState.step > 0) {
const remaining = chordState.candidateIds.filter((id) =>
keepsPendingPrefix(previousById.get(id), id),
);
if (remaining.length === 0) {
clearChord();
} else if (remaining.length !== chordState.candidateIds.length) {
chordState = { step: chordState.step, candidateIds: remaining };
}
}
}
function prepare(bindings: readonly KeybindingInput[]): StoredKeybinding[] {
const claimed = new Set<string>();
return bindings.map((input) => {
const owner = input.owner ?? null;
const key = `${owner ?? ""}\u0000${input.id}`;
const taken = registrationsById.get(input.id)?.some((entry) => entry.owner === owner);
if (taken || claimed.has(key)) {
throw new DuplicateKeybindingError(input.id, owner);
}
claimed.add(key);
return {
input,
owner,
defaultChord: parseChord(input.combo, input.repeat),
registeredAt: nextOrder + claimed.size - 1,
};
});
}
function register(bindings: readonly KeybindingInput[]): () => void {
if (bindings.length === 0) {
return () => {};
}
const entries = prepare(bindings);
nextOrder += entries.length;
for (const entry of entries) {
registrationsById.set(entry.input.id, [
...(registrationsById.get(entry.input.id) ?? []),
entry,
]);
}
rebuild();
notify();
let disposed = false;
return () => {
if (disposed) return;
disposed = true;
for (const entry of entries) {
const remaining = (registrationsById.get(entry.input.id) ?? []).filter(
(candidate) => candidate !== entry,
);
if (remaining.length === 0) {
registrationsById.delete(entry.input.id);
} else {
registrationsById.set(entry.input.id, remaining);
}
}
rebuild();
notify();
};
}
/** Tries each candidate by rank until one's action takes the key. */
function dispatchFirst(
candidates: ReadonlyArray<{ binding: EffectiveKeybinding; rank: number }>,
event: KeyboardShortcutInput,
step: number,
): EffectiveKeybinding | null {
const ordered = [...candidates].sort(
(left, right) =>
right.rank - left.rank || left.binding.registeredAt - right.binding.registeredAt,
);
for (const { binding } of ordered) {
const index =
binding.parsedChord[step]?.code === "Digit" ? (parseDigit(event) ?? undefined) : undefined;
const handled = actions.dispatch(
binding.actionId,
index !== undefined ? { index } : undefined,
);
if (handled) {
return binding;
}
}
return null;
}
function handledBy(binding: EffectiveKeybinding): KeybindingDispatchResult {
return {
handled: true,
chordPending: false,
preventDefault: binding.preventDefault,
stopPropagation: binding.stopPropagation,
binding,
};
}
return {
registerBinding(binding) {
return register([binding]);
},
registerBindings(bindings) {
return register(bindings);
},
setOverrides(nextOverrides) {
overrides = { ...nextOverrides };
rebuild();
notify();
},
getOverrides() {
return overrides;
},
getBindings() {
return effectiveList;
},
getBinding(id) {
return effectiveById.get(id) ?? null;
},
getDisplayKeys(actionId, platform) {
return displayKeysFor(effectiveList, actionId, platform);
},
getChordState() {
return chordState;
},
resetChord() {
if (clearChord()) notify();
},
dispatchKeyDown(event, context) {
if (isModifierKeyCode(event.code)) {
return chordState.step > 0 ? CHORD_PENDING : UNHANDLED;
}
const activeScopes = scopes.getActiveScopes();
const step = chordState.step;
const pool =
step === 0
? effectiveList
: chordState.candidateIds.flatMap((id) => effectiveById.get(id) ?? []);
const completing: Array<{ binding: EffectiveKeybinding; rank: number }> = [];
const advancing: EffectiveKeybinding[] = [];
for (const binding of pool) {
const combo = binding.parsedChord[step];
if (!combo || !matchesCombo(combo, event, context.isMac)) continue;
const rank = rankWhen(binding.when, context, activeScopes);
if (rank === null) continue;
if (binding.parsedChord.length === step + 1) {
completing.push({ binding, rank });
} else if (step > 0 || actions.canDispatch(binding.actionId)) {
advancing.push(binding);
}
}
// A chord start reserves its prefix over a single-key binding on the same keys.
if (step === 0 && advancing.length > 0) {
setChord(1, advancing);
return CHORD_PENDING;
}
const matched = dispatchFirst(completing, event, step);
if (matched) {
if (clearChord()) notify();
return handledBy(matched);
}
if (advancing.length > 0) {
setChord(step + 1, advancing);
return CHORD_PENDING;
}
if (clearChord()) notify();
return UNHANDLED;
},
getConflicts(queryOptions) {
const conflicts: KeybindingConflict[] = [];
for (let i = 0; i < effectiveList.length; i += 1) {
for (let j = i + 1; j < effectiveList.length; j += 1) {
const conflict = detectConflict(effectiveList[i], effectiveList[j], queryOptions);
if (conflict) conflicts.push(conflict);
}
}
return conflicts;
},
findConflictsForBinding(target, queryOptions) {
let subject: EffectiveKeybinding;
if (typeof target === "string") {
const existing = effectiveById.get(target);
if (!existing) return [];
subject = existing;
} else {
if (target.combo === "") return [];
let parsedChord: KeyCombo[];
try {
parsedChord = parseBindingChord(target.combo);
} catch {
return [];
}
const existing = target.id !== undefined ? effectiveById.get(target.id) : undefined;
const isOverride = target.isOverride === true || existing !== undefined;
const baseWhen = target.when ?? registrationsById.get(target.id ?? "")?.[0]?.input.when;
const when = isOverride
? whenForOverride(baseWhen, parsedChord)
: guardPrintable(baseWhen, parsedChord);
subject = {
id: target.id ?? "",
actionId: target.actionId ?? existing?.actionId ?? "",
owner: null,
combo: target.combo,
defaultCombo: existing?.defaultCombo ?? target.combo,
parsedChord,
...(when !== undefined ? { when } : {}),
preventDefault: true,
stopPropagation: true,
holdRelease: false,
isOverridden: isOverride,
registeredAt: 0,
};
}
return effectiveList.flatMap(
(candidate) => detectConflict(subject, candidate, queryOptions) ?? [],
);
},
subscribe(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
dispose() {
clearChord();
},
};
}
@@ -1,4 +1,4 @@
import type { KeyboardShortcutInput } from "../keyboard-shortcuts";
import type { KeyboardShortcutInput } from "./key-event";
export interface KeyboardInputEvent extends KeyboardShortcutInput {
isComposing?: boolean;
+16 -38
View File
@@ -1,59 +1,37 @@
import {
resolveKeyboardShortcut,
type ChordState,
type KeyboardShortcutContext,
type KeyboardShortcutMatch,
type ParsedShortcutBinding,
} from "../keyboard-shortcuts";
import type { KeyboardShortcutContext } from "./key-event";
import type { KeybindingDispatchResult, KeybindingRegistry } from "./keybinding-registry";
import type { KeyboardSourceInput } from "./sources/contract";
import type { createOverlayRegistry } from "./overlays";
interface KeyboardPipelineOptions {
getContext(): Omit<KeyboardShortcutContext, "focusScope">;
getBindings(): readonly ParsedShortcutBinding[];
keybindings: KeybindingRegistry;
isCapturing(): boolean;
dispatch(match: KeyboardShortcutMatch, input: KeyboardSourceInput): boolean;
overlays: ReturnType<typeof createOverlayRegistry>;
beforeResolve?(input: KeyboardSourceInput): boolean;
chordChanged?(previous: ChordState, next: ChordState, input: KeyboardSourceInput | null): void;
}
function emptyChord(): ChordState {
return { candidateIndices: [], step: 0, timeoutId: null };
/** Runs after a binding's action took the key. */
handled?(result: KeybindingDispatchResult, input: KeyboardSourceInput): void;
}
/** The order a key press is offered in: overlays, then bindings. */
export function createKeyboardPipeline(options: KeyboardPipelineOptions) {
let chord = emptyChord();
function reset() {
const previous = chord;
if (chord.timeoutId !== null) clearTimeout(chord.timeoutId);
chord = emptyChord();
options.chordChanged?.(previous, chord, null);
}
return {
dispose: reset,
dispose() {
options.keybindings.resetChord();
},
keyDown(input: KeyboardSourceInput): boolean {
const event = input.event;
if (options.overlays.dispatch(event)) return true;
if (event.isComposing || event.key === "Process" || options.isCapturing()) return false;
if (options.beforeResolve && !options.beforeResolve(input)) return false;
const previous = chord;
const result = resolveKeyboardShortcut({
event,
context: { ...options.getContext(), focusScope: input.focusScope },
bindings: options.getBindings(),
chordState: chord,
onChordReset: reset,
const result = options.keybindings.dispatchKeyDown(event, {
...options.getContext(),
focusScope: input.focusScope,
});
chord = result.nextChordState;
options.chordChanged?.(previous, chord, input);
if (result.preventDefault) {
event.preventDefault();
event.stopPropagation();
}
if (!result.match) return false;
if (!options.dispatch(result.match, input)) return false;
if (result.match.preventDefault) event.preventDefault();
if (result.match.stopPropagation) event.stopPropagation();
if (result.preventDefault) event.preventDefault();
if (result.stopPropagation) event.stopPropagation();
if (!result.handled) return false;
options.handled?.(result, input);
return true;
},
};
@@ -0,0 +1,57 @@
import { createContext, type ReactNode, useContext, useMemo, useSyncExternalStore } from "react";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import { usesDesktopBindings } from "./conventions";
import {
type DisplayPlatform,
displayKeysFor,
type EffectiveKeybinding,
type KeybindingRegistry,
} from "./keybinding-registry";
const KeybindingRegistryContext = createContext<KeybindingRegistry | null>(null);
export function KeybindingRegistryProvider({
keybindings,
children,
}: {
keybindings: KeybindingRegistry;
children: ReactNode;
}) {
return (
<KeybindingRegistryContext.Provider value={keybindings}>
{children}
</KeybindingRegistryContext.Provider>
);
}
export function useKeybindingRegistry(): KeybindingRegistry {
const keybindings = useContext(KeybindingRegistryContext);
if (!keybindings) {
throw new Error("Keybinding hooks must be used within KeybindingRegistryProvider");
}
return keybindings;
}
/** The effective bindings, with user overrides applied, in resolution order. */
export function useKeybindings(): readonly EffectiveKeybinding[] {
const keybindings = useKeybindingRegistry();
return useSyncExternalStore(keybindings.subscribe, keybindings.getBindings);
}
/** The platform the app shows shortcut keys for. */
export function getDisplayPlatform(): DisplayPlatform {
return { isMac: getShortcutOs() === "mac", usesDesktopBindings };
}
/**
* The keys a badge shows for `actionId` on this platform, or `null` when it has
* none. `null` ids are accepted so callers can keep the hook unconditional.
*/
export function useShortcutKeys(actionId: string | null): ShortcutKey[][] | null {
const bindings = useKeybindings();
return useMemo(
() => (actionId === null ? null : displayKeysFor(bindings, actionId, getDisplayPlatform())),
[actionId, bindings],
);
}
@@ -1,4 +1,4 @@
import type { KeyboardFocusScope } from "../../actions";
import type { KeyboardFocusScope } from "../key-event";
import type { KeyboardInputEvent } from "../overlays";
export interface KeyboardSourceInput {
event: KeyboardInputEvent;
@@ -19,10 +19,10 @@ export function nativeKeyboardInput(
return { event, focusScope, captureFocusRestore() {} };
}
import type { ChordState, ParsedShortcutBinding } from "../../keyboard-shortcuts";
import type { EffectiveKeybinding, RegistryChordState } from "../keybinding-registry";
export interface KeyboardPolicyInput {
bindings: readonly ParsedShortcutBinding[];
chordState?: ChordState;
bindings: readonly EffectiveKeybinding[];
chordState?: RegistryChordState;
isMac: boolean;
usesDesktopBindings: boolean;
enabled: boolean;
@@ -5,11 +5,16 @@ import {
parseBrowserShortcutInput,
shouldPublishBrowserShortcutPolicy,
} from "./electron-browser";
import { buildEffectiveBindings, resolveKeyboardShortcut } from "../../keyboard-shortcuts";
import { createRecordingCoreRegistries } from "@/core-actions/testing";
import type { ShortcutOverrides } from "../../shortcut-override-store";
function effectiveBindings(overrides: ShortcutOverrides) {
return createRecordingCoreRegistries(overrides).keybindings.getBindings();
}
describe("buildBrowserKeyboardPolicy", () => {
it("publishes only chord starts while no browser chord is pending", () => {
const bindings = buildEffectiveBindings({
const bindings = effectiveBindings({
"workspace-tab-new-ctrl-t-non-mac": "Ctrl+Y",
"workspace-terminal-new-ctrl-shift-t-non-mac": "Ctrl+F12 Ctrl+F11",
});
@@ -45,16 +50,13 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("publishes a chord continuation only after its browser start crosses the boundary", () => {
const bindings = buildEffectiveBindings({
"workspace-terminal-new-ctrl-shift-t-non-mac": "Ctrl+F12 Ctrl+F11",
});
const chordIndex = bindings.findIndex(
(binding) => binding.id === "workspace-terminal-new-ctrl-shift-t-non-mac",
);
const overrides = { "workspace-terminal-new-ctrl-shift-t-non-mac": "Ctrl+F12 Ctrl+F11" };
const core = createRecordingCoreRegistries(overrides);
const bindings = core.keybindings.getBindings();
const policy = buildBrowserKeyboardPolicy({
bindings,
chordState: { candidateIndices: [chordIndex], step: 1, timeoutId: null },
chordState: { candidateIds: ["workspace-terminal-new-ctrl-shift-t-non-mac"], step: 1 },
isMac: false,
usesDesktopBindings: true,
});
@@ -77,32 +79,30 @@ describe("buildBrowserKeyboardPolicy", () => {
shift: false,
});
const result = resolveKeyboardShortcut({
event: {
altKey: false,
code: "F11",
ctrlKey: true,
key: "F11",
metaKey: false,
repeat: false,
shiftKey: false,
},
context: {
commandCenterOpen: false,
focusScope: "browser",
usesDesktopBindings: true,
isMac: false,
},
chordState: { candidateIndices: [chordIndex], step: 1, timeoutId: null },
onChordReset: () => undefined,
bindings,
const browserContext = {
commandCenterOpen: false,
focusScope: "browser" as const,
usesDesktopBindings: true,
isMac: false,
};
const ctrlKey = (key: string) => ({
altKey: false,
code: key,
ctrlKey: true,
key,
metaKey: false,
repeat: false,
shiftKey: false,
});
core.keybindings.dispatchKeyDown(ctrlKey("F12"), browserContext);
core.keybindings.dispatchKeyDown(ctrlKey("F11"), browserContext);
expect(result.match?.action).toBe("workspace.terminal.new");
expect(core.ranIds()).toEqual(["paseo/workspace.terminal.new"]);
core.keybindings.dispose();
});
it("rejects an entire chord when a continuation cannot cross the browser boundary", () => {
const bindings = buildEffectiveBindings({
const bindings = effectiveBindings({
"settings-toggle-ctrl-comma-non-mac": "Ctrl+F10 F9",
});
@@ -129,7 +129,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("publishes Mod bindings for the current shortcut platform", () => {
const bindings = buildEffectiveBindings({
const bindings = effectiveBindings({
"workspace-tab-new-cmd-t-mac": "Mod+Y",
});
@@ -146,7 +146,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("keeps Ctrl+W out of the window menu after the tab-close shortcut is remapped", () => {
const bindings = buildEffectiveBindings({
const bindings = effectiveBindings({
"workspace-tab-close-current-ctrl-w-non-mac": "Ctrl+Y",
});
@@ -175,7 +175,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("leaves macOS browser back and forward shortcuts in the guest", () => {
const bindings = buildEffectiveBindings({});
const bindings = effectiveBindings({});
const policy = buildBrowserKeyboardPolicy({ bindings, isMac: true, usesDesktopBindings: true });
@@ -192,7 +192,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("marks editable-only exclusions for enforcement inside the guest", () => {
const bindings = buildEffectiveBindings({});
const bindings = effectiveBindings({});
const policy = buildBrowserKeyboardPolicy({ bindings, isMac: true, usesDesktopBindings: true });
expect(policy.prefixes).toContainEqual({
@@ -206,7 +206,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("does not publish plain browser keys", () => {
const bindings = buildEffectiveBindings({});
const bindings = effectiveBindings({});
const policy = buildBrowserKeyboardPolicy({
bindings,
isMac: false,
@@ -230,7 +230,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("publishes Cmd+B with its logical key for non-QWERTY layouts", () => {
const bindings = buildEffectiveBindings({});
const bindings = effectiveBindings({});
const policy = buildBrowserKeyboardPolicy({ bindings, isMac: true, usesDesktopBindings: true });
expect(policy.prefixes).toContainEqual({
@@ -244,7 +244,7 @@ describe("buildBrowserKeyboardPolicy", () => {
});
it("publishes the physical code needed for macOS Option shortcuts", () => {
const bindings = buildEffectiveBindings({});
const bindings = effectiveBindings({});
const policy = buildBrowserKeyboardPolicy({ bindings, isMac: true, usesDesktopBindings: true });
expect(policy.prefixes).toContainEqual({
@@ -263,8 +263,8 @@ describe("shouldPublishBrowserShortcutPolicy", () => {
expect(
shouldPublishBrowserShortcutPolicy({
isBrowserInput: false,
previousChordState: { candidateIndices: [1], step: 1, timeoutId: null },
nextChordState: { candidateIndices: [], step: 0, timeoutId: null },
previousChordState: { candidateIds: ["agent-interrupt"], step: 1 },
nextChordState: { candidateIds: [], step: 0 },
}),
).toBe(true);
});
@@ -342,19 +342,15 @@ describe("Electron guest source through shared resolution", () => {
it("replays guest input through user rebinds and preserves focus restoration", async () => {
const { createKeyboardPipeline } = await import("../pipeline");
const { createOverlayRegistry } = await import("../overlays");
const actions: string[] = [];
const core = createRecordingCoreRegistries({ "command-center-toggle-cmd-k-mac": "Cmd+J" });
const restored: string[] = [];
let receive: (payload: unknown) => void = () => {};
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac: true, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({ "command-center-toggle-cmd-k-mac": "Cmd+J" }),
keybindings: core.keybindings,
isCapturing: () => false,
overlays: createOverlayRegistry(),
dispatch: (match, input) => {
actions.push(match.action);
input.captureFocusRestore();
return true;
},
handled: (_result, input) => input.captureFocusRestore(),
});
const detach = attachElectronBrowserSource(
{
@@ -383,14 +379,14 @@ describe("Electron guest source through shared resolution", () => {
meta: true,
shift: false,
});
expect(actions).toEqual(["command-center.toggle"]);
expect(core.ranIds()).toEqual(["paseo/command-center.toggle"]);
expect(restored).toEqual(["tab-1"]);
detach();
pipeline.dispose();
});
it("publishes Ctrl+Tab and Ctrl+Shift+Tab and forwards guest keyUp payloads", () => {
const bindings = buildEffectiveBindings({});
const bindings = effectiveBindings({});
const policy = buildBrowserKeyboardPolicy({ bindings, isMac: true, usesDesktopBindings: true });
expect(policy.prefixes).toContainEqual({
@@ -1,10 +1,7 @@
import {
type ChordState,
matchesKeyboardShortcutContext,
type KeyboardShortcutInput,
type ParsedShortcutBinding,
} from "../../keyboard-shortcuts";
import type { KeyCombo } from "../../shortcut-string";
import type { KeyboardShortcutInput } from "../key-event";
import type { EffectiveKeybinding, RegistryChordState } from "../keybinding-registry";
import { evaluateWhen, toWhenClauses } from "../when";
export interface BrowserShortcutPrefix {
alt: boolean;
@@ -31,16 +28,16 @@ export interface BrowserKeyboardPolicy {
}
interface BrowserShortcutPolicyInput {
bindings: readonly ParsedShortcutBinding[];
chordState?: ChordState;
bindings: readonly EffectiveKeybinding[];
chordState?: RegistryChordState;
isMac: boolean;
usesDesktopBindings: boolean;
}
export function shouldPublishBrowserShortcutPolicy(input: {
isBrowserInput: boolean;
nextChordState: ChordState;
previousChordState: ChordState;
nextChordState: RegistryChordState;
previousChordState: RegistryChordState;
}): boolean {
return (
input.isBrowserInput || (input.previousChordState.step > 0 && input.nextChordState.step === 0)
@@ -131,10 +128,16 @@ function isBrowserNativeNavigationPrefix(prefix: BrowserShortcutPrefix, isMac: b
);
}
function canCrossBrowserBoundary(binding: ParsedShortcutBinding, isMac: boolean): boolean {
const holdRelease = binding.action === "workspace.switcher.cycle";
/** `false` when the binding never fires in a text field, so the pane forwards it only outside one. */
function editableGuard(binding: EffectiveKeybinding): false | undefined {
return toWhenClauses(binding.when).every((clause) => clause.editable === false)
? false
: undefined;
}
function canCrossBrowserBoundary(binding: EffectiveKeybinding, isMac: boolean): boolean {
return binding.parsedChord.every((combo) => {
const prefix = prefixFromCombo(combo, isMac, binding.when?.editable, holdRelease);
const prefix = prefixFromCombo(combo, isMac, editableGuard(binding), binding.holdRelease);
return prefix !== null && !isBrowserNativeNavigationPrefix(prefix, isMac);
});
}
@@ -163,18 +166,13 @@ function buildBrowserShortcutPrefixes(input: BrowserShortcutPolicyInput): Browse
commandCenterOpen: false,
};
const candidates =
input.chordState && input.chordState.step > 0
? input.chordState.candidateIndices
: input.bindings.map((_, index) => index);
const step = input.chordState?.step ?? 0;
const candidateIds = new Set(input.chordState?.candidateIds ?? []);
const candidates =
step > 0 ? input.bindings.filter((binding) => candidateIds.has(binding.id)) : input.bindings;
for (const index of candidates) {
const binding = input.bindings[index];
if (!binding) {
continue;
}
if (!matchesKeyboardShortcutContext(binding.when, context)) {
for (const binding of candidates) {
if (!evaluateWhen(binding.when, context, [])) {
continue;
}
if (!canCrossBrowserBoundary(binding, input.isMac)) {
@@ -184,8 +182,7 @@ function buildBrowserShortcutPrefixes(input: BrowserShortcutPolicyInput): Browse
if (!combo) {
continue;
}
const holdRelease = binding.action === "workspace.switcher.cycle";
const prefix = prefixFromCombo(combo, input.isMac, binding.when?.editable, holdRelease);
const prefix = prefixFromCombo(combo, input.isMac, editableGuard(binding), binding.holdRelease);
if (!prefix) {
continue;
}
@@ -1,5 +1,6 @@
import { requireNativeModule } from "expo-modules-core";
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
import { createIosHardwareClaimBridge } from "./ios-claims";
interface HardwareKeyboardModule {
getHardwareKeyboardPresent(): boolean;
addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void };
@@ -11,6 +12,7 @@ interface HardwareKeyboardModule {
): { remove(): void };
}
const module = requireNativeModule<HardwareKeyboardModule>("PaseoHardwareKeyboard");
const claimBridge = createIosHardwareClaimBridge(module);
export function subscribeHardwareKeyboard(
handler: (event: HardwareKeyboardEvent) => void,
): () => void {
@@ -18,10 +20,10 @@ export function subscribeHardwareKeyboard(
return () => subscription.remove();
}
export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void {
module.setOverlayKeys(keys);
claimBridge.setOverlayKeys(keys);
}
export function setHardwareKeyboardClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void {
module.setClaimedShortcuts(shortcuts);
claimBridge.setClaimedShortcuts(shortcuts);
}
export function getHardwareKeyboardPresent(): boolean {
@@ -1,4 +1,4 @@
import type { KeyboardShortcutInput } from "../../keyboard-shortcuts";
import type { KeyboardShortcutInput } from "../key-event";
export interface HardwareKeyboardEvent extends KeyboardShortcutInput {
isComposing: boolean;
phase: "down" | "up";
@@ -0,0 +1,79 @@
import type { ClaimedShortcut } from "./hardware";
export interface IosHardwareClaimTarget {
setOverlayKeys(keys: readonly string[]): void;
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
}
function isPlainEnterClaim(shortcut: ClaimedShortcut): boolean {
return shortcut.code === "Enter" && !shortcut.shift && !shortcut.alt;
}
function serializeOverlayKeys(keys: readonly string[]): string {
return keys.join("|");
}
function serializeClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): string {
return shortcuts.map((s) => `${s.code}:${s.shift}:${s.alt}`).join("|");
}
function mergeOverlayKeys(baseKeys: readonly string[], claimsPlainEnter: boolean): string[] {
const deduped: string[] = [];
for (const key of baseKeys) {
if (!deduped.includes(key)) {
deduped.push(key);
}
}
if (claimsPlainEnter && !deduped.includes("Enter")) {
deduped.push("Enter");
}
return deduped;
}
/**
* Routes unmodified `Enter` claims into iOS `setOverlayKeys` so
* `PaseoHardwareKeyboardModule.swift`'s `isPlainReturnClaimed` suppresses
* composer Return submission without registering duplicate UIKeyCommands.
*/
export function createIosHardwareClaimBridge(target: IosHardwareClaimTarget) {
let overlayKeys: readonly string[] = [];
let claimsPlainEnter = false;
let lastOverlayKey: string | null = null;
let lastClaimedKey: string | null = null;
function flushOverlayKeys(): void {
const merged = mergeOverlayKeys(overlayKeys, claimsPlainEnter);
const nextKey = serializeOverlayKeys(merged);
if (lastOverlayKey === nextKey) {
return;
}
lastOverlayKey = nextKey;
target.setOverlayKeys(merged);
}
return {
setOverlayKeys(keys: readonly string[]): void {
overlayKeys = [...keys];
flushOverlayKeys();
},
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void {
const nextClaimsPlainEnter = shortcuts.some(isPlainEnterClaim);
const filtered = nextClaimsPlainEnter
? shortcuts.filter((shortcut) => !isPlainEnterClaim(shortcut))
: [...shortcuts];
if (claimsPlainEnter !== nextClaimsPlainEnter) {
claimsPlainEnter = nextClaimsPlainEnter;
flushOverlayKeys();
}
const nextKey = serializeClaimedShortcuts(filtered);
if (lastClaimedKey === nextKey) {
return;
}
lastClaimedKey = nextKey;
target.setClaimedShortcuts(filtered);
},
};
}
@@ -1,5 +1,6 @@
import { matchesKeyboardShortcutContext } from "../../keyboard-shortcuts";
import type { KeyCombo } from "../../shortcut-string";
import { focusSurfaces } from "../focus-surfaces";
import { evaluateWhen } from "../when";
import { overlays } from "../overlays";
import {
nativeKeyboardInput,
@@ -7,6 +8,7 @@ import {
type KeyboardSourceHandlers,
} from "./contract";
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
interface HardwareKeySource {
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
subscribeBlur?(handler: () => void): () => void;
@@ -16,6 +18,30 @@ interface HardwareKeySource {
const DIGIT_CODES = Array.from({ length: 9 }, (_, index) => `Digit${index + 1}`);
function isClaimableCombo(combo: KeyCombo, isChordContinuation: boolean): boolean {
// Cmd/Ctrl combos are never typed into text controls, and Backspace must
// stay with text fields so deletion is never intercepted.
if (combo.meta || combo.ctrl || combo.mod) {
return false;
}
if (combo.code === "Backspace") {
return false;
}
if (isChordContinuation) {
return true;
}
return Boolean(combo.shift || combo.alt);
}
function addClaimedCombo(claimed: Map<string, ClaimedShortcut>, combo: KeyCombo): void {
const shift = combo.shift === true;
const alt = combo.alt === true;
for (const code of combo.code === "Digit" ? DIGIT_CODES : [combo.code]) {
const key = `${code}:${shift}:${alt}`;
claimed.set(key, { code, shift, alt });
}
}
/**
* The shortcuts a focused text control would otherwise type or act on.
*
@@ -24,7 +50,7 @@ const DIGIT_CODES = Array.from({ length: 9 }, (_, index) => `Digit${index + 1}`)
* cycles the agent mode and the composer also inserts a tab. Cmd and Ctrl
* combos do not type, and the platform's own editing combos stay with the text
* control through `editable: false`. Unmodified keys belong to overlays and the
* composer's Return.
* composer's Return unless a multi-step chord is awaiting its next key.
*/
function claimedShortcuts(
policy: KeyboardPolicyInput | null,
@@ -37,17 +63,23 @@ function claimedShortcuts(
commandCenterOpen,
focusScope: focusSurfaces.resolve(commandCenterOpen, true),
};
const step = policy.chordState?.step ?? 0;
const candidateIds = new Set(policy.chordState?.candidateIds ?? []);
const bindings =
step > 0 ? policy.bindings.filter((binding) => candidateIds.has(binding.id)) : policy.bindings;
const claimed = new Map<string, ClaimedShortcut>();
for (const binding of policy.bindings) {
const combo = binding.parsedChord[0];
if (!combo || binding.preventDefault === false) continue;
if (combo.meta || combo.ctrl || combo.mod || !(combo.shift || combo.alt)) continue;
if (!matchesKeyboardShortcutContext(binding.when, context)) continue;
const shift = combo.shift === true;
const alt = combo.alt === true;
for (const code of combo.code === "Digit" ? DIGIT_CODES : [combo.code]) {
claimed.set(`${code}:${shift}:${alt}`, { code, shift, alt });
}
for (const binding of bindings) {
const combo = binding.parsedChord[step];
if (!combo) continue;
// The resolver suppresses every step that only advances a chord; the
// action's pass-through policy applies to the completing step alone.
const completes = binding.parsedChord.length === step + 1;
if (completes && !binding.preventDefault) continue;
if (!isClaimableCombo(combo, step > 0)) continue;
// Claims are computed without the scope stack, so a binding that needs a
// named scope is never claimed.
if (!evaluateWhen(binding.when, context, [])) continue;
addClaimedCombo(claimed, combo);
}
return [...claimed.values()];
}
@@ -55,6 +87,7 @@ function claimedShortcuts(
export function createHardwareKeyboardSource(source: HardwareKeySource) {
let policy: KeyboardPolicyInput | null = null;
let updateClaims = () => {};
return {
publishPolicy(next: KeyboardPolicyInput) {
policy = next;
@@ -0,0 +1,100 @@
import { describe, expect, it } from "vitest";
import type { KeyboardShortcutContext } from "./key-event";
import { evaluateWhen, rankWhen, whenClausesOverlap } from "./when";
function state(overrides: Partial<KeyboardShortcutContext> = {}): KeyboardShortcutContext {
return {
isMac: true,
usesDesktopBindings: true,
focusScope: "other",
commandCenterOpen: false,
...overrides,
};
}
describe("evaluateWhen", () => {
it("derives editable and terminal from the live focus scope", () => {
const composer = state({ focusScope: "message-input" });
const field = state({ focusScope: "editable" });
const terminal = state({ focusScope: "terminal" });
const other = state();
expect(evaluateWhen({ editable: false }, composer, [])).toBe(false);
expect(evaluateWhen({ editable: false }, field, [])).toBe(false);
expect(evaluateWhen({ editable: false }, other, [])).toBe(true);
expect(evaluateWhen({ editable: true }, field, [])).toBe(true);
expect(evaluateWhen({ terminal: false }, terminal, [])).toBe(false);
expect(evaluateWhen({ terminal: true }, terminal, [])).toBe(true);
});
it("reads platform and command center from the context it is given", () => {
expect(evaluateWhen({ mac: true }, state({ isMac: false }), [])).toBe(false);
expect(evaluateWhen({ desktop: false }, state({ usesDesktopBindings: true }), [])).toBe(false);
expect(evaluateWhen({ commandCenter: false }, state({ commandCenterOpen: true }), [])).toBe(
false,
);
expect(evaluateWhen({ focusScope: ["terminal", "browser"] }, state(), [])).toBe(false);
expect(evaluateWhen({ focusScope: ["terminal", "other"] }, state(), [])).toBe(true);
});
it("ANDs fields in a clause, ORs clauses in an array, and requires an active named scope", () => {
const when = [
{ scope: "inbox/list", editable: false },
{ scope: ["inbox/a", "inbox/b"] },
] as const;
expect(evaluateWhen(when, state(), [])).toBe(false);
expect(evaluateWhen(when, state(), ["inbox/list"])).toBe(true);
expect(evaluateWhen(when, state({ focusScope: "editable" }), ["inbox/list"])).toBe(false);
expect(evaluateWhen(when, state({ focusScope: "editable" }), ["inbox/b"])).toBe(true);
expect(evaluateWhen(undefined, state(), [])).toBe(true);
});
});
describe("rankWhen", () => {
it("ranks a clause by the innermost active scope it names, above unscoped clauses", () => {
const active = ["inbox/list", "inbox/popover"];
expect(rankWhen(undefined, state(), active)).toBe(0);
expect(rankWhen({ editable: false }, state(), active)).toBe(0);
expect(rankWhen({ scope: "inbox/list" }, state(), active)).toBe(1);
expect(rankWhen({ scope: "inbox/popover" }, state(), active)).toBe(2);
expect(rankWhen({ scope: ["inbox/popover", "inbox/list"] }, state(), active)).toBe(2);
expect(rankWhen({ scope: "inbox/other" }, state(), active)).toBeNull();
});
it("uses the best matching clause of an OR array", () => {
const when = [{ scope: "inbox/list" }, { scope: "inbox/popover", terminal: true }];
const active = ["inbox/list", "inbox/popover"];
expect(rankWhen(when, state(), active)).toBe(1);
expect(rankWhen(when, state({ focusScope: "terminal" }), active)).toBe(2);
});
});
describe("whenClausesOverlap", () => {
it("treats distinct named scopes as disjoint and identical scopes as overlapping", () => {
expect(whenClausesOverlap({ scope: "inbox/list1" }, { scope: "inbox/list2" })).toBe(false);
expect(whenClausesOverlap({ scope: "inbox/list1" }, { scope: "inbox/list1" })).toBe(true);
expect(whenClausesOverlap({ scope: ["a/x", "a/y"] }, { scope: "a/y" })).toBe(true);
});
it("overlaps unscoped with scoped predicates unless another field is disjoint", () => {
expect(whenClausesOverlap(undefined, { scope: "inbox/list" })).toBe(true);
expect(whenClausesOverlap({ mac: true }, { mac: false, scope: "inbox/list" })).toBe(false);
expect(whenClausesOverlap({ commandCenter: false }, { commandCenter: true })).toBe(false);
});
it("checks focus scope against editable and terminal", () => {
expect(whenClausesOverlap({ editable: false }, { focusScope: "message-input" })).toBe(false);
expect(whenClausesOverlap({ terminal: false }, { focusScope: "terminal" })).toBe(false);
expect(whenClausesOverlap({ terminal: true }, { focusScope: "terminal" })).toBe(true);
expect(whenClausesOverlap({ editable: true }, { focusScope: "other" })).toBe(false);
});
it("checks OR arrays pairwise", () => {
expect(
whenClausesOverlap([{ mac: true }, { scope: "a/one" }], [{ mac: false, scope: "a/two" }]),
).toBe(false);
expect(
whenClausesOverlap([{ mac: true }, { scope: "a/one" }], [{ mac: false, scope: "a/one" }]),
).toBe(true);
});
});
+185
View File
@@ -0,0 +1,185 @@
import type { ActiveScopes } from "@/actions";
import type { KeyboardFocusScope, KeyboardShortcutContext } from "./key-event";
const ALL_FOCUS_SCOPES: readonly KeyboardFocusScope[] = [
"terminal",
"message-input",
"command-center",
"editable",
"browser",
"other",
];
const EDITABLE_FOCUS_SCOPES: ReadonlySet<KeyboardFocusScope> = new Set([
"message-input",
"editable",
]);
/** Every field narrows the clause; an absent field matches anything. */
export interface WhenClause {
mac?: boolean;
desktop?: boolean;
/** Focus is on a text control (`message-input` or `editable` focus scope). */
editable?: boolean;
/** Focus is on a terminal. */
terminal?: boolean;
commandCenter?: boolean;
focusScope?: KeyboardFocusScope | readonly KeyboardFocusScope[];
/** A named action scope that must be active, such as `"inbox/list"`. */
scope?: string | readonly string[];
}
/** One clause, or clauses where any one matching is enough. */
export type When = WhenClause | readonly WhenClause[];
export function toWhenClauses(when: When | undefined): readonly WhenClause[] {
if (when === undefined) {
return [{}];
}
return isWhenArray(when) ? when : [when];
}
function isWhenArray(when: When): when is readonly WhenClause[] {
return Array.isArray(when);
}
function toList<T extends string>(value: T | readonly T[]): readonly T[] {
return typeof value === "string" ? [value] : value;
}
function matchesContext(clause: WhenClause, context: KeyboardShortcutContext): boolean {
if (clause.mac !== undefined && clause.mac !== context.isMac) return false;
if (clause.desktop !== undefined && clause.desktop !== context.usesDesktopBindings) return false;
if (clause.commandCenter !== undefined && clause.commandCenter !== context.commandCenterOpen) {
return false;
}
if (
clause.editable !== undefined &&
clause.editable !== EDITABLE_FOCUS_SCOPES.has(context.focusScope)
) {
return false;
}
if (clause.terminal !== undefined && clause.terminal !== (context.focusScope === "terminal")) {
return false;
}
if (clause.focusScope !== undefined && !toList(clause.focusScope).includes(context.focusScope)) {
return false;
}
return true;
}
function rankClause(
clause: WhenClause,
context: KeyboardShortcutContext,
scopes: ActiveScopes,
): number | null {
if (!matchesContext(clause, context)) {
return null;
}
if (clause.scope === undefined) {
return 0;
}
let innermost = -1;
for (const name of toList(clause.scope)) {
innermost = Math.max(innermost, scopes.lastIndexOf(name));
}
return innermost === -1 ? null : innermost + 1;
}
/**
* Matches `when` against the live keyboard context and the active scopes.
*
* Returns `null` when nothing matches. Otherwise returns the rank of the best
* matching clause: `0` for a clause that names no scope, and one more than the
* stack position of the innermost active scope it names. A higher rank means
* a more deeply nested surface, so it takes precedence.
*/
export function rankWhen(
when: When | undefined,
context: KeyboardShortcutContext,
scopes: ActiveScopes,
): number | null {
let best: number | null = null;
for (const clause of toWhenClauses(when)) {
const rank = rankClause(clause, context, scopes);
if (rank !== null && (best === null || rank > best)) {
best = rank;
}
}
return best;
}
/** The platform the app shows shortcut keys for. */
export interface DisplayPlatform {
isMac: boolean;
usesDesktopBindings: boolean;
}
/** Whether `when` can hold on `platform`, ignoring focus and scopes. */
export function whenMatchesPlatform(when: When | undefined, platform: DisplayPlatform): boolean {
return toWhenClauses(when).some(
(clause) =>
(clause.mac === undefined || clause.mac === platform.isMac) &&
(clause.desktop === undefined || clause.desktop === platform.usesDesktopBindings),
);
}
export function evaluateWhen(
when: When | undefined,
context: KeyboardShortcutContext,
scopes: ActiveScopes,
): boolean {
return rankWhen(when, context, scopes) !== null;
}
function booleansOverlap(left: boolean | undefined, right: boolean | undefined): boolean {
return left === undefined || right === undefined || left === right;
}
function scopesOverlap(
left: string | readonly string[] | undefined,
right: string | readonly string[] | undefined,
): boolean {
if (left === undefined || right === undefined) {
return true;
}
const rightList = toList(right);
return toList(left).some((name) => rightList.includes(name));
}
function allowedFocusScopes(clause: WhenClause): Set<KeyboardFocusScope> {
const allowed = new Set(
clause.focusScope === undefined ? ALL_FOCUS_SCOPES : toList(clause.focusScope),
);
for (const focusScope of allowed) {
const editable = EDITABLE_FOCUS_SCOPES.has(focusScope);
const terminal = focusScope === "terminal";
if (clause.editable !== undefined && clause.editable !== editable) {
allowed.delete(focusScope);
} else if (clause.terminal !== undefined && clause.terminal !== terminal) {
allowed.delete(focusScope);
}
}
return allowed;
}
function clausesOverlap(left: WhenClause, right: WhenClause): boolean {
if (!booleansOverlap(left.mac, right.mac)) return false;
if (!booleansOverlap(left.desktop, right.desktop)) return false;
if (!booleansOverlap(left.commandCenter, right.commandCenter)) return false;
if (!scopesOverlap(left.scope, right.scope)) return false;
const rightFocus = allowedFocusScopes(right);
return [...allowedFocusScopes(left)].some((focusScope) => rightFocus.has(focusScope));
}
/**
* Whether two predicates can hold at the same time, for static conflict
* warnings. Distinct named scopes count as disjoint: when both are active, the
* runtime rank decides which one wins.
*/
export function whenClausesOverlap(left: When | undefined, right: When | undefined): boolean {
const rightClauses = toWhenClauses(right);
return toWhenClauses(left).some((leftClause) =>
rightClauses.some((rightClause) => clausesOverlap(leftClause, rightClause)),
);
}
@@ -1,28 +0,0 @@
import { createContext, type ReactNode, useContext, useRef } from "react";
import { createKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher";
type KeyboardActionDispatcher = ReturnType<typeof createKeyboardActionDispatcher>;
const KeyboardActionDispatcherContext = createContext<KeyboardActionDispatcher | null>(null);
export function KeyboardActionDispatcherProvider({ children }: { children: ReactNode }) {
const dispatcherRef = useRef<KeyboardActionDispatcher | null>(null);
if (!dispatcherRef.current) {
dispatcherRef.current = createKeyboardActionDispatcher();
}
return (
<KeyboardActionDispatcherContext.Provider value={dispatcherRef.current}>
{children}
</KeyboardActionDispatcherContext.Provider>
);
}
export function useKeyboardActionDispatcher(): KeyboardActionDispatcher {
const dispatcher = useContext(KeyboardActionDispatcherContext);
if (!dispatcher) {
throw new Error("useKeyboardActionDispatcher must be used within its provider");
}
return dispatcher;
}
@@ -1,219 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
createKeyboardActionDispatcher,
type KeyboardActionDefinition,
} from "./keyboard-action-dispatcher";
describe("keyboard-action-dispatcher", () => {
let dispatcher: ReturnType<typeof createKeyboardActionDispatcher>;
beforeEach(() => {
dispatcher = createKeyboardActionDispatcher();
});
it("dispatches to the highest-priority active handler", () => {
const calls: string[] = [];
const action: KeyboardActionDefinition = {
id: "message-input.dictation-toggle",
scope: "message-input",
};
dispatcher.registerHandler({
handlerId: "low",
actions: [action.id],
enabled: true,
priority: 100,
isActive: () => true,
handle: () => {
calls.push("low");
return true;
},
});
dispatcher.registerHandler({
handlerId: "high",
actions: [action.id],
enabled: true,
priority: 200,
isActive: () => true,
handle: () => {
calls.push("high");
return true;
},
});
const handled = dispatcher.dispatch(action);
expect(handled).toBe(true);
expect(calls).toEqual(["high"]);
});
it("skips disabled and inactive handlers", () => {
const handle = vi.fn(() => true);
const action: KeyboardActionDefinition = {
id: "message-input.dictation-toggle",
scope: "message-input",
};
dispatcher.registerHandler({
handlerId: "disabled",
actions: [action.id],
enabled: false,
priority: 300,
isActive: () => true,
handle,
});
dispatcher.registerHandler({
handlerId: "inactive",
actions: [action.id],
enabled: true,
priority: 200,
isActive: () => false,
handle,
});
dispatcher.registerHandler({
handlerId: "active",
actions: [action.id],
enabled: true,
priority: 100,
isActive: () => true,
handle,
});
const handled = dispatcher.dispatch(action);
expect(handled).toBe(true);
expect(handle).toHaveBeenCalledTimes(1);
});
it("dispatches to the active mounted tab when a newer hidden tab is inactive", () => {
const calls: string[] = [];
const action: KeyboardActionDefinition = {
id: "message-input.dictation-toggle",
scope: "message-input",
};
dispatcher.registerHandler({
handlerId: "visible-tab",
actions: [action.id],
enabled: true,
priority: 100,
isActive: () => true,
handle: () => {
calls.push("visible-tab");
return true;
},
});
dispatcher.registerHandler({
handlerId: "hidden-tab",
actions: [action.id],
enabled: true,
priority: 100,
isActive: () => false,
handle: () => {
calls.push("hidden-tab");
return true;
},
});
const handled = dispatcher.dispatch(action);
expect(handled).toBe(true);
expect(calls).toEqual(["visible-tab"]);
});
it("tries lower-priority handlers when a higher one does not consume the action", () => {
const calls: string[] = [];
const action: KeyboardActionDefinition = {
id: "message-input.focus",
scope: "message-input",
};
dispatcher.registerHandler({
handlerId: "first",
actions: [action.id],
enabled: true,
priority: 200,
isActive: () => true,
handle: () => {
calls.push("first");
return false;
},
});
dispatcher.registerHandler({
handlerId: "second",
actions: [action.id],
enabled: true,
priority: 100,
isActive: () => true,
handle: () => {
calls.push("second");
return true;
},
});
const handled = dispatcher.dispatch(action);
expect(handled).toBe(true);
expect(calls).toEqual(["first", "second"]);
});
it("does not dispatch after a handler is unregistered", () => {
const handle = vi.fn(() => true);
const action: KeyboardActionDefinition = {
id: "message-input.dictation-cancel",
scope: "message-input",
};
const unregister = dispatcher.registerHandler({
handlerId: "handler",
actions: [action.id],
enabled: true,
priority: 100,
isActive: () => true,
handle,
});
unregister();
const handled = dispatcher.dispatch(action);
expect(handled).toBe(false);
expect(handle).not.toHaveBeenCalled();
});
it("does not let an old registration remove its same-id replacement", () => {
const oldHandle = vi.fn(() => true);
const replacementHandle = vi.fn(() => true);
const action: KeyboardActionDefinition = {
id: "workspace.tab.target.agent",
scope: "workspace",
};
const unregisterOld = dispatcher.registerHandler({
handlerId: "workspace-new-tab-menu:server:pane",
actions: [action.id],
enabled: true,
priority: 200,
handle: oldHandle,
});
dispatcher.registerHandler({
handlerId: "workspace-new-tab-menu:server:pane",
actions: [action.id],
enabled: true,
priority: 200,
handle: replacementHandle,
});
unregisterOld();
expect(dispatcher.dispatch(action)).toBe(true);
expect(replacementHandle).toHaveBeenCalledOnce();
expect(oldHandle).not.toHaveBeenCalled();
});
});
@@ -1,179 +0,0 @@
export type KeyboardActionScope = "global" | "message-input" | "sidebar" | "workspace";
export type WorkspacePanelTarget = "changes" | "files" | "pull-request";
export type WorkspacePanelPlacement = "supporting" | "side-pane" | "focused-pane";
export type KeyboardActionId =
| "agent.interrupt"
| "message-input.focus"
| "message-input.send"
| "message-input.dictation-toggle"
| "message-input.dictation-cancel"
| "message-input.dictation-confirm"
| "message-input.voice-toggle"
| "message-input.voice-mute-toggle"
| "message-input.mode-cycle"
| "message-input.model-toggle"
| "message-input.effort-cycle"
| "workspace.agent.new"
| "workspace.tab.menu.open"
| "workspace.tab.target.agent"
| "workspace.tab.target.browser"
| "workspace.tab.target.changes"
| "workspace.tab.target.files"
| "workspace.tab.close-current"
| "workspace.tab.navigate-index"
| "workspace.tab.navigate-relative"
| "workspace.tab.open"
| "workspace.tab.rename-current"
| "workspace.tab.reload-current"
| "workspace.tab.copy-resume-command"
| "workspace.tab.copy-id"
| "workspace.tab.copy-file-path"
| "workspace.tab.reveal-in-files"
| "workspace.tab.close-left"
| "workspace.tab.close-right"
| "workspace.tab.close-others"
| "workspace.pane.split.right"
| "workspace.pane.split.down"
| "workspace.pane.focus.left"
| "workspace.pane.focus.right"
| "workspace.pane.focus.up"
| "workspace.pane.focus.down"
| "workspace.pane.move-tab.left"
| "workspace.pane.move-tab.right"
| "workspace.pane.move-tab.up"
| "workspace.pane.move-tab.down"
| "workspace.pane.close"
| "workspace.focus.toggle"
| "workspace.terminal.new"
| "workspace.browser.new"
| "sidebar.toggle.right"
| "sidebar.toggle.both"
| "workspace.new"
| "workspace.project.pick"
| "worktree.new"
| "workspace.archive"
| "workspace.archive.undo"
| "workspace.pin"
// Command-center only: no keybind, so these are absent from route-shortcut.ts.
| "workspace.rename"
| "workspace.setup.show";
export type KeyboardActionDefinition =
| { id: "agent.interrupt"; scope: KeyboardActionScope }
| { id: "message-input.focus"; scope: KeyboardActionScope }
| { id: "message-input.send"; scope: KeyboardActionScope }
| { id: "message-input.dictation-toggle"; scope: KeyboardActionScope }
| { id: "message-input.dictation-cancel"; scope: KeyboardActionScope }
| { id: "message-input.dictation-confirm"; scope: KeyboardActionScope }
| { id: "message-input.voice-toggle"; scope: KeyboardActionScope }
| { id: "message-input.voice-mute-toggle"; scope: KeyboardActionScope }
| { id: "message-input.mode-cycle"; scope: KeyboardActionScope }
| { id: "message-input.model-toggle"; scope: KeyboardActionScope }
| { id: "message-input.effort-cycle"; scope: KeyboardActionScope }
| { id: "workspace.agent.new"; scope: KeyboardActionScope }
| { id: "workspace.tab.menu.open"; scope: KeyboardActionScope }
| { id: "workspace.tab.target.agent"; scope: KeyboardActionScope }
| { id: "workspace.tab.target.browser"; scope: KeyboardActionScope }
| { id: "workspace.tab.target.changes"; scope: KeyboardActionScope }
| { id: "workspace.tab.target.files"; scope: KeyboardActionScope }
| { id: "workspace.tab.close-current"; scope: KeyboardActionScope }
| { id: "workspace.tab.navigate-index"; scope: KeyboardActionScope; index: number }
| { id: "workspace.tab.navigate-relative"; scope: KeyboardActionScope; delta: 1 | -1 }
| {
id: "workspace.tab.open";
scope: KeyboardActionScope;
target: WorkspacePanelTarget;
placement: WorkspacePanelPlacement;
}
| { id: "workspace.tab.rename-current"; scope: KeyboardActionScope }
| { id: "workspace.tab.reload-current"; scope: KeyboardActionScope }
| { id: "workspace.tab.copy-resume-command"; scope: KeyboardActionScope }
| { id: "workspace.tab.copy-id"; scope: KeyboardActionScope }
| { id: "workspace.tab.copy-file-path"; scope: KeyboardActionScope }
| { id: "workspace.tab.reveal-in-files"; scope: KeyboardActionScope }
| { id: "workspace.tab.close-left"; scope: KeyboardActionScope }
| { id: "workspace.tab.close-right"; scope: KeyboardActionScope }
| { id: "workspace.tab.close-others"; scope: KeyboardActionScope }
| { id: "workspace.pane.split.right"; scope: KeyboardActionScope }
| { id: "workspace.pane.split.down"; scope: KeyboardActionScope }
| { id: "workspace.pane.focus.left"; scope: KeyboardActionScope }
| { id: "workspace.pane.focus.right"; scope: KeyboardActionScope }
| { id: "workspace.pane.focus.up"; scope: KeyboardActionScope }
| { id: "workspace.pane.focus.down"; scope: KeyboardActionScope }
| { id: "workspace.pane.move-tab.left"; scope: KeyboardActionScope }
| { id: "workspace.pane.move-tab.right"; scope: KeyboardActionScope }
| { id: "workspace.pane.move-tab.up"; scope: KeyboardActionScope }
| { id: "workspace.pane.move-tab.down"; scope: KeyboardActionScope }
| { id: "workspace.pane.close"; scope: KeyboardActionScope }
| { id: "workspace.focus.toggle"; scope: KeyboardActionScope }
| { id: "workspace.terminal.new"; scope: KeyboardActionScope }
| { id: "workspace.browser.new"; scope: KeyboardActionScope }
| { id: "sidebar.toggle.right"; scope: KeyboardActionScope }
| { id: "sidebar.toggle.both"; scope: KeyboardActionScope }
| { id: "workspace.new"; scope: KeyboardActionScope }
| { id: "workspace.project.pick"; scope: KeyboardActionScope }
| { id: "worktree.new"; scope: KeyboardActionScope }
| { id: "workspace.archive"; scope: KeyboardActionScope }
| { id: "workspace.archive.undo"; scope: KeyboardActionScope }
| { id: "workspace.pin"; scope: KeyboardActionScope }
| { id: "workspace.rename"; scope: KeyboardActionScope }
| { id: "workspace.setup.show"; scope: KeyboardActionScope };
export interface KeyboardActionHandler {
handlerId: string;
actions: readonly KeyboardActionId[];
enabled: boolean;
priority: number;
isActive?: () => boolean;
handle: (action: KeyboardActionDefinition) => boolean;
}
type KeyboardActionRegistryEntry = KeyboardActionHandler & {
registeredAt: number;
};
export function createKeyboardActionDispatcher() {
let nextRegistrationOrder = 1;
const handlers = new Map<string, KeyboardActionRegistryEntry>();
return {
registerHandler(handler: KeyboardActionHandler) {
const entry: KeyboardActionRegistryEntry = {
...handler,
registeredAt: nextRegistrationOrder++,
};
handlers.set(handler.handlerId, entry);
return () => {
const current = handlers.get(handler.handlerId);
if (current !== entry) {
return;
}
handlers.delete(handler.handlerId);
};
},
dispatch(action: KeyboardActionDefinition): boolean {
const candidates = Array.from(handlers.values())
.filter((handler) => handler.actions.includes(action.id))
.filter((handler) => handler.enabled)
.filter((handler) => (handler.isActive ? handler.isActive() : true))
.sort((left, right) => {
if (left.priority !== right.priority) {
return right.priority - left.priority;
}
return right.registeredAt - left.registeredAt;
});
for (const handler of candidates) {
if (handler.handle(action)) {
return true;
}
}
return false;
},
};
}
File diff suppressed because it is too large Load Diff
@@ -1,23 +1,19 @@
import { describe, expect, it } from "vitest";
import { buildEffectiveBindings } from "./keyboard-shortcuts";
import { createRecordingCoreRegistries } from "@/core-actions/testing";
import { createKeyboardPipeline } from "./internal/pipeline";
import { createOverlayRegistry } from "./internal/overlays";
describe("DOM source adapter", () => {
it("runs DOM input through the same resolver, preserving cancellation and cleanup", async () => {
const { attachDomKeyboardSource } = await import("./internal/sources/dom.web");
const actions: string[] = [];
const core = createRecordingCoreRegistries({ "command-center-toggle-cmd-k-mac": "Cmd+J" });
const input = document.createElement("textarea");
input.dataset.testid = "message-input";
document.body.append(input);
input.focus();
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac: true, usesDesktopBindings: false, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({ "command-center-toggle-cmd-k-mac": "Cmd+J" }),
keybindings: core.keybindings,
isCapturing: () => false,
dispatch: (match) => {
actions.push(match.action);
return true;
},
overlays: createOverlayRegistry(),
});
const detach = attachDomKeyboardSource({
@@ -35,13 +31,13 @@ describe("DOM source adapter", () => {
cancelable: true,
});
input.dispatchEvent(event);
expect(actions).toEqual(["command-center.toggle"]);
expect(core.ranIds()).toEqual(["paseo/command-center.toggle"]);
expect(event.defaultPrevented).toBe(true);
detach();
input.dispatchEvent(
new KeyboardEvent("keydown", { key: "j", code: "KeyJ", metaKey: true, bubbles: true }),
);
expect(actions).toHaveLength(1);
expect(core.ranIds()).toHaveLength(1);
input.remove();
pipeline.dispose();
});
@@ -1,9 +1,34 @@
import { describe, expect, it } from "vitest";
import { buildEffectiveBindings } from "./keyboard-shortcuts";
import { createRecordingCoreRegistries } from "@/core-actions/testing";
import type { ShortcutOverrides } from "./shortcut-override-store";
import { createKeyboardPipeline } from "./internal/pipeline";
import { createOverlayRegistry } from "./internal/overlays";
import { nativeKeyboardInput } from "./internal/sources/contract";
function effectiveBindings(overrides: ShortcutOverrides = {}) {
return createRecordingCoreRegistries(overrides).keybindings.getBindings();
}
/** The real binding table behind a pipeline, recording each action that runs. */
function createCorePipeline({
isMac = true,
overrides = {},
overlays = createOverlayRegistry(),
}: {
isMac?: boolean;
overrides?: ShortcutOverrides;
overlays?: ReturnType<typeof createOverlayRegistry>;
} = {}) {
const core = createRecordingCoreRegistries(overrides);
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac, usesDesktopBindings: true, commandCenterOpen: false }),
keybindings: core.keybindings,
isCapturing: () => false,
overlays,
});
return { pipeline, ran: core.ran, ranIds: core.ranIds };
}
function keyboardEvent(key: string, code: string, isMac = true) {
return {
key,
@@ -20,22 +45,14 @@ function keyboardEvent(key: string, code: string, isMac = true) {
describe("shared keyboard source pipeline", () => {
it.each([true, false])("resolves hardware input and user rebinds with mac=%s", (isMac) => {
const actions: string[] = [];
const bindings = buildEffectiveBindings({ "command-center-toggle-cmd-k-mac": "Cmd+J" });
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => bindings,
isCapturing: () => false,
dispatch: (match) => {
actions.push(match.action);
return true;
},
overlays: createOverlayRegistry(),
const { pipeline, ranIds } = createCorePipeline({
isMac,
overrides: { "command-center-toggle-cmd-k-mac": "Cmd+J" },
});
pipeline.keyDown(nativeKeyboardInput(keyboardEvent("k", "KeyK", isMac), "message-input"));
expect(actions).toEqual(isMac ? [] : ["command-center.toggle"]);
expect(ranIds()).toEqual(isMac ? [] : ["paseo/command-center.toggle"]);
pipeline.keyDown(nativeKeyboardInput(keyboardEvent("j", "KeyJ", isMac), "message-input"));
expect(actions).toEqual(["command-center.toggle"]);
expect(ranIds()).toEqual(["paseo/command-center.toggle"]);
pipeline.dispose();
});
});
@@ -43,17 +60,7 @@ describe("shared keyboard source pipeline", () => {
describe("overlay and focus precedence in the source pipeline", () => {
it("dismisses an overlay without interrupting, then interrupts only the composer", () => {
const registry = createOverlayRegistry();
const actions: string[] = [];
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac: true, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({}),
isCapturing: () => false,
dispatch: (match) => {
actions.push(match.action);
return true;
},
overlays: registry,
});
const { pipeline, ranIds } = createCorePipeline({ overlays: registry });
let dismissals = 0;
const remove = registry.register({
getLayer: () => 20,
@@ -67,12 +74,12 @@ describe("overlay and focus precedence in the source pipeline", () => {
const escape = { ...keyboardEvent("Escape", "Escape"), metaKey: false };
pipeline.keyDown(nativeKeyboardInput(escape, "message-input"));
expect(dismissals).toBe(1);
expect(actions).toEqual([]);
expect(ranIds()).toEqual([]);
remove();
pipeline.keyDown(nativeKeyboardInput(escape, "terminal"));
expect(actions).toEqual([]);
expect(ranIds()).toEqual([]);
pipeline.keyDown(nativeKeyboardInput(escape, "message-input"));
expect(actions).toEqual(["agent.interrupt"]);
expect(ranIds()).toEqual(["paseo/agent.interrupt"]);
pipeline.dispose();
});
@@ -87,13 +94,7 @@ describe("overlay and focus precedence in the source pipeline", () => {
return true;
},
});
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac: true, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({}),
isCapturing: () => false,
dispatch: () => true,
overlays: registry,
});
const { pipeline } = createCorePipeline({ overlays: registry });
pipeline.keyDown(
nativeKeyboardInput(
{ ...keyboardEvent("Enter", "Enter"), metaKey: false, isComposing: true },
@@ -108,19 +109,9 @@ describe("overlay and focus precedence in the source pipeline", () => {
it.each([true, false])(
"uses hardware conventions for workspace index jumps with mac=%s",
(isMac) => {
const payloads: unknown[] = [];
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({}),
isCapturing: () => false,
dispatch: (match) => {
payloads.push([match.action, match.payload]);
return true;
},
overlays: createOverlayRegistry(),
});
const { pipeline, ran } = createCorePipeline({ isMac });
pipeline.keyDown(nativeKeyboardInput(keyboardEvent("3", "Digit3", isMac), "message-input"));
expect(payloads).toEqual([["workspace.navigate.index", { index: 3 }]]);
expect(ran).toEqual([{ actionId: "paseo/workspace.navigate.index", index: 3 }]);
pipeline.dispose();
},
);
@@ -132,22 +123,12 @@ describe("hardware source adapter", () => {
async (isMac) => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const { focusSurfaces } = await import("./internal/focus-surfaces");
const actions: string[] = [];
const releases: string[] = [];
const events = new Set<
(event: import("./internal/sources/hardware").HardwareKeyboardEvent) => void
>();
const releaseFocus = focusSurfaces.declare("message-input");
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac, usesDesktopBindings: true, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({}),
isCapturing: () => false,
dispatch: (match) => {
actions.push(match.action);
return true;
},
overlays: createOverlayRegistry(),
});
const { pipeline, ranIds } = createCorePipeline({ isMac });
const detach = createHardwareKeyboardSource({
subscribe(handler) {
events.add(handler);
@@ -171,7 +152,7 @@ describe("hardware source adapter", () => {
};
for (const listener of events) listener(down);
for (const listener of events) listener({ ...down, phase: "up" });
expect(actions).toEqual(["command-center.toggle"]);
expect(ranIds()).toEqual(["paseo/command-center.toggle"]);
expect(releases).toEqual(["k"]);
detach();
releaseFocus();
@@ -195,7 +176,7 @@ describe("hardware source adapter", () => {
},
});
source.publishPolicy({
bindings: buildEffectiveBindings({}),
bindings: effectiveBindings({}),
isMac: true,
usesDesktopBindings: true,
enabled: true,
@@ -229,7 +210,7 @@ describe("hardware source adapter", () => {
expect(claimed).toEqual([]);
source.publishPolicy({
bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Alt+M" }),
bindings: effectiveBindings({ "message-input-mode-cycle-shift-tab": "Alt+M" }),
isMac: true,
usesDesktopBindings: true,
enabled: true,
@@ -241,7 +222,7 @@ describe("hardware source adapter", () => {
// A chord's later step is only a shortcut while the chord is in progress;
// claiming it always would stop the composer typing a capital A.
source.publishPolicy({
bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Mod+J Shift+A" }),
bindings: effectiveBindings({ "message-input-mode-cycle-shift-tab": "Mod+J Shift+A" }),
isMac: true,
usesDesktopBindings: true,
enabled: true,
@@ -252,14 +233,14 @@ describe("hardware source adapter", () => {
const releaseFinal = focusSurfaces.declare("message-input");
source.publishPolicy({
bindings: buildEffectiveBindings({}),
bindings: effectiveBindings({}),
isMac: true,
usesDesktopBindings: true,
enabled: false,
});
expect(claimed).toEqual([]);
source.publishPolicy({
bindings: buildEffectiveBindings({}),
bindings: effectiveBindings({}),
isMac: true,
usesDesktopBindings: true,
enabled: true,
@@ -298,6 +279,177 @@ describe("hardware source adapter", () => {
detach();
expect(blurListeners.size).toBe(0);
});
it("claims a pending chord's next key, even unmodified, only while the chord waits", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const { focusSurfaces } = await import("./internal/focus-surfaces");
let claimed: string[] = [];
const source = createHardwareKeyboardSource({
subscribe: () => () => {},
setOverlayKeys() {},
setClaimedShortcuts(shortcuts) {
claimed = shortcuts.map(({ code, shift, alt }) =>
[alt && "Alt", shift && "Shift", code].filter(Boolean).join("+"),
);
},
});
const bindings = effectiveBindings({ "message-input-mode-cycle-shift-tab": "Mod+J A" });
const chordId = "message-input-mode-cycle-shift-tab";
const publish = (step: number) =>
source.publishPolicy({
bindings,
chordState: { step, candidateIds: step > 0 ? [chordId] : [] },
isMac: true,
usesDesktopBindings: true,
enabled: true,
});
const releaseComposer = focusSurfaces.declare("message-input");
const detach = source.attach({
keyDown() {},
keyUp() {},
blur() {},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
});
publish(0);
expect(claimed).toEqual([]);
publish(1);
expect(claimed).toEqual(["KeyA"]);
publish(0);
expect(claimed).toEqual([]);
detach();
releaseComposer();
});
it("claims an intermediate chord step even when the action passes its final key through", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const { focusSurfaces } = await import("./internal/focus-surfaces");
let claimed: string[] = [];
const source = createHardwareKeyboardSource({
subscribe: () => () => {},
setOverlayKeys() {},
setClaimedShortcuts(shortcuts) {
claimed = shortcuts.map(({ code }) => code);
},
});
// Interrupt agent lets its key through to the composer (`preventDefault: false`).
const bindings = effectiveBindings({ "agent-interrupt": "Mod+J Enter K" });
const publish = (step: number) =>
source.publishPolicy({
bindings,
chordState: { step, candidateIds: ["agent-interrupt"] },
isMac: true,
usesDesktopBindings: true,
enabled: true,
});
const releaseComposer = focusSurfaces.declare("message-input");
const detach = source.attach({
keyDown() {},
keyUp() {},
blur() {},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
});
publish(1);
expect(claimed).toEqual(["Enter"]);
publish(2);
expect(claimed).toEqual([]);
detach();
releaseComposer();
});
it("routes a pending chord's plain Enter to iOS overlay keys and leaves the shared source unchanged", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const { createIosHardwareClaimBridge } = await import("./internal/sources/ios-claims");
const { focusSurfaces } = await import("./internal/focus-surfaces");
const { overlays } = await import("./internal/overlays");
const bindings = effectiveBindings({
"message-input-mode-cycle-shift-tab": "Mod+J Enter",
});
const chordId = "message-input-mode-cycle-shift-tab";
const policy = (step: number) => ({
bindings,
chordState: { step, candidateIds: step > 0 ? [chordId] : [] },
isMac: true,
usesDesktopBindings: true,
enabled: true,
});
const handlers = {
keyDown() {},
keyUp() {},
blur() {},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
};
const releaseComposer = focusSurfaces.declare("message-input");
// The shared source stays platform-agnostic: Enter is a claimed shortcut,
// so Android never sees it among its overlay keys.
let sharedOverlayKeys: readonly string[] = [];
let sharedClaims: readonly { code: string }[] = [];
const shared = createHardwareKeyboardSource({
subscribe: () => () => {},
setOverlayKeys(keys) {
sharedOverlayKeys = keys;
},
setClaimedShortcuts(shortcuts) {
sharedClaims = shortcuts;
},
});
const detachShared = shared.attach(handlers);
shared.publishPolicy(policy(1));
expect(sharedClaims).toEqual([{ code: "Enter", shift: false, alt: false }]);
expect(sharedOverlayKeys).toEqual([]);
detachShared();
// iOS moves plain Enter into overlay keys, where the native module
// suppresses composer Return, and sends each change once.
const iosOverlayKeys: string[][] = [];
const iosClaims: string[][] = [];
const bridge = createIosHardwareClaimBridge({
setOverlayKeys(keys) {
iosOverlayKeys.push([...keys]);
},
setClaimedShortcuts(shortcuts) {
iosClaims.push(shortcuts.map((shortcut) => shortcut.code));
},
});
const ios = createHardwareKeyboardSource({
subscribe: () => () => {},
setOverlayKeys: bridge.setOverlayKeys,
setClaimedShortcuts: bridge.setClaimedShortcuts,
});
const detachIos = ios.attach(handlers);
ios.publishPolicy(policy(0));
expect(iosOverlayKeys).toEqual([[]]);
expect(iosClaims).toEqual([[]]);
ios.publishPolicy(policy(1));
expect(iosOverlayKeys).toEqual([[], ["Enter"]]);
expect(iosClaims).toEqual([[]]);
ios.publishPolicy(policy(0));
expect(iosOverlayKeys).toEqual([[], ["Enter"], []]);
// An overlay that already holds Enter keeps it after the chord ends.
const releaseOverlay = overlays.register({
getLayer: () => 20,
getKeys: () => ["Enter"],
onKeyDown: () => false,
});
expect(iosOverlayKeys).toEqual([[], ["Enter"], [], ["Enter"]]);
ios.publishPolicy(policy(1));
ios.publishPolicy(policy(0));
expect(iosOverlayKeys).toHaveLength(4);
releaseOverlay();
expect(iosOverlayKeys).toEqual([[], ["Enter"], [], ["Enter"], []]);
detachIos();
releaseComposer();
});
});
function modifierKey(
@@ -1,464 +0,0 @@
import { describe, expect, it } from "vitest";
import {
routeKeyboardShortcut,
type ShortcutAction,
type ShortcutRoutingContext,
} from "./route-shortcut";
const SIDEBAR_TARGETS = [
{ serverId: "srv", workspaceId: "ws-1" },
{ serverId: "srv", workspaceId: "ws-2" },
{ serverId: "srv", workspaceId: "ws-3" },
{ serverId: "srv", workspaceId: "ws-4" },
{ serverId: "srv", workspaceId: "ws-5" },
] as const;
function makeCtx(overrides: Partial<ShortcutRoutingContext> = {}): ShortcutRoutingContext {
return {
pathname: "/h/srv/workspace/ws-2",
isMobile: false,
sidebarShortcutTargets: SIDEBAR_TARGETS,
navigationActiveWorkspace: null,
commandCenterOpen: false,
shortcutsDialogOpen: false,
...overrides,
};
}
describe("routeKeyboardShortcut — dispatch passthroughs", () => {
it.each([
["agent.interrupt", { id: "agent.interrupt", scope: "global" }],
["workspace.tab.menu.open", { id: "workspace.tab.menu.open", scope: "workspace" }],
["workspace.tab.target.agent", { id: "workspace.tab.target.agent", scope: "workspace" }],
["workspace.tab.target.browser", { id: "workspace.tab.target.browser", scope: "workspace" }],
["workspace.tab.target.changes", { id: "workspace.tab.target.changes", scope: "workspace" }],
["workspace.tab.target.files", { id: "workspace.tab.target.files", scope: "workspace" }],
["workspace.new", { id: "workspace.new", scope: "sidebar" }],
["workspace.project.pick", { id: "workspace.project.pick", scope: "workspace" }],
["workspace.archive", { id: "workspace.archive", scope: "sidebar" }],
["workspace.pin", { id: "workspace.pin", scope: "sidebar" }],
["worktree.new", { id: "worktree.new", scope: "sidebar" }],
["workspace.terminal.new", { id: "workspace.terminal.new", scope: "workspace" }],
["workspace.tab.close.current", { id: "workspace.tab.close-current", scope: "workspace" }],
["sidebar.toggle.right", { id: "sidebar.toggle.right", scope: "sidebar" }],
["workspace.pane.split.right", { id: "workspace.pane.split.right", scope: "workspace" }],
["workspace.pane.split.down", { id: "workspace.pane.split.down", scope: "workspace" }],
["workspace.pane.focus.left", { id: "workspace.pane.focus.left", scope: "workspace" }],
["workspace.pane.focus.right", { id: "workspace.pane.focus.right", scope: "workspace" }],
["workspace.pane.focus.up", { id: "workspace.pane.focus.up", scope: "workspace" }],
["workspace.pane.focus.down", { id: "workspace.pane.focus.down", scope: "workspace" }],
["workspace.pane.move-tab.left", { id: "workspace.pane.move-tab.left", scope: "workspace" }],
["workspace.pane.move-tab.right", { id: "workspace.pane.move-tab.right", scope: "workspace" }],
["workspace.pane.move-tab.up", { id: "workspace.pane.move-tab.up", scope: "workspace" }],
["workspace.pane.move-tab.down", { id: "workspace.pane.move-tab.down", scope: "workspace" }],
["workspace.pane.close", { id: "workspace.pane.close", scope: "workspace" }],
["view.toggle.focus", { id: "workspace.focus.toggle", scope: "workspace" }],
])("%s → dispatch %j", (action, expected) => {
expect(routeKeyboardShortcut({ action, payload: null }, makeCtx())).toEqual({
kind: "dispatch",
action: expected,
});
});
it("closes desktop settings when Escape routes through agent interrupt", () => {
expect(
routeKeyboardShortcut(
{ action: "agent.interrupt", payload: null },
makeCtx({ pathname: "/settings/general" }),
),
).toEqual<ShortcutAction>({ kind: "navigate-last-workspace" });
});
it("keeps agent interrupt behavior on compact settings layouts", () => {
expect(
routeKeyboardShortcut(
{ action: "agent.interrupt", payload: null },
makeCtx({ pathname: "/settings/general", isMobile: true }),
),
).toEqual<ShortcutAction>({
kind: "dispatch",
action: { id: "agent.interrupt", scope: "global" },
});
});
});
describe("routeKeyboardShortcut — workspace.tab.navigate", () => {
it("forwards index payloads to the workspace.tab.navigate-index dispatch", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.tab.navigate.index", payload: { index: 3 } },
makeCtx(),
),
).toEqual<ShortcutAction>({
kind: "dispatch",
action: { id: "workspace.tab.navigate-index", scope: "workspace", index: 3 },
});
});
it("returns none when index payload is missing", () => {
expect(
routeKeyboardShortcut({ action: "workspace.tab.navigate.index", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "none" });
});
it("forwards delta payloads to the workspace.tab.navigate-relative dispatch", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.tab.navigate.relative", payload: { delta: -1 } },
makeCtx(),
),
).toEqual<ShortcutAction>({
kind: "dispatch",
action: { id: "workspace.tab.navigate-relative", scope: "workspace", delta: -1 },
});
});
it("returns none when delta payload is missing", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.tab.navigate.relative", payload: null },
makeCtx(),
),
).toEqual<ShortcutAction>({ kind: "none" });
});
});
describe("routeKeyboardShortcut — workspace.navigate.index", () => {
it("navigates to the sidebar target at index-1", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.index", payload: { index: 4 } },
makeCtx(),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "ws-4",
});
});
it("returns none when the target index is out of range", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.index", payload: { index: 99 } },
makeCtx(),
),
).toEqual<ShortcutAction>({ kind: "none" });
});
it("returns none when the index payload is missing", () => {
expect(
routeKeyboardShortcut({ action: "workspace.navigate.index", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "none" });
});
it("returns none when there are no sidebar targets", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.index", payload: { index: 1 } },
makeCtx({ sidebarShortcutTargets: [] }),
),
).toEqual<ShortcutAction>({ kind: "none" });
});
});
describe("routeKeyboardShortcut — workspace.navigate.relative", () => {
const STATUS_VISUAL_TARGETS = [
{ serverId: "srv", workspaceId: "needs-input" },
{ serverId: "srv", workspaceId: "running-new" },
{ serverId: "srv", workspaceId: "running-old" },
{ serverId: "srv", workspaceId: "done" },
] as const;
it("uses the retained navigation workspace selection over a stale pathname", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: 1 } },
makeCtx({
pathname: "/h/srv/workspace/ws-2",
navigationActiveWorkspace: { serverId: "srv", workspaceId: "ws-4" },
}),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "ws-5",
});
});
it("moves from status row 2 to row 3 using status visual target order", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: 1 } },
makeCtx({
pathname: "/h/srv/workspace/ui-expose-archive-worktrees-on-merge",
sidebarShortcutTargets: STATUS_VISUAL_TARGETS,
navigationActiveWorkspace: { serverId: "srv", workspaceId: "running-new" },
}),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "running-old",
});
});
it("moves backward from status row 2 to row 1 using status visual target order", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: -1 } },
makeCtx({
pathname: "/h/srv/workspace/ui-expose-archive-worktrees-on-merge",
sidebarShortcutTargets: STATUS_VISUAL_TARGETS,
navigationActiveWorkspace: { serverId: "srv", workspaceId: "running-new" },
}),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "needs-input",
});
});
it("moves backward from status row 3 to row 2 using status visual target order", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: -1 } },
makeCtx({
pathname: "/h/srv/workspace/running-old",
sidebarShortcutTargets: STATUS_VISUAL_TARGETS,
navigationActiveWorkspace: { serverId: "srv", workspaceId: "running-old" },
}),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "running-new",
});
});
it("falls back to the pathname workspace when no retained selection exists", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: -1 } },
makeCtx({ pathname: "/h/srv/workspace/ws-3", navigationActiveWorkspace: null }),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "ws-2",
});
});
it("wraps from the last target forward to the first", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: 1 } },
makeCtx({ navigationActiveWorkspace: { serverId: "srv", workspaceId: "ws-5" } }),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "ws-1",
});
});
it("returns none when there are no sidebar targets", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: 1 } },
makeCtx({ sidebarShortcutTargets: [] }),
),
).toEqual<ShortcutAction>({ kind: "none" });
});
it("returns none when the delta payload is missing", () => {
expect(
routeKeyboardShortcut({ action: "workspace.navigate.relative", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "none" });
});
it("falls back to the first target when the current workspace is not in the sidebar", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta: 1 } },
makeCtx({
pathname: "/settings/general",
navigationActiveWorkspace: { serverId: "other", workspaceId: "ws-x" },
}),
),
).toEqual<ShortcutAction>({
kind: "navigate-workspace",
serverId: "srv",
workspaceId: "ws-1",
});
});
});
describe("routeKeyboardShortcut — message-input.action", () => {
it.each([
["focus", "message-input.focus"],
["send", "message-input.send"],
["dictation-toggle", "message-input.dictation-toggle"],
["dictation-cancel", "message-input.dictation-cancel"],
["dictation-confirm", "message-input.dictation-confirm"],
["voice-toggle", "message-input.voice-toggle"],
["voice-mute-toggle", "message-input.voice-mute-toggle"],
["model-toggle", "message-input.model-toggle"],
["effort-cycle", "message-input.effort-cycle"],
["mode-cycle", "message-input.mode-cycle"],
] as const)("kind=%s → dispatch %s", (kind, id) => {
expect(
routeKeyboardShortcut({ action: "message-input.action", payload: { kind } }, makeCtx()),
).toEqual<ShortcutAction>({
kind: "dispatch",
action: { id, scope: "message-input" },
});
});
it("returns none when kind is missing", () => {
expect(
routeKeyboardShortcut({ action: "message-input.action", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "none" });
});
});
describe("routeKeyboardShortcut — settings.toggle", () => {
it("pushes to the settings root when not currently in settings", () => {
expect(
routeKeyboardShortcut(
{ action: "settings.toggle", payload: null },
makeCtx({ pathname: "/h/srv/workspace/ws-2" }),
),
).toEqual<ShortcutAction>({ kind: "router-push", route: "/settings" });
});
it("navigates to the last workspace when leaving settings on desktop", () => {
expect(
routeKeyboardShortcut(
{ action: "settings.toggle", payload: null },
makeCtx({
pathname: "/settings/general",
isMobile: false,
}),
),
).toEqual<ShortcutAction>({ kind: "navigate-last-workspace" });
});
it("falls back to router.back() on mobile", () => {
expect(
routeKeyboardShortcut(
{ action: "settings.toggle", payload: null },
makeCtx({
pathname: "/settings/general",
isMobile: true,
}),
),
).toEqual<ShortcutAction>({ kind: "router-back" });
});
});
describe("routeKeyboardShortcut — callbacks and pickers", () => {
it.each([
["sidebar.toggle.left", "toggle-agent-list"],
["sidebar.toggle.both", "toggle-both-sidebars"],
["theme.cycle", "cycle-theme"],
] as const)("%s → callback %s", (action, name) => {
expect(routeKeyboardShortcut({ action, payload: null }, makeCtx())).toEqual<ShortcutAction>({
kind: "callback",
name,
});
});
it("agent.new → open-project-picker", () => {
expect(
routeKeyboardShortcut({ action: "agent.new", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "open-project-picker" });
});
});
describe("routeKeyboardShortcut — toggle dialogs", () => {
it("opens the command center directly into the files sub-list from a workspace", () => {
expect(
routeKeyboardShortcut({ action: "command-center.files", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({
kind: "command-center-toggle",
nextOpen: true,
sublistId: "files",
});
});
it("leaves the file-search shortcut to the project-picker host outside a workspace", () => {
expect(
routeKeyboardShortcut(
{ action: "command-center.files", payload: null },
makeCtx({ pathname: "/settings" }),
),
).toEqual<ShortcutAction>({
kind: "dispatch",
action: { id: "workspace.project.pick", scope: "workspace" },
});
});
it("opens the command center when closed", () => {
expect(
routeKeyboardShortcut(
{ action: "command-center.toggle", payload: null },
makeCtx({ commandCenterOpen: false }),
),
).toEqual<ShortcutAction>({ kind: "command-center-toggle", nextOpen: true });
});
it("closes the command center when open", () => {
expect(
routeKeyboardShortcut(
{ action: "command-center.toggle", payload: null },
makeCtx({ commandCenterOpen: true }),
),
).toEqual<ShortcutAction>({ kind: "command-center-toggle", nextOpen: false });
});
it("toggles the shortcuts dialog", () => {
expect(
routeKeyboardShortcut(
{ action: "shortcuts.dialog.toggle", payload: null },
makeCtx({ shortcutsDialogOpen: false }),
),
).toEqual<ShortcutAction>({ kind: "shortcuts-dialog-toggle", nextOpen: true });
expect(
routeKeyboardShortcut(
{ action: "shortcuts.dialog.toggle", payload: null },
makeCtx({ shortcutsDialogOpen: true }),
),
).toEqual<ShortcutAction>({ kind: "shortcuts-dialog-toggle", nextOpen: false });
});
});
describe("routeKeyboardShortcut — workspace.switcher.cycle", () => {
it("routes forward and backward cycle deltas", () => {
expect(
routeKeyboardShortcut(
{ action: "workspace.switcher.cycle", payload: { delta: 1 } },
makeCtx(),
),
).toEqual<ShortcutAction>({ kind: "workspace-switcher-cycle", delta: 1 });
expect(
routeKeyboardShortcut(
{ action: "workspace.switcher.cycle", payload: { delta: -1 } },
makeCtx(),
),
).toEqual<ShortcutAction>({ kind: "workspace-switcher-cycle", delta: -1 });
expect(
routeKeyboardShortcut({ action: "workspace.switcher.cycle", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "none" });
});
});
describe("routeKeyboardShortcut — unknown actions", () => {
it("returns none for unknown action ids", () => {
expect(
routeKeyboardShortcut({ action: "totally.made.up", payload: null }, makeCtx()),
).toEqual<ShortcutAction>({ kind: "none" });
});
});
-235
View File
@@ -1,235 +0,0 @@
import { COMMAND_CENTER_FILES_SUBLIST_ID } from "@/command-center/sublist";
import type { KeyboardShortcutPayload, MessageInputKeyboardActionKind } from "@/keyboard/actions";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import { buildSettingsRoute, parseHostWorkspaceRouteFromPathname } from "@/utils/host-routes";
import {
getRelativeSidebarShortcutTarget,
type SidebarShortcutWorkspaceTarget,
} from "@/utils/sidebar-shortcuts";
export interface ShortcutRoutingContext {
pathname: string;
isMobile: boolean;
sidebarShortcutTargets: ReadonlyArray<SidebarShortcutWorkspaceTarget>;
navigationActiveWorkspace: SidebarShortcutWorkspaceTarget | null;
commandCenterOpen: boolean;
shortcutsDialogOpen: boolean;
}
export interface ShortcutRoutingInput {
action: string;
payload: KeyboardShortcutPayload;
}
export type ShortcutCallbackName = "toggle-agent-list" | "toggle-both-sidebars" | "cycle-theme";
export type ShortcutAction =
| { kind: "none" }
| { kind: "dispatch"; action: KeyboardActionDefinition }
| { kind: "navigate-workspace"; serverId: string; workspaceId: string }
| { kind: "workspace-switcher-cycle"; delta: 1 | -1 }
| { kind: "navigate-last-workspace" }
| { kind: "router-replace"; route: string }
| { kind: "router-back" }
| { kind: "router-push"; route: string }
| { kind: "open-project-picker" }
| { kind: "callback"; name: ShortcutCallbackName }
| { kind: "command-center-toggle"; nextOpen: boolean; sublistId?: string }
| { kind: "shortcuts-dialog-toggle"; nextOpen: boolean };
const NONE: ShortcutAction = { kind: "none" };
// Action ids whose routing is a no-payload pass-through to the dispatcher.
const PASSTHROUGH_DISPATCH: Record<string, KeyboardActionDefinition> = {
"agent.interrupt": { id: "agent.interrupt", scope: "global" },
"workspace.tab.menu.open": { id: "workspace.tab.menu.open", scope: "workspace" },
"workspace.tab.target.agent": { id: "workspace.tab.target.agent", scope: "workspace" },
"workspace.tab.target.browser": { id: "workspace.tab.target.browser", scope: "workspace" },
"workspace.tab.target.changes": { id: "workspace.tab.target.changes", scope: "workspace" },
"workspace.tab.target.files": { id: "workspace.tab.target.files", scope: "workspace" },
"workspace.new": { id: "workspace.new", scope: "sidebar" },
"workspace.project.pick": { id: "workspace.project.pick", scope: "workspace" },
"workspace.archive": { id: "workspace.archive", scope: "sidebar" },
"workspace.archive.undo": { id: "workspace.archive.undo", scope: "global" },
"workspace.pin": { id: "workspace.pin", scope: "sidebar" },
"worktree.new": { id: "worktree.new", scope: "sidebar" },
"workspace.terminal.new": { id: "workspace.terminal.new", scope: "workspace" },
"workspace.tab.close.current": { id: "workspace.tab.close-current", scope: "workspace" },
"sidebar.toggle.right": { id: "sidebar.toggle.right", scope: "sidebar" },
"workspace.pane.split.right": { id: "workspace.pane.split.right", scope: "workspace" },
"workspace.pane.split.down": { id: "workspace.pane.split.down", scope: "workspace" },
"workspace.pane.focus.left": { id: "workspace.pane.focus.left", scope: "workspace" },
"workspace.pane.focus.right": { id: "workspace.pane.focus.right", scope: "workspace" },
"workspace.pane.focus.up": { id: "workspace.pane.focus.up", scope: "workspace" },
"workspace.pane.focus.down": { id: "workspace.pane.focus.down", scope: "workspace" },
"workspace.pane.move-tab.left": { id: "workspace.pane.move-tab.left", scope: "workspace" },
"workspace.pane.move-tab.right": { id: "workspace.pane.move-tab.right", scope: "workspace" },
"workspace.pane.move-tab.up": { id: "workspace.pane.move-tab.up", scope: "workspace" },
"workspace.pane.move-tab.down": { id: "workspace.pane.move-tab.down", scope: "workspace" },
"workspace.pane.close": { id: "workspace.pane.close", scope: "workspace" },
"view.toggle.focus": { id: "workspace.focus.toggle", scope: "workspace" },
};
const SIMPLE_CALLBACKS: Record<string, ShortcutCallbackName> = {
"sidebar.toggle.left": "toggle-agent-list",
"sidebar.toggle.both": "toggle-both-sidebars",
"theme.cycle": "cycle-theme",
};
const MESSAGE_INPUT_DISPATCH: Record<
MessageInputKeyboardActionKind,
KeyboardActionDefinition | null
> = {
focus: { id: "message-input.focus", scope: "message-input" },
send: { id: "message-input.send", scope: "message-input" },
"dictation-toggle": { id: "message-input.dictation-toggle", scope: "message-input" },
"dictation-cancel": { id: "message-input.dictation-cancel", scope: "message-input" },
"dictation-confirm": { id: "message-input.dictation-confirm", scope: "message-input" },
"voice-toggle": { id: "message-input.voice-toggle", scope: "message-input" },
"voice-mute-toggle": { id: "message-input.voice-mute-toggle", scope: "message-input" },
"model-toggle": { id: "message-input.model-toggle", scope: "message-input" },
"effort-cycle": { id: "message-input.effort-cycle", scope: "message-input" },
"mode-cycle": { id: "message-input.mode-cycle", scope: "message-input" },
};
function hasPayloadKey<K extends "index" | "delta" | "kind">(
payload: KeyboardShortcutPayload,
key: K,
): payload is Extract<KeyboardShortcutPayload, Record<K, unknown>> {
return !!payload && typeof payload === "object" && key in payload;
}
function dispatch(action: KeyboardActionDefinition): ShortcutAction {
return { kind: "dispatch", action };
}
function routeWorkspaceTabNavigateIndex(payload: KeyboardShortcutPayload): ShortcutAction {
if (!hasPayloadKey(payload, "index")) return NONE;
return dispatch({
id: "workspace.tab.navigate-index",
scope: "workspace",
index: payload.index,
});
}
function routeWorkspaceTabNavigateRelative(payload: KeyboardShortcutPayload): ShortcutAction {
if (!hasPayloadKey(payload, "delta")) return NONE;
return dispatch({
id: "workspace.tab.navigate-relative",
scope: "workspace",
delta: payload.delta,
});
}
function routeWorkspaceNavigateIndex(
payload: KeyboardShortcutPayload,
ctx: ShortcutRoutingContext,
): ShortcutAction {
if (!hasPayloadKey(payload, "index")) return NONE;
const target = ctx.sidebarShortcutTargets[payload.index - 1] ?? null;
if (!target) return NONE;
return {
kind: "navigate-workspace",
serverId: target.serverId,
workspaceId: target.workspaceId,
};
}
function routeWorkspaceNavigateRelative(
payload: KeyboardShortcutPayload,
ctx: ShortcutRoutingContext,
): ShortcutAction {
if (!hasPayloadKey(payload, "delta")) return NONE;
if (ctx.sidebarShortcutTargets.length === 0) return NONE;
const currentWorkspace =
ctx.navigationActiveWorkspace ?? parseHostWorkspaceRouteFromPathname(ctx.pathname);
const target = getRelativeSidebarShortcutTarget({
targets: ctx.sidebarShortcutTargets,
currentTarget: currentWorkspace
? { serverId: currentWorkspace.serverId, workspaceId: currentWorkspace.workspaceId }
: null,
delta: payload.delta,
});
if (!target) return NONE;
return {
kind: "navigate-workspace",
serverId: target.serverId,
workspaceId: target.workspaceId,
};
}
function routeMessageInputAction(payload: KeyboardShortcutPayload): ShortcutAction {
if (!hasPayloadKey(payload, "kind")) return NONE;
const action = MESSAGE_INPUT_DISPATCH[payload.kind];
if (!action) return NONE;
return dispatch(action);
}
function routeSettingsToggle(ctx: ShortcutRoutingContext): ShortcutAction {
if (!ctx.pathname.startsWith("/settings")) {
return { kind: "router-push", route: buildSettingsRoute() };
}
if (!ctx.isMobile) {
return { kind: "navigate-last-workspace" };
}
return { kind: "router-back" };
}
export function routeKeyboardShortcut(
input: ShortcutRoutingInput,
ctx: ShortcutRoutingContext,
): ShortcutAction {
const passthrough = PASSTHROUGH_DISPATCH[input.action];
if (passthrough) {
if (
input.action === "agent.interrupt" &&
ctx.pathname.startsWith("/settings") &&
!ctx.isMobile
) {
return { kind: "navigate-last-workspace" };
}
return dispatch(passthrough);
}
const callback = SIMPLE_CALLBACKS[input.action];
if (callback) {
return { kind: "callback", name: callback };
}
switch (input.action) {
case "workspace.tab.navigate.index":
return routeWorkspaceTabNavigateIndex(input.payload);
case "workspace.tab.navigate.relative":
return routeWorkspaceTabNavigateRelative(input.payload);
case "workspace.navigate.index":
return routeWorkspaceNavigateIndex(input.payload, ctx);
case "workspace.navigate.relative":
return routeWorkspaceNavigateRelative(input.payload, ctx);
case "workspace.switcher.cycle":
return hasPayloadKey(input.payload, "delta")
? { kind: "workspace-switcher-cycle", delta: input.payload.delta }
: NONE;
case "message-input.action":
return routeMessageInputAction(input.payload);
case "agent.new":
return { kind: "open-project-picker" };
case "settings.toggle":
return routeSettingsToggle(ctx);
case "command-center.toggle":
return { kind: "command-center-toggle", nextOpen: !ctx.commandCenterOpen };
case "command-center.files":
if (parseHostWorkspaceRouteFromPathname(ctx.pathname)) {
return {
kind: "command-center-toggle",
nextOpen: true,
sublistId: COMMAND_CENTER_FILES_SUBLIST_ID,
};
}
return dispatch({ id: "workspace.project.pick", scope: "workspace" });
case "shortcuts.dialog.toggle":
return { kind: "shortcuts-dialog-toggle", nextOpen: !ctx.shortcutsDialogOpen };
default:
return NONE;
}
}
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
import type { ShortcutOverrides } from "@/keyboard/shortcut-override-store";
import {
createShortcutOverrideStore,
type ShortcutOverrideStore,
@@ -1,4 +1,11 @@
import { UNASSIGNED_COMBO, type ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
/**
* The stored value meaning "the user deliberately unassigned this shortcut".
* Distinct from a missing key, which means "no override, use the default".
*/
export const UNASSIGNED_COMBO = null;
/** User rebinds keyed by binding id. Storage is unvalidated JSON. */
export type ShortcutOverrides = Record<string, string | null>;
const EMPTY_OVERRIDES: ShortcutOverrides = {};
@@ -124,6 +124,12 @@ describe("comboStringToShortcutKeys", () => {
expect(comboStringToShortcutKeys("Mod+K")).toEqual(["mod", "K"]);
});
it("drops the Shift that a shifted character already implies", () => {
expect(comboStringToShortcutKeys("Shift+?")).toEqual(["?"]);
expect(comboStringToShortcutKeys("Cmd+Shift+?")).toEqual(["mod", "?"]);
expect(comboStringToShortcutKeys("Shift+/")).toEqual(["shift", "/"]);
});
it("hands named keys to the display table under the names it uses", () => {
expect(comboStringToShortcutKeys("Cmd+Shift+ArrowLeft")).toEqual(["mod", "shift", "Left"]);
expect(formatShortcut(comboStringToShortcutKeys("Cmd+Shift+ArrowLeft"), "mac")).toBe("⇧⌘←");
@@ -200,10 +200,22 @@ const DISPLAY_KEY_ALIASES: Record<string, string> = {
Escape: "Esc",
};
/** Keys that are themselves a shifted character, so their Shift goes without saying. */
const SHIFTED_CHARACTERS: ReadonlySet<string> = new Set(
Object.entries(KEY_MAP).flatMap(([name, mapping]) =>
mapping.key !== undefined &&
Object.values(KEY_MAP).some((other) => other.shiftedKey === mapping.key)
? [name]
: [],
),
);
export function comboStringToShortcutKeys(comboString: string): ShortcutKey[] {
const parts = comboString.split("+");
const impliesShift = SHIFTED_CHARACTERS.has(parts.at(-1) ?? "");
const keys: ShortcutKey[] = [];
for (const part of parts) {
if (part === "Shift" && impliesShift) continue;
switch (part) {
case "Cmd":
keys.push("mod");
@@ -257,6 +269,22 @@ export function isModifierKeyCode(code: string): boolean {
return MODIFIER_CODES.has(code);
}
/**
* Unmodified or Shift-only combos on character/digit/space keys would type
* into a focused text control, so bindings using them require `editable: false`.
* Non-printable keys (`Enter`, `Tab`, `Escape`, `Backspace`, arrows, `F1`-`F12`)
* and modified combos (`Cmd`, `Ctrl`, `Alt`, `Mod`) are excluded.
*/
export function isPrintableKeyCombo(combo: KeyCombo): boolean {
if (combo.mod || combo.meta || combo.ctrl || combo.alt) {
return false;
}
if (combo.code === "Digit") {
return true;
}
return combo.key !== undefined && combo.key.length === 1;
}
export function keyboardEventToComboString(
event: Pick<KeyboardEvent, "key" | "code" | "altKey" | "ctrlKey" | "metaKey" | "shiftKey">,
): string | null {
+64 -198
View File
@@ -1,3 +1,4 @@
import { isWeb } from "@/constants/platform";
import { usesDesktopBindings } from "./internal/conventions";
import { createKeyboardPipeline } from "./internal/pipeline";
import { overlays } from "./internal/overlays";
@@ -6,101 +7,78 @@ import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources
import type { KeyboardSourceInput } from "./internal/sources/contract";
import type { KeyboardInputEvent } from "./internal/overlays";
import { hasActiveOverlay } from "./internal/overlay-dispatch";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { usePathname, useRouter } from "expo-router";
import type { KeybindingDispatchResult, RegistryChordState } from "./internal/keybinding-registry";
import { useKeybindingRegistry, useKeybindings } from "./internal/react";
import { useEffect, useMemo, useRef } from "react";
import { usePathname } from "expo-router";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
import {
type ChordState,
buildEffectiveBindings,
getWorkspaceIndexJumpModifierKey,
getWorkspaceSwitcherReleaseModifier,
} from "@/keyboard/keyboard-shortcuts";
import { shouldPublishBrowserShortcutPolicy } from "@/keyboard/internal/sources/electron-browser";
import type { KeyboardShortcutPayload } from "@/keyboard/actions";
import {
routeKeyboardShortcut,
type ShortcutAction,
type ShortcutCallbackName,
} from "@/keyboard/route-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import { useOpenAddProject } from "@/hooks/use-open-add-project";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { buildOpenProjectRoute } from "@/utils/host-routes";
import {
type ActiveWorkspaceSelection,
getLastWorkspaceSelection,
navigateToLastWorkspace,
useActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { getWorkspaceIndexJumpModifierKey } from "@/core-actions";
import {
cancelWorkspaceSwitcherIfPending,
handleWorkspaceSwitcherBlur,
handleWorkspaceSwitcherKeyUp,
triggerWorkspaceSwitcherCycle,
} from "@/workspace-switcher";
const SIDEBAR_ACTION_PREFIX = "paseo/sidebar.";
/**
* Feeds every key source into the keybinding registry, and keeps the native
* and browser-pane key policies in step with the effective bindings.
*/
export function useKeyboardShortcuts({
enabled,
isMobile,
isWorkspaceFocusModeEnabled,
toggleAgentList,
toggleBothSidebars,
exitFocusMode,
cycleTheme,
}: {
enabled: boolean;
isMobile: boolean;
isWorkspaceFocusModeEnabled: boolean;
toggleAgentList: () => void;
toggleBothSidebars?: () => void;
exitFocusMode: () => void;
cycleTheme?: () => void;
}) {
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const keybindings = useKeybindingRegistry();
const bindings = useKeybindings();
const pathname = usePathname();
const router = useRouter();
const resetModifiers = useKeyboardShortcutsStore((s) => s.resetModifiers);
const { overrides } = useKeyboardShortcutOverrides();
const bindings = useMemo(() => buildEffectiveBindings(overrides), [overrides]);
const isMac = getShortcutOs() === "mac";
const openProjectPickerAction = useOpenAddProject();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const keyboardWorkspaceSelectionRef = useRef<ActiveWorkspaceSelection | null>(null);
const publishBrowserShortcutPolicy = useCallback(
(chordState?: ChordState) => {
const lastInputWasBrowserRef = useRef(false);
useEffect(() => {
const publish = (chordState?: RegistryChordState) =>
publishKeyboardPolicy({ bindings, chordState, isMac, usesDesktopBindings, enabled });
},
[bindings, enabled, isMac],
);
publish();
let previous = keybindings.getChordState();
return keybindings.subscribe(() => {
const next = keybindings.getChordState();
if (next === previous) return;
const nativeChordChanged =
!isWeb &&
(previous.step !== next.step || previous.candidateIds.length !== next.candidateIds.length);
const shouldPublish =
nativeChordChanged ||
shouldPublishBrowserShortcutPolicy({
isBrowserInput: lastInputWasBrowserRef.current,
previousChordState: previous,
nextChordState: next,
});
previous = next;
if (shouldPublish) publish(next);
});
}, [bindings, enabled, isMac, keybindings]);
useEffect(() => {
if (activeWorkspaceSelection) {
keyboardWorkspaceSelectionRef.current = activeWorkspaceSelection;
}
}, [activeWorkspaceSelection]);
useEffect(() => {
publishBrowserShortcutPolicy();
}, [publishBrowserShortcutPolicy]);
// Only the modifier that actually performs the workspace-index jump on this
// runtime should reveal the sidebar number badges (Alt on web, Cmd on
// desktop Mac, Ctrl on desktop non-Mac). The store ORs altDown/cmdOrCtrlDown
// to drive badge visibility, so we set the flag matching this runtime.
// Derived from the effective bindings: `null` when the user unassigned or
// rebound the jump shortcut, and no `event.key` ever equals null, so the
// badges simply never appear.
// Only the modifier that performs the workspace-index jump on this runtime
// reveals the sidebar number badges. `null` when the user unassigned or
// rebound the jump, so the badges never appear.
const badgeModifierKey = getWorkspaceIndexJumpModifierKey(
{ isMac, usesDesktopBindings: usesDesktopBindings },
{ isMac, usesDesktopBindings },
bindings,
);
// The keyup listener matches the released key against the current modifier,
// so a modifier held while the jump binding changes could never be released
// and the badges would stay up until a blur. Clear them when it changes.
// A modifier held while the jump binding changes could never be released,
// so clear the badges when it changes.
useEffect(() => {
resetModifiers();
}, [badgeModifierKey, resetModifiers]);
@@ -114,138 +92,12 @@ export function useKeyboardShortcuts({
}
};
const callbacksByName: Record<ShortcutCallbackName, (() => void) | undefined> = {
"toggle-agent-list": toggleAgentList,
"toggle-both-sidebars": toggleBothSidebars,
"cycle-theme": cycleTheme,
};
const performShortcutAction = (
action: ShortcutAction,
captureFocusRestore: () => void,
): boolean => {
switch (action.kind) {
case "none":
return false;
case "dispatch":
return keyboardActionDispatcher.dispatch(action.action);
case "navigate-workspace":
keyboardWorkspaceSelectionRef.current = {
serverId: action.serverId,
workspaceId: action.workspaceId,
};
navigateToWorkspace({ serverId: action.serverId, workspaceId: action.workspaceId });
return true;
case "workspace-switcher-cycle": {
const currentWorkspace = activeWorkspaceSelection
? (getLastWorkspaceSelection() ?? activeWorkspaceSelection)
: null;
const releaseModifier = getWorkspaceSwitcherReleaseModifier({
delta: action.delta,
isMac,
usesDesktopBindings,
bindings,
});
return triggerWorkspaceSwitcherCycle({
delta: action.delta,
releaseModifier,
currentWorkspace,
});
}
case "navigate-last-workspace":
if (navigateToLastWorkspace()) {
return true;
}
router.replace(buildOpenProjectRoute());
return true;
case "router-replace":
router.replace(action.route as Parameters<typeof router.replace>[0]);
return true;
case "router-back":
router.back();
return true;
case "router-push":
router.push(action.route as Parameters<typeof router.push>[0]);
return true;
case "open-project-picker":
void openProjectPickerAction();
return true;
case "callback":
callbacksByName[action.name]?.();
return true;
case "command-center-toggle": {
if (action.nextOpen) {
captureFocusRestore();
}
useKeyboardShortcutsStore
.getState()
.setCommandCenterOpen(
action.nextOpen,
action.sublistId ? { sublistId: action.sublistId } : undefined,
);
return true;
}
case "shortcuts-dialog-toggle":
useKeyboardShortcutsStore.getState().setShortcutsDialogOpen(action.nextOpen);
return true;
}
};
const routeAndPerformShortcut = (input: {
action: string;
payload: KeyboardShortcutPayload;
captureFocusRestore: () => void;
}): boolean => {
const store = useKeyboardShortcutsStore.getState();
const shortcutAction = routeKeyboardShortcut(
{ action: input.action, payload: input.payload },
{
pathname,
isMobile,
sidebarShortcutTargets: store.sidebarShortcutWorkspaceTargets,
navigationActiveWorkspace:
keyboardWorkspaceSelectionRef.current ?? activeWorkspaceSelection,
commandCenterOpen: store.commandCenterOpen,
shortcutsDialogOpen: store.shortcutsDialogOpen,
},
);
const handled = performShortcutAction(shortcutAction, input.captureFocusRestore);
if (handled && isWorkspaceFocusModeEnabled && input.action.startsWith("sidebar.")) {
exitFocusMode();
}
return handled;
};
const getContext = useStableEvent(() => ({
isMac,
usesDesktopBindings: usesDesktopBindings,
usesDesktopBindings,
commandCenterOpen: useKeyboardShortcutsStore.getState().commandCenterOpen,
}));
const getBindings = useStableEvent(() => bindings);
const isCapturing = useStableEvent(() => useKeyboardShortcutsStore.getState().capturingShortcut);
const dispatchMatch = useStableEvent(
(match: import("./keyboard-shortcuts").KeyboardShortcutMatch, input: KeyboardSourceInput) =>
routeAndPerformShortcut({
action: match.action,
payload: match.payload,
captureFocusRestore: input.captureFocusRestore,
}),
);
const chordChanged = useStableEvent(
(previous: ChordState, next: ChordState, input: KeyboardSourceInput | null) => {
const isBrowserInput = input !== null && "browserId" in input.event;
if (
!input ||
shouldPublishBrowserShortcutPolicy({
isBrowserInput,
previousChordState: previous,
nextChordState: next,
})
) {
publishBrowserShortcutPolicy(next);
}
},
);
const beforeResolve = useStableEvent((input: KeyboardSourceInput) => {
const event = input.event;
const key = event.key ?? "";
@@ -261,26 +113,30 @@ export function useKeyboardShortcuts({
state.resetModifiers();
}
}
return true;
});
const handled = useStableEvent((result: KeybindingDispatchResult) => {
if (isWorkspaceFocusModeEnabled && result.binding?.actionId.startsWith(SIDEBAR_ACTION_PREFIX)) {
exitFocusMode();
}
});
const pipeline = useMemo(
() =>
createKeyboardPipeline({
getContext,
getBindings,
keybindings,
isCapturing,
dispatch: dispatchMatch,
overlays,
beforeResolve,
chordChanged,
handled,
}),
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
[getContext, keybindings, isCapturing, beforeResolve, handled],
);
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
heldModifiers.handleKeyDown(input.event);
lastInputWasBrowserRef.current = "browserId" in input.event;
if (
(input.event.key === "Escape" || input.event.code === "Escape") &&
cancelWorkspaceSwitcherIfPending()
@@ -289,7 +145,17 @@ export function useKeyboardShortcuts({
input.event.stopPropagation();
return true;
}
return pipeline.keyDown(input);
const commandCenterWasOpen = useKeyboardShortcutsStore.getState().commandCenterOpen;
const handledKey = pipeline.keyDown(input);
// Remember where focus was, so closing the command center returns it there.
if (
handledKey &&
!commandCenterWasOpen &&
useKeyboardShortcutsStore.getState().commandCenterOpen
) {
input.captureFocusRestore();
}
return handledKey;
});
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
@@ -490,21 +490,17 @@ describe("DOM source through the shared resolver", () => {
const { attachDomKeyboardSource } = await import("@/keyboard/internal/sources/dom.web");
const { createKeyboardPipeline } = await import("@/keyboard/internal/pipeline");
const { createOverlayRegistry } = await import("@/keyboard/internal/overlays");
const { buildEffectiveBindings } = await import("@/keyboard/keyboard-shortcuts");
const actions: string[] = [];
const { createRecordingCoreRegistries } = await import("@/core-actions/testing");
const core = createRecordingCoreRegistries({ "command-center-toggle-cmd-k-mac": "Cmd+J" });
const input = document.createElement("textarea");
input.dataset.testid = "message-input-root";
document.body.append(input);
input.focus();
const pipeline = createKeyboardPipeline({
getContext: () => ({ isMac: true, usesDesktopBindings: false, commandCenterOpen: false }),
getBindings: () => buildEffectiveBindings({ "command-center-toggle-cmd-k-mac": "Cmd+J" }),
keybindings: core.keybindings,
isCapturing: () => false,
overlays: createOverlayRegistry(),
dispatch: (match) => {
actions.push(match.action);
return true;
},
});
const detach = attachDomKeyboardSource({
keyDown: pipeline.keyDown,
@@ -521,7 +517,7 @@ describe("DOM source through the shared resolver", () => {
cancelable: true,
});
input.dispatchEvent(event);
expect(actions).toEqual(["command-center.toggle"]);
expect(core.ranIds()).toEqual(["paseo/command-center.toggle"]);
expect(event.defaultPrevented).toBe(true);
detach();
pipeline.dispose();
+40 -46
View File
@@ -14,9 +14,8 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TerminalProfileIcon } from "@/components/terminal-profile-icon";
import { Shortcut } from "@/components/ui/shortcut";
import { isWeb } from "@/constants/platform";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import { useShortcutKeys } from "@/keyboard";
import { useActionHandler, useActionScope } from "@/actions";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelIconProps } from "@/panels/panel-registry";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
@@ -54,6 +53,34 @@ function LauncherShortcut({ actionId }: { actionId: string }): ReactElement | nu
return keys ? <Shortcut chord={keys} /> : null;
}
const NEW_TAB_PANEL_ACTIONS = [
"paseo/workspace.tab.target.agent",
"paseo/workspace.terminal.new",
"paseo/workspace.tab.target.browser",
"paseo/workspace.tab.target.changes",
"paseo/workspace.tab.target.files",
] as const;
function launcherForAction(
actionId: string,
itemsById: ReadonlyMap<string, WorkspaceTabLaunchItem>,
): WorkspaceTabLaunchItem | undefined {
switch (actionId) {
case "paseo/workspace.tab.target.agent":
return itemsById.get("agent");
case "paseo/workspace.terminal.new":
return itemsById.get("terminal");
case "paseo/workspace.tab.target.browser":
return itemsById.get("browser");
case "paseo/workspace.tab.target.changes":
return itemsById.get("changes") ?? itemsById.get("diff");
case "paseo/workspace.tab.target.files":
return itemsById.get("files");
default:
return undefined;
}
}
function rowStyle({
pressed,
hovered = false,
@@ -196,51 +223,18 @@ const NewTabPanel = memo(function NewTabPanel(): ReactElement {
};
}, [focusPane, isInteractive]);
const handleKeyboardAction = useCallback(
(action: KeyboardActionDefinition): boolean => {
if (action.id === "workspace.agent.new" || action.id === "workspace.tab.target.agent") {
itemsById.get("agent")?.launch({ kind: "replace", tabId });
return true;
}
if (action.id === "workspace.terminal.new") {
itemsById.get("terminal")?.launch({ kind: "replace", tabId });
return true;
}
if (action.id === "workspace.browser.new" || action.id === "workspace.tab.target.browser") {
itemsById.get("browser")?.launch({ kind: "replace", tabId });
return true;
}
if (action.id === "workspace.tab.target.changes") {
const changesItem = itemsById.get("changes") ?? itemsById.get("diff");
if (!changesItem) return false;
changesItem.launch({ kind: "replace", tabId });
return true;
}
if (action.id === "workspace.tab.target.files") {
const filesItem = itemsById.get("files");
if (!filesItem) return false;
filesItem.launch({ kind: "replace", tabId });
return true;
}
return false;
// The panel stands in for the tab it will replace, so its launchers take the
// new-tab keys ahead of the workspace while it holds the pane's focus.
const actionScope = useActionScope("paseo/new-tab", { active: handlesWorkspaceShortcuts });
useActionHandler(
NEW_TAB_PANEL_ACTIONS,
({ actionId }) => {
const item = launcherForAction(actionId, itemsById);
if (!item) return { handled: false };
item.launch({ kind: "replace", tabId });
},
[itemsById, tabId],
{ scope: actionScope },
);
useKeyboardActionHandler({
handlerId: `new-tab:${tabId}`,
actions: [
"workspace.agent.new",
"workspace.terminal.new",
"workspace.browser.new",
"workspace.tab.target.agent",
"workspace.tab.target.browser",
"workspace.tab.target.changes",
"workspace.tab.target.files",
],
enabled: handlesWorkspaceShortcuts,
priority: 250,
handle: handleKeyboardAction,
});
return (
<View ref={containerRef} style={styles.container} testID="workspace-new-tab-panel">
@@ -6,6 +6,7 @@ import type { ComboboxItem } from "@getpaseo/plugin/client/ui";
import type { ToastApi } from "@/components/toast-host";
import { ComposerControlSurfaceProvider } from "@/composer/agent-controls/composer-control";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { CoreActionsProvider } from "@/core-actions";
import { i18n } from "@/i18n/i18next";
import { Combobox } from "./composer-controls";
@@ -60,17 +61,19 @@ function Harness({
const [queryClient] = React.useState(() => new QueryClient());
return (
<QueryClientProvider client={queryClient}>
<ToastApiProvider api={toast}>
<ComposerControlSurfaceProvider value="field">
<Combobox
title="Issue"
icon="CircleDot"
value={value}
search={search}
onSelect={onSelect}
/>
</ComposerControlSurfaceProvider>
</ToastApiProvider>
<CoreActionsProvider>
<ToastApiProvider api={toast}>
<ComposerControlSurfaceProvider value="field">
<Combobox
title="Issue"
icon="CircleDot"
value={value}
search={search}
onSelect={onSelect}
/>
</ComposerControlSurfaceProvider>
</ToastApiProvider>
</CoreActionsProvider>
</QueryClientProvider>
);
}
@@ -3,7 +3,7 @@ import type { CreateWorkspaceRequestOptions } from "@getpaseo/client/internal/da
import type { AgentSnapshotPayload, CreationSnapshot } from "@getpaseo/protocol/messages";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useIsFocused } from "expo-router/react-navigation";
import { useTranslation } from "react-i18next";
@@ -60,8 +60,7 @@ import {
useWorkspaceDraftSubmissionStore,
type PendingWorkspaceDraftSetup,
} from "@/stores/workspace-draft-submission-store";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActionHandler, useActionScope } from "@/actions";
import { useFormPreferences } from "@/hooks/use-form-preferences";
import type { CreateAgentInitialValues } from "@/hooks/use-agent-form-state";
import { toErrorMessage } from "@/utils/error-messages";
@@ -202,11 +201,7 @@ function noopChangeAttachments() {}
function noopClearDraft() {}
const getTerminalDraftRevision = () => 0;
// Stable reference so the keyboard-action handler doesn't re-register each render.
const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [
"workspace.project.pick",
"workspace.new",
];
const PROJECT_PICK_ACTIONS = ["paseo/workspace.project.pick", "paseo/workspace.new"] as const;
interface WorkspaceIsolationState {
isolation: "local" | "worktree";
@@ -999,7 +994,6 @@ export function NewWorkspaceScreen({
const isDraftHandoffActive = useIsNewWorkspaceDraftHandoffActive({ draftId, selectedServerId });
const isStillOnCreateScreen = useNewWorkspaceScreenPresence();
const isScreenFocused = useIsFocused();
const projectPickHandlerId = useId();
// Launch target: what the composer submits to (chat agent, or a terminal
// profile). Mirrors useWorkspaceIsolation's pattern below: the derived
@@ -1282,19 +1276,13 @@ export function NewWorkspaceScreen({
setProjectPickerOpen(true);
}, []);
// On this screen, both project-pick and new-workspace open the chooser.
// Take precedence over global new-workspace navigation to preserve the draft.
const handleProjectPick = useCallback(() => {
openProjectPicker();
return true;
}, [openProjectPicker]);
useKeyboardActionHandler({
handlerId: `new-workspace-project-pick:${projectPickHandlerId}`,
actions: PROJECT_PICK_ACTIONS,
enabled: isScreenFocused,
isActive: isStillOnCreateScreen,
priority: 10,
handle: handleProjectPick,
// On this screen, both project-pick and new-workspace open the chooser. The
// screen's scope takes them ahead of global new-workspace navigation, which
// would drop the draft.
const actionScope = useActionScope("paseo/new-workspace", { active: isScreenFocused });
useActionHandler(PROJECT_PICK_ACTIONS, openProjectPicker, {
scope: actionScope,
enabled: isStillOnCreateScreen,
});
const openIsolationPicker = useCallback(() => {
@@ -5,7 +5,7 @@ import { ChevronDown } from "lucide-react-native";
import { ComboboxTrigger, type ComboboxTriggerState } from "@/components/ui/combobox-trigger";
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useShortcutKeys } from "@/keyboard";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import { ICON_SIZE, type Theme } from "@/styles/theme";

Some files were not shown because too many files have changed in this diff Show More