Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 3572c40232 fix(app): reveal the active workspace tab when tabs overflow (#12203)
Tab selection updates the pane even when its chip is clipped by the strip. Scroll the strip when the rendered selection changes so the user can see which tab is active.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-06 06:43:25 +00:00
SunicemanandShane Su 8514a14d8f fix(usage): recognize rejected Z.ai logins in HTTP 200 responses (#11208)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-12-06 06:42:41 +00:00
paseo-bot[bot] 94164a28e2 test(server): restore the upstream clone in fork checkout tests (#12208)
The fork fixture reads a directory that the lazy clone helper no longer returns. Create the clone before advancing upstream so the tests reach their branch comparison assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-06 06:25:14 +00:00
Mohamed Boudra 7e93dde3af feat: run every shortcut through shared action and keybinding registries, and let plugins add shortcuts (#12122)
* feat(app): add Phase 0 action and keybinding registries

* fix(app): address Phase 0 registry review feedback

* fix(app): address bot review findings on Phase 0 registries

* fix(app): isolate iOS plain Enter chord claiming from Android

* fix(keyboard): pass holdRelease when building browser registry prefixes after rebase

* fix(keyboard): address global fallback, key/code conflict, and printable E2E reviews

* test(e2e): use shared command-center helpers in keyboard shortcut spec

* refactor(app): reshape Phase 0 action and keybinding registries

@/actions now owns only action definitions, mounted handlers, the scope
stack and opaque owners, and imports nothing from @/keyboard. `when`, the
printable guard, conflicts and the display lookup live in @/keyboard.

- Scopes are an ordered stack: the innermost active scope wins, ties go to
  the earliest registration. Specificity weights, overlay depth, surface
  ids and priorities are gone.
- Keyboard context reaches dispatch with the key event; no store keeps a
  copy and there is no setContext.
- A registration carries an opaque owner. Two owners of one id are one
  action or binding; removing either leaves the other; the same owner
  twice throws. Which owner's `run` fires is an injected rule, wired at
  app start in Phase 1A.
- Handlers decline with `{ handled: false }`; a promise counts as handled
  and its rejection goes to onError. Payloads pass through untouched; a
  Digit binding supplies `index`.
- Removed the legacy-table adapter, the unwired registry builders in the
  native and Electron browser key sources, and module-load singletons.

* fix(app): claim intermediate iOS chord steps for pass-through actions

The resolver suppresses every key that only advances a chord, but the
native claim builder skipped any binding whose action passes its key
through (`preventDefault: false`), at every step. With Interrupt agent
rebound to `Cmd+J Enter K`, the intermediate Return stayed with the iOS
composer and could send the draft. The pass-through policy now applies
only to the step that completes the chord.

* fix(app): bind action handlers to one scope activation, not a scope name

Two panes showing the same panel both activate `inbox/list`. With handlers
matched by name, the earliest pane's handler ran even while only the other
pane was active. `activate()` now returns a `ScopeActivation`, and a
handler binds to the activation of the surface it is mounted in, so it
runs only while that activation is active. Keybinding `when` still
matches scopes by name.

* refactor(app): run core shortcuts on the action and keybinding registries

Every core action and default binding is now registered as `paseo/*` at app
start by CoreActionsProvider. The key pipeline, Command Center, Settings ->
Shortcuts, the shortcuts dialog and every badge read the registries, and an
action id is the only key for dispatch, badges and rows. The legacy binding
table, the keyboard action dispatcher, route-shortcut, workspace-shortcuts and
useKeyboardActionHandler are deleted.

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

The legacy table suites are ported to the registries with the same cases.

* docs(app): record chord timing and Android dev-menu keys for device QA

* fix(app): keep literal digit overrides and free chord prefixes no surface can run

Settings saved a captured digit literally (Ctrl+3) before it captured number
groups as Digit. Dispatch took `index` from the effective combo, so those
overrides matched but jumped nowhere. The binding's declared combo now decides
whether it supplies the pressed digit.

Every core action got a declining `run`, so the registry counted actions only a
mounted surface implements as available, and their chords reserved a prefix
other shortcuts use (New terminal on Ctrl+K J blocked Command Center in
Settings). Only the app shell's actions get a `run` now.

* fix(app): send composer keys to the focused composer and Escape to desktop Settings

Scope order follows activation order, so it could not tell which surface the
user was in. With the main pane's composer focused and an Explorer dock agent
tab activated later, Escape and the other composer keys went to the dock. On
desktop Settings, a composer that activated after Settings took Escape and
interrupted the hidden agent instead of closing Settings.

Composer handlers now register through useComposerKeyboardActions, which
enables only the composer whose input has focus and falls back to the
innermost composer when no input has focus. Composers go inactive while
desktop Settings covers the workspace, so Settings' unscoped Escape handler
is the only one left. Compact Settings still lets Escape interrupt the agent.

@/keyboard no longer imports @/core-actions or @/workspace-switcher:
useKeyboardShortcuts takes the badge modifier and the key-down, key-up, blur
and handled hooks, and core-actions supplies them in useCoreKeyboardShortcuts.

* fix(app): keep composer keys with the last-focused composer after a blur

The focus record cleared on blur, so clicking the main agent's timeline
handed Escape, Ctrl/Cmd+L and the other composer keys to an Explorer dock
composer that had activated later. The record now holds the last-focused
active composer and clears only when that composer deactivates or unmounts.

Adds a Playwright spec for the live paths: Escape after the main composer
blurs interrupts only the main agent with a running dock agent beside it,
focusing the dock moves Escape there, and Escape on desktop Settings closes
Settings and leaves the agent running.

* test(app): read the composer Escape spec as user steps

* feat(app): tell the user in Settings when a captured shortcut cannot fire or collides

Capturing a printable key for a binding that only applies while typing
(mode cycle on Shift+M) used to save and never fire. Settings now asks the
keybinding registry (`checkCapture`) and refuses such a combo with a reason.

A combo that shares a key press with another binding is saved and shown on
both rows as "Also used by ...". A user-set binding now wins over a default
at the same rank instead of losing to whichever registered first; this is the
only change to dispatch order. Shipped defaults share no key press, which a
test pins so a fresh install shows no warning.

* fix(app): warn on both rows when a shortcut collides through an alternate binding, and keep user-set first in the switcher

Settings checked only the binding each row displays, so a row whose action
also answers to an alternate key (Explorer sidebar on Ctrl+`) showed no
warning when another action took that key. Notices now come from the
registry's conflict pairs, so both actions hear about the collision.

The chord matcher used by surfaces that read keys themselves picked the
earliest-registered binding and ignored the user-set-first order the
registry applies, so a rebind could resolve differently in the workspace
switcher than in the app.

* feat(plugins): let plugins add actions and keyboard shortcuts

Plugins register actions and keybindings on the app's action and keybinding
registries through addAction, addKeybinding, useActionScope, useActionHandler,
Shortcut, and `action` on Command Center items. Ids are namespaced per plugin,
so user overrides survive reloads and reinstalls.

A plugin installed on several hosts is one action with one owner per host.
The owner order runs a global action on the active host, else the plugin's
preferred host, else the first online host; workspace and agent actions run
on the active host only.

Dialogs, menus and the Command Center now cover the scopes beneath them, so a
screen's shortcut does not fire through an overlay and returns when it closes.

plugin-examples/shortcuts and its browser E2E drive every scenario.

* fix(app): cover the app from every focus-holding overlay and run Command Center rows for the screen beneath

Overlay registration now owns the action cover: an overlay that takes focus
covers the app and hands its content the cover as `actionScope`. Comboboxes,
the model pickers, the host chooser, the lightbox, the modal profile drawer
and the workspace switcher HUD had no cover, so the screen beneath kept its
keys. A cover also hides handlers mounted in no scope; before, workspace
shortcuts such as Ctrl+Shift+T ran behind dialogs, and select mode's archive
under a menu fell through to the global archive of the open workspace.

Command Center rows asked the registry while their own cover was still up, so
a row backed only by a mounted handler (a plugin screen's action, New
workspace, New tab) did nothing. Rows now ask with `beneath` the Command
Center cover. Scopes and handlers register in layout effects so a scope shown
as active takes keys before paint.

A chord now reserves its first key only when it ranks ahead of every runnable
binding the same key completes, so a plugin's default `Mod+K J` no longer
takes Ctrl+K from the Command Center. A chord the user sets still does.

* fix(app): let a saved chord continue past a shorter default chord on the same keys

The precedence check ran only on a chord's first key. On a later key, a default chord that the key completed ran before a higher-ranked chord that the key continued, so a saved Ctrl+G J K never got past a plugin's Ctrl+G J. Every press now walks completing and advancing bindings in one precedence order.

* fix(app): order the workspace switcher's own key matches as the registry does

createChordMatcher still let a chord start beat a single key on the same press, while the registry now orders both by precedence. With Next saved as Ctrl+J and Previous as Ctrl+J K, Ctrl+J opened the switcher as Next but started Previous's chord inside it. The matcher now sorts its matches with the registry's byPrecedence.

* fix(app): close the compact model selector sheet with the shortcut that opened it

The sheet covers the app while open, which hides the trigger's toggle handler, so its shortcut needs a handler inside the cover, as the desktop picker and composer sheets have.

* fix(app): claim the next key of a scoped chord on iPad

The native source checked each pending chord candidate's `when` again
with an empty scope stack, so a chord that needs a named scope never
claimed its next key, and a focused text field typed it. The registry
already checked `when` with the scope stack when it accepted the first
key, so continuations now claim from the candidate list.

* fix(app): claim native shortcut keys only while their scope is visible

The previous fix claimed a pending chord's next key without checking
`when` again, so opening Command Center mid-chord kept the claim and
UIKit swallowed the first letter typed into its search field. Key sources
now read the visible action scopes and recompute claims when they change,
the same way they follow focus and Command Center. A scoped binding
claims its key only while no overlay hides its scope.

* fix(app): keep a scoped binding's first key with the iPad text field

Reading the scope stack for every claim made a scoped Shift or Option
binding claim its first key, even when its handler was disabled, so a
focused text field lost the key and nothing ran. First keys are checked
without the scope stack again, as before this branch. Only a pending
chord's next key follows the visible scopes.

* fix(app): show every shortcut and real names in Settings, Command Center and badges

- Settings → Shortcuts lists a row per binding an action has on this
  platform. It showed only the first, so a collision notice could name a key
  the user could not see or rebind (Explorer sidebar's second key, a plugin
  action bound to two keys). Notices are keyed by binding.
- A collision names the other action by its Settings label, else its
  registered title. It used to fall back to the raw action id for any
  action without a Settings row, such as dictation confirm.
- A plugin's Command Center group is titled with its display name, as
  Settings does, instead of its install id.
- A shortcut badge inside a filled (accent or destructive) button reads in
  the button's foreground color. Button tells its badges; no new props.

* fix(app): keep shortcut rows unique and tell an action's rows apart for screen readers

A further row of an action is identified by the action id and its binding
id, so a plugin that names a binding after another action cannot produce
two rows with the same React key or test id. The menu button of an action
with several rows is named by that row's keys.

* fix(app): number an action's shortcut rows so their menu names never coincide

A row's menu name used its current keys, or its default keys while unassigned,
so moving a key between an action's rows (or clearing both) gave two buttons
the same name. Rows are now numbered (1/2, 2/2) next to their current keys.

* fix(app): keep pending chord policy when bindings change mid-chord
2026-12-06 12:24:12 +07:00
Matchy 0cc69e9e55 fix(app): keep the selection toast's exit button in its trailing corner (#11274)
The sidebar selection toast let its row wrap. When the sidebar is
narrower than the toast's natural width (it can go down to 200px),
Archive and the exit X wrapped onto a second line under the count, so
the X sat next to Archive instead of in the toast's trailing corner.

Drop the wrap. The count is already limited to one line and can shrink,
so on a narrow sidebar it truncates and Archive and X stay on its line.
The count keeps flexShrink rather than flex: 1, because a zero flex
basis inside the content-sized toast can collapse the text on native.

The browser test mounts the sidebar at its minimum and default widths
and checks that the count, Archive and X share a line with X on the
toast's inner right edge. It fails on the old layout at 200px.
2026-12-06 05:12:38 +00:00
Mohamed BoudraandOrcun Simsek 459b1123f4 Start and compare new worktrees against the repository default branch (#12128)
* fix(server): create worktrees from fresh default bases

Resolve base inputs consistently before creation and persist the selected ref so comparisons follow the same branch. This is the server phase of the workspace base selection change.

Co-authored-by: Orcun Simsek <orcun@joyolabs.com>

* fix(server): preserve worktree base tracking mappings

Use tracked custom defaults and remote fetch mappings, and fetch change request bases before recording them.

* fix(server): keep tag bases and mapped pull request bases working

Branch-only base resolution dropped the existing `--base <tag|sha>`
support. Tags and commits now resolve after every branch candidate
misses; they skip the remote refresh, compare by commit, and merge into
base refuses them.

Pull request checkout built `refs/remotes/<remote>/<base>` and refreshed
it as a tracking destination, so a custom fetch mapping such as
`release -> origin/main` force-fetched the wrong branch into the
comparison ref. Checkout now resolves the base from the serving remote's
fetch mapping. When the candidate tracking ref belongs to another remote
branch, checkout keeps only the base name and leaves that ref untouched.

* fix(server): resolve pull request branch-off bases like checkout

Branch off from a pull request built `refs/remotes/<remote>/<base>` and
force-fetched the target into it. With a renamed fetch mapping, that
pinned a ref Git never updates, or overwrote a tracking ref that the
fetch config assigns to another branch. Branch-off now uses the same
serving-remote resolution as checkout, so both pull request paths agree
on which ref tracks the base.

* fix(server): merge into the branch a tracking base actually fetches

Merge into base took the local target from the tracking ref's suffix.
Now that worktrees pin the tracking ref named by the fetch mapping, a
base such as `refs/remotes/origin/mirror/main` that fetches `main` merged
into a local `mirror/main` instead. The target now comes from the same
fetch-mapping lookup that refreshes the base, and merges still refuse
refs outside origin or refs several branches map to.

Test fixtures that wrote origin tracking refs without an origin remote
now configure one, since Git removes a remote's tracking refs with it.

* fix(server): keep a local base whose upstream has another name

A bare base name resolved to its local branch's upstream whatever that
upstream was called. Git sets the upstream from the start point
(`git switch -c feature origin/main`), so `--base feature` started the
workspace at `origin/main` without the branch's commits, and merge into
base then targeted `main`. The upstream now stands in only when the
remote branch has the same name, which still covers fork clones whose
`main` tracks `upstream/main` and custom defaults like `dev` tracking
`origin/dev`.

* fix(server): find bare base branches through the fetch mapping

A bare base name found its remote copy by spelling the tracking ref
`refs/remotes/<remote>/<name>`, while refresh and merge read the fetch
mapping. With `release` fetched into `origin/integration`, creating from
bare `integration` started at `release` and merged into local `release`.
Lookup now asks the same fetch-mapping rule that pull request bases and
refresh use, so a tracking ref that holds another branch never stands in
for the branch the caller named.

* fix(server): target the fetched branch when creating a pull request

Create PR sent the tracking ref's own suffix as the forge target, so a base
stored as refs/remotes/origin/mirror/main (fetched from main) asked the forge
for mirror/main. Merge and Create PR now share one lookup of the branch a base
ref stands for, through the remote's fetch mapping; tag and commit bases are
refused before pushing.

* test(server): retry temp dir cleanup after killing hung ACP children

On Windows a killed process can keep its working directory open for a moment
after it exits, so deleting the test directory right after the hung child is
killed failed with EBUSY. Cleanup now retries like the other process-owning
test suites.

* refactor(server): resolve worktree bases through one conventional owner

Drop the custom fetch-refspec mapping. A base resolves through the
conventional refs/remotes/<remote>/<branch> layout, split on the longest
configured remote name, for creation, merge, and Create PR alike.

The read side now asks the same owner for the repository default branch,
by name, so a local checkout on that branch still reads as on base.

Base input is validated once at the edge:
- An empty base is rejected; callers that name none ask for the
  repository default and fail with "Unable to resolve repository default
  branch" when there is none.
- Ref expressions (@, a bare remote name, heads/..., remotes/...,
  revision suffixes) are rejected instead of freezing to a commit.
- The baseBranch alias applies only to a branch-off without a change
  request, so it can no longer replace a checkout target.

The MCP and CLI help now say a bare branch resolves remote-first and
that refs/heads/<name> branches from local commits.

* fix(server): compare against the only remote's default branch

A checkout whose only remote is not origin, on a feature branch with no
local default branch, reported its base as "main" but had no ahead or
behind count, and a base diff failed. The read side now names the
default from the same owner as creation, and a bare name that matches no
local or origin branch fell through to `git rev-parse main`, which Git
cannot resolve. Such a name now resolves the way a new worktree base
does, through the remote that has the branch.

* fix(server): keep default base reads in the caller's Git lane

The read side resolves the repository default through the shared base
owner, which ran its Git reads with the global runner. An
observation-driven status refresh therefore submitted normal-priority
commands from the background lane. The owner now takes the caller's
runner, and checkout reads pass the one from their context.

* fix(server): reject a blank base instead of branching from the default

A whitespace-only base was trimmed to empty and replaced with the
repository default before validation, so the request created a worktree
from a branch the caller did not choose. Only an omitted base defaults
now; a supplied one goes through the base validator, which rejects it
with "Base branch is required".

* fix(app): read the default base and base branch from the daemon

New Workspace guessed its starting ref from the checkout's upstream, so a
checkout on a feature branch preselected that feature branch, and the Git
actions regex-parsed the base ref, so a worktree checked out on main with
base refs/remotes/origin/main was treated as off its base and offered merge
and PR actions.

checkout_status now carries two optional fields from the base-ref owner:
defaultBaseRef (the ref a fresh worktree starts from) and baseRefBranch
(the branch the base stands for, its remote, and whether the checkout is
on it). A fork whose main tracks upstream/main resolves the same base for
status, diff and creation. Older apps ignore the fields; older daemons
leave them undefined and the app keeps its previous logic behind
COMPAT(checkoutDefaultBaseRef) and COMPAT(checkoutBaseRefBranch).

An agent fork still starts from the source agent's local branch. The
Changes base picker shows "main (local)" when the base is pinned to the
local branch of a checkout that has origin, since the label otherwise
drops "origin/" and both would read "main".

* test(app): give the no-comparison-base journey a checkout with no default

A sole local branch such as dev is now the repository default, so a
checkout on it compares against itself instead of reporting no base. Only
a detached HEAD among several custom branches with no remote leaves the
base unresolved.

* fix(server): update a fork from the base it compares against

A fork's feature checkout compared against upstream/main, which its local
main tracks, but Update from base still chose between local main and
origin/main, so it reported success without the upstream commits Changes
showed as missing. And a diff that named origin/main explicitly was
rerouted to upstream/main because the short ref was stripped to a bare
name before the tracking lookup.

Only a bare branch name now follows the remote branch its local branch
tracks, and both the comparison and Update from base use that rule.

* fix(server): compare an implicit base against the ref it selected

A checkout with no stored base reported its default as a ref, for
example refs/remotes/upstream/main, but turned it into the name "main"
and resolved that name again for the comparison and for Update from
base. When local main tracked a different remote than the one that
advertises the default, Changes compared against origin/main, counted
nothing behind, and Update from base left the upstream commits out.

With no stored base, the comparison and the base diff use the selected
ref. Update from base merges it when it is on a remote other than
origin, and keeps choosing the further-ahead of local and origin main
otherwise. Merging into the base and opening a PR still target the
branch name.

* fix(server): compare the base branch and detached HEAD against the selected default

The checkout snapshot skipped comparison resolution when the checkout sat on
its base branch or had no current branch. Status then re-resolved the display
name, so a fork whose default is upstream/main compared against origin/main
while reporting upstream/main as its default. Resolve the comparison ref once
whenever a base exists; ahead/behind and shortstat keep their own rule for
skipping counts on the base branch.

* fix(server): keep upstream counts when the checked-out default branch moves

Since the snapshot resolves a comparison ref on the base branch, a checkout on
main has a comparison ref equal to its upstream. The ref refresh took that match
as license to reuse the base counts, but ahead/behind is deliberately null on
the base branch, so a fetch turned the upstream state into unknown and Changes
disabled Pull. Reuse the base counts only when the refresh produced them.

* fix(server): count a default-branch checkout against the ref Changes compares with

On the base branch the composer count always compared against origin/<branch>,
while the Changes diff now compares against the selected default. On a fork
whose default is upstream/main, the count included upstream commits the panel
excluded. Use the snapshot's remote comparison ref for the count, falling back
to origin/<branch> when there is none.

---------

Co-authored-by: Orcun Simsek <orcun@joyolabs.com>
2026-12-06 11:54:19 +07:00
Mohamed Boudra 4b40bb0667 fix(nix): apply patches/ before the Nix build (#12199)
The Nix build installs with --ignore-scripts, so the root postinstall that
applies patches/ never ran. The web bundle imports lucide-react-native/context,
which only exists after patches/lucide-react-native+1.50.0.patch, so Web
Bundling failed with "Unable to resolve module lucide-react-native/context".

Run scripts/postinstall-patches.mjs at the start of both buildPhases. It spawns
patch-package by name, so node_modules/.bin goes on PATH (npm run does that
for postinstall, a bare node call does not).

Also run the Nix workflow when patches/ or the patch script change.
2026-12-06 11:46:26 +07:00
889f8b796a fix(app): only show grab cursor when image preview can pan (#11778)
* fix(app): only show grab cursor when image preview can pan

The web zoomable viewport showed grab/grabbing whenever scale > 1, even
when the scaled image still fit inside the viewport and could not move.
Derive the cursor from the same pan bounds clampTransform uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): track drag state with the same pan predicate as the cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(app): cover image preview cursor in a real browser

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep fitted image dimensions within the viewport

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-06 04:42:59 +00:00
Ryan大然 18897a99fa Keep a tilde with whitespace on both sides out of strikethrough (#11824)
md4c let a tilde open strikethrough when whitespace followed it and close
it when whitespace preceded it, so ranges such as `10:00` ~ `12:00` paired
up and struck out everything between them, inline code included. A
strikethrough opener now needs text after it and a closer text before it,
as GFM's flanking rules require. `~~text~~` and `~text~` still strike
through.

Web runs the parser as WASM, so src/web/wasm/md4c.js is rebuilt with
emsdk 4.0.10 per docs/markdown-renderer.md and lib/module is its Babel
output. A rebuild of the unchanged sources parses every Markdown file in
the repository the same as the previous artifact, and so does the fixed
build.

Fixes #11629
2026-12-06 03:43:08 +00:00
311 changed files with 15094 additions and 6772 deletions
+2
View File
@@ -22,6 +22,8 @@ on:
- "packages/desktop/**"
- "plugins/**"
- "skills/**"
- "patches/**"
- "scripts/postinstall-patches.mjs"
- "scripts/trace-daemon.mjs"
- "scripts/is-main-module.mjs"
- "scripts/build-daemon-web-ui.mjs"
+54 -54
View File
@@ -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
+77 -5
View File
@@ -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
View File
@@ -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"
+6
View File
@@ -99,6 +99,12 @@ buildNpmPackage {
buildPhase = ''
runHook preBuild
# npm ci runs with --ignore-scripts, so the root postinstall that applies
# patches/ never runs. The web bundle imports modules those patches add
# (lucide-react-native/context). The script spawns patch-package by name,
# which only resolves with node_modules/.bin on PATH (npm run sets it).
PATH="$PWD/node_modules/.bin:$PATH" node scripts/postinstall-patches.mjs
# Native deps (terminal emulation; libuv-linked on Linux)
npm rebuild node-pty
+6
View File
@@ -90,6 +90,12 @@ buildNpmPackage rec {
buildPhase = ''
runHook preBuild
# npm ci runs with --ignore-scripts, so the root postinstall that applies
# patches/ never runs. The web bundle imports modules those patches add
# (lucide-react-native/context). The script spawns patch-package by name,
# which only resolves with node_modules/.bin on PATH (npm run sets it).
PATH="$PWD/node_modules/.bin:$PATH" node scripts/postinstall-patches.mjs
# Rebuild only node-pty (native addon for terminal emulation). The sherpa
# speech runtime ships prebuilt platform packages and is copied into the
# daemon closure by scripts/trace-daemon.mjs.
@@ -19,7 +19,12 @@ import {
} from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
import { seedSavedSettingsHosts } from "../support/helpers/settings";
import { submitNewWorkspaceEmpty } from "../support/helpers/new-workspace";
import {
expectPickerSelected,
selectWorkspaceIsolation,
submitNewWorkspaceEmpty,
} from "../support/helpers/new-workspace";
import { checkoutBranch } from "../support/helpers/workspace";
const test = base.extend<{
seedForkWorkspace: (options: MockAgentOptions) => Promise<MockAgentWorkspace>;
@@ -176,7 +181,9 @@ test.describe("Assistant fork menu", () => {
title: "Assistant fork workspace",
initialPrompt: "emit 1 coalesced agent stream updates for assistant fork new workspace.",
model: "ten-second-stream",
repo: { withRemote: true, branches: ["main", "feature/fork-source"] },
});
checkoutBranch(session.cwd, "feature/fork-source");
await openAgentRoute(page, session);
await expectComposerVisible(page);
@@ -188,6 +195,11 @@ test.describe("Assistant fork menu", () => {
await expect(page).toHaveURL(/\/new\?.*draftId=/, { timeout: 30_000 });
await expectChatHistoryAttachment(page);
// A fork continues the source agent's work, so it starts from the branch that agent is
// on rather than the repository default a fresh workspace starts from.
await selectWorkspaceIsolation(page, "worktree");
await expectPickerSelected(page, "feature/fork-source");
await page.getByTestId("host-picker-trigger").click();
await page
.getByTestId("new-workspace-host-picker-option-secondary-assistant-fork-host")
@@ -272,6 +272,10 @@ test.afterEach(async () => {
test("Changes without a comparison base explains how to view pending changes", async ({ page }) => {
const workspace = await createWorkspaceWithManyTinyDiffs(2, "dev");
// A sole branch such as dev is the repository default. With several custom branches, no
// remote and a detached HEAD, nothing says which branch to compare against.
execFileSync("git", ["branch", "release"], { cwd: workspace.repoPath });
execFileSync("git", ["checkout", "--detach"], { cwd: workspace.repoPath, stdio: "ignore" });
await openWorkspaceChangesTree(page, workspace);
await expect(
page.getByText("Comparison base is unavailable. Select Uncommitted to view pending changes."),
@@ -584,6 +588,33 @@ test("Changes selects exact local and remote bases and retains the selection aft
);
});
test("Changes treats a worktree on the default branch as on its base and labels a local pin", async ({
page,
}, testInfo) => {
const workspace = await createWorktreeCheckedOutOnMain();
await openWorkspaceChangesTree(page, workspace);
const tree = page.getByTestId("changes-tree-panel").filter({ visible: true });
const picker = tree.getByTestId("workspace-base-branch-trigger");
await test.step("a worktree on main compares against origin and offers no feature actions", async () => {
await expect(picker).toHaveText("main");
await expectNoFeatureActions(page);
await page.screenshot({ path: testInfo.outputPath("on-base-worktree.png") });
});
await test.step("pinning local main reads as local next to origin", async () => {
await chooseBase(page, picker, "main");
await expect(picker).toHaveText("main (local)");
await expectNoFeatureActions(page);
await page.screenshot({ path: testInfo.outputPath("local-base-pinned.png") });
});
await test.step("pinning origin main drops the qualifier again", async () => {
await chooseBase(page, picker, "origin/main");
await expect(picker).toHaveText("main");
});
});
test("Changes lets a compact workspace change its base in a sheet", async ({ page }, testInfo) => {
const workspace = await createWorktreeWithCommittedDiff();
execFileSync("git", ["branch", "release"], { cwd: workspace.repoPath });
@@ -2272,6 +2303,27 @@ async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void>
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function chooseBase(page: Page, picker: Locator, label: string): Promise<void> {
await picker.click();
await page
.getByTestId("combobox-desktop-container")
.getByRole("button", { name: label, exact: true })
.click();
}
// Merging, merging the base in and opening a PR only make sense on a branch off the base.
async function expectNoFeatureActions(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toHaveAccessibleName("Archive workspace", {
timeout: 30_000,
});
await page.getByTestId("changes-primary-cta-caret").click();
await expect(page.getByTestId("changes-primary-cta-menu")).toBeVisible();
for (const action of ["merge-branch", "merge-from-base", "pr"]) {
await expect(page.getByTestId(`changes-menu-${action}`)).toHaveCount(0);
}
await page.keyboard.press("Escape");
}
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
@@ -2417,6 +2469,34 @@ async function createWorktreeWithCommittedDiff(): Promise<DirtyWorkspace> {
return { id: created.workspace.id, repoPath: cwd };
}
// The user checks out the default branch itself in a worktree while the main checkout sits on
// other work, so the worktree is on its own base.
async function createWorktreeCheckedOutOnMain(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-on-base-", {
withRemote: true,
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
});
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close();
await repo.cleanup();
},
});
execFileSync("git", ["checkout", "-b", "unrelated"], { cwd: repo.path });
const created = await client.createWorkspace({
source: {
kind: "worktree",
cwd: repo.path,
action: "checkout",
refName: "main",
worktreeSlug: "on-main",
},
});
if (!created.workspace) throw new Error(created.error ?? "Failed to create worktree");
return { id: created.workspace.id, repoPath: created.workspace.workspaceDirectory };
}
async function createWorkspaceWithCommittedDiff(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-committed-", {
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
@@ -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);
+30 -1
View File
@@ -38,6 +38,7 @@ import {
submitNewWorkspacePrompt,
} from "../support/helpers/new-workspace";
import {
checkoutBranch,
commitLocalOnly,
createTempGitRepo,
readRepoRef,
@@ -816,6 +817,34 @@ test.describe("New workspace flow", () => {
}
});
test("branches off the repository default when the checkout is on a feature branch", async ({
page,
}) => {
const tempRepo = await createTempGitRepo("ref-default-feature-", {
withRemote: true,
branches: ["main", "feature/unrelated"],
});
try {
const originHead = readRepoRef(tempRepo.path, "refs/remotes/origin/main");
checkoutBranch(tempRepo.path, "feature/unrelated");
const featureHead = commitLocalOnly(tempRepo.path, "feature work");
const openedProject = await openWorktreeComposerForRepo(page, tempRepo.path);
await expectPickerSelected(page, "main");
const created = await createWorktreeAndRead(page, openedProject);
expect(created.branchInfo.hasAncestor(originHead)).toBe(true);
expect(created.branchInfo.hasAncestor(featureHead)).toBe(false);
expect(await readWorktreeBaseMetadata(created.workspaceDirectory)).toEqual({
baseRefName: "main",
baseRef: "refs/remotes/origin/main",
});
} finally {
await tempRepo.cleanup();
}
});
test("branches off the local ref when the local row is chosen explicitly", async ({
page,
}, testInfo) => {
@@ -864,7 +893,7 @@ test.describe("New workspace flow", () => {
// tracks gets its own row rather than silently sharing origin's. Two rows reading
// "main" is the ambiguity this whole change exists to remove.
await expectStartingRefRows(page, [
"main (upstream), upstream branch",
"main (upstream), default branch",
"main, origin branch",
]);
await expectPickerSelected(page, "main (upstream)");
@@ -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);
@@ -204,6 +204,11 @@ export async function trackForkUpstream(repoPath: string): Promise<string> {
.trim();
}
/** Leaves the checkout on `branch`, the way a user working on a feature has it. */
export function checkoutBranch(repoPath: string, branch: string): void {
execSync(`git checkout ${JSON.stringify(branch)}`, { cwd: repoPath, stdio: "ignore" });
}
export function readRepoRef(repoPath: string, ref: string): string {
return execSync(`git rev-parse ${JSON.stringify(ref)}`, { cwd: repoPath, stdio: "pipe" })
.toString()
@@ -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 },
]);
});
});
+37
View File
@@ -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);
};
},
};
}
+164
View File
@@ -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 () => {
+8 -26
View File
@@ -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],
+3 -3
View File
@@ -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) => {
@@ -1536,3 +1536,31 @@ describe("web KaTeX .woff2-only stylesheet sync", () => {
expect(katexStylesSource).toContain(".enrm-text .katex-display{margin:0}");
});
});
describe("strikethrough tildes", () => {
function struckText(node: ASTNode): string[] {
const text = (child: ASTNode): string =>
child.content ?? (child.children ?? []).map(text).join("");
if (node.type === "Strikethrough") return [text(node)];
return (node.children ?? []).flatMap(struckText);
}
it.each([
"Time window: `10:00` ~ `12:00` (UTC+8 `18:00` ~ `20:00`)",
"Versions 1.2 ~ 1.4 and 2.0 ~ 2.1",
"A ~ B ~~ C",
])("keeps tildes with whitespace on both sides literal: %s", async (source) => {
const tree = await parseMarkdown(source, { latexMath: false });
expect(struckText(tree)).toEqual([]);
});
it.each([
["~~gone~~ stays", ["gone"]],
["~gone~ stays", ["gone"]],
["Keep `10:00` ~ `12:00` but ~~drop this~~.", ["drop this"]],
["(~~a~~) and ~b~.", ["a", "b"]],
])("strikes through tilde pairs that flank text: %s", async (source, expected) => {
const tree = await parseMarkdown(source, { latexMath: false });
expect(struckText(tree)).toEqual(expected);
});
});
@@ -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(
+23 -12
View File
@@ -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>
);
}
+8 -4
View File
@@ -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"));
});
});
+59 -4
View File
@@ -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(
@@ -0,0 +1,100 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ZoomableViewport } from "./index.web";
function nextFrame(): Promise<number> {
return new Promise((resolve) => requestAnimationFrame(resolve));
}
async function settle() {
await act(async () => {
await nextFrame();
await nextFrame();
});
}
function canvas(): HTMLElement {
const element = document.querySelector<HTMLElement>('[data-testid="viewport-canvas"]');
if (!element) throw new Error("canvas not rendered");
return element;
}
function cursor(): string {
return getComputedStyle(canvas()).cursor;
}
async function wheelZoomIn() {
const bounds = canvas().getBoundingClientRect();
await act(async () => {
canvas().dispatchEvent(
new WheelEvent("wheel", {
bubbles: true,
cancelable: true,
deltaY: -100,
clientX: bounds.left + bounds.width / 2,
clientY: bounds.top + bounds.height / 2,
}),
);
});
await settle();
}
const CONTENT_SIZE = { width: 1600, height: 1000 };
const VIEWPORT_STYLE = { flex: 1 };
const FILL_STYLE = { width: "100%", height: "100%", background: "#3a7" };
describe("ZoomableViewport cursor", () => {
let host: HTMLDivElement;
let root: Root;
beforeEach(() => {
host = document.createElement("div");
host.style.cssText = "position:fixed;left:0;top:0;width:800px;height:600px;display:flex;";
document.body.appendChild(host);
root = createRoot(host);
});
async function renderViewport(contentSize = CONTENT_SIZE, fit?: { padding: number }) {
await act(async () => {
root.render(
<ZoomableViewport
contentSize={contentSize}
fit={fit}
style={VIEWPORT_STYLE}
testID="viewport"
wheelActivation="always"
>
<div style={FILL_STYLE} />
</ZoomableViewport>,
);
});
await settle();
}
afterEach(() => {
act(() => root.unmount());
host.remove();
});
it("shows grab only once the zoomed image overflows the viewport", async () => {
await renderViewport(CONTENT_SIZE, { padding: 100 });
// Fitted to 600x375 inside 800x600.
expect(cursor()).toBe("default");
await wheelZoomIn(); // 125%: 750x469, still fits.
expect(cursor()).toBe("default");
await wheelZoomIn(); // ~156%: 938x586, overflows width.
expect(cursor()).toBe("grab");
});
it("keeps the cursor at default when an unpadded image fits at 100%", async () => {
await renderViewport({ width: 1060, height: 600 });
expect(cursor()).toBe("default");
await wheelZoomIn();
expect(cursor()).toBe("grab");
});
});
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
FIT_TRANSFORM,
canPanContent,
clampTransform,
fitContentSize,
isActivePinchUpdate,
@@ -105,4 +106,16 @@ describe("zoomable viewport geometry", () => {
}),
).toEqual({ scale: 0.25, x: 0, y: 0 });
});
it("can pan only when the scaled content overflows the viewport on some axis", () => {
expect(canPanContent(1, fittedContent, viewport)).toBe(false);
// Zoomed above 100% but still fits on both axes.
expect(canPanContent(1, { width: 400, height: 300 }, viewport)).toBe(false);
expect(canPanContent(1.25, { width: 600, height: 400 }, viewport)).toBe(false);
// Overflows width only.
expect(canPanContent(1.25, fittedContent, viewport)).toBe(true);
// Overflows height only.
expect(canPanContent(1.25, { width: 400, height: 500 }, viewport)).toBe(true);
expect(canPanContent(0.5, fittedContent, viewport)).toBe(false);
});
});
@@ -67,8 +67,9 @@ export function fitContentSize(
);
const fitScale = Math.min(availableWidth / content.width, availableHeight / content.height);
return {
width: content.width * fitScale,
height: content.height * fitScale,
// A fitted edge can round past the available size after scaling.
width: Math.min(availableWidth, content.width * fitScale),
height: Math.min(availableHeight, content.height * fitScale),
};
}
@@ -83,6 +84,26 @@ function clampOffset(offset: number, maximum: number): number {
return Math.min(maximum, Math.max(-maximum, offset));
}
function panBounds(
fittedContent: ViewportSize,
viewport: ViewportSize,
scale: number,
): ViewportPoint {
return {
x: Math.max(0, (fittedContent.width * scale - viewport.width) / 2),
y: Math.max(0, (fittedContent.height * scale - viewport.height) / 2),
};
}
export function canPanContent(
scale: number,
fittedContent: ViewportSize,
viewport: ViewportSize,
): boolean {
const bounds = panBounds(fittedContent, viewport, scale);
return bounds.x > 0 || bounds.y > 0;
}
export function clampTransform(
transform: ViewportTransform,
fittedContent: ViewportSize,
@@ -90,12 +111,11 @@ export function clampTransform(
limits: ViewportScaleLimits,
): ViewportTransform {
const scale = clampScale(transform.scale, limits);
const maxX = Math.max(0, (fittedContent.width * scale - viewport.width) / 2);
const maxY = Math.max(0, (fittedContent.height * scale - viewport.height) / 2);
const bounds = panBounds(fittedContent, viewport, scale);
return {
scale,
x: clampOffset(transform.x, maxX),
y: clampOffset(transform.y, maxY),
x: clampOffset(transform.x, bounds.x),
y: clampOffset(transform.y, bounds.y),
};
}
@@ -3,6 +3,7 @@ import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import {
FIT_TRANSFORM,
canPanContent,
fitContentSize,
isPointInsideTransformedContent,
panContent,
@@ -140,30 +141,41 @@ export function ZoomableViewport({
return () => activeCanvas.removeEventListener("wheel", zoomWithWheel);
}, [wheelActivation, zoomAt]);
const beginPointer = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
if (event.pointerType !== "mouse") setHasTouchInput(true);
if (pointersRef.current.size === 0) suppressClickRef.current = false;
event.currentTarget.setPointerCapture(event.pointerId);
pointersRef.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
const points = Array.from(pointersRef.current.values());
if (points.length >= 2) {
const canPanAtCurrentTransform = useCallback(
() =>
fittedContent !== null &&
viewport !== null &&
canPanContent(transformRef.current.scale, fittedContent, viewport),
[fittedContent, viewport],
);
const beginPointer = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
if (event.pointerType !== "mouse") setHasTouchInput(true);
if (pointersRef.current.size === 0) suppressClickRef.current = false;
event.currentTarget.setPointerCapture(event.pointerId);
pointersRef.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
const points = Array.from(pointersRef.current.values());
if (points.length >= 2) {
gestureRef.current = {
type: "pinch",
distance: distance(points),
midpoint: midpoint(points),
};
setIsDragging(true);
return;
}
gestureRef.current = {
type: "pinch",
distance: distance(points),
midpoint: midpoint(points),
type: "drag",
pointerId: event.pointerId,
startPoint: points[0],
startTransform: transformRef.current,
};
setIsDragging(true);
return;
}
gestureRef.current = {
type: "drag",
pointerId: event.pointerId,
startPoint: points[0],
startTransform: transformRef.current,
};
setIsDragging(transformRef.current.scale > 1);
}, []);
setIsDragging(canPanAtCurrentTransform());
},
[canPanAtCurrentTransform],
);
const movePointer = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
@@ -219,26 +231,29 @@ export function ZoomableViewport({
[commitTransform, fittedContent, limits, viewport],
);
const endPointer = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
pointersRef.current.delete(event.pointerId);
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
const remaining = Array.from(pointersRef.current.entries());
if (remaining.length === 1) {
const [pointerId, point] = remaining[0];
gestureRef.current = {
type: "drag",
pointerId,
startPoint: point,
startTransform: transformRef.current,
};
setIsDragging(transformRef.current.scale > 1);
return;
}
gestureRef.current = null;
setIsDragging(false);
}, []);
const endPointer = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
pointersRef.current.delete(event.pointerId);
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
const remaining = Array.from(pointersRef.current.entries());
if (remaining.length === 1) {
const [pointerId, point] = remaining[0];
gestureRef.current = {
type: "drag",
pointerId,
startPoint: point,
startTransform: transformRef.current,
};
setIsDragging(canPanAtCurrentTransform());
return;
}
gestureRef.current = null;
setIsDragging(false);
},
[canPanAtCurrentTransform],
);
const handleCanvasClick = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
@@ -261,9 +276,13 @@ export function ZoomableViewport({
const renderedCanvasStyle = useMemo<React.CSSProperties>(() => {
let cursor: React.CSSProperties["cursor"] = "default";
if (transform.scale > 1) cursor = isDragging ? "grabbing" : "grab";
const canPan =
fittedContent !== null &&
viewport !== null &&
canPanContent(transform.scale, fittedContent, viewport);
if (canPan) cursor = isDragging ? "grabbing" : "grab";
return { ...canvasDomStyle, cursor };
}, [isDragging, transform.scale]);
}, [fittedContent, isDragging, transform.scale, viewport]);
const renderedContentStyle = useMemo<React.CSSProperties>(
() => ({
...contentDomStyle,
@@ -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"
+51 -101
View File
@@ -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;
}
+5 -5
View File
@@ -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
+13 -1
View File
@@ -2,7 +2,6 @@ import type { SendShortcut } from "@/hooks/use-settings";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type { MessagePayload, TextReplacement } from "@/composer/types";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
export type SendBehavior = ActiveTurnBehavior | "queue";
@@ -98,6 +97,19 @@ export function applyDictationTranscript(text: string, ctx: DictationTranscriptC
});
}
/** What the composer's keyboard actions ask the message input to do. */
export type MessageInputKeyboardActionKind =
| "focus"
| "send"
| "dictation-toggle"
| "dictation-cancel"
| "dictation-confirm"
| "voice-toggle"
| "voice-mute-toggle"
| "mode-cycle"
| "model-toggle"
| "effort-cycle";
interface MessageInputKeyboardActions {
focusInput: () => void;
isDictationRecording: () => boolean;
@@ -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"]);
});
});
+74 -7
View File
@@ -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;
}
+11
View File
@@ -0,0 +1,11 @@
export { CoreActionsProvider, createCoreRegistries } from "./internal/provider";
export type { CoreRegistries } from "./internal/provider";
export { useAppShellActions } from "./internal/app-shell-actions";
export { 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" },
},
];
@@ -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);
});
@@ -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;
}
+62
View File
@@ -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">
+11 -6
View File
@@ -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;
+5
View File
@@ -469,6 +469,7 @@ interface ChangesPullRequestLinkModel extends Pick<PrHint, "forge" | "number" |
interface ChangesRepositoryToolbarModel {
baseRef: string | null;
hasRemote: boolean;
isWorktree: boolean;
branchName: string | null;
cwd: string;
@@ -497,6 +498,7 @@ interface ChangesHeaderProps {
interface BuildChangesHeaderModelInput {
baseRef: string | null;
hasRemote: boolean;
isWorktree: boolean;
branchName: string | null;
committedDescription?: string;
@@ -522,6 +524,7 @@ function buildChangesHeaderModel(input: BuildChangesHeaderModelInput): {
return {
repository: {
baseRef: input.baseRef,
hasRemote: input.hasRemote,
isWorktree: input.isWorktree,
branchName: input.branchName,
cwd: input.cwd,
@@ -670,6 +673,7 @@ function ChangesRepositoryToolbar({
workspaceId={model.workspaceId}
cwd={model.cwd}
baseRef={model.baseRef}
hasRemote={model.hasRemote}
/>
</>
) : null}
@@ -1892,6 +1896,7 @@ export function ChangesSurface({
() =>
buildChangesHeaderModel({
baseRef: baseRef ?? null,
hasRemote: status?.isGit === true && status.hasRemote,
isWorktree: isManagedWorktree(status),
branchName: currentBranchName,
committedDescription: committedDiffDescription,

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