mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-06 07:06:16 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3572c40232 | ||
|
|
8514a14d8f | ||
|
|
94164a28e2 | ||
|
|
7e93dde3af |
@@ -21,60 +21,60 @@ This is an npm workspace monorepo:
|
||||
|
||||
At the start of non-trivial work, list `docs/` and skim anything relevant to the task.
|
||||
|
||||
| Doc | What's in it |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| [docs/product.md](docs/product.md) | What Paseo is, who it's for, where it's going |
|
||||
| [docs/architecture.md](docs/architecture.md) | System design, package layering, WebSocket protocol, agent lifecycle, data flow |
|
||||
| [docs/agent-lifecycle.md](docs/agent-lifecycle.md) | Agent states, parent/child relationships, archive semantics, tabs vs archive, subagents track |
|
||||
| [docs/data-model.md](docs/data-model.md) | File-based JSON persistence, Zod schemas, atomic writes, no migrations |
|
||||
| [docs/glossary.md](docs/glossary.md) | Authoritative terminology — UI label wins, no synonyms |
|
||||
| [docs/coding-standards.md](docs/coding-standards.md) | Type hygiene, error handling, state design, React patterns, file organization |
|
||||
| [docs/design.md](docs/design.md) | Design system — tokens, buttons, hierarchy, density, alignment rails, states, what's forbidden |
|
||||
| [docs/forms.md](docs/forms.md) | Form architecture — non-React form model, form kit, load-state gating; the schedule form is the golden example |
|
||||
| [docs/hover.md](docs/hover.md) | Hover — the canonical pattern (plain View + onPointerEnter/Leave, separate inner Pressable) and the three ways agents break it |
|
||||
| [docs/unistyles.md](docs/unistyles.md) | Unistyles gotchas — `useUnistyles()` is forbidden, alternatives in order |
|
||||
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
||||
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
|
||||
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
||||
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
|
||||
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
||||
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
||||
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
||||
| [docs/providers.md](docs/providers.md) | Adding a new agent provider end-to-end |
|
||||
| [docs/forge-providers.md](docs/forge-providers.md) | Adding a git forge: registry/manifest, drop-in checklist, self-host/GHES, the two facts tiers |
|
||||
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
|
||||
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
|
||||
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
|
||||
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
|
||||
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
|
||||
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
|
||||
| [docs/protocol-compatibility.md](docs/protocol-compatibility.md) | Why app/daemon versions drift, protocol vs feature contract, capability gating, COMPAT tagging |
|
||||
| [docs/protocol-validation.md](docs/protocol-validation.md) | zod-aot generated inbound WebSocket validation, patched compiler regressions, schema-purity rules |
|
||||
| [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries |
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
| [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization |
|
||||
| [docs/qa.md](docs/qa.md) | QA evidence bar for pull requests — platform matrix, version drift, performance, UI proof |
|
||||
| [docs/mobile-testing.md](docs/mobile-testing.md) | Maestro and mobile test workflows |
|
||||
| [docs/mobile-panels.md](docs/mobile-panels.md) | Compact left/center/right panel ownership, worklet motion, gesture revisions, and Fabric constraints |
|
||||
| [docs/explorer-sidebar.md](docs/explorer-sidebar.md) | Explorer sidebar, side-pane, and compact workspace sheet host contracts, lifecycle, placement, routing preferences |
|
||||
| [docs/ad-hoc-daemon-testing.md](docs/ad-hoc-daemon-testing.md) | Isolated in-process daemon test harness |
|
||||
| [docs/browser-capture-harness.md](docs/browser-capture-harness.md) | Real-Electron browser screenshot harness and compositor-surface gotcha |
|
||||
| [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata |
|
||||
| [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security |
|
||||
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
|
||||
| [docs/terminal-worker.md](docs/terminal-worker.md) | Terminal worker process model, socket/record/secret, protocol-bump rule and draining, the worker's file copy, Windows desktop |
|
||||
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
|
||||
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
|
||||
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
|
||||
| Doc | What's in it |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [docs/product.md](docs/product.md) | What Paseo is, who it's for, where it's going |
|
||||
| [docs/architecture.md](docs/architecture.md) | System design, package layering, WebSocket protocol, agent lifecycle, data flow |
|
||||
| [docs/agent-lifecycle.md](docs/agent-lifecycle.md) | Agent states, parent/child relationships, archive semantics, tabs vs archive, subagents track |
|
||||
| [docs/data-model.md](docs/data-model.md) | File-based JSON persistence, Zod schemas, atomic writes, no migrations |
|
||||
| [docs/glossary.md](docs/glossary.md) | Authoritative terminology — UI label wins, no synonyms |
|
||||
| [docs/coding-standards.md](docs/coding-standards.md) | Type hygiene, error handling, state design, React patterns, file organization |
|
||||
| [docs/design.md](docs/design.md) | Design system — tokens, buttons, hierarchy, density, alignment rails, states, what's forbidden |
|
||||
| [docs/forms.md](docs/forms.md) | Form architecture — non-React form model, form kit, load-state gating; the schedule form is the golden example |
|
||||
| [docs/hover.md](docs/hover.md) | Hover — the canonical pattern (plain View + onPointerEnter/Leave, separate inner Pressable) and the three ways agents break it |
|
||||
| [docs/unistyles.md](docs/unistyles.md) | Unistyles gotchas — `useUnistyles()` is forbidden, alternatives in order |
|
||||
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
||||
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | Action and keybinding registries, action scopes, overlay covers, plugin actions, key sources, badges, iOS `UIKeyCommand` limits |
|
||||
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
||||
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
|
||||
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
||||
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
||||
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
||||
| [docs/providers.md](docs/providers.md) | Adding a new agent provider end-to-end |
|
||||
| [docs/forge-providers.md](docs/forge-providers.md) | Adding a git forge: registry/manifest, drop-in checklist, self-host/GHES, the two facts tiers |
|
||||
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
|
||||
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
|
||||
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
|
||||
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
|
||||
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
|
||||
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
|
||||
| [docs/protocol-compatibility.md](docs/protocol-compatibility.md) | Why app/daemon versions drift, protocol vs feature contract, capability gating, COMPAT tagging |
|
||||
| [docs/protocol-validation.md](docs/protocol-validation.md) | zod-aot generated inbound WebSocket validation, patched compiler regressions, schema-purity rules |
|
||||
| [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries |
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
| [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization |
|
||||
| [docs/qa.md](docs/qa.md) | QA evidence bar for pull requests — platform matrix, version drift, performance, UI proof |
|
||||
| [docs/mobile-testing.md](docs/mobile-testing.md) | Maestro and mobile test workflows |
|
||||
| [docs/mobile-panels.md](docs/mobile-panels.md) | Compact left/center/right panel ownership, worklet motion, gesture revisions, and Fabric constraints |
|
||||
| [docs/explorer-sidebar.md](docs/explorer-sidebar.md) | Explorer sidebar, side-pane, and compact workspace sheet host contracts, lifecycle, placement, routing preferences |
|
||||
| [docs/ad-hoc-daemon-testing.md](docs/ad-hoc-daemon-testing.md) | Isolated in-process daemon test harness |
|
||||
| [docs/browser-capture-harness.md](docs/browser-capture-harness.md) | Real-Electron browser screenshot harness and compositor-surface gotcha |
|
||||
| [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata |
|
||||
| [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security |
|
||||
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
|
||||
| [docs/terminal-worker.md](docs/terminal-worker.md) | Terminal worker process model, socket/record/secret, protocol-bump rule and draining, the worker's file copy, Windows desktop |
|
||||
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
|
||||
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
|
||||
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
|
||||
|
||||
### Writing docs
|
||||
|
||||
|
||||
@@ -1,6 +1,63 @@
|
||||
# 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 while no overlay covers the app, 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 (`APP_SHELL_ACTION_IDS` in [`app-shell-runs.ts`](../packages/app/src/core-actions/internal/app-shell-runs.ts)). Every other core action has no `run`, so it can run only while a surface handles it. Do not give such an action a declining `run`: an action with a `run` counts as available, and its chords then reserve a first step that another shortcut needs.
|
||||
|
||||
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 binding declared with `Digit` supplies data, as `index`. It keeps supplying the pressed digit when an override narrows it to one digit, because Settings saved captured digits literally before it captured number groups.
|
||||
|
||||
## 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.
|
||||
|
||||
Scopes order by activation, so they cannot tell which of two active surfaces the user is in. Say that with `enabled`:
|
||||
|
||||
- Several composers can be active at once, such as the main pane's and an Explorer dock agent tab's. Composer handlers register through `useComposerKeyboardActions` ([`composer/keyboard-scope.tsx`](../packages/app/src/composer/keyboard-scope.tsx)), which enables only the composer whose input had focus last. A blur, such as a click on the timeline, keeps that composer; deactivating or unmounting it releases the keys. Until an active composer's input has had focus, the innermost composer wins.
|
||||
- Desktop Settings covers the workspace, which stays mounted beneath it. Composers go inactive while `useSettingsCoversWorkspace()` holds, so Escape reaches Settings' handler and closes Settings. Compact Settings covers nothing, and Escape there still interrupts the agent.
|
||||
|
||||
An overlay that holds the keyboard, such as a dialog, a menu or the Command Center, covers the app while it is open. `useOverlayRegistration` makes the cover when the overlay takes focus (`manageFocus`, on by default) and returns it as `actionScope`. Pass the overlay's scope `name`, such as `paseo/dialog`, and wrap its content in `<ActionScope activation={actionScope}>`. While the overlay is the latest cover, it hides every activation not inside it, including ones made after it opened, and every handler mounted in no scope. An action's `run` stays available. A shortcut that a screen beneath the dialog handles does nothing while the dialog is open, and works again when it closes.
|
||||
|
||||
A registration that only claims keys, such as the hover card or select mode's Escape, passes `manageFocus: false` and covers nothing. `<ActionCover name>` covers without a key registration; only the mobile menu sheet uses it. An overlay opened with a shortcut closes with the same shortcut only through a handler inside its cover, such as `KeyboardToggleClose` in the model picker, because the cover hides the trigger's handler.
|
||||
|
||||
A Command Center row runs its action for the screen beneath the Command Center. The row calls `canDispatch` and `dispatch` with `{ beneath: "paseo/command-center" }`, which answer as if the latest Command Center cover were closed. The list is built for each opening, so it shows only rows that a handler on that screen or the action's `run` can take.
|
||||
|
||||
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, a user-set binding wins over a default, then 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. On every step, a key continues a chord only when the chord ranks ahead of every runnable binding that the key completes. A plugin's default `Mod+K J` therefore leaves Ctrl+K to the Command Center until the user sets that chord, and a saved `Ctrl+G J K` continues past a default `Ctrl+G J`.
|
||||
|
||||
Settings → Shortcuts asks the registry about every captured combo with `checkCapture` (`canFire`, `conflicts`). A combo that can never fire for that binding is refused with a reason and cannot be saved: an unmodified or Shift-only printable key on a binding whose `when` only holds while typing, such as mode cycle on `Shift+M`. A combo that shares a key press with another binding is saved and shown on both rows as "Also used by …", and the user-set binding runs. The shipped defaults share no key press, so a fresh install shows no warning.
|
||||
|
||||
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`.
|
||||
|
||||
## Plugin actions
|
||||
|
||||
Plugins register actions and bindings through the same two registries; the author contract is in [Actions and keyboard shortcuts](../public-docs/plugins/reference.md#actions). [`plugins/shortcuts/`](../packages/app/src/plugins/shortcuts/index.ts) connects each installation's contributions.
|
||||
|
||||
- Ids are namespaced: the plugin's `open` is the action `plugin-<pluginId>/open`, its binding ids are `plugin-<pluginId>/<id>`, and its scopes are `plugin-<pluginId>/<name>`. Overrides key off these ids, so the user's rebinding survives reinstalls and reloads.
|
||||
- A plugin installed on several hosts adds the same action once per host. The registry keeps one action whose owners are the host ids; core actions have owner `null`. `pluginActionOwnerOrder`, passed to `CoreActionsProvider`, picks the host that runs it: a global action runs on the host of the screen the user is on, else the host the user last picked for the plugin's screens, else the first online host. A workspace or agent action runs only on the active host. Offline hosts never run.
|
||||
- Every plugin screen, panel and popover activates `paseo/plugin-surface`. A plugin handler without `scope` belongs to that activation, so two panes of the same panel never run each other's handlers.
|
||||
- Core actions and bindings register before any plugin, so a core default binding is tried before a plugin binding on the same key.
|
||||
- Settings → Shortcuts and the shortcuts dialog add one section per plugin, titled with its name, with one row per action across all hosts.
|
||||
|
||||
## Badges and routing
|
||||
|
||||
@@ -26,8 +83,14 @@ after the focused text control has already handled the press, so the pipeline's
|
||||
must be claimed up front. `UIKeyCommand` takes only those keys: composer Return, the
|
||||
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
|
||||
`sources/native.ts` computes the claims from the published bindings, the focus scope,
|
||||
Command Center and the visible action scopes, and recomputes them when any of these
|
||||
change. A first key is checked without the action scope stack, so a binding whose
|
||||
`when` names an action scope never claims its first key. While a chord waits, only the
|
||||
next key of each pending candidate is claimed, and a scoped candidate keeps its claim
|
||||
while its scope stays visible. A covering overlay drops the claim, so the key reaches
|
||||
the overlay's text field. 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 +119,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 +182,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.
|
||||
|
||||
+9
-5
@@ -1,7 +1,7 @@
|
||||
# Plugins
|
||||
|
||||
Local plugins contribute daemon RPCs, native app surfaces, workspace panels, Command Center items,
|
||||
client slash commands, timeline items, notifications, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
keyboard shortcuts, client slash commands, timeline items, notifications, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
Paseo executes `index.server.ts` in a subprocess and `index.client.tsx` in every connected app.
|
||||
|
||||
> **Trust every plugin you add.** `paseo plugin add` and `paseo plugin install` mean “I trust this codebase.” Plugins are unsandboxed: server code and preparation commands run with the daemon user's access on the daemon host, and client contributions run inside Paseo. The repository's dependencies and future updates are part of that trust decision. With `--host`, preparation runs on that remote daemon host.
|
||||
@@ -431,7 +431,7 @@ When the same plugin contribution exists on multiple hosts, Paseo shows it once
|
||||
adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and
|
||||
query cache. Explicit SDK targets follow the [host API contract](../public-docs/plugins/reference.md#discover-hosts-and-target-another-host).
|
||||
|
||||
Workspace panels, Command Center items, and client slash commands are client contributions. The
|
||||
Workspace panels, Command Center items, actions, keybindings, and client slash commands are client contributions. The
|
||||
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
|
||||
carry `workspaceId`, validated read-only `params` (with host-enforced `agentId` on agent panels),
|
||||
`revision`, and `tab`; optional `identity(params)` sets the coalescing key on the persisted
|
||||
@@ -464,6 +464,10 @@ See the public [navigation fields](../public-docs/plugins/reference.md#screens-a
|
||||
and [external links and workspace browsers](../public-docs/plugins/reference.md#external-links-and-workspace-browsers)
|
||||
for the author-facing contract.
|
||||
|
||||
Plugin actions and keybindings join the app's action and keybinding registries. Namespacing, which
|
||||
host runs an action, and the Settings sections are in
|
||||
[Plugin actions](keyboard-shortcuts.md#plugin-actions).
|
||||
|
||||
### Plugin icons
|
||||
|
||||
The [public reference](../public-docs/plugins/reference.md#icons) owns the author API: a contribution
|
||||
@@ -915,9 +919,9 @@ implementations and `toPluginComposer`; never branch on `context` in the host.
|
||||
`useComposers` and `composers()` reach an agent's model by reference (`plugins/composer-items/source.ts`):
|
||||
`PluginInstallationProvider` provides the plugin's source to every surface, and
|
||||
`createPluginCapabilities` puts `composers` on every command context. `{ focused: true }` is the
|
||||
agent Command Center registration hands to agent items, published through `plugins/focused-agent.ts`
|
||||
(null outside a workspace route). The source reads that module, not the navigation or layout
|
||||
stores, so the plugin runtime does not import them. The remembered workspace selection is
|
||||
agent Command Center registration hands to agent items, published with the active host and
|
||||
workspace through `plugins/location.ts` (null when no host is active). The source and plugin actions
|
||||
read that module, not the navigation or layout stores, so the plugin runtime does not import them. The remembered workspace selection is
|
||||
navigation restore state and is not the focused agent. The query-cache subscriptions react to
|
||||
`updated` events only: a `useQuery` in another component's render announces `added`, and a
|
||||
subscriber that updates then triggers React's "update a component while rendering a different one"
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { dragTabIntoExplorer, ensureExplorerSidebar } from "../support/helpers/workspace-tabs";
|
||||
|
||||
type SeededWorkspace = Awaited<ReturnType<typeof seedWorkspace>>;
|
||||
type Pane = "main" | "dock";
|
||||
|
||||
const PANE_TEST_IDS: Record<Pane, string> = {
|
||||
main: "workspace-pane-main",
|
||||
dock: "workspace-explorer-sidebar",
|
||||
};
|
||||
|
||||
test.use({ viewport: { width: 1600, height: 900 } });
|
||||
|
||||
function pane(page: Page, which: Pane) {
|
||||
return page.getByTestId(PANE_TEST_IDS[which]).filter({ visible: true });
|
||||
}
|
||||
|
||||
function composerInput(page: Page, which: Pane) {
|
||||
return pane(page, which).getByRole("textbox", { name: "Message agent..." });
|
||||
}
|
||||
|
||||
function agentTab(page: Page, which: Pane, agentId: string) {
|
||||
return pane(page, which).getByTestId(`workspace-tab-agent_${agentId}`);
|
||||
}
|
||||
|
||||
/** Starts a long-streaming mock agent and waits until its tab shows in the main pane. */
|
||||
async function startRunningAgent(
|
||||
page: Page,
|
||||
workspace: SeededWorkspace,
|
||||
title: string,
|
||||
): Promise<string> {
|
||||
const agent = await workspace.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title,
|
||||
modeId: "load-test",
|
||||
model: "one-minute-stream",
|
||||
initialPrompt: `Keep running ${title}.`,
|
||||
});
|
||||
await workspace.client.waitForAgentUpsert(
|
||||
agent.id,
|
||||
(snapshot) => snapshot.status === "running",
|
||||
15_000,
|
||||
);
|
||||
await expect(agentTab(page, "main", agent.id)).toBeVisible();
|
||||
return agent.id;
|
||||
}
|
||||
|
||||
/** Moves an agent's tab into the Explorer dock, then shows the other agent in the main pane. */
|
||||
async function dockAgentBesideMain(page: Page, dockAgentId: string, mainAgentId: string) {
|
||||
await ensureExplorerSidebar(page);
|
||||
await dragTabIntoExplorer(page, `agent_${dockAgentId}`);
|
||||
await expect(agentTab(page, "dock", dockAgentId)).toBeVisible();
|
||||
// Click the tab's leading edge; its close button overlays the trailing edge on hover.
|
||||
await agentTab(page, "main", mainAgentId).click({ position: { x: 12, y: 13 } });
|
||||
await expect(composerInput(page, "dock")).toBeVisible();
|
||||
}
|
||||
|
||||
async function focusComposer(page: Page, which: Pane) {
|
||||
await composerInput(page, which).click();
|
||||
}
|
||||
|
||||
/** Leaves the composer the way a click on the agent's timeline does. */
|
||||
async function blurComposer(page: Page, which: Pane) {
|
||||
await composerInput(page, which).blur();
|
||||
}
|
||||
|
||||
async function openSettings(page: Page) {
|
||||
await page.getByTestId("sidebar-settings").filter({ visible: true }).first().click();
|
||||
await expect(page).toHaveURL(/\/settings/);
|
||||
}
|
||||
|
||||
async function agentStatus(workspace: SeededWorkspace, agentId: string): Promise<string | null> {
|
||||
const fetched = await workspace.client.fetchAgent({ agentId });
|
||||
return fetched?.agent.status ?? null;
|
||||
}
|
||||
|
||||
async function expectAgentInterrupted(workspace: SeededWorkspace, agentId: string) {
|
||||
await expect.poll(() => agentStatus(workspace, agentId), { timeout: 15_000 }).toBe("idle");
|
||||
}
|
||||
|
||||
async function expectAgentRunning(workspace: SeededWorkspace, agentId: string) {
|
||||
expect(await agentStatus(workspace, agentId)).toBe("running");
|
||||
}
|
||||
|
||||
test("Escape interrupts the agent whose composer had focus last, not the Explorer dock's", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "composer-escape-dock-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
const mainAgentId = await startRunningAgent(page, workspace, "main agent");
|
||||
// The dock's composer mounts after the main pane's.
|
||||
const dockAgentId = await startRunningAgent(page, workspace, "dock agent");
|
||||
await dockAgentBesideMain(page, dockAgentId, mainAgentId);
|
||||
|
||||
await test.step("Escape after the main composer blurs interrupts only the main agent", async () => {
|
||||
await focusComposer(page, "main");
|
||||
await blurComposer(page, "main");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectAgentInterrupted(workspace, mainAgentId);
|
||||
await expectAgentRunning(workspace, dockAgentId);
|
||||
});
|
||||
|
||||
await test.step("Escape in the dock's composer interrupts the dock agent", async () => {
|
||||
await focusComposer(page, "dock");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectAgentInterrupted(workspace, dockAgentId);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Escape on desktop Settings closes it and leaves the agent running", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "composer-escape-settings-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
const agentId = await startRunningAgent(page, workspace, "running agent");
|
||||
await focusComposer(page, "main");
|
||||
await openSettings(page);
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${workspace.workspaceId}`));
|
||||
await expectAgentRunning(workspace, agentId);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
type TerminalProfile,
|
||||
} from "../support/helpers/new-workspace-launch";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { runCommandCenterItem } from "../support/helpers/command-center";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
@@ -192,6 +193,20 @@ test.describe("Tab creation", () => {
|
||||
await expect(agent).toBeFocused();
|
||||
});
|
||||
|
||||
test("the Command Center's New terminal row replaces a focused New tab", async ({ page }) => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openNewTabMenuWithShortcut(page);
|
||||
const tabs = (await getTabTestIds(page)).length;
|
||||
|
||||
await runCommandCenterItem(page, "New terminal");
|
||||
|
||||
await expect(
|
||||
page.getByTestId("workspace-new-tab-panel").filter({ visible: true }),
|
||||
).toBeHidden();
|
||||
await expectTerminalSurfaceVisible(page);
|
||||
await expect.poll(async () => (await getTabTestIds(page)).length).toBe(tabs);
|
||||
});
|
||||
|
||||
test("the Agent menu creates a draft and shows its composer within the visual budget", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { runCommandCenterItem } from "../support/helpers/command-center";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
@@ -161,6 +162,23 @@ test.describe("New workspace entry points", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the Command Center's New workspace row opens the project picker on the New Workspace screen", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seeded: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-command-center-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
|
||||
await runCommandCenterItem(page, "New workspace");
|
||||
await expect(page.getByPlaceholder("Search projects")).toBeVisible();
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Ctrl+N opens the project picker with search focused", async ({ page }) => {
|
||||
const seeded: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-shortcut-" });
|
||||
|
||||
|
||||
@@ -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,172 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import { closeCommandCenter } from "../support/helpers/command-center";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { runCommand } from "../support/helpers/plugin-sidebar-items";
|
||||
import {
|
||||
activateList,
|
||||
closeDialogWithEscape,
|
||||
closeRecentDecisions,
|
||||
expectInboxOpen,
|
||||
expectSelection,
|
||||
expectSubmitted,
|
||||
findCommandCenterRow,
|
||||
focusDecisionPane,
|
||||
installShortcutsExample,
|
||||
installShortcutsExampleOnTwoHosts,
|
||||
expectInboxOpenOn,
|
||||
showScreenOnHost,
|
||||
decisionList,
|
||||
openHelpDialog,
|
||||
openRecentDecisions,
|
||||
searchField,
|
||||
SHORTCUTS_PLUGIN_NAME,
|
||||
} from "../support/helpers/plugin-shortcuts";
|
||||
import {
|
||||
openShortcutSettings,
|
||||
pressCapturedKeys,
|
||||
saveRebinding,
|
||||
shortcutRow,
|
||||
startRebinding,
|
||||
} from "../support/helpers/shortcut-settings";
|
||||
|
||||
// Linux Chromium is not mac: the example's Mod+Shift+I is Ctrl+Shift+I here.
|
||||
test.describe("Plugin shortcuts", () => {
|
||||
test("the example's keys open its screen, move the active list and submit the focused pane", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const example = await installShortcutsExample(page);
|
||||
try {
|
||||
await test.step("Ctrl+Shift+I opens the Inbox from a workspace", async () => {
|
||||
await page.keyboard.press("Control+Shift+I");
|
||||
await expectInboxOpen(page);
|
||||
await expectSelection(page, "Open", "Approve the migration");
|
||||
});
|
||||
|
||||
await test.step("J moves the active list only", async () => {
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Open", "Merge the docs");
|
||||
|
||||
await activateList(page, "Done");
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
await expectSelection(page, "Open", "Merge the docs");
|
||||
});
|
||||
|
||||
await test.step("typing j in the search field types it", async () => {
|
||||
await searchField(page).click();
|
||||
await page.keyboard.press("j");
|
||||
await expect(searchField(page)).toHaveValue("j");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
await searchField(page).fill("");
|
||||
});
|
||||
|
||||
await test.step("a dialog over the list stops K, and closing it gives K back", async () => {
|
||||
const dialog = await openHelpDialog(page);
|
||||
await page.keyboard.press("k");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
await closeDialogWithEscape(page, dialog);
|
||||
|
||||
await page.keyboard.press("k");
|
||||
await expectSelection(page, "Done", "Pick a logo");
|
||||
});
|
||||
|
||||
await test.step("a popover over the list takes J, and closing it gives J back", async () => {
|
||||
await openRecentDecisions(page);
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Recent", "Open the beta");
|
||||
await expectSelection(page, "Done", "Pick a logo");
|
||||
await closeRecentDecisions(page);
|
||||
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
});
|
||||
|
||||
await test.step("the Next decision row in the Command Center moves the active list", async () => {
|
||||
await activateList(page, "Open");
|
||||
await (await findCommandCenterRow(page, "Next decision")).click();
|
||||
await expectSelection(page, "Open", "Ship the release");
|
||||
});
|
||||
|
||||
await test.step("the Command Center row and the popover badge show the keys", async () => {
|
||||
const row = await findCommandCenterRow(page, "Open Inbox");
|
||||
await expect(row).toContainText("Ctrl+Shift+I");
|
||||
await closeCommandCenter(page);
|
||||
|
||||
await openRecentDecisions(page);
|
||||
await expect(page.getByRole("button", { name: /^Open Inbox/ })).toContainText(
|
||||
"Ctrl+Shift+I",
|
||||
);
|
||||
await closeRecentDecisions(page);
|
||||
});
|
||||
|
||||
await test.step("Ctrl+Enter submits the decision in the focused pane only", async () => {
|
||||
await example.openWorkspace();
|
||||
await runCommand(page, "Compare decisions");
|
||||
await expectSubmitted(page, "Approve the migration", false);
|
||||
await expectSubmitted(page, "Ship the release", false);
|
||||
|
||||
await focusDecisionPane(page, "Ship the release");
|
||||
await page.keyboard.press("Control+Enter");
|
||||
await expectSubmitted(page, "Ship the release", true);
|
||||
await expectSubmitted(page, "Approve the migration", false);
|
||||
|
||||
await focusDecisionPane(page, "Approve the migration");
|
||||
await page.keyboard.press("Control+Enter");
|
||||
await expectSubmitted(page, "Approve the migration", true);
|
||||
});
|
||||
|
||||
await test.step("Settings lists the actions under the plugin's name, and a new key replaces the old", async () => {
|
||||
await openShortcutSettings(page);
|
||||
await expect(page.getByText(SHORTCUTS_PLUGIN_NAME, { exact: true })).toBeVisible();
|
||||
await expect(shortcutRow(page, "Open Inbox")).toContainText("Ctrl+Shift+I");
|
||||
await expect(shortcutRow(page, "Next decision")).toContainText("J");
|
||||
|
||||
await startRebinding(page, "Open Inbox");
|
||||
await pressCapturedKeys(page, "Control+Shift+U");
|
||||
await saveRebinding(page, "Open Inbox");
|
||||
await expect(shortcutRow(page, "Open Inbox")).toContainText("Ctrl+Shift+U");
|
||||
|
||||
await page.keyboard.press("Control+Shift+U");
|
||||
await expectInboxOpen(page);
|
||||
|
||||
const row = await findCommandCenterRow(page, "Open Inbox");
|
||||
await expect(row).toContainText("Ctrl+Shift+U");
|
||||
await closeCommandCenter(page);
|
||||
});
|
||||
} finally {
|
||||
await example.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a plugin on two hosts has one Settings row and keeps its shortcut when one host goes offline", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const hosts = await installShortcutsExampleOnTwoHosts(page);
|
||||
try {
|
||||
await test.step("Settings lists each action once", async () => {
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
await expect(shortcutRow(page, "Open Inbox")).toHaveCount(1);
|
||||
await expect(shortcutRow(page, "Next decision")).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("Ctrl+Shift+I opens the Inbox, and the user moves it to Secondary", async () => {
|
||||
await page.keyboard.press("Control+Shift+I");
|
||||
await expect(decisionList(page, "Open")).toBeVisible();
|
||||
await showScreenOnHost(page, "Secondary");
|
||||
await expectInboxOpenOn(page, hosts.secondaryServerId);
|
||||
});
|
||||
|
||||
await test.step("with Secondary offline, Ctrl+Shift+I opens the Inbox on Primary", async () => {
|
||||
await hosts.disconnectSecondary();
|
||||
await page.keyboard.press("Control+Shift+I");
|
||||
await expectInboxOpenOn(page, hosts.primaryServerId);
|
||||
});
|
||||
} finally {
|
||||
await hosts.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
cancelRebinding,
|
||||
openShortcutSettings,
|
||||
pressCapturedKeys,
|
||||
saveRebinding,
|
||||
shortcutRow,
|
||||
startRebinding,
|
||||
} from "../support/helpers/shortcut-settings";
|
||||
|
||||
// Linux Chromium is not mac: Toggle command center is Ctrl+K, and Toggle
|
||||
// Explorer sidebar has a row for Ctrl+E and another for its alternate, Ctrl+`.
|
||||
const COMMAND_CENTER = "Toggle command center";
|
||||
const EXPLORER_SIDEBAR = "Toggle Explorer sidebar";
|
||||
const MODE_CYCLE = "Cycle agent mode";
|
||||
|
||||
function explorerBackquoteRow(page: Page) {
|
||||
return shortcutRow(page, EXPLORER_SIDEBAR).filter({ hasText: "`" });
|
||||
}
|
||||
|
||||
test.describe("Settings → Shortcuts capture", () => {
|
||||
test("refuses a key that can never fire, warns on a collision and lets the user's choice win", async ({
|
||||
page,
|
||||
}) => {
|
||||
await openShortcutSettings(page);
|
||||
|
||||
await test.step("refuses a plain key for a shortcut that only works while typing", async () => {
|
||||
await startRebinding(page, MODE_CYCLE);
|
||||
await pressCapturedKeys(page, "Shift+M");
|
||||
|
||||
const row = shortcutRow(page, MODE_CYCLE);
|
||||
await expect(row.getByRole("alert")).toHaveText(
|
||||
"This shortcut works while typing, so it needs Ctrl, Cmd or Alt.",
|
||||
);
|
||||
await expect(row.getByText("End with a number from 1 to 9.")).toBeHidden();
|
||||
await expect(row.getByRole("button", { name: "Done" })).toBeDisabled();
|
||||
|
||||
await pressCapturedKeys(page, "Backspace", "Control+M");
|
||||
await expect(row.getByRole("alert")).toBeHidden();
|
||||
await expect(row.getByRole("button", { name: "Done" })).toBeEnabled();
|
||||
|
||||
await cancelRebinding(page, MODE_CYCLE);
|
||||
await expect(row.getByText("Press shortcut...")).toBeHidden();
|
||||
});
|
||||
|
||||
await test.step("warns on a collision on both rows and still saves", async () => {
|
||||
await startRebinding(page, COMMAND_CENTER);
|
||||
await pressCapturedKeys(page, "Control+Backquote");
|
||||
await expect(shortcutRow(page, COMMAND_CENTER)).toContainText(
|
||||
`Also used by ${EXPLORER_SIDEBAR}`,
|
||||
);
|
||||
await saveRebinding(page, COMMAND_CENTER);
|
||||
|
||||
await expect(shortcutRow(page, COMMAND_CENTER)).toContainText(
|
||||
`Also used by ${EXPLORER_SIDEBAR}`,
|
||||
);
|
||||
await expect(shortcutRow(page, EXPLORER_SIDEBAR)).toHaveCount(2);
|
||||
await expect(
|
||||
page.getByRole("button", { name: `Actions for ${EXPLORER_SIDEBAR} (1/2, Ctrl+E)` }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: `Actions for ${EXPLORER_SIDEBAR} (2/2, Ctrl+\`)` }),
|
||||
).toBeVisible();
|
||||
await expect(explorerBackquoteRow(page)).toContainText(`Also used by ${COMMAND_CENTER}`);
|
||||
await expect(
|
||||
shortcutRow(page, EXPLORER_SIDEBAR).filter({ hasNotText: "`" }),
|
||||
).not.toContainText("Also used by");
|
||||
});
|
||||
|
||||
await test.step("runs the user's shortcut, not the default it shares keys with", async () => {
|
||||
await page.keyboard.press("Control+Backquote");
|
||||
|
||||
await expect(page.getByTestId("command-center-panel")).toBeVisible();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,12 @@
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
createWorkspaceTabs,
|
||||
expectSelectedWorkspaceTabInView,
|
||||
openOverflowingWorkspaceTabs,
|
||||
openWorkspaceTabTarget,
|
||||
panWorkspaceTabsWithWheel,
|
||||
selectFirstWorkspaceTab,
|
||||
switchWorkspaceTab,
|
||||
} from "../support/helpers/workspace-tabs-wheel-scroll";
|
||||
|
||||
test("a vertical mouse wheel pans the overflowing workspace tab strip", async ({
|
||||
@@ -12,3 +17,39 @@ test("a vertical mouse wheel pans the overflowing workspace tab strip", async ({
|
||||
await openOverflowingWorkspaceTabs(page, workspace);
|
||||
await panWorkspaceTabsWithWheel(page);
|
||||
});
|
||||
|
||||
test("the active workspace tab stays in view as tabs are opened and switched", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const workspace = await withWorkspace({ prefix: "workspace-tabs-active-" });
|
||||
await page.setViewportSize({ width: 1100, height: 800 });
|
||||
await workspace.navigateTo();
|
||||
await openWorkspaceTabTarget(page, "Diff");
|
||||
|
||||
await test.step("reveal a new tab and the draft that replaces it", async () => {
|
||||
await createWorkspaceTabs(page, 15);
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 15, count: 16, label: "New tab" });
|
||||
await openWorkspaceTabTarget(page, "Agent");
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 15, count: 16, label: "New Agent" });
|
||||
});
|
||||
|
||||
await test.step("wrap from Diff to New Agent and back", async () => {
|
||||
await selectFirstWorkspaceTab(page);
|
||||
await switchWorkspaceTab(page, "previous");
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 15, count: 16, label: "New Agent" });
|
||||
await switchWorkspaceTab(page, "next");
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 0, count: 16, label: "Diff" });
|
||||
});
|
||||
|
||||
await test.step("step forward past the right edge of the strip", async () => {
|
||||
await switchWorkspaceTab(page, "next", 8);
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 8, count: 16, label: "New tab" });
|
||||
});
|
||||
|
||||
await test.step("reveal a new tab in a narrower desktop window", async () => {
|
||||
await page.setViewportSize({ width: 860, height: 800 });
|
||||
await createWorkspaceTabs(page, 1);
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 16, count: 17, label: "New tab" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,6 +21,21 @@ export async function openCommandCenterWithShortcut(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("command-center-panel")).toBeVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the Command Center with its keys, so the screen beneath keeps its focus, and runs the row
|
||||
* whose title starts with `title`.
|
||||
*/
|
||||
export async function runCommandCenterItem(page: Page, title: string): Promise<void> {
|
||||
await openCommandCenterWithShortcut(page);
|
||||
const panel = page.getByTestId("command-center-panel");
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
await panel
|
||||
.getByRole("button", { name: new RegExp(`^${title}`) })
|
||||
.first()
|
||||
.click();
|
||||
await expect(panel).not.toBeVisible();
|
||||
}
|
||||
|
||||
export async function closeCommandCenter(page: Page): Promise<void> {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByTestId("command-center-panel")).not.toBeVisible();
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { gotoAppShell } from "./app";
|
||||
import { openCommandCenter } from "./command-center";
|
||||
import { addConnectedHostAndReload } from "./hosts";
|
||||
import { startIsolatedHostDaemon } from "./isolated-host-daemon";
|
||||
import { seedMockAgentWorkspace, openAgentRoute } from "./mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
||||
import { approveClientPluginsInUi } from "./plugin-execution-approval";
|
||||
import { copyPluginExample } from "./plugin-fixture";
|
||||
import { getServerId } from "./server-id";
|
||||
import { selectWorkspaceInSidebar } from "./sidebar";
|
||||
|
||||
export const SHORTCUTS_PLUGIN = "shortcuts";
|
||||
export const SHORTCUTS_PLUGIN_NAME = "Shortcut examples";
|
||||
|
||||
/**
|
||||
* Installs `plugin-examples/shortcuts` on the worker's daemon, opens a workspace with an agent and
|
||||
* allows the plugin to run. The page stays on that workspace.
|
||||
*/
|
||||
export async function installShortcutsExample(page: Page) {
|
||||
const example = await copyPluginExample("shortcuts");
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-shortcuts-",
|
||||
title: "Shortcuts agent",
|
||||
});
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
async function close() {
|
||||
await client.removePlugin(SHORTCUTS_PLUGIN).catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await client.close();
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(example.directory);
|
||||
await page.setViewportSize({ width: 1600, height: 900 });
|
||||
await openAgentRoute(page, workspace);
|
||||
await approveClientPluginsInUi(page, [SHORTCUTS_PLUGIN]);
|
||||
// Shortcut badges show once a hardware keyboard has been seen.
|
||||
await page.keyboard.press("Shift");
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
close,
|
||||
/** Opens the seeded workspace from the sidebar. */
|
||||
openWorkspace: () => selectWorkspaceInSidebar(page, workspace.workspaceId),
|
||||
};
|
||||
}
|
||||
|
||||
export function decisionList(page: Page, title: string): Locator {
|
||||
return page.getByText(new RegExp(`^${title} selection: `)).filter({ visible: true });
|
||||
}
|
||||
|
||||
export async function expectSelection(page: Page, list: string, decision: string): Promise<void> {
|
||||
await expect(decisionList(page, list)).toHaveText(`${list} selection: ${decision}`);
|
||||
}
|
||||
|
||||
export async function expectInboxOpen(page: Page): Promise<void> {
|
||||
await expect(page).toHaveURL(/\/plugin\/shortcuts\/surface\/inbox/);
|
||||
await expect(decisionList(page, "Open")).toBeVisible();
|
||||
}
|
||||
|
||||
/** Makes a list on the Inbox the active one by pressing its title. */
|
||||
export async function activateList(page: Page, list: string): Promise<void> {
|
||||
await page.getByRole("button", { name: list, exact: true }).click();
|
||||
await expect(page.getByText(`${list} (active)`, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export function searchField(page: Page): Locator {
|
||||
return page.getByRole("textbox", { name: "Search decisions" });
|
||||
}
|
||||
|
||||
export async function openHelpDialog(page: Page): Promise<Locator> {
|
||||
await page.getByRole("button", { name: "How to decide", exact: true }).click();
|
||||
const dialog = page.getByRole("dialog").filter({ hasText: "How to decide" });
|
||||
await expect(dialog).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
export async function closeDialogWithEscape(page: Page, dialog: Locator): Promise<void> {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
}
|
||||
|
||||
export async function openRecentDecisions(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Recent decisions", exact: true }).click();
|
||||
await expect(decisionList(page, "Recent")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function closeRecentDecisions(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(decisionList(page, "Recent")).toBeHidden();
|
||||
}
|
||||
|
||||
/** The Command Center row for `title`, searched for and left open. */
|
||||
export async function findCommandCenterRow(page: Page, title: string): Promise<Locator> {
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
const row = panel.getByRole("button", { name: new RegExp(`^${title}`) });
|
||||
await expect(row).toBeVisible();
|
||||
return row;
|
||||
}
|
||||
|
||||
export function decisionPanel(page: Page, decision: string): Locator {
|
||||
return page
|
||||
.getByTestId(/^workspace-pane-/)
|
||||
.filter({ has: page.getByText(decision, { exact: true }) })
|
||||
.filter({ visible: true });
|
||||
}
|
||||
|
||||
export async function expectSubmitted(page: Page, decision: string, submitted: boolean) {
|
||||
const status = decisionPanel(page, decision).getByText(
|
||||
submitted ? `Submitted: ${decision}` : "Not submitted",
|
||||
{ exact: true },
|
||||
);
|
||||
await expect(status).toBeVisible();
|
||||
}
|
||||
|
||||
/** Focuses the pane that shows `decision` by clicking its submit status. */
|
||||
export async function focusDecisionPane(page: Page, decision: string): Promise<void> {
|
||||
await decisionPanel(page, decision)
|
||||
.getByText(/^(Not submitted|Submitted: .*)$/)
|
||||
.click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs `plugin-examples/shortcuts` on the worker's daemon ("Primary") and on a second daemon
|
||||
* ("Secondary"), connects the app to both and allows the plugin on each.
|
||||
*/
|
||||
export async function installShortcutsExampleOnTwoHosts(page: Page) {
|
||||
const example = await copyPluginExample("shortcuts");
|
||||
const primary = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const secondary = await startIsolatedHostDaemon("plugin-shortcuts-secondary");
|
||||
const remote = await connectNewWorkspaceDaemonClient({
|
||||
port: secondary.port,
|
||||
ownProjects: false,
|
||||
});
|
||||
const previous = await primary.getDaemonConfig();
|
||||
async function close() {
|
||||
await remote.close().catch(() => undefined);
|
||||
await secondary.close();
|
||||
await primary.removePlugin(SHORTCUTS_PLUGIN).catch(() => undefined);
|
||||
await primary.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await primary.close();
|
||||
await example.cleanup();
|
||||
}
|
||||
try {
|
||||
for (const client of [primary, remote]) {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(example.directory);
|
||||
}
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, {
|
||||
serverId: secondary.serverId,
|
||||
label: "Secondary",
|
||||
port: secondary.port,
|
||||
primaryLabel: "Primary",
|
||||
});
|
||||
// One prompt per host.
|
||||
await approveClientPluginsInUi(page, [SHORTCUTS_PLUGIN, SHORTCUTS_PLUGIN]);
|
||||
await page.keyboard.press("Shift");
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
primaryServerId: getServerId(),
|
||||
secondaryServerId: secondary.serverId,
|
||||
close,
|
||||
async disconnectSecondary() {
|
||||
await secondary.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function expectInboxOpenOn(page: Page, serverId: string): Promise<void> {
|
||||
await expect(page).toHaveURL(new RegExp(`/h/${serverId}/plugin/shortcuts/surface/inbox`));
|
||||
await expect(decisionList(page, "Open")).toBeVisible();
|
||||
}
|
||||
|
||||
/** Picks the host the open plugin screen shows, with the host filter in its header. */
|
||||
export async function showScreenOnHost(page: Page, label: string): Promise<void> {
|
||||
await page.getByRole("button", { name: /^Filter: / }).click();
|
||||
await page.getByRole("button", { name: new RegExp(`^${label}`) }).click();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "./app";
|
||||
import { openSettingsSection } from "./settings";
|
||||
|
||||
/** Settings → Shortcuts, opened through the sidebar like a user would. */
|
||||
export async function openShortcutSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("sidebar-search")).toBeVisible({ timeout: 30_000 });
|
||||
// A hardware keyboard has to be detected before Settings lists shortcuts.
|
||||
await page.keyboard.press("Shift");
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
}
|
||||
|
||||
export function shortcutRow(page: Page, action: string): Locator {
|
||||
return page
|
||||
.getByTestId(/^shortcut-row-/)
|
||||
.filter({ has: page.getByText(action, { exact: true }) });
|
||||
}
|
||||
|
||||
export async function startRebinding(page: Page, action: string): Promise<void> {
|
||||
await page.getByRole("button", { name: `Actions for ${action}` }).click();
|
||||
await page.getByTestId(/^shortcut-bind-/).click();
|
||||
await expect(shortcutRow(page, action).getByText("Press shortcut...")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function pressCapturedKeys(page: Page, ...keys: string[]): Promise<void> {
|
||||
for (const key of keys) {
|
||||
await page.keyboard.press(key);
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveRebinding(page: Page, action: string): Promise<void> {
|
||||
await shortcutRow(page, action).getByRole("button", { name: "Done" }).click();
|
||||
}
|
||||
|
||||
export async function cancelRebinding(page: Page, action: string): Promise<void> {
|
||||
await shortcutRow(page, action).getByRole("button", { name: "Cancel" }).click();
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { pressNewTabShortcut } from "./launcher";
|
||||
import { panWorkspaceTabsWithWheel } from "./workspace-tabs";
|
||||
import type { CreatedWorkspace } from "./with-workspace";
|
||||
@@ -14,9 +14,51 @@ export async function openOverflowingWorkspaceTabs(
|
||||
await page.setViewportSize(OVERFLOWING_TABS_VIEWPORT);
|
||||
await workspace.navigateTo();
|
||||
|
||||
for (let index = 0; index < OVERFLOWING_TABS_COUNT; index += 1) {
|
||||
await createWorkspaceTabs(page, OVERFLOWING_TABS_COUNT);
|
||||
}
|
||||
|
||||
export async function createWorkspaceTabs(page: Page, count: number) {
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
await pressNewTabShortcut(page);
|
||||
}
|
||||
}
|
||||
|
||||
export { panWorkspaceTabsWithWheel };
|
||||
|
||||
function workspaceTabs(page: Page) {
|
||||
return page
|
||||
.getByTestId("workspace-tabs-scroll")
|
||||
.getByRole("button")
|
||||
.and(page.locator("[aria-selected]"));
|
||||
}
|
||||
|
||||
export async function openWorkspaceTabTarget(page: Page, target: "Diff" | "Agent") {
|
||||
await page
|
||||
.getByTestId("workspace-new-tab-panel")
|
||||
.filter({ visible: true })
|
||||
.getByRole("button", { name: target, exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function selectFirstWorkspaceTab(page: Page) {
|
||||
await workspaceTabs(page).first().click();
|
||||
}
|
||||
|
||||
export async function switchWorkspaceTab(page: Page, direction: "previous" | "next", steps = 1) {
|
||||
const shortcut = direction === "previous" ? "Alt+Shift+BracketLeft" : "Alt+Shift+BracketRight";
|
||||
for (let step = 0; step < steps; step += 1) {
|
||||
await page.keyboard.press(shortcut);
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectSelectedWorkspaceTabInView(
|
||||
page: Page,
|
||||
{ index, count, label }: { index: number; count: number; label: string },
|
||||
) {
|
||||
const tabs = workspaceTabs(page);
|
||||
await expect(tabs).toHaveCount(count);
|
||||
const tab = tabs.nth(index);
|
||||
await expect(tab).toHaveText(label);
|
||||
await expect(tab).toHaveAttribute("aria-selected", "true");
|
||||
await expect.soft(tab).toBeInViewport({ ratio: 0.99, timeout: 3_000 });
|
||||
}
|
||||
|
||||
@@ -233,9 +233,10 @@ export async function panWorkspaceTabsWithWheel(page: Page): Promise<void> {
|
||||
const overflow = () => strip.evaluate((element) => element.scrollWidth - element.clientWidth);
|
||||
const scrollLeft = () => strip.evaluate((element) => element.scrollLeft);
|
||||
await expect.poll(overflow).toBeGreaterThan(0);
|
||||
expect(await scrollLeft()).toBe(0);
|
||||
|
||||
await strip.hover();
|
||||
await page.mouse.wheel(0, -(await strip.evaluate((element) => element.scrollWidth)));
|
||||
await expect.poll(scrollLeft).toBe(0);
|
||||
|
||||
await page.mouse.wheel(0, 200);
|
||||
await expect.poll(scrollLeft).toBeGreaterThan(0);
|
||||
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
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("ActionScopeStore overlays", () => {
|
||||
it("hides the scopes beneath an open overlay and keeps the scopes inside it", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
const list = scopes.activate("inbox/list");
|
||||
const dialog = scopes.activate("paseo/dialog", { covers: true });
|
||||
const field = scopes.activate("inbox/field", { parent: dialog });
|
||||
|
||||
expect(scopes.getActiveScopes()).toEqual(["paseo/dialog", "inbox/field"]);
|
||||
expect(scopes.depthOf(list)).toBeNull();
|
||||
expect([scopes.depthOf(dialog), scopes.depthOf(field)]).toEqual([1, 2]);
|
||||
|
||||
field.release();
|
||||
dialog.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list"]);
|
||||
expect(scopes.depthOf(list)).toBe(1);
|
||||
list.release();
|
||||
});
|
||||
|
||||
it("keeps a scope that activates beneath an open overlay hidden until the overlay closes", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
const dialog = scopes.activate("paseo/dialog", { covers: true });
|
||||
const list = scopes.activate("inbox/list");
|
||||
|
||||
expect(scopes.getActiveScopes()).toEqual(["paseo/dialog"]);
|
||||
expect(scopes.depthOf(list)).toBeNull();
|
||||
|
||||
dialog.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list"]);
|
||||
list.release();
|
||||
});
|
||||
|
||||
it("lets an overlay opened from inside another overlay hide the outer one's scopes", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
const dialog = scopes.activate("paseo/dialog", { covers: true });
|
||||
const list = scopes.activate("inbox/list", { parent: dialog });
|
||||
const menu = scopes.activate("paseo/menu", { covers: true, parent: list });
|
||||
const popoverList = scopes.activate("inbox/list", { parent: menu });
|
||||
|
||||
expect(scopes.getActiveScopes()).toEqual(["paseo/menu", "inbox/list"]);
|
||||
expect(scopes.depthOf(list)).toBeNull();
|
||||
expect(scopes.depthOf(popoverList)).toBe(2);
|
||||
|
||||
popoverList.release();
|
||||
menu.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["paseo/dialog", "inbox/list"]);
|
||||
expect(scopes.depthOf(list)).toBe(2);
|
||||
list.release();
|
||||
dialog.release();
|
||||
});
|
||||
|
||||
it("does not run a handler whose scope an overlay hides, and runs it again once it closes", () => {
|
||||
const { registry, scopes } = createHarness();
|
||||
const calls: string[] = [];
|
||||
const list = scopes.activate("inbox/list");
|
||||
registry.registerHandler(
|
||||
"inbox/item.next",
|
||||
() => {
|
||||
calls.push("list");
|
||||
},
|
||||
{ scope: list },
|
||||
);
|
||||
|
||||
const dialog = scopes.activate("paseo/dialog", { covers: true });
|
||||
expect(registry.canDispatch("inbox/item.next")).toBe(false);
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(false);
|
||||
|
||||
dialog.release();
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual(["list"]);
|
||||
list.release();
|
||||
});
|
||||
|
||||
it("hides a handler mounted in no scope while an overlay is open, and still runs the action's run", () => {
|
||||
const { registry, scopes } = createHarness();
|
||||
const calls: string[] = [];
|
||||
registry.registerAction({
|
||||
id: "paseo/workspace.archive",
|
||||
title: "Archive",
|
||||
run: () => void calls.push("run"),
|
||||
});
|
||||
// Like the archive handler for the open workspace, which no surface scope encloses.
|
||||
registry.registerHandler("paseo/workspace.archive", () => void calls.push("open workspace"));
|
||||
|
||||
const menu = scopes.activate("paseo/menu", { covers: true });
|
||||
expect(registry.dispatch("paseo/workspace.archive")).toBe(true);
|
||||
expect(registry.dispatch("paseo/workspace.archive", { beneath: "paseo/menu" })).toBe(true);
|
||||
|
||||
menu.release();
|
||||
expect(registry.dispatch("paseo/workspace.archive")).toBe(true);
|
||||
expect(calls).toEqual(["run", "open workspace", "open workspace"]);
|
||||
});
|
||||
|
||||
it("runs the handler beneath a named overlay, as the Command Center does for the row the user picked", () => {
|
||||
const { registry, scopes } = createHarness();
|
||||
const calls: string[] = [];
|
||||
const list = scopes.activate("inbox/list");
|
||||
registry.registerHandler("inbox/item.next", () => void calls.push("list"), { scope: list });
|
||||
const dialog = scopes.activate("paseo/dialog", { covers: true });
|
||||
const commandCenter = scopes.activate("paseo/command-center", { covers: true });
|
||||
registry.registerHandler("inbox/item.next", () => void calls.push("dialog"), {
|
||||
scope: scopes.activate("inbox/list", { parent: dialog }),
|
||||
});
|
||||
|
||||
const beneath = { beneath: "paseo/command-center" };
|
||||
expect(registry.canDispatch("inbox/item.next")).toBe(false);
|
||||
expect(registry.canDispatch("inbox/item.next", beneath)).toBe(true);
|
||||
expect(registry.dispatch("inbox/item.next", beneath)).toBe(true);
|
||||
// The dialog the Command Center opened over still hides the screen beneath it.
|
||||
expect(calls).toEqual(["dialog"]);
|
||||
expect(scopes.getActiveScopes()).toEqual(["paseo/command-center"]);
|
||||
|
||||
commandCenter.release();
|
||||
dialog.release();
|
||||
list.release();
|
||||
});
|
||||
});
|
||||
|
||||
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 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
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,
|
||||
ScopeActivationOptions,
|
||||
ScopeVisibilityOptions,
|
||||
} from "./internal/action-scope-store";
|
||||
export {
|
||||
ActionCover,
|
||||
ActionRegistryProvider,
|
||||
ActionScope,
|
||||
useActionHandler,
|
||||
useActionRegistry,
|
||||
useActionScope,
|
||||
useActionScopeStore,
|
||||
} from "./internal/react";
|
||||
export type { UseActionHandlerOptions, UseActionScopeOptions } from "./internal/react";
|
||||
@@ -0,0 +1,357 @@
|
||||
import type {
|
||||
ActionScopeStore,
|
||||
ScopeActivation,
|
||||
ScopeVisibilityOptions,
|
||||
} 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 extends ScopeVisibilityOptions {
|
||||
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, options?: ScopeVisibilityOptions): 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,
|
||||
visibility: ScopeVisibilityOptions | undefined,
|
||||
): StoredHandler[] {
|
||||
const ranked: Array<{ entry: StoredHandler; rank: number }> = [];
|
||||
for (const entry of handlersById.get(actionId) ?? []) {
|
||||
const rank = scopes.depthOf(entry.scope, visibility);
|
||||
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, visibility) {
|
||||
return (
|
||||
eligibleHandlers(actionId, visibility).length > 0 || eligibleRunners(actionId).length > 0
|
||||
);
|
||||
},
|
||||
|
||||
dispatch(actionId, input) {
|
||||
for (const entry of eligibleHandlers(actionId, input)) {
|
||||
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,178 @@
|
||||
/** 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;
|
||||
}
|
||||
|
||||
export interface ScopeActivationOptions {
|
||||
/** The activation of the surface this one is mounted in. */
|
||||
parent?: ScopeActivation | null;
|
||||
/**
|
||||
* An overlay, such as a dialog, menu or the Command Center. While it is the
|
||||
* latest open overlay, it hides every scope that is not mounted inside it,
|
||||
* and every handler mounted in no scope. The action's `run` stays available.
|
||||
*/
|
||||
covers?: boolean;
|
||||
}
|
||||
|
||||
export interface ScopeVisibilityOptions {
|
||||
/**
|
||||
* Answers as if the latest open overlay activated under this name were
|
||||
* closed, so the surface beneath it is visible. The Command Center runs the
|
||||
* action the user picked for the screen beneath it this way.
|
||||
*/
|
||||
beneath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. The latest open overlay hides everything beneath it,
|
||||
* including what no scope encloses.
|
||||
*/
|
||||
export interface ActionScopeStore {
|
||||
/** Pushes `scope` as the innermost scope. */
|
||||
activate(scope: string, options?: ScopeActivationOptions): 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 or while an overlay hides it. `null` as
|
||||
* the activation stands for what no scope encloses: depth 0, and hidden like
|
||||
* any other scope while an overlay is open.
|
||||
*/
|
||||
depthOf(activation: ScopeActivation | null, options?: ScopeVisibilityOptions): number | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
interface ActivationEntry {
|
||||
readonly activation: ScopeActivation;
|
||||
readonly parent: ScopeActivation | null;
|
||||
readonly covers: boolean;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function isInside(
|
||||
entry: ActivationEntry,
|
||||
ancestor: ActivationEntry,
|
||||
byActivation: ReadonlyMap<ScopeActivation, ActivationEntry>,
|
||||
): boolean {
|
||||
let current: ActivationEntry | undefined = entry;
|
||||
while (current) {
|
||||
if (current === ancestor) return true;
|
||||
current = current.parent ? byActivation.get(current.parent) : undefined;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The activations no overlay hides: all of them, or the latest overlay and what it holds. */
|
||||
function visibleActivations(entries: readonly ActivationEntry[]): ScopeActivation[] {
|
||||
const top = entries.findLast((entry) => entry.covers);
|
||||
if (!top) {
|
||||
return entries.map((entry) => entry.activation);
|
||||
}
|
||||
const byActivation = new Map(entries.map((entry) => [entry.activation, entry]));
|
||||
return entries
|
||||
.filter((entry) => isInside(entry, top, byActivation))
|
||||
.map((entry) => entry.activation);
|
||||
}
|
||||
|
||||
/** `entries` without the latest overlay named `scope` and what it holds. */
|
||||
function withoutOverlay(entries: readonly ActivationEntry[], scope: string): ActivationEntry[] {
|
||||
const overlay = entries.findLast((entry) => entry.covers && entry.activation.scope === scope);
|
||||
if (!overlay) return [...entries];
|
||||
const byActivation = new Map(entries.map((entry) => [entry.activation, entry]));
|
||||
return entries.filter((entry) => !isInside(entry, overlay, byActivation));
|
||||
}
|
||||
|
||||
export function createActionScopeStore(): ActionScopeStore {
|
||||
const entries: ActivationEntry[] = [];
|
||||
const listeners = new Set<() => void>();
|
||||
let visible: ScopeActivation[] = [];
|
||||
let activeScopes: ActiveScopes = [];
|
||||
|
||||
function commit(): void {
|
||||
visible = visibleActivations(entries);
|
||||
const next = orderActiveScopes(visible);
|
||||
if (sameScopes(activeScopes, next)) {
|
||||
return;
|
||||
}
|
||||
activeScopes = next;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
activate(scope, options = {}) {
|
||||
if (scope.trim().length === 0) {
|
||||
throw new Error("Action scope name must be non-empty");
|
||||
}
|
||||
const activation: ScopeActivation = {
|
||||
scope,
|
||||
release() {
|
||||
const index = entries.findIndex((entry) => entry.activation === activation);
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
entries.splice(index, 1);
|
||||
commit();
|
||||
},
|
||||
};
|
||||
entries.push({
|
||||
activation,
|
||||
parent: options.parent ?? null,
|
||||
covers: options.covers ?? false,
|
||||
});
|
||||
commit();
|
||||
return activation;
|
||||
},
|
||||
|
||||
getActiveScopes() {
|
||||
return activeScopes;
|
||||
},
|
||||
|
||||
depthOf(activation, options) {
|
||||
const open =
|
||||
options?.beneath === undefined ? entries : withoutOverlay(entries, options.beneath);
|
||||
if (activation === null) {
|
||||
return open.some((entry) => entry.covers) ? null : 0;
|
||||
}
|
||||
const shown = open === entries ? visible : visibleActivations(open);
|
||||
const index = shown.indexOf(activation);
|
||||
return index === -1 ? null : index + 1;
|
||||
},
|
||||
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
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;
|
||||
}
|
||||
|
||||
export function useActionScopeStore(): ActionScopeStore {
|
||||
return useActionRegistries().scopes;
|
||||
}
|
||||
|
||||
export interface UseActionScopeOptions {
|
||||
active: boolean;
|
||||
/**
|
||||
* For an overlay, such as a dialog, menu or the Command Center: while open,
|
||||
* it hides every scope not mounted inside it and every handler mounted in no
|
||||
* scope. Wrap its content in `ActionScope` so the scopes inside stay active.
|
||||
*/
|
||||
covers?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates `name` while `active` holds, as the innermost scope, inside the
|
||||
* enclosing `ActionScope`. Returns the activation, or `null` while inactive.
|
||||
* A scope inside an inactive surface stays inactive; an overlay opens anyway.
|
||||
* Pass the activation to `ActionScope` or to `useActionHandler`'s `scope`.
|
||||
*/
|
||||
export function useActionScope(
|
||||
name: string,
|
||||
options: UseActionScopeOptions,
|
||||
): ScopeActivation | null {
|
||||
const { scopes } = useActionRegistries();
|
||||
const enclosingScope = useContext(EnclosingScopeContext);
|
||||
const [activation, setActivation] = useState<ScopeActivation | null>(null);
|
||||
const covers = options.covers ?? false;
|
||||
const parent = enclosingScope ?? null;
|
||||
const active = options.active && (covers || enclosingScope !== null);
|
||||
// Layout effects, here and in `useActionHandler`: a scope the screen shows as active takes keys
|
||||
// before the screen paints, so a key pressed right after a click reaches it.
|
||||
useLayoutEffect(() => {
|
||||
if (!active) return;
|
||||
const next = scopes.activate(name, { parent, covers });
|
||||
setActivation(next);
|
||||
return () => {
|
||||
next.release();
|
||||
setActivation((current) => (current === next ? null : current));
|
||||
};
|
||||
}, [scopes, name, active, parent, covers]);
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The content of an open overlay that registers no keys, such as the mobile
|
||||
* menu sheet. While mounted it hides every scope not mounted inside it and
|
||||
* every handler mounted in no scope, so a key the surface beneath binds does
|
||||
* nothing until the overlay closes. An overlay that registers keys gets its
|
||||
* cover from `useOverlayRegistration` instead.
|
||||
*/
|
||||
export function ActionCover({ name, children }: { name: string; children: ReactNode }) {
|
||||
const activation = useActionScope(name, { active: true, covers: true });
|
||||
return <ActionScope activation={activation}>{children}</ActionScope>;
|
||||
}
|
||||
|
||||
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(" ");
|
||||
|
||||
useLayoutEffect(() => {
|
||||
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]);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import React from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { act, cleanup, render } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
ActionRegistryProvider,
|
||||
ActionScope,
|
||||
createActionRegistry,
|
||||
createActionScopeStore,
|
||||
useActionHandler,
|
||||
useActionScope,
|
||||
} from "@/actions";
|
||||
|
||||
const NEXT = "inbox/item.next";
|
||||
|
||||
function createRegistries() {
|
||||
const scopes = createActionScopeStore();
|
||||
const actions = createActionRegistry({ scopes });
|
||||
actions.registerAction({ id: NEXT, title: "Next" });
|
||||
return { scopes, actions };
|
||||
}
|
||||
|
||||
function List({ name, ran }: { name: string; ran: string[] }) {
|
||||
const scope = useActionScope("inbox/list", { active: true });
|
||||
useActionHandler(
|
||||
NEXT,
|
||||
() => {
|
||||
ran.push(name);
|
||||
},
|
||||
{ scope },
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
function Surface({ active, children }: { active: boolean; children: React.ReactNode }) {
|
||||
const activation = useActionScope("inbox/surface", { active });
|
||||
return <ActionScope activation={activation}>{children}</ActionScope>;
|
||||
}
|
||||
|
||||
function Dialog({ open, children }: { open: boolean; children: React.ReactNode }) {
|
||||
const cover = useActionScope("paseo/dialog", { active: open, covers: true });
|
||||
return open ? <ActionScope activation={cover}>{children}</ActionScope> : null;
|
||||
}
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("useActionScope", () => {
|
||||
it("keeps a scope mounted in an inactive surface inactive until the surface activates", () => {
|
||||
const registries = createRegistries();
|
||||
const ran: string[] = [];
|
||||
const app = (active: boolean) => (
|
||||
<ActionRegistryProvider {...registries}>
|
||||
<Surface active={active}>
|
||||
<List name="list" ran={ran} />
|
||||
</Surface>
|
||||
</ActionRegistryProvider>
|
||||
);
|
||||
const view = render(app(false));
|
||||
|
||||
expect(registries.scopes.getActiveScopes()).toEqual([]);
|
||||
expect(registries.actions.dispatch(NEXT)).toBe(false);
|
||||
|
||||
view.rerender(app(true));
|
||||
expect(registries.scopes.getActiveScopes()).toEqual(["inbox/surface", "inbox/list"]);
|
||||
act(() => {
|
||||
registries.actions.dispatch(NEXT);
|
||||
});
|
||||
expect(ran).toEqual(["list"]);
|
||||
});
|
||||
|
||||
it("gives the key to the list inside an open dialog, and back to the list beneath on close", () => {
|
||||
const registries = createRegistries();
|
||||
const ran: string[] = [];
|
||||
const app = (open: boolean) => (
|
||||
<ActionRegistryProvider {...registries}>
|
||||
<List name="beneath" ran={ran} />
|
||||
<Surface active>
|
||||
<Dialog open={open}>
|
||||
<List name="inside" ran={ran} />
|
||||
</Dialog>
|
||||
</Surface>
|
||||
</ActionRegistryProvider>
|
||||
);
|
||||
const view = render(app(true));
|
||||
|
||||
expect(registries.scopes.getActiveScopes()).toEqual(["paseo/dialog", "inbox/list"]);
|
||||
registries.actions.dispatch(NEXT);
|
||||
|
||||
view.rerender(app(false));
|
||||
registries.actions.dispatch(NEXT);
|
||||
expect(ran).toEqual(["inside", "beneath"]);
|
||||
});
|
||||
|
||||
it("opens an overlay from inside an inactive surface", () => {
|
||||
const registries = createRegistries();
|
||||
const ran: string[] = [];
|
||||
render(
|
||||
<ActionRegistryProvider {...registries}>
|
||||
<List name="beneath" ran={ran} />
|
||||
<Surface active={false}>
|
||||
<Dialog open>
|
||||
<List name="inside" ran={ran} />
|
||||
</Dialog>
|
||||
</Surface>
|
||||
</ActionRegistryProvider>,
|
||||
);
|
||||
|
||||
registries.actions.dispatch(NEXT);
|
||||
expect(ran).toEqual(["inside"]);
|
||||
});
|
||||
|
||||
it("takes a key in the same commit that shows the list active", () => {
|
||||
const registries = createRegistries();
|
||||
const ran: string[] = [];
|
||||
const root = createRoot(document.createElement("div"));
|
||||
const app = (active: boolean) => (
|
||||
<ActionRegistryProvider {...registries}>
|
||||
<Surface active>
|
||||
<ActiveList active={active} ran={ran} />
|
||||
</Surface>
|
||||
</ActionRegistryProvider>
|
||||
);
|
||||
flushSync(() => root.render(app(false)));
|
||||
|
||||
// A click that activates the list commits synchronously, and the key comes before any later task.
|
||||
flushSync(() => root.render(app(true)));
|
||||
registries.actions.dispatch(NEXT);
|
||||
|
||||
expect(ran).toEqual(["list"]);
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
function ActiveList({ active, ran }: { active: boolean; ran: string[] }) {
|
||||
const scope = useActionScope("inbox/list", { active });
|
||||
useActionHandler(
|
||||
NEXT,
|
||||
() => {
|
||||
ran.push("list");
|
||||
},
|
||||
{ scope },
|
||||
);
|
||||
return null;
|
||||
}
|
||||
@@ -317,7 +317,7 @@ function AgentProfileDrawerContent({
|
||||
[onClose, state.isSubmitting],
|
||||
);
|
||||
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: true,
|
||||
layer: drawerLayer,
|
||||
@@ -366,7 +366,7 @@ function AgentProfileDrawerContent({
|
||||
const drawerPanel = (
|
||||
<WindowChromeRegion corners="top-right">
|
||||
<OverlayLayerProvider layer={drawerLayer}>
|
||||
<View ref={setOverlayScope} style={drawerStyle} testID="agent-profile-drawer">
|
||||
<View ref={overlayHandle.ref} style={drawerStyle} testID="agent-profile-drawer">
|
||||
<DrawerHeader
|
||||
serverId={serverId}
|
||||
mode={mode}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { createRegistriesRoot } from "@/core-actions/testing";
|
||||
import { PortalProvider } from "@gorhom/portal";
|
||||
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -26,7 +27,7 @@ beforeEach(() => {
|
||||
host = document.createElement("div");
|
||||
host.style.width = "880px";
|
||||
document.body.appendChild(host);
|
||||
root = createRoot(host);
|
||||
root = createRegistriesRoot(host);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
@@ -43,6 +43,8 @@ import { CommandCenterRootActions } from "@/command-center/root-registration";
|
||||
import { CommandCenterProvider } from "@/command-center/provider";
|
||||
import { CommandCenterWorkspaceActions } from "@/command-center/workspace-registration";
|
||||
import { PluginCommandCenterActions } from "@/plugins/command-center/registration";
|
||||
import { PluginShortcuts, pluginActionOwnerOrder } from "@/plugins/shortcuts";
|
||||
import { pluginRegistry } from "@/plugins/registry";
|
||||
import { AddProjectFlowHost } from "@/components/add-project-flow-host";
|
||||
import { WorktreeSetupCalloutSource } from "@/components/worktree-setup-callout-source";
|
||||
import { DownloadToast } from "@/components/download-toast";
|
||||
@@ -109,11 +111,9 @@ 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";
|
||||
import { useKeyboardShortcuts } from "@/keyboard/use-shortcuts";
|
||||
import { reportNativeUserActivity } from "@/hooks/native-user-activity";
|
||||
import { KeyboardShiftProvider } from "@/keyboard/shift";
|
||||
import { useCompactWebViewportZoomLock } from "@/hooks/use-compact-web-viewport-zoom-lock";
|
||||
@@ -121,10 +121,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, useCoreKeyboardShortcuts } from "@/core-actions";
|
||||
import { polyfillCrypto } from "@/polyfills/crypto";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
@@ -388,7 +385,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 +416,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");
|
||||
|
||||
useKeyboardShortcuts({
|
||||
useAppShellActions({ isMobile: isCompactLayout, toggleAgentList, cycleTheme });
|
||||
useCoreKeyboardShortcuts({
|
||||
enabled: keyboardShortcutsEnabled,
|
||||
isMobile: isCompactLayout,
|
||||
isWorkspaceFocusModeEnabled,
|
||||
toggleAgentList,
|
||||
toggleBothSidebars: toggleDesktopSidebars,
|
||||
exitFocusMode,
|
||||
cycleTheme,
|
||||
});
|
||||
|
||||
useActiveWorktreeNewAction();
|
||||
useGlobalNewWorkspaceAction();
|
||||
|
||||
const activeWorkspace = useActiveWorkspaceSelection();
|
||||
@@ -567,6 +548,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<CommandCenterRootActions />
|
||||
<CommandCenterWorkspaceActions />
|
||||
<PluginCommandCenterActions />
|
||||
<PluginShortcuts plugins={pluginRegistry} />
|
||||
<WorkspacePinShortcutHandler />
|
||||
<WorkspaceRenameHost />
|
||||
<WorkspaceArchiveUndoShortcutHost />
|
||||
@@ -1014,7 +996,7 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
|
||||
|
||||
function RootProviders({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<KeyboardActionDispatcherProvider>
|
||||
<CoreActionsProvider orderOwners={pluginActionOwnerOrder}>
|
||||
<WindowLayoutProvider>
|
||||
<WindowChromeProvider>
|
||||
<KeyboardProvider>
|
||||
@@ -1024,7 +1006,7 @@ function RootProviders({ children }: { children: ReactNode }) {
|
||||
</KeyboardProvider>
|
||||
</WindowChromeProvider>
|
||||
</WindowLayoutProvider>
|
||||
</KeyboardActionDispatcherProvider>
|
||||
</CoreActionsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ import {
|
||||
navigateToWorkspace,
|
||||
useActiveWorkspaceSelection,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { ActionScope, useActionRegistry } from "@/actions";
|
||||
import {
|
||||
clearCommandCenterFocusRestoreElement,
|
||||
takeCommandCenterFocusRestoreElement,
|
||||
@@ -88,7 +88,7 @@ import {
|
||||
COMMAND_CENTER_SECTION_GAP,
|
||||
type CommandCenterListMetrics,
|
||||
} from "./list-metrics";
|
||||
import { useCommandCenterContributions } from "./provider";
|
||||
import { COMMAND_CENTER_SCOPE, useCommandCenterContributions } from "./provider";
|
||||
import { createWorkspaceRanker } from "./workspace-search";
|
||||
import {
|
||||
joinSubtitleParts,
|
||||
@@ -366,7 +366,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);
|
||||
@@ -595,11 +595,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,
|
||||
@@ -1124,7 +1123,8 @@ export function CommandCenter() {
|
||||
},
|
||||
[state],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
name: COMMAND_CENTER_SCOPE,
|
||||
keys: state.activeSublist ? SUBLIST_OVERLAY_KEYS : ROOT_OVERLAY_KEYS,
|
||||
active: state.open,
|
||||
layer: modalLayer,
|
||||
@@ -1179,30 +1179,20 @@ export function CommandCenter() {
|
||||
accessible={false}
|
||||
>
|
||||
<OverlayLayerProvider layer={modalLayer}>
|
||||
<View style={styles.header} testID="command-center-header">
|
||||
<View style={styles.searchRow}>
|
||||
<TextInput
|
||||
testID="command-center-input"
|
||||
ref={bottomSheetInputRef}
|
||||
initialValue={state.query}
|
||||
variant="bottom-sheet"
|
||||
onChangeText={state.setQuery}
|
||||
onSubmitEditing={submit}
|
||||
placeholder={placeholder}
|
||||
style={[styles.input, styles.growingInput]}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoFocus
|
||||
/>
|
||||
<FileSearchLoadingIndicator
|
||||
loading={state.fileSearchLoading}
|
||||
label={t("shell.commandCenter.searchingFiles")}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.tabBar}>{scopeBar}</View>
|
||||
{fileSearchError}
|
||||
<BottomSheetFlatList ref={bottomSheetListRef} {...commonListProps} />
|
||||
<ActionScope activation={overlayHandle.actionScope}>
|
||||
<CommandCenterSearchHeader
|
||||
inputRef={bottomSheetInputRef}
|
||||
variant="bottom-sheet"
|
||||
query={state.query}
|
||||
onChangeQuery={state.setQuery}
|
||||
onSubmit={submit}
|
||||
placeholder={placeholder}
|
||||
loading={state.fileSearchLoading}
|
||||
/>
|
||||
<View style={styles.tabBar}>{scopeBar}</View>
|
||||
{fileSearchError}
|
||||
<BottomSheetFlatList ref={bottomSheetListRef} {...commonListProps} />
|
||||
</ActionScope>
|
||||
</OverlayLayerProvider>
|
||||
</IsolatedBottomSheetModal>
|
||||
);
|
||||
@@ -1218,38 +1208,28 @@ export function CommandCenter() {
|
||||
animationType="fade"
|
||||
onRequestClose={isNative ? state.requestClose : undefined}
|
||||
>
|
||||
<View style={styles.overlay}>
|
||||
<Pressable style={styles.backdrop} onPress={state.close} />
|
||||
<View
|
||||
ref={setOverlayScope}
|
||||
testID="command-center-panel"
|
||||
style={styles.panel}
|
||||
onPointerMove={isWeb ? interaction.pointerMoved : undefined}
|
||||
>
|
||||
<View style={styles.header} testID="command-center-header">
|
||||
<View style={styles.searchRow}>
|
||||
<TextInput
|
||||
testID="command-center-input"
|
||||
ref={inputRef}
|
||||
initialValue={state.query}
|
||||
onChangeText={state.setQuery}
|
||||
placeholder={placeholder}
|
||||
style={[styles.input, styles.growingInput]}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoFocus
|
||||
/>
|
||||
<FileSearchLoadingIndicator
|
||||
loading={state.fileSearchLoading}
|
||||
label={t("shell.commandCenter.searchingFiles")}
|
||||
/>
|
||||
</View>
|
||||
<ActionScope activation={overlayHandle.actionScope}>
|
||||
<View style={styles.overlay}>
|
||||
<Pressable style={styles.backdrop} onPress={state.close} />
|
||||
<View
|
||||
ref={overlayHandle.ref}
|
||||
testID="command-center-panel"
|
||||
style={styles.panel}
|
||||
onPointerMove={isWeb ? interaction.pointerMoved : undefined}
|
||||
>
|
||||
<CommandCenterSearchHeader
|
||||
inputRef={inputRef}
|
||||
query={state.query}
|
||||
onChangeQuery={state.setQuery}
|
||||
placeholder={placeholder}
|
||||
loading={state.fileSearchLoading}
|
||||
/>
|
||||
<View style={styles.tabBar}>{scopeBar}</View>
|
||||
{fileSearchError}
|
||||
<FlatList ref={listRef} {...commonListProps} />
|
||||
</View>
|
||||
<View style={styles.tabBar}>{scopeBar}</View>
|
||||
{fileSearchError}
|
||||
<FlatList ref={listRef} {...commonListProps} />
|
||||
</View>
|
||||
</View>
|
||||
</ActionScope>
|
||||
</Modal>
|
||||
</OverlayLayerProvider>
|
||||
);
|
||||
@@ -1385,6 +1365,49 @@ function CommandCenterTabPills({
|
||||
);
|
||||
}
|
||||
|
||||
function CommandCenterSearchHeader({
|
||||
inputRef,
|
||||
variant,
|
||||
query,
|
||||
onChangeQuery,
|
||||
onSubmit,
|
||||
placeholder,
|
||||
loading,
|
||||
}: {
|
||||
inputRef: React.RefObject<EditingTextInputHandle | null>;
|
||||
variant?: "bottom-sheet";
|
||||
query: string;
|
||||
onChangeQuery: (query: string) => void;
|
||||
onSubmit?: () => void;
|
||||
placeholder: string;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.header} testID="command-center-header">
|
||||
<View style={styles.searchRow}>
|
||||
<TextInput
|
||||
testID="command-center-input"
|
||||
ref={inputRef}
|
||||
initialValue={query}
|
||||
variant={variant}
|
||||
onChangeText={onChangeQuery}
|
||||
onSubmitEditing={onSubmit}
|
||||
placeholder={placeholder}
|
||||
style={[styles.input, styles.growingInput]}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoFocus
|
||||
/>
|
||||
<FileSearchLoadingIndicator
|
||||
loading={loading}
|
||||
label={t("shell.commandCenter.searchingFiles")}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FileSearchLoadingIndicator({ loading, label }: { loading: boolean; label: string }) {
|
||||
return (
|
||||
<View style={styles.fileSearchStatus} testID="command-center-file-search-status">
|
||||
|
||||
@@ -2,13 +2,19 @@ import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useSyncExternalStore,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useActionRegistry } from "@/actions";
|
||||
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
|
||||
import type { CommandCenterContribution } from "./contributions";
|
||||
import { createCommandCenterRegistry, type CommandCenterRegistry } from "./registry";
|
||||
|
||||
/** The action scope the open Command Center covers the app with. */
|
||||
export const COMMAND_CENTER_SCOPE = "paseo/command-center";
|
||||
|
||||
const CommandCenterRegistryContext = createContext<CommandCenterRegistry | null>(null);
|
||||
|
||||
export function CommandCenterProvider({ children }: { children: ReactNode }) {
|
||||
@@ -54,3 +60,30 @@ export function useCommandCenterActions(input: {
|
||||
return () => registry.remove(owner);
|
||||
}, [input.actions, input.enabled, owner, registry]);
|
||||
}
|
||||
|
||||
export interface CommandCenterActionRunner {
|
||||
/** Whether the open Command Center lists `actionId`: the screen beneath it can run it. */
|
||||
canDispatch(actionId: string): boolean;
|
||||
/** Runs `actionId` for the screen beneath the Command Center, as its keys would there. */
|
||||
dispatch(actionId: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs registry actions from Command Center rows. The open Command Center covers the screen
|
||||
* beneath it, so a row asks the registry as if it were closed; a handler mounted on that screen
|
||||
* takes the action ahead of the action's `run`, as it does for the action's keys. A new runner
|
||||
* comes with each opening, so rows answer for the screen the user opened the Command Center on.
|
||||
*/
|
||||
export function useCommandCenterActionRunner(): CommandCenterActionRunner {
|
||||
const actions = useActionRegistry();
|
||||
const open = useKeyboardShortcutsStore((state) => state.commandCenterOpen);
|
||||
return useMemo(() => {
|
||||
const beneath = { beneath: COMMAND_CENTER_SCOPE };
|
||||
return {
|
||||
canDispatch: (actionId) => open && actions.canDispatch(actionId, beneath),
|
||||
dispatch: (actionId) => {
|
||||
actions.dispatch(actionId, beneath);
|
||||
},
|
||||
};
|
||||
}, [actions, 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";
|
||||
@@ -19,12 +18,10 @@ 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 { 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";
|
||||
@@ -38,10 +35,9 @@ 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";
|
||||
import { useCommandCenterActionRunner, useCommandCenterActions } from "./provider";
|
||||
import { buildGroupingContribution } from "./root-contributions";
|
||||
|
||||
const ThemedPlus = withUnistyles(Plus, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
@@ -123,11 +119,11 @@ function SwitchWorkspaceIcon({ size }: CommandCenterIconProps) {
|
||||
}
|
||||
|
||||
export function CommandCenterRootActions() {
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const actionRegistry = useCommandCenterActionRunner();
|
||||
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();
|
||||
@@ -145,11 +141,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",
|
||||
@@ -168,8 +163,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"),
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -180,15 +174,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"),
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -207,9 +200,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"),
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -300,9 +291,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.
|
||||
@@ -327,9 +316,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"),
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -374,9 +361,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"),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -400,16 +385,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 ArrowDownToLine from "lucide-react-native/icons/arrow-down-to-line";
|
||||
@@ -28,11 +29,8 @@ 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 { useHostFeature } from "@/runtime/host-features";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceDirectory, useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
@@ -43,7 +41,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,
|
||||
@@ -54,14 +51,12 @@ import { getLabelCommandCenterIcon } from "@/workspace-labels/command-center-ico
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { getCommandCenterIcon } from "./icon";
|
||||
import type { CommandCenterIcon } from "./contributions";
|
||||
import { useCommandCenterActions } from "./provider";
|
||||
import { useCommandCenterActionRunner, useCommandCenterActions } from "./provider";
|
||||
import {
|
||||
buildWorkspaceCommandCenterContributions,
|
||||
buildWorkspaceFileSearchContribution,
|
||||
type WorkspaceCommandCenterLabelChoice,
|
||||
type WorkspaceCommandCenterShortcuts,
|
||||
} from "./workspace-contributions";
|
||||
import { resolveWorkspaceCommandCenterShortcuts } from "./workspace-shortcuts";
|
||||
|
||||
const WORKSPACE_COMMAND_CENTER_ICONS = {
|
||||
newAgent: getCommandCenterIcon(SquarePen),
|
||||
@@ -106,11 +101,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
|
||||
@@ -166,7 +156,7 @@ function useWorkspaceLabelCatalog(
|
||||
function useWorkspaceFileSearchAction(
|
||||
serverId: string | null,
|
||||
workspaceId: string | null,
|
||||
shortcutKeys: WorkspaceCommandCenterShortcuts["searchFiles"],
|
||||
shortcutKeys: ShortcutKey[][] | undefined,
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const actions = useMemo(
|
||||
@@ -189,7 +179,8 @@ function useWorkspaceFileSearchAction(
|
||||
}
|
||||
|
||||
export function useWorkspaceCommandCenterActions(): void {
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const actionRegistry = useCommandCenterActionRunner();
|
||||
const bindings = useKeybindings();
|
||||
const { t } = useTranslation();
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
@@ -228,7 +219,6 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
fields?.setupStatus ?? null,
|
||||
supportsSetupObservation,
|
||||
);
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
const { gitActions, isGit, archiveWorkspace } = useGitActions({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId,
|
||||
@@ -257,8 +247,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(
|
||||
() =>
|
||||
@@ -315,7 +309,7 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
archiveWorkspace: staticIcon(GIT_ACTION_ICONS.archive),
|
||||
git: (action) => staticIcon(action.icon),
|
||||
},
|
||||
shortcuts,
|
||||
shortcutKeys,
|
||||
capabilities: {
|
||||
canSplitPanes: supportsDesktopPaneSplits() && !isCompact,
|
||||
canOpenBrowserTabs: getIsElectron(),
|
||||
@@ -329,9 +323,9 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
currentBranch,
|
||||
isPinned,
|
||||
labelCatalog,
|
||||
dispatch: (action) => {
|
||||
dispatch: (actionId) => {
|
||||
clearCommandCenterFocusRestoreElement();
|
||||
keyboardActionDispatcher.dispatch(action);
|
||||
actionRegistry.dispatch(actionId);
|
||||
},
|
||||
runGitAction,
|
||||
archiveWorkspace,
|
||||
@@ -353,10 +347,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,3 +1,4 @@
|
||||
import { ActionScope } from "@/actions";
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
@@ -828,7 +829,8 @@ function AdaptiveModalSheetPresentation({
|
||||
() => ["Escape", ...(keyboard?.keys ?? []).filter((key) => key !== "Escape")],
|
||||
[keyboard?.keys],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
name: "paseo/dialog",
|
||||
keys: overlayKeys,
|
||||
active: visible,
|
||||
layer: modalLayer,
|
||||
@@ -872,18 +874,20 @@ function AdaptiveModalSheetPresentation({
|
||||
presentation={presentation}
|
||||
>
|
||||
<OverlayLayerProvider layer={modalLayer}>
|
||||
<CompactSheetBody
|
||||
header={header}
|
||||
showCloseButton={showCloseButton}
|
||||
onClose={onClose}
|
||||
testID={testID}
|
||||
footer={footerView}
|
||||
scrollable={scrollable}
|
||||
bodyStyle={bodyStyle}
|
||||
contentStyle={contentStyle}
|
||||
>
|
||||
{children}
|
||||
</CompactSheetBody>
|
||||
<ActionScope activation={overlayHandle.actionScope}>
|
||||
<CompactSheetBody
|
||||
header={header}
|
||||
showCloseButton={showCloseButton}
|
||||
onClose={onClose}
|
||||
testID={testID}
|
||||
footer={footerView}
|
||||
scrollable={scrollable}
|
||||
bodyStyle={bodyStyle}
|
||||
contentStyle={contentStyle}
|
||||
>
|
||||
{children}
|
||||
</CompactSheetBody>
|
||||
</ActionScope>
|
||||
</OverlayLayerProvider>
|
||||
</IsolatedBottomSheetModal>
|
||||
);
|
||||
@@ -924,8 +928,8 @@ function AdaptiveModalSheetPresentation({
|
||||
const desktopContent = (
|
||||
<View style={desktopOverlayStyle} testID={testID}>
|
||||
<DismissBackdrop label={t("common.actions.dismiss")} onPress={onClose} />
|
||||
<View ref={setOverlayScope} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
|
||||
{cardInner}
|
||||
<View ref={overlayHandle.ref} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
|
||||
<ActionScope activation={overlayHandle.actionScope}>{cardInner}</ActionScope>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { WindowLayoutProvider } from "@/window-layout";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import { RetainedChatContent as NativeChatContent } from "@/panels/retained-chat-content.native";
|
||||
import { RetainedChatContent as WebChatContent } from "@/panels/retained-chat-content.web";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
|
||||
|
||||
interface FrameSample {
|
||||
@@ -92,11 +93,13 @@ afterEach(() => {
|
||||
|
||||
function renderLightbox(source: ImageLightboxSource | null) {
|
||||
root.render(
|
||||
<SafeAreaProvider>
|
||||
<WindowLayoutProvider>
|
||||
<AttachmentLightbox source={source} onClose={noop} />
|
||||
</WindowLayoutProvider>
|
||||
</SafeAreaProvider>,
|
||||
<CoreRegistriesProvider>
|
||||
<SafeAreaProvider>
|
||||
<WindowLayoutProvider>
|
||||
<AttachmentLightbox source={source} onClose={noop} />
|
||||
</WindowLayoutProvider>
|
||||
</SafeAreaProvider>
|
||||
</CoreRegistriesProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -173,15 +176,17 @@ describe("AttachmentLightbox when its chat leaves the screen", () => {
|
||||
const uri = URL.createObjectURL(await createPng(400, 300));
|
||||
const showThread = (active: boolean) =>
|
||||
root.render(
|
||||
<SafeAreaProvider>
|
||||
<WindowLayoutProvider>
|
||||
<RetainedPanelActivity active={active}>
|
||||
<ChatContent>
|
||||
<ThreadWithImage uri={uri} />
|
||||
</ChatContent>
|
||||
</RetainedPanelActivity>
|
||||
</WindowLayoutProvider>
|
||||
</SafeAreaProvider>,
|
||||
<CoreRegistriesProvider>
|
||||
<SafeAreaProvider>
|
||||
<WindowLayoutProvider>
|
||||
<RetainedPanelActivity active={active}>
|
||||
<ChatContent>
|
||||
<ThreadWithImage uri={uri} />
|
||||
</ChatContent>
|
||||
</RetainedPanelActivity>
|
||||
</WindowLayoutProvider>
|
||||
</SafeAreaProvider>
|
||||
</CoreRegistriesProvider>,
|
||||
);
|
||||
await act(async () => showThread(true));
|
||||
await act(async () => openImage?.());
|
||||
|
||||
@@ -5,6 +5,7 @@ import { JSDOM } from "jsdom";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import type { AttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
|
||||
|
||||
const { theme, imageMetadata, useAttachmentPreviewUrlMock } = vi.hoisted(() => {
|
||||
@@ -163,7 +164,7 @@ afterEach(() => {
|
||||
|
||||
function render(element: React.ReactElement) {
|
||||
act(() => {
|
||||
root?.render(element);
|
||||
root?.render(<CoreRegistriesProvider>{element}</CoreRegistriesProvider>);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
|
||||
},
|
||||
[onClose],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: open,
|
||||
layer: modalLayer,
|
||||
@@ -97,7 +97,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
|
||||
where the image was opened (inside a sheet tab, the bottom one is already spent). */}
|
||||
<WindowSafeArea>
|
||||
<WindowChromeRootRegion corners="both">
|
||||
<View ref={setOverlayScope} style={styles.root}>
|
||||
<View ref={overlayHandle.ref} style={styles.root}>
|
||||
<Pressable
|
||||
testID="attachment-lightbox-backdrop"
|
||||
accessibilityRole="button"
|
||||
|
||||
@@ -28,7 +28,11 @@ import {
|
||||
type ToolbarGlyph,
|
||||
} from "@/components/ui/control-geometry";
|
||||
|
||||
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
|
||||
import {
|
||||
KeyboardToggleClose,
|
||||
useKeyboardToggle,
|
||||
type KeyboardToggleAction,
|
||||
} from "@/hooks/use-keyboard-toggle";
|
||||
|
||||
const DEFAULT_TRIGGER_DECORATION = { showCaret: true, tooltip: undefined };
|
||||
const SHEET_SNAP_POINTS = ["80%", "90%"];
|
||||
@@ -174,6 +178,7 @@ function DesktopCombinedModelSelector({
|
||||
onEditProfile={onEditProfile ? actions.handleEditProfile : undefined}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
toggleActionId={toggleAction?.id}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
@@ -319,6 +324,7 @@ function CompactCombinedModelSelector({
|
||||
contentStyle={styles.sheetBody}
|
||||
testID="model-selector-sheet"
|
||||
>
|
||||
<KeyboardToggleClose actionId={toggleAction?.id} onClose={handleClose} />
|
||||
<MobileModelPageView
|
||||
page={page}
|
||||
selectedProvider={selectedProvider}
|
||||
|
||||
@@ -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,10 @@ 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";
|
||||
import { usePluginShortcutSections } from "@/plugins/shortcuts";
|
||||
import { useInstalledPlugins } from "@/plugins/registry";
|
||||
|
||||
const SNAP_POINTS: string[] = ["70%", "92%"];
|
||||
|
||||
@@ -22,21 +19,6 @@ export function KeyboardShortcutsDialog() {
|
||||
const setOpen = useKeyboardShortcutsStore((s) => s.setShortcutsDialogOpen);
|
||||
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 visibleSections = useMemo(
|
||||
() => filterShortcutHelpSections({ sections, query, translate: t, shortcutOs }),
|
||||
[query, sections, shortcutOs, t],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setQuery("");
|
||||
}, [open]);
|
||||
@@ -63,37 +45,62 @@ export function KeyboardShortcutsDialog() {
|
||||
testID="keyboard-shortcuts-dialog"
|
||||
snapPoints={SNAP_POINTS}
|
||||
>
|
||||
<View testID="keyboard-shortcuts-dialog-content" style={styles.content}>
|
||||
{visibleSections.map((section) => (
|
||||
<View key={section.title} 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}
|
||||
</View>
|
||||
{row.chord === null ? (
|
||||
<Text style={styles.rowUnassigned}>{t("settings.shortcuts.unassigned")}</Text>
|
||||
) : (
|
||||
<Shortcut chord={row.chord} style={styles.rowShortcut} />
|
||||
)}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
{visibleSections.length === 0 ? (
|
||||
<Text style={styles.empty}>{t("common.empty.noResults")}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<ShortcutsDialogContent query={query} />
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function ShortcutsDialogContent({ query }: { query: string }) {
|
||||
const { t } = useTranslation();
|
||||
const shortcutOs = getShortcutOs();
|
||||
// Effective bindings, so a shortcut the user unassigned lists no keys here
|
||||
// instead of advertising a default that no longer fires.
|
||||
const bindings = useKeybindings();
|
||||
const pluginSections = usePluginShortcutSections(useInstalledPlugins());
|
||||
const sections = useMemo(
|
||||
() =>
|
||||
buildShortcutSections({
|
||||
bindings,
|
||||
platform: getDisplayPlatform(),
|
||||
translate: t,
|
||||
sections: pluginSections,
|
||||
}),
|
||||
[bindings, pluginSections, t],
|
||||
);
|
||||
const visibleSections = useMemo(
|
||||
() => filterShortcutHelpSections({ sections, query, shortcutOs }),
|
||||
[query, sections, shortcutOs],
|
||||
);
|
||||
|
||||
return (
|
||||
<View testID="keyboard-shortcuts-dialog-content" style={styles.content}>
|
||||
{visibleSections.map((section) => (
|
||||
<View key={section.id} style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>{section.title}</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}>{row.label}</Text>
|
||||
{row.note ? <Text style={styles.rowNote}>{row.note}</Text> : null}
|
||||
</View>
|
||||
{row.chord === null ? (
|
||||
<Text style={styles.rowUnassigned}>{t("settings.shortcuts.unassigned")}</Text>
|
||||
) : (
|
||||
<Shortcut chord={row.chord} style={styles.rowShortcut} />
|
||||
)}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
{visibleSections.length === 0 ? (
|
||||
<Text style={styles.empty}>{t("common.empty.noResults")}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
content: {
|
||||
gap: theme.spacing[4],
|
||||
|
||||
@@ -80,7 +80,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,
|
||||
@@ -451,8 +451,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) => {
|
||||
|
||||
@@ -68,6 +68,7 @@ import {
|
||||
} from "@/components/ui/scroll-reveal";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import type { KeyboardInputEvent } from "@/keyboard";
|
||||
import { KeyboardToggleClose } from "@/hooks/use-keyboard-toggle";
|
||||
import { useCurrentOverlayLayer } from "@/lib/overlay-root";
|
||||
import type { ModelFoldKind } from "@/provider-selection/model-curation";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
@@ -113,6 +114,8 @@ export interface DesktopModelPickerProps extends ModelPickerActions {
|
||||
selectedModel: string;
|
||||
profiles: AgentProfilePicker | null;
|
||||
serverId: string | null;
|
||||
/** The keyboard action that opened the picker; it closes it too. */
|
||||
toggleActionId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,6 +133,7 @@ export function DesktopModelPicker({
|
||||
selectedModel,
|
||||
profiles,
|
||||
serverId,
|
||||
toggleActionId,
|
||||
...actions
|
||||
}: DesktopModelPickerProps) {
|
||||
const input = useMemo<ModelPickerInput<AgentProfilePickerRow>>(
|
||||
@@ -144,6 +148,7 @@ export function DesktopModelPicker({
|
||||
);
|
||||
const layout = resolveModelPickerLayout(input);
|
||||
const height = useMemo(() => resolveModelPickerHeight(input), [input]);
|
||||
const close = useCallback(() => onOpenChange(false), [onOpenChange]);
|
||||
const keyboardHandlerRef = useRef<KeyboardHandler | null>(null);
|
||||
const keyboard = useMemo<SheetKeyboard>(
|
||||
() => ({
|
||||
@@ -168,6 +173,7 @@ export function DesktopModelPicker({
|
||||
desktopChildrenScrollEnabled={false}
|
||||
keyboard={keyboard}
|
||||
>
|
||||
<KeyboardToggleClose actionId={toggleActionId} onClose={close} />
|
||||
<ModelPickerBody
|
||||
input={input}
|
||||
pickerHeight={height}
|
||||
|
||||
@@ -140,9 +140,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 {
|
||||
@@ -267,7 +266,6 @@ interface ProjectHeaderRowProps {
|
||||
chevron: "expand" | "collapse" | null;
|
||||
onPress: () => void;
|
||||
worktreeTarget: SidebarProjectHostTarget | null;
|
||||
isProjectActive?: boolean;
|
||||
onWorkspacePress?: () => void;
|
||||
onWorktreeCreated?: (workspaceId: string) => void;
|
||||
shortcutNumber?: number | null;
|
||||
@@ -427,7 +425,6 @@ function ProjectRowTrailingActions({
|
||||
settingsTarget,
|
||||
projectPath,
|
||||
isHovered,
|
||||
isProjectActive,
|
||||
onBeginWorkspaceSetup,
|
||||
onRemoveProject,
|
||||
removeProjectStatus,
|
||||
@@ -438,7 +435,6 @@ function ProjectRowTrailingActions({
|
||||
settingsTarget: { serverId: string; projectId: string } | null;
|
||||
projectPath: string;
|
||||
isHovered: boolean;
|
||||
isProjectActive: boolean;
|
||||
onBeginWorkspaceSetup: () => void;
|
||||
onRemoveProject?: () => void;
|
||||
removeProjectStatus: "idle" | "pending" | "success";
|
||||
@@ -452,7 +448,6 @@ function ProjectRowTrailingActions({
|
||||
displayName={displayName}
|
||||
onPress={onBeginWorkspaceSetup}
|
||||
visible={actionsVisible}
|
||||
showShortcutHint={isProjectActive}
|
||||
testID={`sidebar-project-new-worktree-${projectViewKey}`}
|
||||
/>
|
||||
) : null}
|
||||
@@ -747,17 +742,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 }) => [
|
||||
@@ -809,9 +801,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>
|
||||
@@ -895,7 +884,6 @@ function ProjectHeaderRow({
|
||||
chevron,
|
||||
onPress,
|
||||
worktreeTarget,
|
||||
isProjectActive = false,
|
||||
onWorkspacePress,
|
||||
onWorktreeCreated: _onWorktreeCreated,
|
||||
shortcutNumber = null,
|
||||
@@ -993,7 +981,6 @@ function ProjectHeaderRow({
|
||||
settingsTarget={settingsTarget}
|
||||
projectPath={projectPath}
|
||||
isHovered={isHovered}
|
||||
isProjectActive={isProjectActive}
|
||||
onBeginWorkspaceSetup={handleBeginWorkspaceSetup}
|
||||
onRemoveProject={onRemoveProject}
|
||||
removeProjectStatus={removeProjectStatus}
|
||||
@@ -1351,7 +1338,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,
|
||||
@@ -1674,12 +1661,6 @@ function ProjectBlock({
|
||||
enabled: collapsed,
|
||||
});
|
||||
|
||||
const active = isProjectSelectedByRoute({
|
||||
selection: activeWorkspaceSelection,
|
||||
project,
|
||||
enabled: selectionEnabled,
|
||||
});
|
||||
|
||||
const renderWorkspaceRow = useCallback(
|
||||
(
|
||||
item: SidebarWorkspacePlacement,
|
||||
@@ -1883,7 +1864,6 @@ function ProjectBlock({
|
||||
worktreeTarget={
|
||||
rowModel.trailingAction.kind === "new_workspace" ? rowModel.trailingAction.target : null
|
||||
}
|
||||
isProjectActive={active}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
onWorktreeCreated={onWorktreeCreated}
|
||||
drag={drag}
|
||||
@@ -2897,7 +2877,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
projectActionTooltipShortcut: {},
|
||||
projectShortcutBadgeOverlay: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[2] + 1,
|
||||
|
||||
@@ -20,7 +20,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";
|
||||
@@ -71,8 +71,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),
|
||||
|
||||
@@ -8,7 +8,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";
|
||||
|
||||
@@ -42,7 +42,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,
|
||||
@@ -769,7 +769,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(
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
createControlGeometry,
|
||||
type ControlSize,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { ShortcutToneProvider, type ShortcutTone } from "@/components/ui/shortcut";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
type ButtonVariant = "default" | "secondary" | "outline" | "ghost" | "destructive";
|
||||
@@ -156,6 +157,12 @@ const styles = StyleSheet.create((theme) => {
|
||||
};
|
||||
});
|
||||
|
||||
function shortcutToneFor(variant: ButtonVariant): ShortcutTone {
|
||||
if (variant === "default") return "accent";
|
||||
if (variant === "destructive") return "destructive";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
variant = "secondary",
|
||||
@@ -240,6 +247,8 @@ export function Button({
|
||||
[accessibilityStateProp, isDisabled, loading],
|
||||
);
|
||||
|
||||
const shortcutTone = shortcutToneFor(variant);
|
||||
|
||||
function resolveIconMapping() {
|
||||
if (variant === "default") {
|
||||
return accentForegroundIconMapping;
|
||||
@@ -263,18 +272,20 @@ export function Button({
|
||||
onHoverOut={handleHoverOut}
|
||||
style={pressableStyle}
|
||||
>
|
||||
<ThemedButtonIcon
|
||||
loading={loading}
|
||||
leftIcon={leftIcon}
|
||||
iconSize={controlIconSize[size]}
|
||||
uniProps={resolveIconMapping()}
|
||||
/>
|
||||
{children != null ? (
|
||||
<Text numberOfLines={numberOfLines} style={resolvedTextStyle}>
|
||||
{children}
|
||||
</Text>
|
||||
) : null}
|
||||
{trailing}
|
||||
<ShortcutToneProvider tone={shortcutTone}>
|
||||
<ThemedButtonIcon
|
||||
loading={loading}
|
||||
leftIcon={leftIcon}
|
||||
iconSize={controlIconSize[size]}
|
||||
uniProps={resolveIconMapping()}
|
||||
/>
|
||||
{children != null ? (
|
||||
<Text numberOfLines={numberOfLines} style={resolvedTextStyle}>
|
||||
{children}
|
||||
</Text>
|
||||
) : null}
|
||||
{trailing}
|
||||
</ShortcutToneProvider>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ActionScope } from "@/actions";
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { useSettledKeyboardHeight } from "@/keyboard/shift";
|
||||
import { Modal } from "@/components/ui/modal";
|
||||
@@ -1770,7 +1771,7 @@ export function Combobox({
|
||||
},
|
||||
[handleClose, handleDesktopKey, hasChildren, keyboard],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
active: isOpen,
|
||||
layer: floatingLayer,
|
||||
keys: overlayKeys,
|
||||
@@ -1779,6 +1780,9 @@ export function Combobox({
|
||||
});
|
||||
|
||||
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
|
||||
const coveredChildren = (
|
||||
<ActionScope activation={overlayHandle.actionScope}>{children}</ActionScope>
|
||||
);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
@@ -1811,7 +1815,7 @@ export function Combobox({
|
||||
handleSelect={handleSelect}
|
||||
renderOption={renderOption}
|
||||
>
|
||||
{children}
|
||||
{coveredChildren}
|
||||
</MobileComboboxBody>
|
||||
);
|
||||
}
|
||||
@@ -1824,7 +1828,7 @@ export function Combobox({
|
||||
isOpen={isOpen}
|
||||
handleClose={handleClose}
|
||||
handleDesktopKey={handleDesktopKey}
|
||||
setOverlayScope={setOverlayScope}
|
||||
setOverlayScope={overlayHandle.ref}
|
||||
refs={refs}
|
||||
shouldUseDesktopFade={shouldUseDesktopFade}
|
||||
desktopFrameStyle={desktopFrameStyle}
|
||||
@@ -1851,7 +1855,7 @@ export function Combobox({
|
||||
hasChildren={hasChildren}
|
||||
childrenScrollEnabled={desktopChildrenScrollEnabled}
|
||||
>
|
||||
{children}
|
||||
{coveredChildren}
|
||||
</DesktopComboboxBody>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ function WebHoverCard({
|
||||
[clearGraceTimer, focusInside, open, openNow],
|
||||
);
|
||||
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const { ref: setOverlayScope } = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: !disabled && open,
|
||||
layer,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { act, useEffect, useState, type ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { ScrollView, Text, View, type ViewStyle } from "react-native";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
import {
|
||||
@@ -34,7 +35,7 @@ function mount(node: ReactNode): void {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
act(() => root.render(node));
|
||||
act(() => root.render(<CoreRegistriesProvider>{node}</CoreRegistriesProvider>));
|
||||
mounted.push({ root, container });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ActionScope } from "@/actions";
|
||||
import { navigateMenuKeyboard } from "./keyboard-navigation";
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { Modal } from "@/components/ui/modal";
|
||||
@@ -27,7 +28,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,
|
||||
@@ -520,7 +521,8 @@ export function MenuOverlay({
|
||||
},
|
||||
[onClose],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
name: "paseo/menu",
|
||||
keys: ["Escape"],
|
||||
active: visible,
|
||||
layer: floatingLayer,
|
||||
@@ -536,7 +538,7 @@ export function MenuOverlay({
|
||||
{...{
|
||||
onContextMenu: (event: { preventDefault?: () => void }) => event.preventDefault?.(),
|
||||
}}
|
||||
ref={setOverlayScope}
|
||||
ref={overlayHandle.ref}
|
||||
collapsable={false}
|
||||
style={[
|
||||
styles.overlay,
|
||||
@@ -544,7 +546,7 @@ export function MenuOverlay({
|
||||
isWeb ? { zIndex: floatingLayer } : null,
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
<ActionScope activation={overlayHandle.actionScope}>{children}</ActionScope>
|
||||
</View>
|
||||
</OverlayLayerProvider>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ActionCover } from "@/actions";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
@@ -61,7 +62,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 });
|
||||
@@ -447,7 +448,9 @@ function MenuSheetSurface({
|
||||
const contextBridge = useCallback<ContextBridge>(
|
||||
(content) => (
|
||||
<MenuContextProvider value={menu}>
|
||||
<MenuSurfaceContext.Provider value={surfaceValue}>{content}</MenuSurfaceContext.Provider>
|
||||
<MenuSurfaceContext.Provider value={surfaceValue}>
|
||||
<ActionCover name="paseo/menu">{content}</ActionCover>
|
||||
</MenuSurfaceContext.Provider>
|
||||
</MenuContextProvider>
|
||||
),
|
||||
[menu, surfaceValue],
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Button } from "./button";
|
||||
import { Shortcut } from "./shortcut";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
function mount(node: React.ReactNode) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(node));
|
||||
// A modifier press is how a desktop browser that cannot report a fine pointer proves it has a keyboard.
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "Shift", shiftKey: true }));
|
||||
});
|
||||
}
|
||||
|
||||
function colorOf(element: Element, property: "color" | "backgroundColor"): string {
|
||||
return getComputedStyle(element)[property];
|
||||
}
|
||||
|
||||
/** The element that carries the button's label color: the one whose first text node is the label. */
|
||||
function labelOf(): HTMLElement {
|
||||
const label = [...document.querySelectorAll<HTMLElement>("*")].find((element) =>
|
||||
[...element.childNodes].some(
|
||||
(node) => node.nodeType === Node.TEXT_NODE && node.textContent?.startsWith("Submit"),
|
||||
),
|
||||
);
|
||||
if (!label) throw new Error("no button label");
|
||||
return label;
|
||||
}
|
||||
|
||||
function badgeText(): HTMLElement {
|
||||
const text = [...document.querySelectorAll<HTMLElement>("*")].find(
|
||||
(element) => element.textContent === "K" && element.children.length === 0,
|
||||
);
|
||||
if (!text) throw new Error("no shortcut badge text");
|
||||
return text;
|
||||
}
|
||||
|
||||
describe("Shortcut inside a Button", () => {
|
||||
it.each(["default", "destructive"] as const)(
|
||||
"reads in the %s button's foreground color",
|
||||
(variant) => {
|
||||
mount(
|
||||
<Button variant={variant}>
|
||||
Submit <Shortcut keys={["K"]} />
|
||||
</Button>,
|
||||
);
|
||||
const label = labelOf();
|
||||
const button = document.querySelector<HTMLElement>('[role="button"]');
|
||||
if (!button) throw new Error("no button");
|
||||
|
||||
expect(colorOf(badgeText(), "color")).toBe(colorOf(label, "color"));
|
||||
expect(colorOf(badgeText(), "color")).not.toBe(colorOf(button, "backgroundColor"));
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the neutral badge on a secondary button", () => {
|
||||
mount(
|
||||
<Button variant="secondary">
|
||||
Submit <Shortcut keys={["K"]} />
|
||||
</Button>,
|
||||
);
|
||||
const label = labelOf();
|
||||
|
||||
expect(colorOf(badgeText(), "color")).not.toBe(colorOf(label, "color"));
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,10 @@
|
||||
import React, { useMemo, type ReactElement } from "react";
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { Text, View, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard";
|
||||
@@ -6,6 +12,24 @@ import { normalizeDisplayChord } from "@/components/ui/normalize-display-chord";
|
||||
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
|
||||
/**
|
||||
* What a badge sits on. A button with a filled background tells the badges
|
||||
* inside it, so they read in the button's foreground instead of neutral gray.
|
||||
*/
|
||||
export type ShortcutTone = "neutral" | "accent" | "destructive";
|
||||
|
||||
const ShortcutToneContext = createContext<ShortcutTone>("neutral");
|
||||
|
||||
export function ShortcutToneProvider({
|
||||
tone,
|
||||
children,
|
||||
}: {
|
||||
tone: ShortcutTone;
|
||||
children: ReactNode;
|
||||
}): ReactElement {
|
||||
return <ShortcutToneContext.Provider value={tone}>{children}</ShortcutToneContext.Provider>;
|
||||
}
|
||||
|
||||
export function Shortcut({
|
||||
keys,
|
||||
chord,
|
||||
@@ -18,11 +42,28 @@ export function Shortcut({
|
||||
textStyle?: StyleProp<TextStyle>;
|
||||
}): ReactElement | null {
|
||||
const shortcutsAvailable = useHardwareKeyboardPresent();
|
||||
const tone = useContext(ShortcutToneContext);
|
||||
const displayChord = normalizeDisplayChord(chord, keys);
|
||||
const shortcutOs = getShortcutOs();
|
||||
|
||||
const badgeStyle = useMemo(() => [styles.badge, style], [style]);
|
||||
const textCombinedStyle = useMemo(() => [styles.text, textStyle], [textStyle]);
|
||||
const textCombinedStyle = useMemo(
|
||||
() => [
|
||||
styles.text,
|
||||
tone === "accent" && styles.textOnAccent,
|
||||
tone === "destructive" && styles.textOnDestructive,
|
||||
textStyle,
|
||||
],
|
||||
[tone, textStyle],
|
||||
);
|
||||
const backgroundStyle = useMemo(
|
||||
() => [
|
||||
styles.badgeBackground,
|
||||
tone === "accent" && styles.badgeBackgroundOnAccent,
|
||||
tone === "destructive" && styles.badgeBackgroundOnDestructive,
|
||||
],
|
||||
[tone],
|
||||
);
|
||||
const sequenceStyle = useMemo(() => [styles.sequence, style], [style]);
|
||||
|
||||
if (!shortcutsAvailable) {
|
||||
@@ -39,7 +80,7 @@ export function Shortcut({
|
||||
if (displayChord.length === 1) {
|
||||
return (
|
||||
<View style={badgeStyle}>
|
||||
<View style={styles.badgeBackground} />
|
||||
<View style={backgroundStyle} />
|
||||
<Text style={textCombinedStyle}>{formatShortcut(singleCombo, shortcutOs)}</Text>
|
||||
</View>
|
||||
);
|
||||
@@ -50,7 +91,7 @@ export function Shortcut({
|
||||
{displayChord.map(function (combo) {
|
||||
return (
|
||||
<View key={combo.join("+")} style={styles.badge}>
|
||||
<View style={styles.badgeBackground} />
|
||||
<View style={backgroundStyle} />
|
||||
<Text style={textCombinedStyle}>{formatShortcut(combo, shortcutOs)}</Text>
|
||||
</View>
|
||||
);
|
||||
@@ -73,6 +114,14 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surface3,
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
badgeBackgroundOnAccent: {
|
||||
backgroundColor: theme.colors.accentForeground,
|
||||
opacity: 0.2,
|
||||
},
|
||||
badgeBackgroundOnDestructive: {
|
||||
backgroundColor: theme.colors.destructiveForeground,
|
||||
opacity: 0.2,
|
||||
},
|
||||
sequence: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
@@ -84,4 +133,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
textOnAccent: {
|
||||
color: theme.colors.accentForeground,
|
||||
},
|
||||
textOnDestructive: {
|
||||
color: theme.colors.destructiveForeground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -23,6 +23,7 @@ import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal"
|
||||
import type { KeyboardInputEvent } from "@/keyboard";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { KeyboardToggleClose } from "@/hooks/use-keyboard-toggle";
|
||||
import { AGENT_SHEET_HOME, resolveAgentSheetEscape, type AgentSheetPage } from "./model-sheet-flow";
|
||||
import {
|
||||
AgentSheetHome,
|
||||
@@ -38,6 +39,8 @@ const ESCAPE_KEYS = ["Escape"] as const;
|
||||
export interface AgentSettingsDrawerProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
/** The keyboard action that opened the drawer; it closes it too. */
|
||||
toggleActionId?: string;
|
||||
contextBridge: ContextBridge | null;
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
@@ -67,6 +70,7 @@ export interface AgentSettingsDrawerProps {
|
||||
export function AgentSettingsDrawer({
|
||||
visible,
|
||||
onClose,
|
||||
toggleActionId,
|
||||
contextBridge,
|
||||
providers,
|
||||
selectedProvider,
|
||||
@@ -363,6 +367,7 @@ export function AgentSettingsDrawer({
|
||||
contextBridge={contextBridge}
|
||||
testID="agent-controls-model-sheet"
|
||||
>
|
||||
<KeyboardToggleClose actionId={toggleActionId} onClose={close} />
|
||||
{/* Keyed by page, so each page opens at its top. */}
|
||||
<View key={pageKey(page)} style={styles.page}>
|
||||
{body}
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import React from "react";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { cleanup, fireEvent, render as renderInDom, screen, waitFor } from "@testing-library/react";
|
||||
import Scan from "lucide-react-native/icons/scan";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AgentOptionControl } from "@getpaseo/protocol/agent-types";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { ComposerControls, type ComposerControlItem } from "./composer-control";
|
||||
import { useAgentControlItems } from "./control-items";
|
||||
import { resolveComposerControlPresentation } from "./layout";
|
||||
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
|
||||
/** Renders inside the app's registries, which every popover and sheet needs to cover the app. */
|
||||
function render(ui: React.ReactElement) {
|
||||
return renderInDom(ui, { wrapper: CoreRegistriesProvider });
|
||||
}
|
||||
afterEach(cleanup);
|
||||
|
||||
const base = { id: "x", title: "Context", icon: Scan };
|
||||
|
||||
@@ -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,11 +10,9 @@ 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 { resolveNextAgentModeId } from "@/composer/agent-controls/mode";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { useComposerKeyboardActions, useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { useComposerControlLayout } from "@/composer/agent-controls/layout-context";
|
||||
import { AgentControlTrigger } from "@/composer/agent-controls/control";
|
||||
import { setLiveAgentMode } from "@/composer/agent-mutations";
|
||||
@@ -89,7 +87,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);
|
||||
@@ -220,33 +218,22 @@ const EMPTY_MODES: AgentMode[] = [];
|
||||
* narrow window can still have a keyboard.
|
||||
*/
|
||||
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 enabled = modeControl != null && !modeControl.disabled && modeOptions.length > 1;
|
||||
|
||||
const handle = useCallback(
|
||||
(action: KeyboardActionDefinition): boolean => {
|
||||
if (action.id !== "message-input.mode-cycle" || !enabled || !modeControl) return false;
|
||||
useComposerKeyboardActions(
|
||||
"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,10 +29,11 @@ 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";
|
||||
import { KeyboardToggleClose } from "@/hooks/use-keyboard-toggle";
|
||||
import { useModelPickerShortcut } from "./control-items";
|
||||
import { AgentSettingsDrawer } from "./agent-settings-drawer";
|
||||
import { AgentModeControl } from "./mode-control";
|
||||
@@ -174,6 +175,7 @@ export function CompactModelSheet({
|
||||
}: CompactModelSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const usesBottomSheet = useIsCompactFormFactor();
|
||||
const toggleActionId = useModelPickerShortcut(disabled).action?.id;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const availableProviders = useMemo(() => {
|
||||
if (canSwitchProvider) return providers;
|
||||
@@ -236,6 +238,7 @@ export function CompactModelSheet({
|
||||
<AgentSettingsDrawer
|
||||
visible={isOpen}
|
||||
onClose={close}
|
||||
toggleActionId={toggleActionId}
|
||||
contextBridge={contextBridge}
|
||||
providers={availableProviders}
|
||||
selectedProvider={selectedProvider}
|
||||
@@ -259,6 +262,7 @@ export function CompactModelSheet({
|
||||
<NarrowPaneModelDialog
|
||||
visible={isOpen}
|
||||
onClose={close}
|
||||
toggleActionId={toggleActionId}
|
||||
contextBridge={contextBridge}
|
||||
browser={rootBrowser}
|
||||
canSwitchProvider={canSwitchProvider}
|
||||
@@ -287,6 +291,7 @@ export function CompactModelSheet({
|
||||
function NarrowPaneModelDialog({
|
||||
visible,
|
||||
onClose,
|
||||
toggleActionId,
|
||||
contextBridge,
|
||||
browser,
|
||||
canSwitchProvider,
|
||||
@@ -305,6 +310,8 @@ function NarrowPaneModelDialog({
|
||||
}: {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
/** The keyboard action that opened the dialog; it closes it too. */
|
||||
toggleActionId: string | undefined;
|
||||
contextBridge: ContextBridge | null;
|
||||
browser: ReturnType<typeof useModelBrowser>;
|
||||
canSwitchProvider: boolean;
|
||||
@@ -373,6 +380,7 @@ function NarrowPaneModelDialog({
|
||||
contextBridge={contextBridge}
|
||||
testID="agent-controls-model-sheet"
|
||||
>
|
||||
<KeyboardToggleClose actionId={toggleActionId} onClose={onClose} />
|
||||
<View
|
||||
style={[styles.modelViewport, styles.fixedModelViewport]}
|
||||
testID="agent-controls-model-viewport"
|
||||
|
||||
@@ -118,7 +118,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";
|
||||
@@ -144,15 +144,19 @@ 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, ActionInvocation } from "@/actions";
|
||||
import { submitAgentInput } from "@/composer/submit";
|
||||
import { ComposerRecall } from "@/composer/recall";
|
||||
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
|
||||
import { ComposerKeyboardScopeProvider, useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import {
|
||||
ComposerKeyboardScopeProvider,
|
||||
useComposerKeyboardActions,
|
||||
useComposerKeyboardScope,
|
||||
} from "@/composer/keyboard-scope";
|
||||
import { usePaneHost } from "@/panels/pane-context";
|
||||
import { useSettingsCoversWorkspace } from "@/navigation/settings-presentation/covers-workspace";
|
||||
import { OverlayDismissalScope, useDismissOverlays } from "@/components/ui/overlay-dismissal";
|
||||
import type { PaneHost } from "@/panels/panel-manifest";
|
||||
import { useAppSettings } from "@/hooks/use-settings";
|
||||
@@ -248,10 +252,6 @@ function resolveIsVoiceModeForAgent(
|
||||
return voice?.isVoiceModeForAgent(serverId, agentId) ?? false;
|
||||
}
|
||||
|
||||
function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
|
||||
return isMessageInputFocused ? 200 : 100;
|
||||
}
|
||||
|
||||
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
|
||||
return !hasSoftwareKeyboard && !isMobile;
|
||||
}
|
||||
@@ -587,9 +587,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;
|
||||
@@ -598,10 +607,11 @@ interface DispatchComposerKeyboardActionArgs {
|
||||
focusMessageInputForKeyboardAction: () => void;
|
||||
}
|
||||
|
||||
function dispatchComposerKeyboardAction(args: DispatchComposerKeyboardActionArgs): boolean {
|
||||
function runComposerKeyboardAction(
|
||||
invocation: ActionInvocation,
|
||||
args: ComposerKeyboardActionArgs,
|
||||
): void | ActionDeclined {
|
||||
const {
|
||||
action,
|
||||
isPaneFocused,
|
||||
messageInputRef,
|
||||
isAgentRunning,
|
||||
isCancellingAgent,
|
||||
@@ -609,83 +619,30 @@ 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;
|
||||
}) {
|
||||
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,
|
||||
],
|
||||
/** Runs the composer's keyboard actions; it sits inside the composer's action scope. */
|
||||
function ComposerKeyboardRegistration(props: ComposerKeyboardActionArgs) {
|
||||
useComposerKeyboardActions(COMPOSER_KEYBOARD_ACTIONS, (invocation) =>
|
||||
runComposerKeyboardAction(invocation, props),
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -698,17 +655,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;
|
||||
@@ -1239,10 +1192,13 @@ export function Composer({ isPaneFocused, ...props }: ComposerProps) {
|
||||
const commandCenterPanel = mobilePanelTarget === "agent-list" ? "agent" : mobilePanelTarget;
|
||||
const coveredForCommandCenter =
|
||||
isCompact && isMobilePanelCoveringHost(commandCenterPanel, paneHost);
|
||||
// Desktop Settings covers the workspace, which stays mounted beneath it.
|
||||
const coveredBySettings = useSettingsCoversWorkspace();
|
||||
const isActiveComposer = isPaneFocused && !coveredByOverlayPanel && !coveredBySettings;
|
||||
return (
|
||||
<ComposerKeyboardScopeProvider
|
||||
isPaneFocused={isPaneFocused}
|
||||
isActiveComposer={isPaneFocused && !coveredByOverlayPanel}
|
||||
isActiveComposer={isActiveComposer}
|
||||
isCommandCenterTarget={isPaneFocused && !coveredForCommandCenter}
|
||||
>
|
||||
<OverlayDismissalScope>
|
||||
@@ -1313,8 +1269,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,
|
||||
@@ -1448,7 +1404,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);
|
||||
@@ -1473,9 +1428,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 }) => {
|
||||
@@ -1502,7 +1454,7 @@ function ComposerContentImpl({
|
||||
);
|
||||
const isInputLive = useIsInputLive(messageInputRef);
|
||||
const isPanelActive = useRetainedPanelActive();
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const { isActiveComposer, reportInputFocus } = useComposerKeyboardScope();
|
||||
const inputRevealed = isPanelActive && isActiveComposer;
|
||||
const isActiveComposerRef = useRef(isActiveComposer);
|
||||
isActiveComposerRef.current = isActiveComposer;
|
||||
@@ -2476,12 +2428,12 @@ function ComposerContentImpl({
|
||||
|
||||
const handleFocusChange = useCallback(
|
||||
(focused: boolean) => {
|
||||
setIsMessageInputFocused(focused);
|
||||
reportInputFocus(focused);
|
||||
if (focused) {
|
||||
onAttentionInputFocus?.();
|
||||
}
|
||||
},
|
||||
[onAttentionInputFocus],
|
||||
[onAttentionInputFocus, reportInputFocus],
|
||||
);
|
||||
|
||||
const handleLightboxClose = useCallback(() => {
|
||||
@@ -2745,14 +2697,12 @@ function ComposerContentImpl({
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
handlerId={keyboardHandlerIdRef.current}
|
||||
messageInputRef={messageInputRef}
|
||||
isAgentRunning={isAgentRunning}
|
||||
isCancellingAgent={isCancellingAgent}
|
||||
isConnected={isConnected}
|
||||
handleCancelAgent={handleCancelAgent}
|
||||
focusMessageInputForKeyboardAction={focusMessageInputForKeyboardAction}
|
||||
isMessageInputFocused={isMessageInputFocused}
|
||||
/>
|
||||
<View
|
||||
style={
|
||||
|
||||
@@ -2,6 +2,7 @@ import React from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { dispatchTopOverlayKeyDown } from "@/keyboard";
|
||||
import { useComposerFullscreenExit } from "./fullscreen-exit";
|
||||
|
||||
@@ -15,10 +16,22 @@ it("the native entry claims Escape until fullscreen closes", () => {
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
flushSync(() => root.render(<Harness active />));
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<CoreRegistriesProvider>
|
||||
<Harness active />
|
||||
</CoreRegistriesProvider>,
|
||||
),
|
||||
);
|
||||
expect(dispatchTopOverlayKeyDown(new KeyboardEvent("keydown", { key: "Escape" }))).toBe(true);
|
||||
expect(exits).toBe(1);
|
||||
flushSync(() => root.render(<Harness active={false} />));
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<CoreRegistriesProvider>
|
||||
<Harness active={false} />
|
||||
</CoreRegistriesProvider>,
|
||||
),
|
||||
);
|
||||
expect(dispatchTopOverlayKeyDown(new KeyboardEvent("keydown", { key: "Escape" }))).toBe(false);
|
||||
expect(exits).toBe(1);
|
||||
} finally {
|
||||
|
||||
@@ -23,5 +23,5 @@ export function useComposerFullscreenExit(
|
||||
onExit();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}).ref;
|
||||
}
|
||||
|
||||
@@ -82,11 +82,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 { supportsConfigurableComposerSendKeys } from "@/keyboard";
|
||||
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
@@ -124,6 +123,7 @@ import {
|
||||
runDefaultSendAction,
|
||||
runMessageInputKeyboardAction,
|
||||
stopRealtimeVoice,
|
||||
type MessageInputKeyboardActionKind,
|
||||
} from "./state";
|
||||
|
||||
const DEFAULT_SEND_KEYS: ShortcutKey[][] = [["Enter"]];
|
||||
@@ -1392,9 +1392,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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import React, { useEffect } from "react";
|
||||
import { act, cleanup, render } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { ActionRegistryProvider, useActionHandler } from "@/actions";
|
||||
import { createCoreRegistries, type CoreRegistries } from "@/core-actions";
|
||||
import type { KeyboardShortcutContext } from "@/keyboard";
|
||||
import {
|
||||
ComposerKeyboardScopeProvider,
|
||||
useComposerKeyboardActions,
|
||||
useComposerKeyboardScope,
|
||||
} from "./keyboard-scope";
|
||||
|
||||
const DESKTOP: KeyboardShortcutContext = {
|
||||
isMac: false,
|
||||
usesDesktopBindings: true,
|
||||
focusScope: "message-input",
|
||||
commandCenterOpen: false,
|
||||
};
|
||||
|
||||
const COMPOSER_ACTIONS = ["paseo/agent.interrupt", "paseo/message-input.focus"];
|
||||
|
||||
interface ComposerProps {
|
||||
name: string;
|
||||
ran: string[];
|
||||
isActive?: boolean;
|
||||
isInputFocused?: boolean;
|
||||
}
|
||||
|
||||
function ComposerKeys({ name, ran, isInputFocused = false }: ComposerProps) {
|
||||
const { reportInputFocus } = useComposerKeyboardScope();
|
||||
useEffect(() => reportInputFocus(isInputFocused), [isInputFocused, reportInputFocus]);
|
||||
useComposerKeyboardActions(COMPOSER_ACTIONS, (invocation) => {
|
||||
ran.push(`${name} ${invocation.actionId}`);
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function Composer(props: ComposerProps) {
|
||||
const isActive = props.isActive ?? true;
|
||||
return (
|
||||
<ComposerKeyboardScopeProvider
|
||||
isPaneFocused={isActive}
|
||||
isActiveComposer={isActive}
|
||||
isCommandCenterTarget={isActive}
|
||||
>
|
||||
<ComposerKeys {...props} />
|
||||
</ComposerKeyboardScopeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings registers Escape like the app shell does: while it covers the
|
||||
* workspace on a wide layout. It covers nothing on a compact layout.
|
||||
*/
|
||||
function Settings({ ran, coversWorkspace }: { ran: string[]; coversWorkspace: boolean }) {
|
||||
useActionHandler(
|
||||
"paseo/agent.interrupt",
|
||||
() => {
|
||||
ran.push("settings closed");
|
||||
},
|
||||
{ enabled: coversWorkspace },
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
let core: CoreRegistries;
|
||||
|
||||
function renderApp(children: React.ReactNode) {
|
||||
core = createCoreRegistries();
|
||||
const view = render(
|
||||
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
|
||||
{children}
|
||||
</ActionRegistryProvider>,
|
||||
);
|
||||
return (next: React.ReactNode) =>
|
||||
view.rerender(
|
||||
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
|
||||
{next}
|
||||
</ActionRegistryProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function press(key: string, modifiers: { ctrlKey?: boolean } = {}) {
|
||||
act(() => {
|
||||
core.keybindings.dispatchKeyDown(
|
||||
{
|
||||
key,
|
||||
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
||||
altKey: false,
|
||||
ctrlKey: modifiers.ctrlKey ?? false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
},
|
||||
DESKTOP,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("composer keyboard actions", () => {
|
||||
it("go to the composer whose input has focus, not the one that activated last", () => {
|
||||
const ran: string[] = [];
|
||||
const rerender = renderApp(<Composer name="main pane" ran={ran} isInputFocused />);
|
||||
rerender(
|
||||
<>
|
||||
<Composer name="main pane" ran={ran} isInputFocused />
|
||||
<Composer name="explorer dock" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
press("l", { ctrlKey: true });
|
||||
|
||||
expect(ran).toEqual(["main pane paseo/agent.interrupt", "main pane paseo/message-input.focus"]);
|
||||
});
|
||||
|
||||
it("follow the focus when it moves to another composer's input", () => {
|
||||
const ran: string[] = [];
|
||||
const rerender = renderApp(
|
||||
<>
|
||||
<Composer name="main pane" ran={ran} isInputFocused />
|
||||
<Composer name="explorer dock" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
rerender(
|
||||
<>
|
||||
<Composer name="main pane" ran={ran} />
|
||||
<Composer name="explorer dock" ran={ran} isInputFocused />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["explorer dock paseo/agent.interrupt"]);
|
||||
});
|
||||
|
||||
it("stay with the last-focused composer after its input blurs", () => {
|
||||
const ran: string[] = [];
|
||||
const rerender = renderApp(<Composer name="main pane" ran={ran} isInputFocused />);
|
||||
rerender(
|
||||
<>
|
||||
<Composer name="main pane" ran={ran} isInputFocused />
|
||||
<Composer name="explorer dock" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
// Clicking the main pane's timeline blurs its input.
|
||||
rerender(
|
||||
<>
|
||||
<Composer name="main pane" ran={ran} />
|
||||
<Composer name="explorer dock" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["main pane paseo/agent.interrupt"]);
|
||||
});
|
||||
|
||||
it("go to the innermost composer once the last-focused composer deactivates", () => {
|
||||
const ran: string[] = [];
|
||||
const rerender = renderApp(
|
||||
<>
|
||||
<Composer name="explorer dock" ran={ran} />
|
||||
<Composer name="main pane" ran={ran} isInputFocused />
|
||||
</>,
|
||||
);
|
||||
rerender(
|
||||
<>
|
||||
<Composer name="explorer dock" ran={ran} />
|
||||
<Composer name="main pane" ran={ran} isActive={false} />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["explorer dock paseo/agent.interrupt"]);
|
||||
});
|
||||
|
||||
it("go to the innermost composer while no composer input has had focus", () => {
|
||||
const ran: string[] = [];
|
||||
renderApp(
|
||||
<>
|
||||
<Composer name="running agent" ran={ran} />
|
||||
<Composer name="new workspace draft" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["new workspace draft paseo/agent.interrupt"]);
|
||||
});
|
||||
|
||||
it("ignore an inactive composer's focused input", () => {
|
||||
const ran: string[] = [];
|
||||
renderApp(
|
||||
<>
|
||||
<Composer name="covered" ran={ran} isActive={false} isInputFocused />
|
||||
<Composer name="main pane" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["main pane paseo/agent.interrupt"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Escape on Settings over a running agent", () => {
|
||||
it("closes desktop Settings even when the agent's composer activates after it", () => {
|
||||
const ran: string[] = [];
|
||||
const rerender = renderApp(<Settings ran={ran} coversWorkspace />);
|
||||
// Desktop Settings covers the workspace, so its composers are inactive.
|
||||
rerender(
|
||||
<>
|
||||
<Settings ran={ran} coversWorkspace />
|
||||
<Composer name="running agent" ran={ran} isActive={false} isInputFocused />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["settings closed"]);
|
||||
});
|
||||
|
||||
it("interrupts the agent on compact Settings", () => {
|
||||
const ran: string[] = [];
|
||||
renderApp(
|
||||
<>
|
||||
<Settings ran={ran} coversWorkspace={false} />
|
||||
<Composer name="running agent" ran={ran} />
|
||||
</>,
|
||||
);
|
||||
|
||||
press("Escape");
|
||||
|
||||
expect(ran).toEqual(["running agent paseo/agent.interrupt"]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,14 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type PropsWithChildren,
|
||||
type ReactElement,
|
||||
} from "react";
|
||||
import { ActionScope, type ActionHandler, useActionHandler, useActionScope } from "@/actions";
|
||||
|
||||
interface ComposerKeyboardScopeValue {
|
||||
/**
|
||||
@@ -15,36 +19,99 @@ interface ComposerKeyboardScopeValue {
|
||||
/**
|
||||
* The composer takes input right now: keyboard actions, shortcuts, autocomplete,
|
||||
* and the fullscreen exit action. False while a compact overlay panel covers the
|
||||
* pane, which does not take pane focus.
|
||||
* pane, which does not take pane focus, and while desktop Settings covers the
|
||||
* workspace.
|
||||
*/
|
||||
isActiveComposer: boolean;
|
||||
/** The composer whose settings appear in Command Center. */
|
||||
isCommandCenterTarget: boolean;
|
||||
}
|
||||
|
||||
const ComposerKeyboardScopeContext = createContext<ComposerKeyboardScopeValue>({
|
||||
interface ComposerKeyboardScopeContextValue extends ComposerKeyboardScopeValue {
|
||||
/** The composer's message input gained or lost keyboard focus. */
|
||||
reportInputFocus: (focused: boolean) => void;
|
||||
/** Read on each dispatch: this composer runs the composer keys now. */
|
||||
takesKeys: () => boolean;
|
||||
}
|
||||
|
||||
const ComposerKeyboardScopeContext = createContext<ComposerKeyboardScopeContextValue>({
|
||||
isPaneFocused: false,
|
||||
isActiveComposer: false,
|
||||
isCommandCenterTarget: false,
|
||||
reportInputFocus: () => {},
|
||||
takesKeys: () => false,
|
||||
});
|
||||
|
||||
/**
|
||||
* The active composer whose message input had keyboard focus last. Only one
|
||||
* input holds focus at a time, so one record serves every composer on screen.
|
||||
* It survives a blur, such as a click on the agent's timeline, and clears when
|
||||
* that composer deactivates or unmounts.
|
||||
*/
|
||||
let lastFocusedComposer: object | null = null;
|
||||
|
||||
/**
|
||||
* Every active composer activates its own `paseo/composer` scope, and the
|
||||
* composer's handlers below it belong to that activation.
|
||||
*
|
||||
* Several composers can be active at once, such as the main pane's and an
|
||||
* Explorer dock agent tab's. The one whose input had focus last takes the
|
||||
* composer keys. Until an active composer's input has had focus, the innermost
|
||||
* scope wins.
|
||||
*/
|
||||
export function ComposerKeyboardScopeProvider({
|
||||
isPaneFocused,
|
||||
isActiveComposer,
|
||||
isCommandCenterTarget,
|
||||
children,
|
||||
}: PropsWithChildren<ComposerKeyboardScopeValue>): ReactElement {
|
||||
const value = useMemo(
|
||||
() => ({ isPaneFocused, isActiveComposer, isCommandCenterTarget }),
|
||||
[isPaneFocused, isActiveComposer, isCommandCenterTarget],
|
||||
const [composer] = useState(() => ({}));
|
||||
const [isInputFocused, setInputFocused] = useState(false);
|
||||
useEffect(() => {
|
||||
if (isActiveComposer && isInputFocused) lastFocusedComposer = composer;
|
||||
}, [composer, isActiveComposer, isInputFocused]);
|
||||
useEffect(() => {
|
||||
if (!isActiveComposer) return;
|
||||
return () => {
|
||||
if (lastFocusedComposer === composer) lastFocusedComposer = null;
|
||||
};
|
||||
}, [composer, isActiveComposer]);
|
||||
const takesKeys = useCallback(
|
||||
() => isActiveComposer && (lastFocusedComposer === null || lastFocusedComposer === composer),
|
||||
[composer, isActiveComposer],
|
||||
);
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
isPaneFocused,
|
||||
isActiveComposer,
|
||||
isCommandCenterTarget,
|
||||
reportInputFocus: setInputFocused,
|
||||
takesKeys,
|
||||
}),
|
||||
[isPaneFocused, isActiveComposer, isCommandCenterTarget, takesKeys],
|
||||
);
|
||||
const actionScope = useActionScope("paseo/composer", { active: isActiveComposer });
|
||||
return (
|
||||
<ComposerKeyboardScopeContext.Provider value={value}>
|
||||
{children}
|
||||
<ActionScope activation={actionScope}>{children}</ActionScope>
|
||||
</ComposerKeyboardScopeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useComposerKeyboardScope(): ComposerKeyboardScopeValue {
|
||||
export function useComposerKeyboardScope(): ComposerKeyboardScopeContextValue {
|
||||
return useContext(ComposerKeyboardScopeContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `handler` for the composer's keyboard actions, such as Escape to
|
||||
* interrupt the agent, while this composer takes the composer keys.
|
||||
*/
|
||||
export function useComposerKeyboardActions(
|
||||
actionIds: string | readonly string[],
|
||||
handler: ActionHandler,
|
||||
options: { enabled?: boolean } = {},
|
||||
): void {
|
||||
const { takesKeys } = useComposerKeyboardScope();
|
||||
const enabled = options.enabled ?? true;
|
||||
useActionHandler(actionIds, handler, { enabled: () => enabled && takesKeys() });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { act, useCallback, useState, type ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import { MobilePanelsProvider } from "@/mobile-panels/provider";
|
||||
@@ -33,7 +34,7 @@ function mount(node: ReactNode): HTMLDivElement {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
act(() => root.render(node));
|
||||
act(() => root.render(<CoreRegistriesProvider>{node}</CoreRegistriesProvider>));
|
||||
mounted.push({ root, container });
|
||||
return container;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
export { CoreActionsProvider, createCoreRegistries } from "./internal/provider";
|
||||
export type { CoreRegistries } from "./internal/provider";
|
||||
export { useAppShellActions } from "./internal/app-shell-actions";
|
||||
export { useCoreKeyboardShortcuts } from "./internal/keyboard-shortcuts";
|
||||
export { buildShortcutSections } from "./internal/sections";
|
||||
export { filterShortcutHelpSections } from "./internal/help-search";
|
||||
export type { ShortcutRow, ShortcutSection, ShortcutSectionInput } from "./internal/sections";
|
||||
export {
|
||||
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,89 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { usePathname, useRouter } from "expo-router";
|
||||
import { useActionHandler, useActionRegistry } from "@/actions";
|
||||
import { getDisplayPlatform, useKeybindings } from "@/keyboard";
|
||||
import { useOpenAddProject } from "@/hooks/use-open-add-project";
|
||||
import { useSettingsCoversWorkspace } from "@/navigation/settings-presentation/covers-workspace";
|
||||
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 composers that
|
||||
// stay mounted under it take no keys, so this is the only handler left.
|
||||
const settingsCoversWorkspace = useSettingsCoversWorkspace();
|
||||
useActionHandler("paseo/agent.interrupt", () => returnFromSettings(shell), {
|
||||
enabled: settingsCoversWorkspace,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { KeyboardShortcutContext, KeyboardShortcutInput } from "@/keyboard";
|
||||
import type { ShortcutOverrides } from "@/keyboard/shortcut-override-store";
|
||||
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;
|
||||
overrides?: ShortcutOverrides;
|
||||
}
|
||||
|
||||
/** 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));
|
||||
core.keybindings.setOverrides(state.overrides ?? {});
|
||||
if (state.projectPickerHost) {
|
||||
core.actions.registerHandler("paseo/workspace.project.pick", () => {
|
||||
did.push(["project-pick"]);
|
||||
});
|
||||
}
|
||||
return {
|
||||
actions: core.actions,
|
||||
did,
|
||||
press: (event: Partial<KeyboardShortcutInput>) => pressKey(core, event),
|
||||
};
|
||||
}
|
||||
|
||||
const NON_MAC_DESKTOP: KeyboardShortcutContext = {
|
||||
isMac: false,
|
||||
usesDesktopBindings: true,
|
||||
focusScope: "other",
|
||||
commandCenterOpen: false,
|
||||
};
|
||||
|
||||
function pressKey(
|
||||
core: ReturnType<typeof createCoreRegistries>,
|
||||
event: Partial<KeyboardShortcutInput>,
|
||||
) {
|
||||
return core.keybindings.dispatchKeyDown(
|
||||
{
|
||||
key: "",
|
||||
code: "",
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
...event,
|
||||
},
|
||||
NON_MAC_DESKTOP,
|
||||
);
|
||||
}
|
||||
|
||||
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([]);
|
||||
});
|
||||
|
||||
// Settings saved a captured digit literally before number groups were
|
||||
// captured as `Digit`; those overrides still jump to the pressed number.
|
||||
it.each([
|
||||
{ saved: "Ctrl+3", keys: [{ key: "3", code: "Digit3", ctrlKey: true }] },
|
||||
{
|
||||
saved: "Ctrl+G 3",
|
||||
keys: [
|
||||
{ key: "g", code: "KeyG", ctrlKey: true },
|
||||
{ key: "3", code: "Digit3" },
|
||||
],
|
||||
},
|
||||
])("jumps to the pressed number with a saved literal override $saved", ({ saved, keys }) => {
|
||||
const { press, did } = createShell({
|
||||
overrides: { "workspace-navigate-index-ctrl-digit-non-mac": saved },
|
||||
});
|
||||
for (const key of keys) press(key);
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-3" }]]);
|
||||
});
|
||||
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chords on actions only a mounted surface runs", () => {
|
||||
it("leave the shared prefix to Command Center while no surface can run them", () => {
|
||||
const { press } = createShell({
|
||||
overrides: { "workspace-terminal-new-ctrl-shift-t-non-mac": "Ctrl+K J" },
|
||||
});
|
||||
|
||||
const result = press({ key: "k", code: "KeyK", ctrlKey: true });
|
||||
|
||||
expect(result.chordPending).toBe(false);
|
||||
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { ActionDeclined, ActionHandler } 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";
|
||||
|
||||
const DECLINED: ActionDeclined = { handled: false };
|
||||
|
||||
/** The core actions the app shell runs. Every other core action runs only in a mounted surface. */
|
||||
export const APP_SHELL_ACTION_IDS = [
|
||||
"paseo/project.open",
|
||||
"paseo/settings.toggle",
|
||||
"paseo/command-center.toggle",
|
||||
"paseo/command-center.files",
|
||||
"paseo/shortcuts-dialog.toggle",
|
||||
"paseo/theme.cycle",
|
||||
"paseo/sidebar.toggle.left",
|
||||
"paseo/sidebar.toggle.both",
|
||||
"paseo/workspace.navigate.index",
|
||||
"paseo/workspace.previous",
|
||||
"paseo/workspace.next",
|
||||
"paseo/workspace.switcher.next",
|
||||
"paseo/workspace.switcher.previous",
|
||||
] as const;
|
||||
|
||||
export type AppShellActionId = (typeof APP_SHELL_ACTION_IDS)[number];
|
||||
|
||||
/** The app shell's `run` for each action it owns. */
|
||||
export type AppShellRuns = Readonly<Record<AppShellActionId, ActionHandler>>;
|
||||
|
||||
/** 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): AppShellRuns {
|
||||
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" },
|
||||
},
|
||||
];
|
||||
+683
-539
File diff suppressed because it is too large
Load Diff
+26
-21
@@ -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,11 +23,20 @@ function translate(key: string): string {
|
||||
return EN[key] ?? key;
|
||||
}
|
||||
|
||||
function sections(overrides: ShortcutOverrides = {}) {
|
||||
const { keybindings } = createCoreRegistries();
|
||||
keybindings.setOverrides(overrides);
|
||||
return buildShortcutSections({
|
||||
bindings: keybindings.getBindings(),
|
||||
platform: MAC_DESKTOP,
|
||||
translate,
|
||||
});
|
||||
}
|
||||
|
||||
function filter(query: string, overrides: ShortcutOverrides = {}) {
|
||||
return filterShortcutHelpSections({
|
||||
sections: buildKeyboardShortcutHelpSections(MAC_DESKTOP, buildEffectiveBindings(overrides)),
|
||||
sections: sections(overrides),
|
||||
query,
|
||||
translate,
|
||||
shortcutOs: "mac",
|
||||
});
|
||||
}
|
||||
@@ -67,19 +74,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 +94,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);
|
||||
});
|
||||
+6
-11
@@ -1,9 +1,6 @@
|
||||
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. */
|
||||
export type TranslateHelpKey = (key: string) => string;
|
||||
|
||||
/**
|
||||
* Alternative spellings for one combo, so searching "cmd k" and "command+k" both
|
||||
* find ⌘K. The modifier a user types rarely matches the token the binding
|
||||
@@ -57,26 +54,24 @@ export function shortcutSearchText(chord: ShortcutKey[][], shortcutOs: ShortcutO
|
||||
export function filterShortcutHelpSections({
|
||||
sections,
|
||||
query,
|
||||
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];
|
||||
|
||||
return sections.flatMap((section) => {
|
||||
if (translate(section.titleKey).toLocaleLowerCase().includes(normalizedQuery)) {
|
||||
if (section.title.toLocaleLowerCase().includes(normalizedQuery)) {
|
||||
return [section];
|
||||
}
|
||||
|
||||
const rows = section.rows.filter((row) => {
|
||||
const searchText = [
|
||||
translate(row.labelKey),
|
||||
row.noteKey ? translate(row.noteKey) : row.note,
|
||||
row.label,
|
||||
row.note ?? null,
|
||||
row.chord ? shortcutSearchText(row.chord, shortcutOs) : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
@@ -0,0 +1,47 @@
|
||||
import { getDisplayPlatform, type KeyboardInputEvent, useKeybindings } from "@/keyboard";
|
||||
import { useKeyboardShortcuts } from "@/keyboard/use-shortcuts";
|
||||
import {
|
||||
cancelWorkspaceSwitcherIfPending,
|
||||
handleWorkspaceSwitcherBlur,
|
||||
handleWorkspaceSwitcherKeyUp,
|
||||
} from "@/workspace-switcher";
|
||||
import { getWorkspaceIndexJumpModifierKey } from "./workspace-keys";
|
||||
|
||||
const SIDEBAR_ACTION_PREFIX = "paseo/sidebar.";
|
||||
|
||||
function isEscape(event: KeyboardInputEvent): boolean {
|
||||
return event.key === "Escape" || event.code === "Escape";
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the app's keyboard shortcuts with the core actions' key policy: Escape
|
||||
* cancels a pending workspace switch, the switcher commits on modifier release,
|
||||
* and a sidebar shortcut leaves focus mode.
|
||||
*/
|
||||
export function useCoreKeyboardShortcuts(input: {
|
||||
enabled: boolean;
|
||||
isMobile: boolean;
|
||||
isWorkspaceFocusModeEnabled: boolean;
|
||||
exitFocusMode: () => void;
|
||||
}): void {
|
||||
const bindings = useKeybindings();
|
||||
useKeyboardShortcuts({
|
||||
enabled: input.enabled,
|
||||
isMobile: input.isMobile,
|
||||
// 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.
|
||||
badgeModifierKey: getWorkspaceIndexJumpModifierKey(getDisplayPlatform(), bindings),
|
||||
claimKeyDown: (event) => isEscape(event) && cancelWorkspaceSwitcherIfPending(),
|
||||
keyUp: handleWorkspaceSwitcherKeyUp,
|
||||
blur: handleWorkspaceSwitcherBlur,
|
||||
handled: (result) => {
|
||||
if (
|
||||
input.isWorkspaceFocusModeEnabled &&
|
||||
result.binding?.actionId.startsWith(SIDEBAR_ACTION_PREFIX)
|
||||
) {
|
||||
input.exitFocusMode();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
ActionRegistryProvider,
|
||||
createActionRegistry,
|
||||
createActionScopeStore,
|
||||
type ActionRegistry,
|
||||
type ActionScopeStore,
|
||||
type OrderOwners,
|
||||
} from "@/actions";
|
||||
import {
|
||||
createKeybindingRegistry,
|
||||
KeybindingRegistryProvider,
|
||||
type KeybindingRegistry,
|
||||
} from "@/keyboard";
|
||||
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
|
||||
import { CORE_ACTIONS } from "./actions";
|
||||
import { APP_SHELL_ACTION_IDS, type AppShellActionId, type AppShellRuns } from "./app-shell-runs";
|
||||
import { CORE_BINDINGS } from "./bindings";
|
||||
|
||||
/** The app shell's runs; empty until the shell mounts. */
|
||||
interface RunsSlot {
|
||||
current: Partial<AppShellRuns>;
|
||||
}
|
||||
|
||||
const APP_SHELL_ACTIONS: ReadonlySet<string> = new Set(APP_SHELL_ACTION_IDS);
|
||||
|
||||
function isAppShellAction(actionId: string): actionId is AppShellActionId {
|
||||
return APP_SHELL_ACTIONS.has(actionId);
|
||||
}
|
||||
|
||||
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, orderOwners?: OrderOwners): CoreRegistries {
|
||||
const scopes = createActionScopeStore();
|
||||
const actions = createActionRegistry({ scopes, ...(orderOwners ? { orderOwners } : {}) });
|
||||
const keybindings = createKeybindingRegistry({ actions, scopes });
|
||||
// Only the app shell's actions get a `run`. An action a mounted surface runs
|
||||
// must stay unavailable while no surface handles it, so its chords do not
|
||||
// reserve a prefix another shortcut uses.
|
||||
for (const definition of CORE_ACTIONS) {
|
||||
const actionId = definition.id;
|
||||
if (!isAppShellAction(actionId)) {
|
||||
actions.registerAction(definition);
|
||||
continue;
|
||||
}
|
||||
actions.registerAction({
|
||||
...definition,
|
||||
run: (invocation) => {
|
||||
const run = runs.current[actionId];
|
||||
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: Partial<AppShellRuns> = {}): 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. `orderOwners`
|
||||
* picks which owner's `run` an action with several owners tries first.
|
||||
*/
|
||||
export function CoreActionsProvider({
|
||||
orderOwners,
|
||||
children,
|
||||
}: {
|
||||
orderOwners?: OrderOwners;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [core] = useState(() => {
|
||||
const runs: RunsSlot = { current: {} };
|
||||
return { runs, ...registerCore(runs, orderOwners) };
|
||||
});
|
||||
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: AppShellRuns): void {
|
||||
const slot = useContext(RunsSlotContext);
|
||||
if (!slot) {
|
||||
throw new Error("useCoreActionRuns must be used within CoreActionsProvider");
|
||||
}
|
||||
useLayoutEffect(() => {
|
||||
slot.current = runs;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
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 for the action's first binding on this platform; the action
|
||||
* id and the binding id for any further one. `#` cannot appear in an action
|
||||
* id, so no row's id is another action's.
|
||||
*/
|
||||
id: string;
|
||||
label: string;
|
||||
note?: string;
|
||||
/** The binding a rebind edits. An action with several bindings here has a row for each. */
|
||||
binding: EffectiveKeybinding;
|
||||
/** The keys that fire it, or `null` when the user unassigned it. */
|
||||
chord: ShortcutKey[][] | null;
|
||||
}
|
||||
|
||||
export interface ShortcutSection {
|
||||
id: string;
|
||||
title: string;
|
||||
rows: ShortcutRow[];
|
||||
}
|
||||
|
||||
/** A section listed after core's, such as one per plugin, with its text resolved. */
|
||||
export interface ShortcutSectionInput {
|
||||
id: string;
|
||||
title: string;
|
||||
rows: readonly { actionId: string; label: string }[];
|
||||
}
|
||||
|
||||
function rowsFor(
|
||||
definition: { actionId: string; label: string; note?: string },
|
||||
bindings: readonly EffectiveKeybinding[],
|
||||
platform: DisplayPlatform,
|
||||
): ShortcutRow[] {
|
||||
const rows: ShortcutRow[] = [];
|
||||
for (const binding of bindings) {
|
||||
if (binding.actionId !== definition.actionId || !whenMatchesPlatform(binding.when, platform)) {
|
||||
continue;
|
||||
}
|
||||
const row: ShortcutRow = {
|
||||
id: rows.length === 0 ? definition.actionId : `${definition.actionId}#${binding.id}`,
|
||||
label: definition.label,
|
||||
binding,
|
||||
chord: binding.parsedChord.length === 0 ? null : chordStringToShortcutKeys(binding.combo),
|
||||
};
|
||||
if (definition.note) row.note = definition.note;
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shortcut sections for this platform: core's, then `sections` in order. A
|
||||
* row with no binding here is left out, and so is a section left empty.
|
||||
*/
|
||||
export function buildShortcutSections(input: {
|
||||
bindings: readonly EffectiveKeybinding[];
|
||||
platform: DisplayPlatform;
|
||||
translate: (key: string) => string;
|
||||
sections?: readonly ShortcutSectionInput[];
|
||||
}): ShortcutSection[] {
|
||||
const { bindings, platform, translate } = input;
|
||||
const core: ShortcutSectionInput[] = SHORTCUT_SECTIONS.map((section) => ({
|
||||
id: section.id,
|
||||
title: translate(section.titleKey),
|
||||
rows: section.rows.map((row) => ({
|
||||
actionId: row.actionId,
|
||||
label: translate(row.labelKey),
|
||||
...(row.noteKey ? { note: translate(row.noteKey) } : {}),
|
||||
})),
|
||||
}));
|
||||
return [...core, ...(input.sections ?? [])].flatMap((section) => {
|
||||
const rows = section.rows.flatMap((row) => rowsFor(row, bindings, platform));
|
||||
return rows.length > 0 ? [{ id: section.id, title: section.title, 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;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { ActionRegistryProvider } from "@/actions";
|
||||
import { KeybindingRegistryProvider } from "@/keyboard";
|
||||
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) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's registries for a component test, without the override storage
|
||||
* `CoreActionsProvider` reads. Every overlay that registers keys, such as a
|
||||
* menu, dialog or the Command Center, needs them to cover the app while open.
|
||||
*/
|
||||
export function CoreRegistriesProvider({
|
||||
registries,
|
||||
children,
|
||||
}: {
|
||||
registries?: CoreRegistries;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [core] = useState(() => registries ?? createCoreRegistries());
|
||||
return (
|
||||
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
|
||||
<KeybindingRegistryProvider keybindings={core.keybindings}>
|
||||
{children}
|
||||
</KeybindingRegistryProvider>
|
||||
</ActionRegistryProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/** A React root whose tree sits inside the app's registries, as every screen does in the app. */
|
||||
export function createRegistriesRoot(container: Element): Root {
|
||||
const root = createRoot(container);
|
||||
return {
|
||||
render: (node) => root.render(<CoreRegistriesProvider>{node}</CoreRegistriesProvider>),
|
||||
unmount: () => root.unmount(),
|
||||
};
|
||||
}
|
||||
@@ -13,7 +13,13 @@ import {
|
||||
} from "react-native-safe-area-context";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SheetBottomInset } from "@/components/adaptive-modal-sheet";
|
||||
import { PaneProvider, type PaneContextValue } from "@/panels/pane-context";
|
||||
import {
|
||||
createPaneFocusContextValue,
|
||||
PaneFocusProvider,
|
||||
PaneProvider,
|
||||
type PaneContextValue,
|
||||
} from "@/panels/pane-context";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import type { InstalledPlugin } from "@/plugins/types";
|
||||
import type { PluginFilePanel } from "./panels";
|
||||
import { PluginFilePanelHost } from "./plugin-host";
|
||||
@@ -114,6 +120,8 @@ function createPluginFilePanel(
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
actions: [],
|
||||
keybindings: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
@@ -157,18 +165,24 @@ function mountFilePanel(insets: EdgeInsets, options?: { insideSheet?: boolean })
|
||||
root = createRoot(container);
|
||||
|
||||
const hostNode = (
|
||||
<PaneProvider value={PANE_CONTEXT_VALUE}>
|
||||
<PluginFilePanelHost
|
||||
panel={panel}
|
||||
file={fakeFile}
|
||||
params={FILE_PARAMS}
|
||||
revision={1}
|
||||
workspaceId={WORKSPACE_ID}
|
||||
theme={FILE_THEME}
|
||||
host={FILE_HOST}
|
||||
layout={FILE_LAYOUT}
|
||||
/>
|
||||
</PaneProvider>
|
||||
<CoreRegistriesProvider>
|
||||
<PaneProvider value={PANE_CONTEXT_VALUE}>
|
||||
<PaneFocusProvider
|
||||
value={createPaneFocusContextValue({ isWorkspaceFocused: true, isPaneFocused: true })}
|
||||
>
|
||||
<PluginFilePanelHost
|
||||
panel={panel}
|
||||
file={fakeFile}
|
||||
params={FILE_PARAMS}
|
||||
revision={1}
|
||||
workspaceId={WORKSPACE_ID}
|
||||
theme={FILE_THEME}
|
||||
host={FILE_HOST}
|
||||
layout={FILE_LAYOUT}
|
||||
/>
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
</CoreRegistriesProvider>
|
||||
);
|
||||
const tree = options?.insideSheet ? (
|
||||
<SheetBottomInset style={FILL_STYLE} testID="sheet-body">
|
||||
|
||||
@@ -2,9 +2,11 @@ import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
|
||||
import { usePanelTab } from "@/panels/panel-instance-attributes";
|
||||
import { usePaneFocus } from "@/panels/pane-context";
|
||||
import { PluginInstallationProvider } from "@/plugins/installation-provider";
|
||||
import { usePluginOpenScreen } from "@/plugins/navigation";
|
||||
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
|
||||
import { PluginSurfaceScope } from "@/plugins/shortcuts";
|
||||
import type { BuiltinFilePanelProps, PluginFilePanel } from "./panels";
|
||||
|
||||
type PluginFilePanelHostProps = Omit<BuiltinFilePanelProps, "tab"> & {
|
||||
@@ -32,17 +34,20 @@ export function PluginFilePanelHost({
|
||||
}: PluginFilePanelHostProps) {
|
||||
const { plugin, contribution } = panel;
|
||||
const openScreen = usePluginOpenScreen(plugin);
|
||||
const { isInteractive } = usePaneFocus();
|
||||
const Component = contribution.Component;
|
||||
return (
|
||||
<BottomSafeAreaInset style={styles.container} testID="plugin-file-panel-safe-area">
|
||||
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<MountedPluginFilePanel
|
||||
{...props}
|
||||
openScreen={openScreen}
|
||||
panel={panel}
|
||||
suspendPendingSave={suspendPendingSave}
|
||||
/>
|
||||
<PluginSurfaceScope active={isInteractive}>
|
||||
<MountedPluginFilePanel
|
||||
{...props}
|
||||
openScreen={openScreen}
|
||||
panel={panel}
|
||||
suspendPendingSave={suspendPendingSave}
|
||||
/>
|
||||
</PluginSurfaceScope>
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
</BottomSafeAreaInset>
|
||||
|
||||
@@ -14,7 +14,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";
|
||||
@@ -85,7 +85,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,5 +1,6 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { createRegistriesRoot } from "@/core-actions/testing";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { DaemonClient, FileReadResult } from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -86,7 +87,7 @@ function mountPane(data: PrPaneData, insets = NO_INSETS) {
|
||||
container.style.display = "flex";
|
||||
container.style.flexDirection = "column";
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
root = createRegistriesRoot(container);
|
||||
renderPane(data, insets);
|
||||
const pane = container.querySelector<HTMLElement>('[data-testid="pr-pane"]');
|
||||
if (!pane) throw new Error("The pull request pane did not render");
|
||||
@@ -307,7 +308,7 @@ describe("pull request pane Markdown safety and forge shorthand", () => {
|
||||
container.style.display = "flex";
|
||||
container.style.flexDirection = "column";
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
root = createRegistriesRoot(container);
|
||||
act(() =>
|
||||
root?.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,25 @@ 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()))),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount inside an open popover or dialog: the keyboard action that opened it closes it. The open
|
||||
* overlay covers its trigger, so the trigger's `useKeyboardToggle` handler cannot.
|
||||
*/
|
||||
export function KeyboardToggleClose({
|
||||
actionId,
|
||||
onClose,
|
||||
}: {
|
||||
actionId: string | undefined;
|
||||
onClose: () => void;
|
||||
}): null {
|
||||
useActionHandler(actionId ?? [], onClose);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -240,7 +240,7 @@ export function HostChooserModal() {
|
||||
},
|
||||
[activeOptionIndex, chooseHost, close, options],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
const overlayHandle = useOverlayRegistration({
|
||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
||||
active: request != null,
|
||||
layer: modalLayer,
|
||||
@@ -254,7 +254,7 @@ export function HostChooserModal() {
|
||||
<OverlayLayerProvider layer={modalLayer}>
|
||||
<View style={styles.overlay}>
|
||||
<Pressable style={styles.backdrop} onPress={close} />
|
||||
<View ref={setOverlayScope} style={styles.panel}>
|
||||
<View ref={overlayHandle.ref} style={styles.panel}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.title}>{request.title}</Text>
|
||||
<View style={styles.searchRow}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { CoreRegistriesProvider } from "@/core-actions/testing";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { ALL_HOSTS_OPTION_ID } from "@/components/hosts/host-picker";
|
||||
import { HostFilter } from "@/components/hosts/host-filter";
|
||||
@@ -23,7 +24,13 @@ function mount(element: React.ReactElement): HTMLDivElement {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
act(() => root.render(<QueryClientProvider client={queryClient}>{element}</QueryClientProvider>));
|
||||
act(() =>
|
||||
root.render(
|
||||
<CoreRegistriesProvider>
|
||||
<QueryClientProvider client={queryClient}>{element}</QueryClientProvider>
|
||||
</CoreRegistriesProvider>,
|
||||
),
|
||||
);
|
||||
mountedRoots.push({ root, container });
|
||||
return container;
|
||||
}
|
||||
|
||||
@@ -3215,6 +3215,8 @@ export const ar: TranslationResources = {
|
||||
unavailableOnMobile: "اختصارات لوحة المفاتيح متاحة فقط على سطح المكتب",
|
||||
capturePrompt: "اضغط على الاختصار...",
|
||||
captureIndexPrompt: "اختم برقم من 1 إلى 9.",
|
||||
captureRefused: "يعمل هذا الاختصار أثناء الكتابة، لذا يتطلب Ctrl أو Cmd أو Alt.",
|
||||
collidesWith: "يُستخدم أيضًا في: {{actions}}",
|
||||
unassigned: "غير معين",
|
||||
actions: {
|
||||
menu: "إجراءات {{name}}",
|
||||
|
||||
@@ -3332,6 +3332,8 @@ export const en = {
|
||||
unavailableOnMobile: "Keyboard shortcuts are only available on desktop",
|
||||
capturePrompt: "Press shortcut...",
|
||||
captureIndexPrompt: "End with a number from 1 to 9.",
|
||||
captureRefused: "This shortcut works while typing, so it needs Ctrl, Cmd or Alt.",
|
||||
collidesWith: "Also used by {{actions}}",
|
||||
unassigned: "Not set",
|
||||
actions: {
|
||||
menu: "Actions for {{name}}",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user