mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 14:45:25 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
765aec33e5 | ||
|
|
073743647a | ||
|
|
6b3b349c8b | ||
|
|
b1bb161133 | ||
|
|
2f1fc53cdb | ||
|
|
617ebbdb1a | ||
|
|
c174f475c8 | ||
|
|
6e5f0bd889 | ||
|
|
350a4937d9 |
+3
-3
@@ -22,11 +22,11 @@ The relay is designed to be untrusted. All traffic between your phone and daemon
|
||||
1. The daemon generates a persistent Curve25519 keypair on first run and stores it at `$PASEO_HOME/daemon-keypair.json` with mode `0600`
|
||||
2. The pairing URL (rendered as a QR code or opened directly) carries the daemon's public key in its URL fragment (`https://app.paseo.sh/#offer=...`). Fragments are not sent to the web server, so `app.paseo.sh` never sees the key.
|
||||
3. When the phone connects via the relay, it generates fresh ephemeral keys and sends an `e2ee_hello` message. The daemon will not process any application messages until this handshake completes.
|
||||
4. Updated peers run a Noise `NK` handshake (`Noise_NK_25519_ChaChaPoly_SHA256`) keyed to the daemon's static key: the `e2ee_hello` carries the first Noise message and the daemon's `e2ee_ready` carries the second. Every later frame is a counter-nonced ChaCha20-Poly1305 record. When either side predates this, the session falls back to the legacy construction: a Curve25519 ECDH shared key with XSalsa20-Poly1305 (NaCl `box`) and a random `[24-byte nonce][ciphertext]` bundle. Both modes negotiate `binaryCiphertext`: negotiated application text is carried as a base64 WebSocket text frame, while application binary is carried as a raw WebSocket binary frame. A peer that does not negotiate the capability uses base64 text frames for both kinds. [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) has the exact mapping.
|
||||
4. Updated peers run a Noise `NK` handshake (`Noise_NK_25519_ChaChaPoly_SHA256`) keyed to the daemon's static key: the `e2ee_hello` carries the first Noise message and the daemon's `e2ee_ready` carries the second. Every later frame is a counter-nonced ChaCha20-Poly1305 record. When either side predates this, the session falls back to the legacy construction: a Curve25519 ECDH shared key with XSalsa20-Poly1305 (NaCl `box`) and a random `[24-byte nonce][ciphertext]` bundle. Both modes negotiate `binaryCiphertext`. In protected mode every record then travels as a WebSocket binary frame, and an authenticated `kind` byte inside the record says whether the plaintext is text or binary. In legacy mode negotiated application text is carried as a base64 WebSocket text frame and application binary as a raw WebSocket binary frame. A peer that does not negotiate the capability uses base64 text frames for both kinds. [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) has the exact mapping.
|
||||
|
||||
The WebSocket opcode is preserved end to end after negotiation; the receiver never guesses whether authenticated plaintext is text or binary from its byte contents. The plaintext handshake remains WebSocket text and contains only public keys and capability declarations.
|
||||
After negotiation the receiver never guesses whether authenticated plaintext is text or binary from its byte contents: protected mode reads the authenticated `kind` byte and legacy mode reads the WebSocket opcode. The plaintext handshake remains WebSocket text and contains only public keys and capability declarations.
|
||||
|
||||
When both peers negotiate a frame codec (`frame_codecs`), frames of 1024 bytes or more are compressed statelessly per frame before encryption. Compression never shares dictionary state across frames, never compresses `hello` or `server_info`, and enforces the 100 MiB logical message limit as a hard decompression cap. As with any compression before encryption, compressed frame lengths remain observable to the relay.
|
||||
When both peers negotiate a frame codec (`frame_codecs`), frames of 1024 bytes or more are compressed statelessly per frame before encryption. Compression never shares dictionary state across frames and enforces the 100 MiB logical message limit as a hard decompression cap. `hello` and the `server_info` that answers it are never compressed: the client selects its codec from `server_info`, and the relay E2EE downgrade check reads `server_info` as text. Clients do not advertise codecs on loopback connections, where compression costs CPU and saves no bandwidth. As with any compression before encryption, compressed frame lengths remain observable to the relay.
|
||||
|
||||
The relay sees only: IP addresses, timing, message sizes, session IDs, and the plaintext `e2ee_hello` / `e2ee_ready` handshake frames (which contain only public keys). It cannot read message contents, forge messages, or derive encryption keys from observing the handshake.
|
||||
|
||||
|
||||
@@ -1,40 +1,6 @@
|
||||
# Keyboard shortcuts
|
||||
|
||||
A shortcut is two registrations. An action in the action registry (`@/actions`) is something the app can run. A binding in the keybinding registry (`@/keyboard`) connects keys to an action. `@/keyboard` imports `@/actions`; `@/actions` knows nothing about keys.
|
||||
|
||||
Paseo's own actions and default bindings are in [`core-actions/internal/actions.ts`](../packages/app/src/core-actions/internal/actions.ts) and [`bindings.ts`](../packages/app/src/core-actions/internal/bindings.ts). `CoreActionsProvider` registers them at app start, so Settings, badges and Command Center see every core shortcut before any surface mounts. Add a shortcut by adding a binding; add platform support through a key source.
|
||||
|
||||
## Actions and handlers
|
||||
|
||||
An action id such as `paseo/workspace.tab.next` is the only key for dispatch, badges (`useShortcutKeys`, `Shortcut`), Command Center rows and Settings rows.
|
||||
|
||||
A mounted surface supplies behavior with `useActionHandler(actionId, handler, { enabled, scope })`. Dispatch tries handlers in active action scopes innermost first, then unscoped handlers, with the earliest registration first among equals. When every handler declines, the action's own `run` handles it. The app shell supplies `run` for the core actions no screen owns, through `useCoreActionRuns` in [`app-shell-runs.ts`](../packages/app/src/core-actions/internal/app-shell-runs.ts).
|
||||
|
||||
A handler declines only by returning `{ handled: false }` synchronously. Any other return, including a promise, counts as handled. Express which handler wins with `enabled` and scopes, not with mount order.
|
||||
|
||||
Finite variants are separate actions: `workspace.tab.next` and `workspace.tab.previous`, one action per `message-input.*` operation. Only a `Digit` binding supplies data, as `index`.
|
||||
|
||||
## Action scopes
|
||||
|
||||
A surface that should shadow a shortcut while it is active creates a scope with `useActionScope(name, { active })`, and passes it to its handlers as `scope` or wraps its children in `<ActionScope activation>`. The innermost active scope wins. There are no priorities.
|
||||
|
||||
Example: the composer activates `paseo/composer` while it takes input, and the New Workspace screen activates `paseo/new-workspace` while it is focused. Shift+Tab on the New Workspace screen reaches its composer, and never the mode control of a backgrounded agent composer that is still mounted.
|
||||
|
||||
A handler is bound to one activation, not to a scope name. Two panes that show the same surface activate the same name separately, and a handler in one pane never runs for the other.
|
||||
|
||||
An action scope is different from the focus scope in a binding's `when` clause. Action scopes come from mounted surfaces. The focus scope comes from the focused input; see [Focus scopes](#focus-scopes).
|
||||
|
||||
## Bindings
|
||||
|
||||
A binding has an id, an action id, a combo and a `when` clause. User overrides are keyed by binding id, so never rename a shipped id, even when its combo changes (`agent-new-cmd-shift-o-mac` is bound to Cmd+O).
|
||||
|
||||
Among bindings that match the same key in the same context, the earliest registered wins. If its action declines, the registry tries the next matching binding. A chord's first step is reserved only while the chord's action can run.
|
||||
|
||||
Badges show the first assigned binding for the platform (`displayKeysFor`). Settings → Shortcuts builds its rows from the registry with `buildShortcutSections`, so it lists every core binding with only Settings mounted.
|
||||
|
||||
A surface that reads keys itself while it holds the keyboard, such as the workspace switcher HUD, matches them with `createChordMatcher` against the bindings it picks. A binding whose action finishes when its modifier is released, such as Ctrl+Tab in the switcher, sets `holdRelease`; key sources outside the app, such as the Electron browser pane, forward that key-up.
|
||||
|
||||
Tests that drive real keys through the real table use `createRecordingCoreRegistries` from `@/core-actions/testing`.
|
||||
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.
|
||||
|
||||
## Badges and routing
|
||||
|
||||
@@ -61,9 +27,7 @@ must be claimed up front. `UIKeyCommand` takes only those keys: composer Return,
|
||||
top overlay's Enter and arrows, and the Shift or Option shortcuts whose binding is
|
||||
active in the current focus scope, such as Shift+Tab in the composer.
|
||||
`sources/native.ts` computes the claims from the published bindings and recomputes
|
||||
them when the focus scope changes. Claims are computed without the action scope
|
||||
stack, so a binding whose `when` names an action scope is never claimed. Gate a key
|
||||
that a text control would type with `focusScope`, as mode cycle does. Cmd and Ctrl combos are never claimed, because
|
||||
them when the focus scope changes. 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.
|
||||
@@ -92,15 +56,6 @@ 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
|
||||
@@ -155,6 +110,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 `when: { editable: false }`, and its handler is
|
||||
`enabled` only while it has work. A disabled or declining handler leaves the key
|
||||
workspace archive undo, declares `editable: false` and registers its handler with
|
||||
`isActive` true only while it has work. An inactive handler leaves the key
|
||||
unhandled, so the pipeline skips `preventDefault` and the platform's own undo runs.
|
||||
|
||||
@@ -78,7 +78,14 @@ negotiate connection-scoped framing. Optional `frame_codecs` in `hello` and opti
|
||||
client's local codec list, so selection is deterministic regardless of client list order.
|
||||
Application serializers and routed envelopes use the same boundary. Handshakes (`hello`
|
||||
and `server_info`), frames below 1024 bytes, and incompressible frames keep their
|
||||
existing uncompressed representation. Older peers that omit `frame_codecs` or
|
||||
existing uncompressed representation. The daemon sends `server_info` before it applies the
|
||||
negotiated codec, because the client selects its codec from it. A routed envelope whose
|
||||
enclosed frame is already compressed is forwarded as it is.
|
||||
|
||||
A client omits `frame_codecs` when its transport reports `local` (loopback TCP, Unix
|
||||
socket, named pipe), unless the caller lists codecs explicitly in `capabilities`. Hosts
|
||||
routed through that client still use its installed codecs, so a routed host behind a
|
||||
loopback origin compresses end to end while the origin socket carries the frames as they are. Older peers that omit `frame_codecs` or
|
||||
`features.frameCodecs` exchange uncompressed frames and retain existing frame limits.
|
||||
|
||||
The reserved binary opcode `0x31` is followed by version `1`, original kind
|
||||
@@ -96,12 +103,16 @@ decodes UTF-8 only after END and decode complete. Transfers cannot interleave.
|
||||
Disconnect clears partial state and negotiation.
|
||||
|
||||
Codecs are host-supplied (`DaemonClientConfig.frameCodecs`), not sniffed in client core:
|
||||
Node entry points supply `node:zlib` (sync fast path only when work is bounded below
|
||||
256 KiB, libuv async otherwise so high-ratio inbound frames never stall the event loop),
|
||||
Node entry points supply `node:zlib` (sync up to 256 KiB: encode when the raw frame is at
|
||||
most that, decode when its input and output stay within it; libuv async past it, so high-ratio inbound
|
||||
frames never stall the event loop),
|
||||
web/Electron supplies `CompressionStream("deflate-raw")`, and native iOS/Android
|
||||
supplies the `paseo-compression` Expo module. Async codecs preserve strict FIFO order on
|
||||
both send and receive; a protocol error during async decode closes the socket via
|
||||
`onProtocolError` without delivering queued frames.
|
||||
`onProtocolError` without delivering queued frames. `close()` drops frames still decoding,
|
||||
so a client that disposes a connection never sees its stale frames. When a peer disconnects,
|
||||
the daemon awaits `flushInbound()` before `close()`, so a request the peer sent just before
|
||||
dropping applies as it would uncompressed.
|
||||
|
||||
The lower transport supplies its plaintext frame budget, including encryption
|
||||
overhead. The sender waits for drain between chunks while ordinary messages keep
|
||||
|
||||
@@ -49,5 +49,5 @@ Terminal frames share the daemon main event loop with all agent traffic. The `ev
|
||||
## Known remaining contention (follow-up candidates)
|
||||
|
||||
- A single large `agent_stream` message (e.g. a 250KB diff payload) measurably delays terminal echo (~100ms-class dips) — cost is split between daemon serialization and app-side parse/render on the shared browser main thread. See [agent-stream-performance.md](agent-stream-performance.md) for that pipeline's own budgets.
|
||||
- Relay-attached clients pay pure-JS tweetnacl encryption on the daemon main loop (`packages/relay/src/encrypted-channel.ts`). Negotiated binary application frames stay binary ciphertext and avoid base64 encode/decode; text and mixed-version traffic remain base64 WebSocket text frames.
|
||||
- Relay-attached clients pay pure-JS encryption on the daemon main loop: `@noble/ciphers` ChaCha20-Poly1305 records in protected mode (`packages/relay/src/protected-records.ts`), tweetnacl in legacy mode (`packages/relay/src/encrypted-channel.ts`). Protected peers that negotiate `binaryCiphertext` send every record as a binary frame with no base64 step. Legacy text and peers that predate `binaryCiphertext` still pay base64 encode/decode.
|
||||
- `sendToClient` re-stringifies session messages per socket; only matters for multi-socket connections.
|
||||
|
||||
@@ -1,22 +1,17 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import type { 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_BINDINGS = [
|
||||
"command-center-toggle-cmd-k-mac",
|
||||
"command-center-toggle-ctrl-k-non-mac",
|
||||
] as const;
|
||||
const COMMAND_CENTER_BINDING = "command-center-toggle-ctrl-k-non-mac";
|
||||
|
||||
async function rebindCommandCenter(page: Page, combo: string): Promise<void> {
|
||||
await page.addInitScript(
|
||||
([key, bindingIds, value]) => {
|
||||
const overrides = Object.fromEntries(bindingIds.map((id) => [id, value]));
|
||||
window.localStorage.setItem(key, JSON.stringify(overrides));
|
||||
([key, bindingId, value]) => {
|
||||
window.localStorage.setItem(key, JSON.stringify({ [bindingId]: value }));
|
||||
},
|
||||
[OVERRIDE_STORAGE_KEY, COMMAND_CENTER_BINDINGS, combo] as const,
|
||||
[OVERRIDE_STORAGE_KEY, COMMAND_CENTER_BINDING, combo] as const,
|
||||
);
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("sidebar-search")).toBeVisible({ timeout: 30_000 });
|
||||
@@ -26,18 +21,6 @@ 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");
|
||||
@@ -58,17 +41,4 @@ test.describe("Multi-step shortcut", () => {
|
||||
|
||||
await expectCommandCenterOpen(page);
|
||||
});
|
||||
|
||||
test("typing a rebound printable shortcut inside Command Center enters text instead of toggling it closed", async ({
|
||||
page,
|
||||
}) => {
|
||||
await rebindCommandCenter(page, "J");
|
||||
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await expectCommandCenterSearchAcceptsKey(page, commandCenter, "j");
|
||||
|
||||
await closeCommandCenter(page);
|
||||
await page.keyboard.press("j");
|
||||
await expectCommandCenterOpen(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,8 +97,7 @@ 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. The New Workspace screen's `paseo/new-workspace` action scope
|
||||
// must shadow a backgrounded composer's handler.
|
||||
// permissive/bypass mode. See use-keyboard-action-handler.ts.
|
||||
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);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
||||
import { deflateRawSync } from "node:zlib";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import {
|
||||
decodeHostRouteFrame,
|
||||
@@ -33,15 +33,37 @@ interface HostAdminClient {
|
||||
|
||||
interface BrowserCompressionTraffic {
|
||||
connectedPorts: Set<string>;
|
||||
advertisedCodecs: string[][];
|
||||
/** `frame_codecs` of each hello the browser sent on its own socket; null when omitted. */
|
||||
outerHelloCodecs: Array<string[] | null>;
|
||||
/** `frame_codecs` of each hello the browser sent to a routed host through the primary. */
|
||||
routedHelloCodecs: Array<string[] | null>;
|
||||
outerEncodedFrames: number[];
|
||||
routedEncodedFrames: number[];
|
||||
}
|
||||
|
||||
interface SentHello {
|
||||
type?: string;
|
||||
capabilities?: { frame_codecs?: unknown };
|
||||
}
|
||||
|
||||
function helloCodecs(hello: SentHello): string[] | null {
|
||||
const codecs = hello.capabilities?.frame_codecs;
|
||||
return Array.isArray(codecs) ? (codecs as string[]) : null;
|
||||
}
|
||||
|
||||
function parseJson<T>(text: string): T | null {
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic {
|
||||
const traffic: BrowserCompressionTraffic = {
|
||||
connectedPorts: new Set(),
|
||||
advertisedCodecs: [],
|
||||
outerHelloCodecs: [],
|
||||
routedHelloCodecs: [],
|
||||
outerEncodedFrames: [],
|
||||
routedEncodedFrames: [],
|
||||
};
|
||||
@@ -52,16 +74,21 @@ function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic
|
||||
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
if (typeof payload !== "string") return;
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as {
|
||||
type?: string;
|
||||
capabilities?: { frame_codecs?: unknown };
|
||||
};
|
||||
if (parsed.type === "hello" && Array.isArray(parsed.capabilities?.frame_codecs)) {
|
||||
traffic.advertisedCodecs.push(parsed.capabilities.frame_codecs as string[]);
|
||||
}
|
||||
} catch {
|
||||
// non-JSON text frame
|
||||
const parsed = parseJson<
|
||||
SentHello & { message?: { type?: string; data?: unknown; binary?: unknown } }
|
||||
>(payload);
|
||||
if (parsed?.type === "hello") {
|
||||
traffic.outerHelloCodecs.push(helloCodecs(parsed));
|
||||
return;
|
||||
}
|
||||
const routed = parsed?.message;
|
||||
if (
|
||||
parsed?.type === "session" &&
|
||||
routed?.type === "hosts.route.frame.request" &&
|
||||
typeof routed.data === "string"
|
||||
) {
|
||||
const hello = parseJson<SentHello>(routed.data);
|
||||
if (hello?.type === "hello") traffic.routedHelloCodecs.push(helloCodecs(hello));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -83,13 +110,6 @@ function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic
|
||||
|
||||
if (payload[0] === 0x31 && (payload[3]! & 0x04) !== 0) {
|
||||
traffic.outerEncodedFrames.push(payload.byteLength);
|
||||
if ((payload[3]! & 0x03) === 0x03 && payload[2] === 1) {
|
||||
try {
|
||||
inspectRouted(inflateRawSync(payload.subarray(4)));
|
||||
} catch {
|
||||
// ignore non-single-frame or partial
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
inspectRouted(payload);
|
||||
@@ -99,18 +119,15 @@ function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic
|
||||
return traffic;
|
||||
}
|
||||
|
||||
function hasAdvertisedCodec(traffic: BrowserCompressionTraffic, codecId: string): boolean {
|
||||
for (const codecs of traffic.advertisedCodecs) {
|
||||
if (codecs.includes(codecId)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function waitForAdvertisedCodec(
|
||||
async function expectRoutedHelloAdvertises(
|
||||
traffic: BrowserCompressionTraffic,
|
||||
codecId: string,
|
||||
): Promise<void> {
|
||||
await expect.poll(() => hasAdvertisedCodec(traffic, codecId), { timeout: 20_000 }).toBe(true);
|
||||
await expect
|
||||
.poll(() => traffic.routedHelloCodecs.some((codecs) => codecs?.includes(codecId) === true), {
|
||||
timeout: 20_000,
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function waitForHostOnline(client: HostAdminClient, registrationId: string): Promise<void> {
|
||||
@@ -133,6 +150,7 @@ const SERVED_PROTOCOL_FILES = new Set([
|
||||
"web-frame-codec.js",
|
||||
"frame-transport.js",
|
||||
"websocket-message-limit.js",
|
||||
"binary-frames/host-route.js",
|
||||
]);
|
||||
|
||||
async function verifyProductionWebCodecInChromium(page: Page, bombB64: string, validText: string) {
|
||||
@@ -147,7 +165,7 @@ async function verifyProductionWebCodecInChromium(page: Page, bombB64: string, v
|
||||
});
|
||||
return;
|
||||
}
|
||||
const name = path.basename(url.pathname);
|
||||
const name = url.pathname.slice(1);
|
||||
if (SERVED_PROTOCOL_FILES.has(name)) {
|
||||
const source = await readFile(path.join(PROTOCOL_DIST_DIR, name), "utf8");
|
||||
await route.fulfill({
|
||||
@@ -319,12 +337,17 @@ test.describe("Routed host frame compression in browser", () => {
|
||||
|
||||
await test.step("open the routed host workspace through the primary daemon", async () => {
|
||||
await gotoAppShell(page);
|
||||
await waitForAdvertisedCodec(traffic, "deflate-raw");
|
||||
|
||||
const routedProjectGroup = page.getByRole("group", {
|
||||
name: path.basename(secondaryWorkspace!.repoPath),
|
||||
});
|
||||
await expect(routedProjectGroup).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// The browser reaches the primary over loopback, so its own socket stays uncompressed,
|
||||
// while the routed host session negotiates deflate-raw end to end.
|
||||
expect(traffic.outerHelloCodecs.length).toBeGreaterThan(0);
|
||||
expect(new Set(traffic.outerHelloCodecs)).toEqual(new Set([null]));
|
||||
await expectRoutedHelloAdvertises(traffic, "deflate-raw");
|
||||
await routedProjectGroup.getByRole("button", { name: "main" }).click();
|
||||
await waitForTabBar(page);
|
||||
});
|
||||
@@ -342,11 +365,12 @@ test.describe("Routed host frame compression in browser", () => {
|
||||
expect(traffic.connectedPorts.has(primaryPort)).toBe(true);
|
||||
expect(traffic.connectedPorts.has(String(secondaryDaemon!.port))).toBe(false);
|
||||
|
||||
// Real deflate-raw 0x31 ENCODED frames crossed the routed host channel.
|
||||
// Real deflate-raw 0x31 ENCODED frames crossed the routed host channel, compressed once.
|
||||
expect(traffic.routedEncodedFrames.length).toBeGreaterThan(0);
|
||||
expect(Math.max(...traffic.routedEncodedFrames)).toBeLessThan(
|
||||
largeFileContent.length * 0.35,
|
||||
);
|
||||
expect(traffic.outerEncodedFrames).toEqual([]);
|
||||
});
|
||||
} finally {
|
||||
if (registrationId && primaryClient) {
|
||||
|
||||
@@ -112,24 +112,25 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
await expectSettingsSidebarScrollOffset(page, 0);
|
||||
});
|
||||
|
||||
test("updates appearance without losing the detail scroll or form edits", async ({ page }) => {
|
||||
test("updates typography and normalizes font sizes in one Appearance visit", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
test("shows normalized font sizes after committing out-of-range and empty values", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
await normalizeSettingsFontSizes(page);
|
||||
await test.step("change the syntax theme without losing the detail scroll", async () => {
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
});
|
||||
|
||||
await test.step("apply valid font edits to Settings and the preview", async () => {
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
await test.step("normalize out-of-range and empty font sizes on commit", async () => {
|
||||
await normalizeSettingsFontSizes(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the sidebar context through interface font changes", async ({ page }) => {
|
||||
|
||||
@@ -212,19 +212,11 @@ async function expectAgentConsistentlyIdle(page: Page, title: string): Promise<v
|
||||
await expectTurnCopyButton(page);
|
||||
}
|
||||
|
||||
async function withViewedTimelineScenario(
|
||||
run: (scenario: ViewedTimelineScenario) => Promise<void>,
|
||||
async function openFiveMoreChats(
|
||||
page: Page,
|
||||
scenario: ViewedTimelineScenario,
|
||||
subscriptions: ReturnType<typeof observeTimelineSubscriptions>,
|
||||
) {
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
try {
|
||||
await run(scenario);
|
||||
} finally {
|
||||
await scenario.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function openSevenChats(page: Page, scenario: ViewedTimelineScenario) {
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const additional = [];
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
additional.push(
|
||||
@@ -238,8 +230,6 @@ async function openSevenChats(page: Page, scenario: ViewedTimelineScenario) {
|
||||
}),
|
||||
);
|
||||
}
|
||||
await openAgent(page, scenario, scenario.firstAgentId);
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
for (let index = 0; index < additional.length; index += 1) {
|
||||
await selectAgent(page, `Additional chat ${index + 1}`);
|
||||
}
|
||||
@@ -512,15 +502,6 @@ test.describe("Viewed agent timelines", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("open chats stay current after switching beyond five agents", async ({ page }) => {
|
||||
await withViewedTimelineScenario(async (scenario) => {
|
||||
await openSevenChats(page, scenario);
|
||||
await commitMessage(scenario, scenario.firstAgentId, "Current after seven open chats.");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expectCurrentChatWithoutCatchUp(page, "Current after seven open chats.");
|
||||
});
|
||||
});
|
||||
|
||||
test("a turn that finishes while hidden reopens with consistently idle chrome", async ({
|
||||
page,
|
||||
}) => {
|
||||
@@ -542,35 +523,49 @@ test.describe("Viewed agent timelines", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a hidden retained chat stays current without rendering", async ({ page }) => {
|
||||
test("a retained chat stays current while hidden and after opening seven chats", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60_000);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
try {
|
||||
await openAgent(page, scenario, scenario.firstAgentId, { recordRenders: true });
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
await composer.fill("Unsent draft survives hidden streaming");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
|
||||
const hiddenCommits = await countChatCommits(page, scenario.firstAgentId);
|
||||
expect(hiddenCommits).toBeGreaterThan(0);
|
||||
await commitMessage(
|
||||
scenario,
|
||||
scenario.firstAgentId,
|
||||
"Committed while the first chat is hidden.",
|
||||
);
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toHaveCount(0);
|
||||
expect(await countChatCommits(page, scenario.firstAgentId)).toBe(hiddenCommits);
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("(end of synthetic stream)", { exact: true })).toBeVisible();
|
||||
await expect(composer).toHaveValue("Unsent draft survives hidden streaming");
|
||||
await composer.fill("Draft edited after returning");
|
||||
await expect(composer).toHaveValue("Draft edited after returning");
|
||||
await test.step("Keep a hidden chat current without rendering or losing its draft", async () => {
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
await composer.fill("Unsent draft survives hidden streaming");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([
|
||||
scenario.firstAgentId,
|
||||
scenario.secondAgentId,
|
||||
]);
|
||||
const hiddenCommits = await countChatCommits(page, scenario.firstAgentId);
|
||||
expect(hiddenCommits).toBeGreaterThan(0);
|
||||
await commitMessage(
|
||||
scenario,
|
||||
scenario.firstAgentId,
|
||||
"Committed while the first chat is hidden.",
|
||||
);
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toHaveCount(0);
|
||||
expect(await countChatCommits(page, scenario.firstAgentId)).toBe(hiddenCommits);
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("(end of synthetic stream)", { exact: true })).toBeVisible();
|
||||
await expect(composer).toHaveValue("Unsent draft survives hidden streaming");
|
||||
await composer.fill("Draft edited after returning");
|
||||
await expect(composer).toHaveValue("Draft edited after returning");
|
||||
});
|
||||
|
||||
await test.step("Keep the first chat current after opening seven chats", async () => {
|
||||
await openFiveMoreChats(page, scenario, subscriptions);
|
||||
await commitMessage(scenario, scenario.firstAgentId, "Current after seven open chats.");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expectCurrentChatWithoutCatchUp(page, "Current after seven open chats.");
|
||||
});
|
||||
} finally {
|
||||
await scenario.cleanup();
|
||||
}
|
||||
|
||||
@@ -1,387 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createActionRegistry,
|
||||
createActionScopeStore,
|
||||
DuplicateActionError,
|
||||
InvalidActionIdError,
|
||||
type ActionInvocation,
|
||||
type OrderOwners,
|
||||
} from "@/actions";
|
||||
|
||||
function createHarness(input: { orderOwners?: OrderOwners } = {}) {
|
||||
const scopes = createActionScopeStore();
|
||||
const errors: Array<{ error: unknown; actionId: string; owner: string | null }> = [];
|
||||
const registry = createActionRegistry({
|
||||
scopes,
|
||||
...(input.orderOwners ? { orderOwners: input.orderOwners } : {}),
|
||||
onError: (error, info) => errors.push({ error, ...info }),
|
||||
});
|
||||
return { scopes, registry, errors };
|
||||
}
|
||||
|
||||
function registerRunner(
|
||||
registry: ReturnType<typeof createHarness>["registry"],
|
||||
input: { id: string; owner: string | null; context?: "global" | "workspace" | "agent" },
|
||||
ran: Array<string | null>,
|
||||
) {
|
||||
return registry.registerAction({
|
||||
id: input.id,
|
||||
title: input.id,
|
||||
owner: input.owner,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
run: (invocation) => {
|
||||
ran.push(invocation.owner);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("ActionScopeStore", () => {
|
||||
it("lists active scopes outermost first, with the latest activation innermost", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
const list = scopes.activate("inbox/list");
|
||||
const popover = scopes.activate("inbox/popover");
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list", "inbox/popover"]);
|
||||
expect([scopes.depthOf(list), scopes.depthOf(popover)]).toEqual([1, 2]);
|
||||
|
||||
popover.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list"]);
|
||||
expect(scopes.depthOf(popover)).toBeNull();
|
||||
list.release();
|
||||
expect(scopes.getActiveScopes()).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a name active until every activation releases, at its innermost position", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
const first = scopes.activate("inbox/list");
|
||||
const popover = scopes.activate("inbox/popover");
|
||||
const second = scopes.activate("inbox/list");
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/popover", "inbox/list"]);
|
||||
|
||||
second.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list", "inbox/popover"]);
|
||||
second.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list", "inbox/popover"]);
|
||||
|
||||
first.release();
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/popover"]);
|
||||
popover.release();
|
||||
});
|
||||
|
||||
it("notifies only when the active scope order changes and keeps snapshots stable", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
let notifications = 0;
|
||||
scopes.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
|
||||
const first = scopes.activate("a/one");
|
||||
const snapshot = scopes.getActiveScopes();
|
||||
expect(notifications).toBe(1);
|
||||
expect(scopes.getActiveScopes()).toBe(snapshot);
|
||||
|
||||
const again = scopes.activate("a/one");
|
||||
expect(notifications).toBe(1);
|
||||
again.release();
|
||||
expect(notifications).toBe(1);
|
||||
|
||||
first.release();
|
||||
expect(notifications).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects empty scope names", () => {
|
||||
const scopes = createActionScopeStore();
|
||||
expect(() => scopes.activate(" ")).toThrow(/non-empty/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ActionRegistry", () => {
|
||||
it("validates namespaced action ids", () => {
|
||||
const { registry } = createHarness();
|
||||
expect(() => registry.registerAction({ id: "no-namespace", title: "Bad" })).toThrow(
|
||||
InvalidActionIdError,
|
||||
);
|
||||
const noop = () => {};
|
||||
expect(() => registry.registerHandler("inbox/", noop)).toThrow(InvalidActionIdError);
|
||||
expect(() => registry.registerAction({ id: "inbox/item.next", title: "Next" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("notifies on registration and keeps cleanup idempotent", () => {
|
||||
const { registry } = createHarness();
|
||||
let notifications = 0;
|
||||
registry.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
const unregister = registry.registerAction({ id: "inbox/refresh", title: "Refresh" });
|
||||
expect(notifications).toBe(1);
|
||||
unregister();
|
||||
unregister();
|
||||
expect(notifications).toBe(2);
|
||||
expect(registry.getAction("inbox/refresh")).toBeNull();
|
||||
});
|
||||
|
||||
it("defaults to the global context and no owner", () => {
|
||||
const { registry } = createHarness();
|
||||
registry.registerAction({ id: "paseo/settings.open", title: "Open settings" });
|
||||
expect(registry.getAction("paseo/settings.open")).toEqual({
|
||||
id: "paseo/settings.open",
|
||||
title: "Open settings",
|
||||
context: "global",
|
||||
owners: [null],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ActionRegistry owners", () => {
|
||||
it("merges two owners of one id into one action, and removing either leaves the other", () => {
|
||||
for (const [removed, remaining] of [
|
||||
["host-1", "host-2"],
|
||||
["host-2", "host-1"],
|
||||
] as const) {
|
||||
const { registry } = createHarness();
|
||||
const ran: Array<string | null> = [];
|
||||
const unregister = {
|
||||
"host-1": registerRunner(registry, { id: "inbox/refresh", owner: "host-1" }, ran),
|
||||
"host-2": registerRunner(registry, { id: "inbox/refresh", owner: "host-2" }, ran),
|
||||
};
|
||||
expect(registry.listActions()).toHaveLength(1);
|
||||
expect(registry.getAction("inbox/refresh")?.owners).toEqual(["host-1", "host-2"]);
|
||||
|
||||
unregister[removed]();
|
||||
expect(registry.getAction("inbox/refresh")?.owners).toEqual([remaining]);
|
||||
expect(registry.dispatch("inbox/refresh")).toBe(true);
|
||||
expect(ran).toEqual([remaining]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a second registration of the same id by the same owner", () => {
|
||||
const { registry } = createHarness();
|
||||
registry.registerAction({ id: "inbox/refresh", title: "Refresh", owner: "host-1" });
|
||||
expect(() =>
|
||||
registry.registerAction({ id: "inbox/refresh", title: "Again", owner: "host-1" }),
|
||||
).toThrow(DuplicateActionError);
|
||||
registry.registerAction({ id: "paseo/settings.open", title: "Open settings" });
|
||||
expect(() => registry.registerAction({ id: "paseo/settings.open", title: "Again" })).toThrow(
|
||||
DuplicateActionError,
|
||||
);
|
||||
expect(registry.getAction("inbox/refresh")?.title).toBe("Refresh");
|
||||
});
|
||||
|
||||
it("runs owners in registration order by default", () => {
|
||||
const { registry } = createHarness();
|
||||
const ran: Array<string | null> = [];
|
||||
registerRunner(registry, { id: "inbox/sync", owner: "host-b" }, ran);
|
||||
registerRunner(registry, { id: "inbox/sync", owner: "host-a" }, ran);
|
||||
registry.dispatch("inbox/sync");
|
||||
expect(ran).toEqual(["host-b"]);
|
||||
});
|
||||
|
||||
it("asks the injected rule which owners run, in which order", () => {
|
||||
let active = "host-a";
|
||||
const { registry } = createHarness({
|
||||
orderOwners: (action) => {
|
||||
const rest = action.context === "global" ? action.owners : [];
|
||||
return [active, ...rest.filter((owner) => owner !== active)];
|
||||
},
|
||||
});
|
||||
const ran: Array<string | null> = [];
|
||||
registerRunner(registry, { id: "inbox/sync", owner: "host-b" }, ran);
|
||||
registerRunner(registry, { id: "inbox/sync", owner: "host-a" }, ran);
|
||||
registerRunner(registry, { id: "inbox/open", owner: "host-b", context: "workspace" }, ran);
|
||||
|
||||
registry.dispatch("inbox/sync");
|
||||
expect(ran).toEqual(["host-a"]);
|
||||
|
||||
expect(registry.canDispatch("inbox/open")).toBe(false);
|
||||
expect(registry.dispatch("inbox/open")).toBe(false);
|
||||
active = "host-b";
|
||||
expect(registry.dispatch("inbox/open")).toBe(true);
|
||||
expect(ran).toEqual(["host-a", "host-b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ActionRegistry mounted handlers", () => {
|
||||
it("runs the handler in the innermost active scope, whichever registered first", () => {
|
||||
for (const order of [
|
||||
["list", "popover"],
|
||||
["popover", "list"],
|
||||
] as const) {
|
||||
const { registry, scopes } = createHarness();
|
||||
const activations = {
|
||||
list: scopes.activate("inbox/list"),
|
||||
popover: scopes.activate("inbox/popover"),
|
||||
};
|
||||
const calls: string[] = [];
|
||||
for (const name of order) {
|
||||
registry.registerHandler(
|
||||
"inbox/item.next",
|
||||
() => {
|
||||
calls.push(name);
|
||||
},
|
||||
{ scope: activations[name] },
|
||||
);
|
||||
}
|
||||
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual(["popover"]);
|
||||
|
||||
activations.popover.release();
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual(["popover", "list"]);
|
||||
activations.list.release();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not run a scoped handler once its scope activation is released", () => {
|
||||
const { registry, scopes } = createHarness();
|
||||
const calls: string[] = [];
|
||||
const list = scopes.activate("inbox/list");
|
||||
registry.registerHandler(
|
||||
"inbox/item.next",
|
||||
() => {
|
||||
calls.push("scoped");
|
||||
},
|
||||
{ scope: list },
|
||||
);
|
||||
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
list.release();
|
||||
expect(registry.canDispatch("inbox/item.next")).toBe(false);
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(false);
|
||||
expect(calls).toEqual(["scoped"]);
|
||||
});
|
||||
|
||||
it("runs only the active pane when two panes mount the same scope name", () => {
|
||||
for (const activePane of ["a", "b"] as const) {
|
||||
const { registry, scopes } = createHarness();
|
||||
const panes = { a: scopes.activate("inbox/list"), b: scopes.activate("inbox/list") };
|
||||
const calls: string[] = [];
|
||||
for (const pane of ["a", "b"] as const) {
|
||||
registry.registerHandler(
|
||||
"inbox/item.next",
|
||||
() => {
|
||||
calls.push(pane);
|
||||
},
|
||||
{ scope: panes[pane] },
|
||||
);
|
||||
}
|
||||
panes[activePane === "a" ? "b" : "a"].release();
|
||||
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual([activePane]);
|
||||
expect(scopes.getActiveScopes()).toEqual(["inbox/list"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("prefers an active scoped handler over an unscoped one", () => {
|
||||
const { registry, scopes } = createHarness();
|
||||
const calls: string[] = [];
|
||||
registry.registerHandler("inbox/item.next", () => {
|
||||
calls.push("unscoped");
|
||||
});
|
||||
registry.dispatch("inbox/item.next");
|
||||
|
||||
const list = scopes.activate("inbox/list");
|
||||
registry.registerHandler(
|
||||
"inbox/item.next",
|
||||
() => {
|
||||
calls.push("scoped");
|
||||
},
|
||||
{ scope: list },
|
||||
);
|
||||
registry.dispatch("inbox/item.next");
|
||||
list.release();
|
||||
expect(calls).toEqual(["unscoped", "scoped"]);
|
||||
});
|
||||
|
||||
it("tries equal handlers earliest first, skips disabled ones and falls through on decline", () => {
|
||||
const { registry } = createHarness();
|
||||
const calls: string[] = [];
|
||||
let declines = true;
|
||||
let enabled = true;
|
||||
registry.registerHandler("inbox/item.next", () => {
|
||||
calls.push("declining");
|
||||
return declines ? { handled: false } : undefined;
|
||||
});
|
||||
registry.registerHandler(
|
||||
"inbox/item.next",
|
||||
() => {
|
||||
calls.push("toggled");
|
||||
},
|
||||
{ enabled: () => enabled },
|
||||
);
|
||||
registry.registerHandler("inbox/item.next", () => {
|
||||
calls.push("last");
|
||||
});
|
||||
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual(["declining", "toggled"]);
|
||||
|
||||
enabled = false;
|
||||
calls.length = 0;
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual(["declining", "last"]);
|
||||
|
||||
declines = false;
|
||||
calls.length = 0;
|
||||
expect(registry.dispatch("inbox/item.next")).toBe(true);
|
||||
expect(calls).toEqual(["declining"]);
|
||||
});
|
||||
|
||||
it("runs the action's run after every handler declines", () => {
|
||||
const { registry } = createHarness();
|
||||
const ran: Array<string | null> = [];
|
||||
registerRunner(registry, { id: "inbox/refresh", owner: null }, ran);
|
||||
registry.registerHandler("inbox/refresh", () => ({ handled: false }));
|
||||
expect(registry.dispatch("inbox/refresh")).toBe(true);
|
||||
expect(ran).toEqual([null]);
|
||||
});
|
||||
|
||||
it("passes the index through unchanged", () => {
|
||||
const { registry } = createHarness();
|
||||
const invocations: ActionInvocation[] = [];
|
||||
registry.registerHandler("inbox/item.open", (invocation) => {
|
||||
invocations.push(invocation);
|
||||
});
|
||||
registry.dispatch("inbox/item.open", { index: 3 });
|
||||
expect(invocations).toEqual([{ actionId: "inbox/item.open", owner: null, index: 3 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ActionRegistry errors", () => {
|
||||
it("routes sync throws and async rejections from runs and handlers to onError", async () => {
|
||||
const { registry, errors } = createHarness();
|
||||
const syncError = new Error("sync");
|
||||
const asyncError = new Error("async");
|
||||
const handlerError = new Error("handler async");
|
||||
|
||||
registry.registerAction({
|
||||
id: "inbox/sync.fail",
|
||||
title: "Sync fail",
|
||||
run: () => {
|
||||
throw syncError;
|
||||
},
|
||||
});
|
||||
registry.registerAction({
|
||||
id: "inbox/async.fail",
|
||||
title: "Async fail",
|
||||
owner: "host-a",
|
||||
run: async () => {
|
||||
throw asyncError;
|
||||
},
|
||||
});
|
||||
registry.registerHandler("inbox/handler.fail", async () => {
|
||||
throw handlerError;
|
||||
});
|
||||
|
||||
expect(registry.dispatch("inbox/sync.fail")).toBe(true);
|
||||
expect(registry.dispatch("inbox/async.fail")).toBe(true);
|
||||
expect(registry.dispatch("inbox/handler.fail")).toBe(true);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(errors).toEqual([
|
||||
{ error: syncError, actionId: "inbox/sync.fail", owner: null },
|
||||
{ error: asyncError, actionId: "inbox/async.fail", owner: "host-a" },
|
||||
{ error: handlerError, actionId: "inbox/handler.fail", owner: null },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
export {
|
||||
createActionRegistry,
|
||||
DuplicateActionError,
|
||||
InvalidActionIdError,
|
||||
} from "./internal/action-registry";
|
||||
export type {
|
||||
ActionContext,
|
||||
ActionDeclined,
|
||||
ActionDefinitionInput,
|
||||
ActionDispatchInput,
|
||||
ActionErrorInfo,
|
||||
ActionHandler,
|
||||
ActionHandlerOptions,
|
||||
ActionInvocation,
|
||||
ActionRegistry,
|
||||
ActionRegistryOptions,
|
||||
OrderOwners,
|
||||
RegisteredAction,
|
||||
} from "./internal/action-registry";
|
||||
export { createActionScopeStore } from "./internal/action-scope-store";
|
||||
export type {
|
||||
ActionScopeStore,
|
||||
ActiveScopes,
|
||||
ScopeActivation,
|
||||
} from "./internal/action-scope-store";
|
||||
export {
|
||||
ActionRegistryProvider,
|
||||
ActionScope,
|
||||
useActionHandler,
|
||||
useActionRegistry,
|
||||
useActionScope,
|
||||
} from "./internal/react";
|
||||
export type { UseActionHandlerOptions } from "./internal/react";
|
||||
@@ -1,348 +0,0 @@
|
||||
import type { ActionScopeStore, ScopeActivation } from "./action-scope-store";
|
||||
|
||||
const ACTION_ID_RE = /^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/i;
|
||||
|
||||
export class InvalidActionIdError extends Error {
|
||||
readonly actionId: string;
|
||||
|
||||
constructor(actionId: string) {
|
||||
super(`Invalid action id "${actionId}": expected "<namespace>/<dot.name>"`);
|
||||
this.name = "InvalidActionIdError";
|
||||
this.actionId = actionId;
|
||||
}
|
||||
}
|
||||
|
||||
export class DuplicateActionError extends Error {
|
||||
readonly actionId: string;
|
||||
readonly owner: string | null;
|
||||
|
||||
constructor(actionId: string, owner: string | null) {
|
||||
super(`Action "${actionId}" is already registered by owner ${owner ?? "(none)"}`);
|
||||
this.name = "DuplicateActionError";
|
||||
this.actionId = actionId;
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
|
||||
function assertValidActionId(actionId: string): void {
|
||||
if (!ACTION_ID_RE.test(actionId)) {
|
||||
throw new InvalidActionIdError(actionId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Where an action runs. Same vocabulary as `addCommandCenterItem`'s `context`. */
|
||||
export type ActionContext = "global" | "workspace" | "agent";
|
||||
|
||||
export interface ActionInvocation {
|
||||
readonly actionId: string;
|
||||
/** The owner whose `run` this is; `null` for a mounted handler or an unowned action. */
|
||||
readonly owner: string | null;
|
||||
/** A position the caller picked, such as the third item. */
|
||||
readonly index?: number;
|
||||
}
|
||||
|
||||
/** Return this, synchronously, to pass the action on to the next handler or `run`. */
|
||||
export interface ActionDeclined {
|
||||
readonly handled: false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returning nothing means handled. A returned promise also counts as handled;
|
||||
* its rejection goes to `onError` and is never re-dispatched.
|
||||
*/
|
||||
export type ActionHandler = (invocation: ActionInvocation) => void | ActionDeclined | Promise<void>;
|
||||
|
||||
export interface ActionDefinitionInput {
|
||||
id: string;
|
||||
title: string;
|
||||
icon?: string;
|
||||
/** Defaults to `"global"`. */
|
||||
context?: ActionContext;
|
||||
/** Opaque registrant. Core registers with none (`null`). */
|
||||
owner?: string | null;
|
||||
run?: ActionHandler;
|
||||
}
|
||||
|
||||
export interface RegisteredAction {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly icon?: string;
|
||||
readonly context: ActionContext;
|
||||
/** Every owner that registered this id, earliest first. */
|
||||
readonly owners: readonly (string | null)[];
|
||||
}
|
||||
|
||||
export interface ActionHandlerOptions {
|
||||
/**
|
||||
* The activation of the surface this handler is mounted in. The handler runs
|
||||
* only while that activation is active, and the innermost one wins.
|
||||
*/
|
||||
scope?: ScopeActivation;
|
||||
/** Read on every dispatch. A disabled handler is invisible to `canDispatch`. */
|
||||
enabled?: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks which owners' `run` to try, in order, for one dispatch. The app
|
||||
* supplies it; the registry never learns what an owner is.
|
||||
*/
|
||||
export type OrderOwners = (action: RegisteredAction) => readonly (string | null)[];
|
||||
|
||||
export interface ActionErrorInfo {
|
||||
readonly actionId: string;
|
||||
readonly owner: string | null;
|
||||
}
|
||||
|
||||
export interface ActionRegistryOptions {
|
||||
scopes: ActionScopeStore;
|
||||
/** Defaults to every owner, earliest registration first. */
|
||||
orderOwners?: OrderOwners;
|
||||
onError?: (error: unknown, info: ActionErrorInfo) => void;
|
||||
}
|
||||
|
||||
export interface ActionDispatchInput {
|
||||
index?: number;
|
||||
}
|
||||
|
||||
export interface ActionRegistry {
|
||||
registerAction(definition: ActionDefinitionInput): () => void;
|
||||
registerHandler(
|
||||
actionId: string,
|
||||
handler: ActionHandler,
|
||||
options?: ActionHandlerOptions,
|
||||
): () => void;
|
||||
getAction(actionId: string): RegisteredAction | null;
|
||||
listActions(): readonly RegisteredAction[];
|
||||
/** Whether a dispatch now would reach an enabled handler or a `run`. */
|
||||
canDispatch(actionId: string): boolean;
|
||||
/**
|
||||
* Tries mounted handlers, innermost active scope first, then each owner's
|
||||
* `run` in the injected order. Returns whether one took the action.
|
||||
*/
|
||||
dispatch(actionId: string, input?: ActionDispatchInput): boolean;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
interface StoredDefinition {
|
||||
readonly owner: string | null;
|
||||
readonly title: string;
|
||||
readonly icon?: string;
|
||||
readonly context: ActionContext;
|
||||
readonly run?: ActionHandler;
|
||||
}
|
||||
|
||||
interface StoredHandler {
|
||||
readonly handler: ActionHandler;
|
||||
readonly scope: ScopeActivation | null;
|
||||
readonly enabled: () => boolean;
|
||||
}
|
||||
|
||||
function everyOwner(action: RegisteredAction): readonly (string | null)[] {
|
||||
return action.owners;
|
||||
}
|
||||
|
||||
function defaultOnError(error: unknown, info: ActionErrorInfo): void {
|
||||
console.error(`[actions] "${info.actionId}" failed:`, error);
|
||||
}
|
||||
|
||||
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"then" in value &&
|
||||
typeof value.then === "function"
|
||||
);
|
||||
}
|
||||
|
||||
function isDeclined(value: unknown): value is ActionDeclined {
|
||||
return typeof value === "object" && value !== null && "handled" in value && !value.handled;
|
||||
}
|
||||
|
||||
function alwaysEnabled(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function addToList<T>(map: Map<string, T[]>, key: string, value: T): void {
|
||||
map.set(key, [...(map.get(key) ?? []), value]);
|
||||
}
|
||||
|
||||
function removeFromList<T>(map: Map<string, T[]>, key: string, value: T): boolean {
|
||||
const current = map.get(key);
|
||||
if (!current?.includes(value)) {
|
||||
return false;
|
||||
}
|
||||
const remaining = current.filter((entry) => entry !== value);
|
||||
if (remaining.length === 0) {
|
||||
map.delete(key);
|
||||
} else {
|
||||
map.set(key, remaining);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The earliest registration describes the action; later owners add their `run`. */
|
||||
function toRegisteredAction(
|
||||
id: string,
|
||||
definitions: readonly StoredDefinition[],
|
||||
): RegisteredAction {
|
||||
const [first] = definitions;
|
||||
return {
|
||||
id,
|
||||
title: first.title,
|
||||
...(first.icon !== undefined ? { icon: first.icon } : {}),
|
||||
context: first.context,
|
||||
owners: definitions.map((entry) => entry.owner),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Namespaced actions, the `run` each owner registers for them, and the
|
||||
* handlers mounted surfaces attach. The same id from two owners is one action.
|
||||
*/
|
||||
export function createActionRegistry(options: ActionRegistryOptions): ActionRegistry {
|
||||
const { scopes } = options;
|
||||
const orderOwners = options.orderOwners ?? everyOwner;
|
||||
const onError = options.onError ?? defaultOnError;
|
||||
const definitionsById = new Map<string, StoredDefinition[]>();
|
||||
const handlersById = new Map<string, StoredHandler[]>();
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function notify(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enabled handlers whose scope activation is active: innermost first,
|
||||
* unscoped last, earliest registration first among equals.
|
||||
*/
|
||||
function eligibleHandlers(actionId: string): StoredHandler[] {
|
||||
const ranked: Array<{ entry: StoredHandler; rank: number }> = [];
|
||||
for (const entry of handlersById.get(actionId) ?? []) {
|
||||
const rank = entry.scope === null ? 0 : scopes.depthOf(entry.scope);
|
||||
if (rank === null) continue;
|
||||
if (!entry.enabled()) continue;
|
||||
ranked.push({ entry, rank });
|
||||
}
|
||||
// Array#sort is stable, so equal ranks keep registration order.
|
||||
ranked.sort((left, right) => right.rank - left.rank);
|
||||
return ranked.map(({ entry }) => entry);
|
||||
}
|
||||
|
||||
function eligibleRunners(actionId: string): StoredDefinition[] {
|
||||
const definitions = definitionsById.get(actionId);
|
||||
if (!definitions) {
|
||||
return [];
|
||||
}
|
||||
const runners: StoredDefinition[] = [];
|
||||
for (const owner of orderOwners(toRegisteredAction(actionId, definitions))) {
|
||||
const entry = definitions.find((candidate) => candidate.owner === owner);
|
||||
if (entry?.run) runners.push(entry);
|
||||
}
|
||||
return runners;
|
||||
}
|
||||
|
||||
/** Runs one handler and reports whether it took the action. */
|
||||
function invoke(handler: ActionHandler, invocation: ActionInvocation): boolean {
|
||||
const info = { actionId: invocation.actionId, owner: invocation.owner };
|
||||
let outcome: ReturnType<ActionHandler>;
|
||||
try {
|
||||
outcome = handler(invocation);
|
||||
} catch (error) {
|
||||
onError(error, info);
|
||||
return true;
|
||||
}
|
||||
if (isPromiseLike(outcome)) {
|
||||
outcome.then(undefined, (error: unknown) => onError(error, info));
|
||||
return true;
|
||||
}
|
||||
return !isDeclined(outcome);
|
||||
}
|
||||
|
||||
function invocationFor(
|
||||
actionId: string,
|
||||
owner: string | null,
|
||||
input: ActionDispatchInput | undefined,
|
||||
): ActionInvocation {
|
||||
return {
|
||||
actionId,
|
||||
owner,
|
||||
...(input?.index !== undefined ? { index: input.index } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
registerAction(definition) {
|
||||
assertValidActionId(definition.id);
|
||||
const owner = definition.owner ?? null;
|
||||
if (definitionsById.get(definition.id)?.some((entry) => entry.owner === owner)) {
|
||||
throw new DuplicateActionError(definition.id, owner);
|
||||
}
|
||||
const entry: StoredDefinition = {
|
||||
owner,
|
||||
title: definition.title,
|
||||
...(definition.icon !== undefined ? { icon: definition.icon } : {}),
|
||||
context: definition.context ?? "global",
|
||||
...(definition.run !== undefined ? { run: definition.run } : {}),
|
||||
};
|
||||
addToList(definitionsById, definition.id, entry);
|
||||
notify();
|
||||
return () => {
|
||||
if (removeFromList(definitionsById, definition.id, entry)) {
|
||||
notify();
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
registerHandler(actionId, handler, handlerOptions = {}) {
|
||||
assertValidActionId(actionId);
|
||||
const entry: StoredHandler = {
|
||||
handler,
|
||||
scope: handlerOptions.scope ?? null,
|
||||
enabled: handlerOptions.enabled ?? alwaysEnabled,
|
||||
};
|
||||
addToList(handlersById, actionId, entry);
|
||||
notify();
|
||||
return () => {
|
||||
if (removeFromList(handlersById, actionId, entry)) {
|
||||
notify();
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
getAction(actionId) {
|
||||
const definitions = definitionsById.get(actionId);
|
||||
return definitions ? toRegisteredAction(actionId, definitions) : null;
|
||||
},
|
||||
|
||||
listActions() {
|
||||
return [...definitionsById].map(([id, definitions]) => toRegisteredAction(id, definitions));
|
||||
},
|
||||
|
||||
canDispatch(actionId) {
|
||||
return eligibleHandlers(actionId).length > 0 || eligibleRunners(actionId).length > 0;
|
||||
},
|
||||
|
||||
dispatch(actionId, input) {
|
||||
for (const entry of eligibleHandlers(actionId)) {
|
||||
if (invoke(entry.handler, invocationFor(actionId, null, input))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (const entry of eligibleRunners(actionId)) {
|
||||
if (entry.run && invoke(entry.run, invocationFor(actionId, entry.owner, input))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
/** Active named scopes, outermost first. The last entry is the innermost scope. */
|
||||
export type ActiveScopes = readonly string[];
|
||||
|
||||
/**
|
||||
* One mounted surface's activation of a named scope. Two panes showing the
|
||||
* same panel activate the same name separately, and a handler bound to one
|
||||
* activation never runs for the other.
|
||||
*/
|
||||
export interface ScopeActivation {
|
||||
readonly scope: string;
|
||||
/** Idempotent. A released activation stays inactive; activate again for a new one. */
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stack of named action scopes that mounted surfaces activate, such as
|
||||
* `"inbox/list"` under `"inbox/popover"`. The innermost active scope wins; no
|
||||
* weights or priorities.
|
||||
*/
|
||||
export interface ActionScopeStore {
|
||||
/** Pushes `scope` as the innermost scope. */
|
||||
activate(scope: string): ScopeActivation;
|
||||
/** Stable between changes, so it can back `useSyncExternalStore`. */
|
||||
getActiveScopes(): ActiveScopes;
|
||||
/**
|
||||
* How deep `activation` sits in the stack: 1 for the outermost, higher for
|
||||
* inner ones, `null` once released.
|
||||
*/
|
||||
depthOf(activation: ScopeActivation): number | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
function sameScopes(left: ActiveScopes, right: ActiveScopes): boolean {
|
||||
return left.length === right.length && left.every((scope, index) => scope === right[index]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A name activated more than once stays active until every activation is
|
||||
* released, and sits at the position of its innermost activation.
|
||||
*/
|
||||
function orderActiveScopes(activations: readonly ScopeActivation[]): ActiveScopes {
|
||||
const innermostIndex = new Map<string, number>();
|
||||
for (const [index, { scope }] of activations.entries()) {
|
||||
innermostIndex.set(scope, index);
|
||||
}
|
||||
return [...innermostIndex.entries()]
|
||||
.sort(([, left], [, right]) => left - right)
|
||||
.map(([scope]) => scope);
|
||||
}
|
||||
|
||||
export function createActionScopeStore(): ActionScopeStore {
|
||||
const activations: ScopeActivation[] = [];
|
||||
const listeners = new Set<() => void>();
|
||||
let activeScopes: ActiveScopes = [];
|
||||
|
||||
function commit(): void {
|
||||
const next = orderActiveScopes(activations);
|
||||
if (sameScopes(activeScopes, next)) {
|
||||
return;
|
||||
}
|
||||
activeScopes = next;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
activate(scope) {
|
||||
if (scope.trim().length === 0) {
|
||||
throw new Error("Action scope name must be non-empty");
|
||||
}
|
||||
const activation: ScopeActivation = {
|
||||
scope,
|
||||
release() {
|
||||
const index = activations.indexOf(activation);
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
activations.splice(index, 1);
|
||||
commit();
|
||||
},
|
||||
};
|
||||
activations.push(activation);
|
||||
commit();
|
||||
return activation;
|
||||
},
|
||||
|
||||
getActiveScopes() {
|
||||
return activeScopes;
|
||||
},
|
||||
|
||||
depthOf(activation) {
|
||||
const index = activations.indexOf(activation);
|
||||
return index === -1 ? null : index + 1;
|
||||
},
|
||||
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { createContext, type ReactNode, useContext, useEffect, useRef, useState } from "react";
|
||||
import type { ActionHandler, ActionRegistry } from "./action-registry";
|
||||
import type { ActionScopeStore, ScopeActivation } from "./action-scope-store";
|
||||
|
||||
interface ActionRegistries {
|
||||
actions: ActionRegistry;
|
||||
scopes: ActionScopeStore;
|
||||
}
|
||||
|
||||
const ActionRegistriesContext = createContext<ActionRegistries | null>(null);
|
||||
|
||||
/**
|
||||
* The activation the surrounding surface handlers belong to. `undefined` means
|
||||
* no surface encloses them; `null` means the enclosing surface is inactive, so
|
||||
* its handlers stay unregistered rather than running unscoped.
|
||||
*/
|
||||
const EnclosingScopeContext = createContext<ScopeActivation | null | undefined>(undefined);
|
||||
|
||||
export function ActionRegistryProvider({
|
||||
actions,
|
||||
scopes,
|
||||
children,
|
||||
}: ActionRegistries & { children: ReactNode }) {
|
||||
const [value] = useState<ActionRegistries>(() => ({ actions, scopes }));
|
||||
return (
|
||||
<ActionRegistriesContext.Provider value={value}>{children}</ActionRegistriesContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function useActionRegistries(): ActionRegistries {
|
||||
const registries = useContext(ActionRegistriesContext);
|
||||
if (!registries) {
|
||||
throw new Error("Action hooks must be used within ActionRegistryProvider");
|
||||
}
|
||||
return registries;
|
||||
}
|
||||
|
||||
export function useActionRegistry(): ActionRegistry {
|
||||
return useActionRegistries().actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates `name` while `active` holds, as the innermost scope. Returns the
|
||||
* activation, or `null` while inactive. Pass it to `ActionScope` or to
|
||||
* `useActionHandler`'s `scope` option.
|
||||
*/
|
||||
export function useActionScope(name: string, options: { active: boolean }): ScopeActivation | null {
|
||||
const { scopes } = useActionRegistries();
|
||||
const [activation, setActivation] = useState<ScopeActivation | null>(null);
|
||||
const { active } = options;
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const next = scopes.activate(name);
|
||||
setActivation(next);
|
||||
return () => {
|
||||
next.release();
|
||||
setActivation((current) => (current === next ? null : current));
|
||||
};
|
||||
}, [scopes, name, active]);
|
||||
return active ? activation : null;
|
||||
}
|
||||
|
||||
/** Puts every `useActionHandler` below it in `activation`. */
|
||||
export function ActionScope({
|
||||
activation,
|
||||
children,
|
||||
}: {
|
||||
activation: ScopeActivation | null;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<EnclosingScopeContext.Provider value={activation}>{children}</EnclosingScopeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export interface UseActionHandlerOptions {
|
||||
/**
|
||||
* Read on every dispatch. `false` leaves the action to the next handler, and
|
||||
* hides this one from badges, Command Center and iOS claims.
|
||||
*/
|
||||
enabled?: boolean | (() => boolean);
|
||||
/** Overrides the enclosing `ActionScope`. `null` keeps the handler unregistered. */
|
||||
scope?: ScopeActivation | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches `handler` to each of `actionIds` for as long as the component is
|
||||
* mounted. It registers once per scope activation and reads the latest
|
||||
* `handler` and `enabled` on each dispatch, so re-renders never reorder it.
|
||||
*/
|
||||
export function useActionHandler(
|
||||
actionIds: string | readonly string[],
|
||||
handler: ActionHandler,
|
||||
options: UseActionHandlerOptions = {},
|
||||
): void {
|
||||
const actions = useActionRegistry();
|
||||
const enclosingScope = useContext(EnclosingScopeContext);
|
||||
const scope = options.scope !== undefined ? options.scope : enclosingScope;
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
const enabledRef = useRef(options.enabled);
|
||||
enabledRef.current = options.enabled;
|
||||
const idsKey = typeof actionIds === "string" ? actionIds : actionIds.join(" ");
|
||||
|
||||
useEffect(() => {
|
||||
if (scope === null || idsKey === "") return;
|
||||
const isEnabled = () => {
|
||||
const enabled = enabledRef.current;
|
||||
if (enabled === undefined) return true;
|
||||
return typeof enabled === "function" ? enabled() : enabled;
|
||||
};
|
||||
const disposers = idsKey.split(" ").map((actionId) =>
|
||||
actions.registerHandler(actionId, (invocation) => handlerRef.current(invocation), {
|
||||
...(scope ? { scope } : {}),
|
||||
enabled: isEnabled,
|
||||
}),
|
||||
);
|
||||
return () => {
|
||||
for (const dispose of disposers) dispose();
|
||||
};
|
||||
}, [actions, scope, idsKey]);
|
||||
}
|
||||
@@ -109,6 +109,7 @@ 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";
|
||||
@@ -120,7 +121,10 @@ 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 { CoreActionsProvider, useAppShellActions } from "@/core-actions";
|
||||
import {
|
||||
KeyboardActionDispatcherProvider,
|
||||
useKeyboardActionDispatcher,
|
||||
} from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { polyfillCrypto } from "@/polyfills/crypto";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
@@ -384,6 +388,7 @@ 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);
|
||||
@@ -415,19 +420,34 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
const chromeEnabled = chromeEnabledOverride ?? daemons.length > 0;
|
||||
const hasMountedDesktopSidebar = useLatchedBoolean(chromeEnabled);
|
||||
const toggleAgentList = isCompactLayout ? toggleMobileAgentList : toggleDesktopAgentList;
|
||||
const toggleDesktopSidebars = useCallback(() => {
|
||||
// The focused workspace owns its layout key, its checkout, and therefore the
|
||||
// only correct answer to "is the explorer open". Let it decide when there is
|
||||
// one: the pathname alone cannot identify the active workspace, because
|
||||
// desktop cold-starts at "/" and restores the workspace from route params.
|
||||
if (keyboardActionDispatcher.dispatch({ id: "sidebar.toggle.both", scope: "sidebar" })) {
|
||||
return;
|
||||
}
|
||||
// Off a workspace route there is no explorer — only the agent list.
|
||||
toggleAgentList();
|
||||
}, [keyboardActionDispatcher, toggleAgentList]);
|
||||
// TODO: stop matching pathname here as a branch. `chromeEnabled` should not
|
||||
// conflate workspace/project-specific chrome (sidebar, mobile gesture) with
|
||||
// global concerns like keyboard shortcuts. Split those out so settings (and
|
||||
// other non-workspace routes) don't need a special-case to keep shortcuts alive.
|
||||
const keyboardShortcutsEnabled = chromeEnabled || pathname.startsWith("/settings");
|
||||
|
||||
useAppShellActions({ isMobile: isCompactLayout, toggleAgentList, cycleTheme });
|
||||
useKeyboardShortcuts({
|
||||
enabled: keyboardShortcutsEnabled,
|
||||
isMobile: isCompactLayout,
|
||||
isWorkspaceFocusModeEnabled,
|
||||
toggleAgentList,
|
||||
toggleBothSidebars: toggleDesktopSidebars,
|
||||
exitFocusMode,
|
||||
cycleTheme,
|
||||
});
|
||||
|
||||
useActiveWorktreeNewAction();
|
||||
useGlobalNewWorkspaceAction();
|
||||
|
||||
const activeWorkspace = useActiveWorkspaceSelection();
|
||||
@@ -994,7 +1014,7 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
|
||||
|
||||
function RootProviders({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<CoreActionsProvider>
|
||||
<KeyboardActionDispatcherProvider>
|
||||
<WindowLayoutProvider>
|
||||
<WindowChromeProvider>
|
||||
<KeyboardProvider>
|
||||
@@ -1004,7 +1024,7 @@ function RootProviders({ children }: { children: ReactNode }) {
|
||||
</KeyboardProvider>
|
||||
</WindowChromeProvider>
|
||||
</WindowLayoutProvider>
|
||||
</CoreActionsProvider>
|
||||
</KeyboardActionDispatcherProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,11 +20,11 @@ import {
|
||||
getWorkspaceSelectionKey,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
type RetainedWorkspaceSelection,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
} from "@/screens/workspace/workspace-deck-retention";
|
||||
import { workspaceDeckRetentionLimit } from "@/constants/resource-budget";
|
||||
import {
|
||||
decodeWorkspaceIdFromPathSegment,
|
||||
parseWorkspaceOpenIntent,
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
stripHostWorkspaceRouteEchoSearchFromBrowserUrlAfterCommit,
|
||||
} from "@/utils/host-route-browser";
|
||||
import { prepareWorkspaceTab } from "@/utils/prepare-workspace-tab";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
|
||||
function getParamValue(value: string | string[] | undefined): string {
|
||||
@@ -167,7 +167,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: retainedSelections,
|
||||
activeSelection,
|
||||
now: reconciliationNow,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
[activeSelection, reconciliationNow, retainedSelections],
|
||||
);
|
||||
@@ -204,7 +204,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: current,
|
||||
activeSelection,
|
||||
now: Date.now(),
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
);
|
||||
}, expirationDelay + 1);
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { usesCompactBottomSheet } from "@/constants/presentation";
|
||||
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
|
||||
import { useProjects } from "@/hooks/use-projects";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||
@@ -70,7 +71,7 @@ import {
|
||||
navigateToWorkspace,
|
||||
useActiveWorkspaceSelection,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { useActionRegistry } from "@/actions";
|
||||
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import {
|
||||
clearCommandCenterFocusRestoreElement,
|
||||
takeCommandCenterFocusRestoreElement,
|
||||
@@ -363,7 +364,7 @@ function useCommandCenterState(
|
||||
interaction: CommandCenterInteraction,
|
||||
getInputHandle: () => EditingTextInputHandle | null,
|
||||
): CommandCenterState {
|
||||
const actionRegistry = useActionRegistry();
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const { t } = useTranslation();
|
||||
const open = useKeyboardShortcutsStore((state) => state.commandCenterOpen);
|
||||
const requestedTab = useKeyboardShortcutsStore((state) => state.commandCenterTab);
|
||||
@@ -592,10 +593,11 @@ function useCommandCenterState(
|
||||
const cancel = focusWithRetries({
|
||||
focus: () => element.focus(),
|
||||
isFocused: () => typeof document !== "undefined" && document.activeElement === element,
|
||||
onTimeout: () => actionRegistry.dispatch("paseo/message-input.focus"),
|
||||
onTimeout: () =>
|
||||
keyboardActionDispatcher.dispatch({ id: "message-input.focus", scope: "message-input" }),
|
||||
});
|
||||
return cancel;
|
||||
}, [actionRegistry, getInputHandle, open]);
|
||||
}, [getInputHandle, keyboardActionDispatcher, open]);
|
||||
|
||||
return {
|
||||
open,
|
||||
@@ -990,7 +992,7 @@ export function CommandCenter() {
|
||||
const bottomSheetListRef = useRef<BottomSheetFlatListMethods>(null);
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const bottomSheetInputRef = useRef<EditingTextInputHandle>(null);
|
||||
const showBottomSheet = isCompact && isNative;
|
||||
const showBottomSheet = isCompact && usesCompactBottomSheet;
|
||||
const getInputHandle = useCallback(
|
||||
() => (showBottomSheet ? bottomSheetInputRef.current : inputRef.current),
|
||||
[showBottomSheet],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { usesDesktopBindings } from "@/keyboard";
|
||||
import { useMemo } from "react";
|
||||
import { router, type Href } from "expo-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -20,11 +21,12 @@ 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 { useActionRegistry } from "@/actions";
|
||||
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard";
|
||||
import { displayKeysFor, getDisplayPlatform, useKeybindings } from "@/keyboard";
|
||||
import { resolveShortcutKeysForAction } from "@/keyboard/keyboard-shortcuts";
|
||||
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
@@ -38,6 +40,7 @@ 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";
|
||||
@@ -122,11 +125,11 @@ function SwitchWorkspaceIcon({ size }: CommandCenterIconProps) {
|
||||
}
|
||||
|
||||
export function CommandCenterRootActions() {
|
||||
const actionRegistry = useActionRegistry();
|
||||
const bindings = useKeybindings();
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
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();
|
||||
@@ -144,10 +147,11 @@ 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",
|
||||
@@ -166,7 +170,8 @@ 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: shortcutKeys("paseo/project.open"),
|
||||
shortcutKeys:
|
||||
resolveShortcutKeysForAction("new-agent", overrides, shortcutPlatform) ?? undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -177,14 +182,15 @@ export function CommandCenterRootActions() {
|
||||
keywords: ["new", "workspace", "worktree", "branch"],
|
||||
visibility: "always",
|
||||
run: () => {
|
||||
actionRegistry.dispatch("paseo/workspace.new");
|
||||
keyboardActionDispatcher.dispatch({ id: "workspace.new", scope: "sidebar" });
|
||||
},
|
||||
presentation: {
|
||||
kind: "action",
|
||||
title: t("sidebar.actions.newWorkspace"),
|
||||
sectionTitle: t("shell.commandCenter.actions"),
|
||||
icon: PlusIcon,
|
||||
shortcutKeys: shortcutKeys("paseo/workspace.new"),
|
||||
shortcutKeys:
|
||||
resolveShortcutKeysForAction("new-workspace", overrides, shortcutPlatform) ?? undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -203,7 +209,9 @@ export function CommandCenterRootActions() {
|
||||
title: t("settings.shortcuts.help.switchRecentWorkspace"),
|
||||
sectionTitle: t("shell.commandCenter.actions"),
|
||||
icon: SwitchWorkspaceIcon,
|
||||
shortcutKeys: shortcutKeys("paseo/workspace.switcher.next"),
|
||||
shortcutKeys:
|
||||
resolveShortcutKeysForAction("workspace-switcher-next", overrides, shortcutPlatform) ??
|
||||
undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -294,7 +302,9 @@ export function CommandCenterRootActions() {
|
||||
title: t("sidebar.actions.settings"),
|
||||
sectionTitle: t("shell.commandCenter.actions"),
|
||||
icon: SettingsIcon,
|
||||
shortcutKeys: shortcutKeys("paseo/settings.toggle"),
|
||||
shortcutKeys:
|
||||
resolveShortcutKeysForAction("toggle-settings", overrides, shortcutPlatform) ??
|
||||
undefined,
|
||||
},
|
||||
},
|
||||
// Toggle left sidebar is global: it calls the panel store directly and works on every route.
|
||||
@@ -319,7 +329,9 @@ export function CommandCenterRootActions() {
|
||||
title: t("settings.shortcuts.help.toggleLeftSidebar"),
|
||||
sectionTitle: t("shell.commandCenter.actions"),
|
||||
icon: PanelLeftIcon,
|
||||
shortcutKeys: shortcutKeys("paseo/sidebar.toggle.left"),
|
||||
shortcutKeys:
|
||||
resolveShortcutKeysForAction("toggle-left-sidebar", overrides, shortcutPlatform) ??
|
||||
undefined,
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -364,7 +376,9 @@ export function CommandCenterRootActions() {
|
||||
title: t("sidebar.help.shortcuts"),
|
||||
sectionTitle: t("shell.commandCenter.actions"),
|
||||
icon: KeyboardIcon,
|
||||
shortcutKeys: shortcutKeys("paseo/shortcuts-dialog.toggle"),
|
||||
shortcutKeys:
|
||||
resolveShortcutKeysForAction("show-shortcuts", overrides, shortcutPlatform) ??
|
||||
undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -388,15 +402,16 @@ export function CommandCenterRootActions() {
|
||||
browserHostLabel,
|
||||
groupMode,
|
||||
homeRoute,
|
||||
actionRegistry,
|
||||
bindings,
|
||||
keyboardActionDispatcher,
|
||||
openAddProject,
|
||||
openImportSession,
|
||||
overrides,
|
||||
schedulesRoute,
|
||||
sessionsRoute,
|
||||
setGroupMode,
|
||||
setShortcutsDialogOpen,
|
||||
settingsRoute,
|
||||
shortcutPlatform,
|
||||
shortcutsAvailable,
|
||||
t,
|
||||
toast,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { GitAction, GitActions } from "@/git/policy";
|
||||
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import {
|
||||
buildWorkspaceCommandCenterContributions,
|
||||
buildWorkspaceFileSearchContribution,
|
||||
@@ -22,14 +23,14 @@ function gitAction(id: GitAction["id"], label: string): GitAction {
|
||||
function source(gitActions: GitActions): {
|
||||
value: WorkspaceCommandCenterSource;
|
||||
runGitActions: GitAction[];
|
||||
dispatched: string[];
|
||||
dispatched: KeyboardActionDefinition[];
|
||||
copiedPaths: number;
|
||||
copiedBranchNames: number;
|
||||
archivedWorkspaces: number;
|
||||
toggledLabels: Array<{ name: string; assigned: boolean }>;
|
||||
} {
|
||||
const runGitActions: GitAction[] = [];
|
||||
const dispatched: string[] = [];
|
||||
const dispatched: KeyboardActionDefinition[] = [];
|
||||
const toggledLabels: Array<{ name: string; assigned: boolean }> = [];
|
||||
const counters = { copiedPaths: 0, copiedBranchNames: 0, archivedWorkspaces: 0 };
|
||||
return {
|
||||
@@ -81,7 +82,7 @@ function source(gitActions: GitActions): {
|
||||
labelsGroup: "Labels",
|
||||
},
|
||||
icons: {},
|
||||
shortcutKeys: () => undefined,
|
||||
shortcuts: {},
|
||||
capabilities: {
|
||||
canSplitPanes: true,
|
||||
canOpenBrowserTabs: true,
|
||||
@@ -95,7 +96,7 @@ function source(gitActions: GitActions): {
|
||||
currentBranch: null,
|
||||
isPinned: false,
|
||||
labelCatalog: null,
|
||||
dispatch: (actionId) => dispatched.push(actionId),
|
||||
dispatch: (action) => dispatched.push(action),
|
||||
runGitAction: (action) => runGitActions.push(action),
|
||||
archiveWorkspace: () => {
|
||||
counters.archivedWorkspaces += 1;
|
||||
@@ -180,7 +181,9 @@ describe("workspace command center contributions", () => {
|
||||
.find((item) => item.id === "tab:reveal-in-files")
|
||||
?.run?.();
|
||||
|
||||
expect(fixture.dispatched).toEqual(["paseo/workspace.tab.reveal-in-files"]);
|
||||
expect(fixture.dispatched).toEqual([
|
||||
{ id: "workspace.tab.reveal-in-files", scope: "workspace" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("omits archive while the workspace cannot be archived", () => {
|
||||
@@ -286,15 +289,21 @@ describe("workspace command center contributions", () => {
|
||||
expect(contributions.some((item) => item.id === "workspace:copy-path")).toBe(true);
|
||||
});
|
||||
|
||||
it("dispatches every tab and pane command through the action registry", () => {
|
||||
it("dispatches every tab and pane command to the workspace scope", () => {
|
||||
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);
|
||||
expect(fixture.dispatched).toContain("paseo/workspace.rename");
|
||||
expect(fixture.dispatched).toContain("paseo/sidebar.toggle.right");
|
||||
// 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);
|
||||
});
|
||||
|
||||
it("keeps workspace creation commands available outside Git", () => {
|
||||
@@ -310,7 +319,7 @@ describe("workspace command center contributions", () => {
|
||||
expect(contributions.some((item) => item.id.startsWith("git:"))).toBe(false);
|
||||
});
|
||||
|
||||
it("dispatches rename", () => {
|
||||
it("dispatches rename to the workspace scope", () => {
|
||||
const fixture = source({ primary: null, secondary: [], menu: [] });
|
||||
const contributions = buildWorkspaceCommandCenterContributions(fixture.value);
|
||||
|
||||
@@ -318,7 +327,7 @@ describe("workspace command center contributions", () => {
|
||||
expect(rename?.presentation).toMatchObject({ title: "Rename workspace" });
|
||||
rename?.run?.();
|
||||
|
||||
expect(fixture.dispatched).toEqual(["paseo/workspace.rename"]);
|
||||
expect(fixture.dispatched).toEqual([{ id: "workspace.rename", scope: "workspace" }]);
|
||||
});
|
||||
|
||||
it("labels active tab rename by the active tab kind", () => {
|
||||
@@ -379,7 +388,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(["paseo/workspace.pin"]);
|
||||
expect(unpinned.dispatched).toEqual([{ id: "workspace.pin", scope: "sidebar" }]);
|
||||
|
||||
const pinned = source({ primary: null, secondary: [], menu: [] });
|
||||
pinned.value.capabilities.canPin = true;
|
||||
@@ -412,7 +421,7 @@ describe("workspace command center contributions", () => {
|
||||
.find((item) => item.id === "workspace:show-setup")
|
||||
?.run?.();
|
||||
|
||||
expect(withSetup.dispatched).toEqual(["paseo/workspace.setup.show"]);
|
||||
expect(withSetup.dispatched).toEqual([{ id: "workspace.setup.show", scope: "workspace" }]);
|
||||
});
|
||||
|
||||
// Regression guard for the registration split: these two are handled only by workspace-screen.tsx
|
||||
@@ -427,8 +436,8 @@ describe("workspace command center contributions", () => {
|
||||
contributions.find((item) => item.id === "workspace:toggle-focus-mode")?.run?.();
|
||||
|
||||
expect(fixture.dispatched).toEqual([
|
||||
"paseo/sidebar.toggle.right",
|
||||
"paseo/workspace.focus.toggle",
|
||||
{ id: "sidebar.toggle.right", scope: "sidebar" },
|
||||
{ id: "workspace.focus.toggle", scope: "workspace" },
|
||||
]);
|
||||
for (const contribution of contributions) {
|
||||
expect(contribution.group).toBe("workspace");
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
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. */
|
||||
@@ -132,12 +134,27 @@ 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;
|
||||
/** The keys a row's badge shows for `actionId`, if it has any. */
|
||||
shortcutKeys(actionId: string): ShortcutKey[][] | undefined;
|
||||
shortcuts: WorkspaceCommandCenterShortcuts;
|
||||
capabilities: {
|
||||
canSplitPanes: boolean;
|
||||
canOpenBrowserTabs: boolean;
|
||||
@@ -158,7 +175,7 @@ export interface WorkspaceCommandCenterSource {
|
||||
* before the catalog has loaded — omits the whole group rather than showing it empty.
|
||||
*/
|
||||
labelCatalog: readonly WorkspaceCommandCenterLabelChoice[] | null;
|
||||
dispatch(actionId: string): void;
|
||||
dispatch(action: KeyboardActionDefinition): void;
|
||||
runGitAction(action: GitAction): void;
|
||||
/** Null while the workspace cannot be archived. A Git workspace archives through `gitActions`. */
|
||||
archiveWorkspace: (() => void) | null;
|
||||
@@ -187,9 +204,7 @@ function buildGitContribution(
|
||||
sectionTitle: source.labels.section,
|
||||
icon: source.icons.git?.(action),
|
||||
shortcutKeys:
|
||||
action.id === "archive-workspace"
|
||||
? source.shortcutKeys("paseo/workspace.archive")
|
||||
: undefined,
|
||||
action.id === "archive-workspace" ? source.shortcuts.archiveWorkspace : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -201,7 +216,8 @@ function buildWorkspaceAction(input: {
|
||||
title: string;
|
||||
keywords: readonly string[];
|
||||
icon?: CommandCenterIcon;
|
||||
actionId: string;
|
||||
shortcutKeys?: ShortcutKey[][];
|
||||
action: KeyboardActionDefinition;
|
||||
visibility: "always" | "query";
|
||||
}): CommandCenterContribution {
|
||||
return {
|
||||
@@ -211,13 +227,13 @@ function buildWorkspaceAction(input: {
|
||||
rank: input.rank,
|
||||
keywords: input.keywords,
|
||||
visibility: input.visibility,
|
||||
run: () => input.source.dispatch(input.actionId),
|
||||
run: () => input.source.dispatch(input.action),
|
||||
presentation: {
|
||||
kind: "action",
|
||||
title: input.title,
|
||||
sectionTitle: input.source.labels.section,
|
||||
icon: input.icon,
|
||||
shortcutKeys: input.source.shortcutKeys(input.actionId),
|
||||
shortcutKeys: input.shortcutKeys,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -257,7 +273,12 @@ function buildPanelContributions(
|
||||
title: source.labels.openPanel(panel.name, "supporting"),
|
||||
keywords: ["open", panel.target, "tab", "supporting"],
|
||||
icon: panel.icon,
|
||||
actionId: `paseo/workspace.tab.open.${panel.target}`,
|
||||
action: {
|
||||
id: "workspace.tab.open",
|
||||
scope: "workspace",
|
||||
target: panel.target,
|
||||
placement: "supporting",
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!source.capabilities.canSplitPanes) continue;
|
||||
@@ -271,7 +292,12 @@ function buildPanelContributions(
|
||||
title: source.labels.openPanel(panel.name, placement),
|
||||
keywords: ["open", panel.target, "tab", placement, "pane"],
|
||||
icon: panel.icon,
|
||||
actionId: `paseo/workspace.tab.open.${panel.target}.${placement}`,
|
||||
action: {
|
||||
id: "workspace.tab.open",
|
||||
scope: "workspace",
|
||||
target: panel.target,
|
||||
placement,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -290,7 +316,8 @@ function buildActiveTabContributions(
|
||||
title: source.labels.previousTab,
|
||||
keywords: ["tab", "previous", "switch", "navigate"],
|
||||
icon: source.icons.previousTab,
|
||||
actionId: "paseo/workspace.tab.previous",
|
||||
shortcutKeys: source.shortcuts.previousTab,
|
||||
action: { id: "workspace.tab.navigate-relative", scope: "workspace", delta: -1 },
|
||||
}),
|
||||
buildQueryAction(source, {
|
||||
id: "tab:next",
|
||||
@@ -298,7 +325,8 @@ function buildActiveTabContributions(
|
||||
title: source.labels.nextTab,
|
||||
keywords: ["tab", "next", "switch", "navigate"],
|
||||
icon: source.icons.nextTab,
|
||||
actionId: "paseo/workspace.tab.next",
|
||||
shortcutKeys: source.shortcuts.nextTab,
|
||||
action: { id: "workspace.tab.navigate-relative", scope: "workspace", delta: 1 },
|
||||
}),
|
||||
buildQueryAction(source, {
|
||||
id: "tab:close-current",
|
||||
@@ -306,7 +334,8 @@ function buildActiveTabContributions(
|
||||
title: source.labels.closeCurrentTab,
|
||||
keywords: ["tab", "close", "current"],
|
||||
icon: source.icons.close,
|
||||
actionId: "paseo/workspace.tab.close-current",
|
||||
shortcutKeys: source.shortcuts.closeCurrentTab,
|
||||
action: { id: "workspace.tab.close-current", scope: "workspace" },
|
||||
}),
|
||||
];
|
||||
if (source.activeTabKind === "agent" || source.activeTabKind === "terminal") {
|
||||
@@ -320,7 +349,7 @@ function buildActiveTabContributions(
|
||||
: source.labels.renameTerminal,
|
||||
keywords: ["tab", "rename", "current"],
|
||||
icon: source.icons.rename,
|
||||
actionId: "paseo/workspace.tab.rename-current",
|
||||
action: { id: "workspace.tab.rename-current", scope: "workspace" },
|
||||
}),
|
||||
buildQueryAction(source, {
|
||||
id: "tab:copy-id",
|
||||
@@ -331,7 +360,7 @@ function buildActiveTabContributions(
|
||||
: source.labels.copyTerminalId,
|
||||
keywords: ["tab", "copy", "id"],
|
||||
icon: source.icons.copy,
|
||||
actionId: "paseo/workspace.tab.copy-id",
|
||||
action: { id: "workspace.tab.copy-id", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -343,7 +372,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.reloadAgent,
|
||||
keywords: ["tab", "agent", "reload"],
|
||||
icon: source.icons.reload,
|
||||
actionId: "paseo/workspace.tab.reload-current",
|
||||
action: { id: "workspace.tab.reload-current", scope: "workspace" },
|
||||
}),
|
||||
buildQueryAction(source, {
|
||||
id: "tab:copy-resume-command",
|
||||
@@ -351,7 +380,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.copyResumeCommand,
|
||||
keywords: ["tab", "agent", "copy", "resume", "command"],
|
||||
icon: source.icons.copy,
|
||||
actionId: "paseo/workspace.tab.copy-resume-command",
|
||||
action: { id: "workspace.tab.copy-resume-command", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -363,7 +392,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.copyFilePath,
|
||||
keywords: ["tab", "file", "copy", "path"],
|
||||
icon: source.icons.copy,
|
||||
actionId: "paseo/workspace.tab.copy-file-path",
|
||||
action: { id: "workspace.tab.copy-file-path", scope: "workspace" },
|
||||
}),
|
||||
buildQueryAction(source, {
|
||||
id: "tab:reveal-in-files",
|
||||
@@ -371,7 +400,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.revealInFiles,
|
||||
keywords: ["tab", "file", "reveal", "files", "explorer"],
|
||||
icon: source.icons.files,
|
||||
actionId: "paseo/workspace.tab.reveal-in-files",
|
||||
action: { id: "workspace.tab.reveal-in-files", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -383,7 +412,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.closeTabsLeft,
|
||||
keywords: ["tab", "close", "left"],
|
||||
icon: source.icons.close,
|
||||
actionId: "paseo/workspace.tab.close-left",
|
||||
action: { id: "workspace.tab.close-left", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -395,7 +424,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.closeTabsRight,
|
||||
keywords: ["tab", "close", "right"],
|
||||
icon: source.icons.close,
|
||||
actionId: "paseo/workspace.tab.close-right",
|
||||
action: { id: "workspace.tab.close-right", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -407,7 +436,7 @@ function buildActiveTabContributions(
|
||||
title: source.labels.closeOtherTabs,
|
||||
keywords: ["tab", "close", "others"],
|
||||
icon: source.icons.close,
|
||||
actionId: "paseo/workspace.tab.close-others",
|
||||
action: { id: "workspace.tab.close-others", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -420,8 +449,9 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
rank: number;
|
||||
title: string;
|
||||
keywords: string[];
|
||||
actionId: string;
|
||||
action: KeyboardActionDefinition;
|
||||
icon?: CommandCenterIcon;
|
||||
shortcutKeys?: ShortcutKey[][];
|
||||
}> = [
|
||||
{
|
||||
id: "pane:split-right",
|
||||
@@ -429,7 +459,8 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.splitRight,
|
||||
keywords: ["split", "pane", "vertical"],
|
||||
icon: source.icons.splitRight,
|
||||
actionId: "paseo/workspace.pane.split.right",
|
||||
shortcutKeys: source.shortcuts.splitRight,
|
||||
action: { id: "workspace.pane.split.right", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:split-down",
|
||||
@@ -437,7 +468,8 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.splitDown,
|
||||
keywords: ["split", "pane", "horizontal"],
|
||||
icon: source.icons.splitDown,
|
||||
actionId: "paseo/workspace.pane.split.down",
|
||||
shortcutKeys: source.shortcuts.splitDown,
|
||||
action: { id: "workspace.pane.split.down", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:focus-left",
|
||||
@@ -445,7 +477,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.focusPaneLeft,
|
||||
keywords: ["pane", "focus", "left"],
|
||||
icon: source.icons.focusPane,
|
||||
actionId: "paseo/workspace.pane.focus.left",
|
||||
action: { id: "workspace.pane.focus.left", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:focus-right",
|
||||
@@ -453,7 +485,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.focusPaneRight,
|
||||
keywords: ["pane", "focus", "right"],
|
||||
icon: source.icons.focusPane,
|
||||
actionId: "paseo/workspace.pane.focus.right",
|
||||
action: { id: "workspace.pane.focus.right", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:focus-up",
|
||||
@@ -461,7 +493,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.focusPaneUp,
|
||||
keywords: ["pane", "focus", "up"],
|
||||
icon: source.icons.focusPane,
|
||||
actionId: "paseo/workspace.pane.focus.up",
|
||||
action: { id: "workspace.pane.focus.up", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:focus-down",
|
||||
@@ -469,7 +501,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.focusPaneDown,
|
||||
keywords: ["pane", "focus", "down"],
|
||||
icon: source.icons.focusPane,
|
||||
actionId: "paseo/workspace.pane.focus.down",
|
||||
action: { id: "workspace.pane.focus.down", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:move-tab-left",
|
||||
@@ -477,7 +509,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.moveTabLeft,
|
||||
keywords: ["pane", "tab", "move", "left"],
|
||||
icon: source.icons.moveTab,
|
||||
actionId: "paseo/workspace.pane.move-tab.left",
|
||||
action: { id: "workspace.pane.move-tab.left", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:move-tab-right",
|
||||
@@ -485,7 +517,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.moveTabRight,
|
||||
keywords: ["pane", "tab", "move", "right"],
|
||||
icon: source.icons.moveTab,
|
||||
actionId: "paseo/workspace.pane.move-tab.right",
|
||||
action: { id: "workspace.pane.move-tab.right", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:move-tab-up",
|
||||
@@ -493,7 +525,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.moveTabUp,
|
||||
keywords: ["pane", "tab", "move", "up"],
|
||||
icon: source.icons.moveTab,
|
||||
actionId: "paseo/workspace.pane.move-tab.up",
|
||||
action: { id: "workspace.pane.move-tab.up", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:move-tab-down",
|
||||
@@ -501,7 +533,7 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.moveTabDown,
|
||||
keywords: ["pane", "tab", "move", "down"],
|
||||
icon: source.icons.moveTab,
|
||||
actionId: "paseo/workspace.pane.move-tab.down",
|
||||
action: { id: "workspace.pane.move-tab.down", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:close",
|
||||
@@ -509,7 +541,8 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.closePane,
|
||||
keywords: ["pane", "close"],
|
||||
icon: source.icons.close,
|
||||
actionId: "paseo/workspace.pane.close",
|
||||
shortcutKeys: source.shortcuts.closePane,
|
||||
action: { id: "workspace.pane.close", scope: "workspace" },
|
||||
},
|
||||
{
|
||||
id: "pane:focus-mode-toggle",
|
||||
@@ -517,7 +550,8 @@ function buildPaneContributions(source: WorkspaceCommandCenterSource): CommandCe
|
||||
title: source.labels.toggleFocusMode,
|
||||
keywords: ["pane", "focus", "mode", "toggle"],
|
||||
icon: source.icons.focusMode,
|
||||
actionId: "paseo/workspace.focus.toggle",
|
||||
shortcutKeys: source.shortcuts.toggleFocusMode,
|
||||
action: { id: "workspace.focus.toggle", scope: "workspace" },
|
||||
},
|
||||
];
|
||||
return paneActions.map((action) => buildQueryAction(source, action));
|
||||
@@ -563,7 +597,8 @@ function buildCreationContributions(
|
||||
title: source.labels.newAgent,
|
||||
keywords: ["tab", "new", "agent", "chat"],
|
||||
icon: source.icons.newAgent,
|
||||
actionId: "paseo/workspace.tab.target.agent",
|
||||
shortcutKeys: source.shortcuts.newAgent,
|
||||
action: { id: "workspace.agent.new", scope: "workspace" },
|
||||
visibility: "always",
|
||||
}),
|
||||
];
|
||||
@@ -576,7 +611,8 @@ function buildCreationContributions(
|
||||
title: source.labels.newTerminal,
|
||||
keywords: ["terminal", "shell", "console"],
|
||||
icon: source.icons.newTerminal,
|
||||
actionId: "paseo/workspace.terminal.new",
|
||||
shortcutKeys: source.shortcuts.newTerminal,
|
||||
action: { id: "workspace.terminal.new", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
if (source.capabilities.canOpenBrowserTabs) {
|
||||
@@ -587,7 +623,7 @@ function buildCreationContributions(
|
||||
title: source.labels.newBrowser,
|
||||
keywords: ["browser", "web", "preview"],
|
||||
icon: source.icons.newBrowser,
|
||||
actionId: "paseo/workspace.tab.target.browser",
|
||||
action: { id: "workspace.browser.new", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -618,7 +654,7 @@ export function buildWorkspaceCommandCenterContributions(
|
||||
title: source.labels.archiveWorkspace,
|
||||
keywords: ["archive", "workspace"],
|
||||
icon: source.icons.archiveWorkspace,
|
||||
shortcutKeys: source.shortcutKeys("paseo/workspace.archive"),
|
||||
shortcutKeys: source.shortcuts.archiveWorkspace,
|
||||
run: source.archiveWorkspace,
|
||||
visibility: "query",
|
||||
}),
|
||||
@@ -634,7 +670,8 @@ 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,
|
||||
actionId: "paseo/workspace.pin",
|
||||
shortcutKeys: source.shortcuts.pinWorkspace,
|
||||
action: { id: "workspace.pin", scope: "sidebar" },
|
||||
visibility: "always",
|
||||
}),
|
||||
);
|
||||
@@ -648,7 +685,7 @@ export function buildWorkspaceCommandCenterContributions(
|
||||
title: source.labels.rename,
|
||||
keywords: ["rename", "title", "name", "label"],
|
||||
icon: source.icons.rename,
|
||||
actionId: "paseo/workspace.rename",
|
||||
action: { id: "workspace.rename", scope: "workspace" },
|
||||
visibility: "query",
|
||||
}),
|
||||
buildWorkspaceCallback({
|
||||
@@ -688,7 +725,7 @@ export function buildWorkspaceCommandCenterContributions(
|
||||
title: source.labels.showSetup,
|
||||
keywords: ["setup", "provision", "install", "bootstrap"],
|
||||
icon: source.icons.showSetup,
|
||||
actionId: "paseo/workspace.setup.show",
|
||||
action: { id: "workspace.setup.show", scope: "workspace" },
|
||||
visibility: "query",
|
||||
}),
|
||||
);
|
||||
@@ -707,7 +744,8 @@ export function buildWorkspaceCommandCenterContributions(
|
||||
title: source.labels.toggleExplorerSidebar,
|
||||
keywords: ["toggle", "sidebar", "explorer", "files", "changes"],
|
||||
icon: source.icons.explorerSidebar,
|
||||
actionId: "paseo/sidebar.toggle.right",
|
||||
shortcutKeys: source.shortcuts.toggleExplorerSidebar,
|
||||
action: { id: "sidebar.toggle.right", scope: "sidebar" },
|
||||
visibility: "query",
|
||||
}),
|
||||
);
|
||||
@@ -724,7 +762,8 @@ export function buildWorkspaceCommandCenterContributions(
|
||||
title: source.labels.toggleFocusMode,
|
||||
keywords: ["toggle", "focus", "zen", "distraction", "fullscreen"],
|
||||
icon: source.icons.toggleFocusMode,
|
||||
actionId: "paseo/workspace.focus.toggle",
|
||||
shortcutKeys: source.shortcuts.toggleFocusMode,
|
||||
action: { id: "workspace.focus.toggle", scope: "workspace" },
|
||||
visibility: "query",
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { displayKeysFor, getDisplayPlatform, useKeybindings } from "@/keyboard";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { usesDesktopBindings } from "@/keyboard";
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
@@ -31,9 +30,11 @@ 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 { useActionRegistry } from "@/actions";
|
||||
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";
|
||||
@@ -44,6 +45,7 @@ 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,
|
||||
@@ -59,7 +61,9 @@ import {
|
||||
buildWorkspaceCommandCenterContributions,
|
||||
buildWorkspaceFileSearchContribution,
|
||||
type WorkspaceCommandCenterLabelChoice,
|
||||
type WorkspaceCommandCenterShortcuts,
|
||||
} from "./workspace-contributions";
|
||||
import { resolveWorkspaceCommandCenterShortcuts } from "./workspace-shortcuts";
|
||||
|
||||
const WORKSPACE_COMMAND_CENTER_ICONS = {
|
||||
newAgent: getCommandCenterIcon(SquarePen),
|
||||
@@ -104,6 +108,11 @@ 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
|
||||
@@ -159,7 +168,7 @@ function useWorkspaceLabelCatalog(
|
||||
function useWorkspaceFileSearchAction(
|
||||
serverId: string | null,
|
||||
workspaceId: string | null,
|
||||
shortcutKeys: ShortcutKey[][] | undefined,
|
||||
shortcutKeys: WorkspaceCommandCenterShortcuts["searchFiles"],
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const actions = useMemo(
|
||||
@@ -182,8 +191,7 @@ function useWorkspaceFileSearchAction(
|
||||
}
|
||||
|
||||
export function useWorkspaceCommandCenterActions(): void {
|
||||
const actionRegistry = useActionRegistry();
|
||||
const bindings = useKeybindings();
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const { t } = useTranslation();
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
@@ -222,6 +230,7 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
fields?.setupStatus ?? null,
|
||||
supportsSetupObservation,
|
||||
);
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
const { gitActions, isGit, archiveWorkspace } = useGitActions({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId,
|
||||
@@ -250,12 +259,8 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
}, [clipboard, fields]);
|
||||
|
||||
const { labelCatalog, toggleLabel } = useWorkspaceLabelCatalog(serverId, fields);
|
||||
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 shortcuts = useMemo(() => resolveWorkspaceShortcuts(overrides), [overrides]);
|
||||
useWorkspaceFileSearchAction(serverId, workspaceId, shortcuts.searchFiles);
|
||||
|
||||
const actions = useMemo(
|
||||
() =>
|
||||
@@ -312,7 +317,7 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
archiveWorkspace: staticIcon(GIT_ACTION_ICONS.archive),
|
||||
git: (action) => staticIcon(action.icon),
|
||||
},
|
||||
shortcutKeys,
|
||||
shortcuts,
|
||||
capabilities: {
|
||||
canSplitPanes: supportsDesktopPaneSplits() && !isCompact,
|
||||
canOpenBrowserTabs: getIsElectron(),
|
||||
@@ -326,9 +331,9 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
currentBranch,
|
||||
isPinned,
|
||||
labelCatalog,
|
||||
dispatch: (actionId) => {
|
||||
dispatch: (action) => {
|
||||
clearCommandCenterFocusRestoreElement();
|
||||
actionRegistry.dispatch(actionId);
|
||||
keyboardActionDispatcher.dispatch(action);
|
||||
},
|
||||
runGitAction,
|
||||
archiveWorkspace,
|
||||
@@ -350,10 +355,10 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
isCompact,
|
||||
isGit,
|
||||
isPinned,
|
||||
actionRegistry,
|
||||
keyboardActionDispatcher,
|
||||
labelCatalog,
|
||||
runGitAction,
|
||||
shortcutKeys,
|
||||
shortcuts,
|
||||
t,
|
||||
toggleLabel,
|
||||
],
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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"]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import DraggableFlatList, {
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { useContentDrag } from "@/components/ui/content-drag";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||
import type {
|
||||
@@ -52,7 +53,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
|
||||
delayMs: HANDLE_HOLD_MS,
|
||||
slopPx: HANDLE_HOLD_SLOP_PX,
|
||||
onArm: () => {
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { usesDesktopBindings } from "@/keyboard";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -6,8 +7,12 @@ 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 { buildShortcutSections, filterShortcutHelpSections } from "@/core-actions";
|
||||
import { getDisplayPlatform, useKeybindings } from "@/keyboard";
|
||||
import {
|
||||
buildEffectiveBindings,
|
||||
buildKeyboardShortcutHelpSections,
|
||||
} from "@/keyboard/keyboard-shortcuts";
|
||||
import { filterShortcutHelpSections } from "@/keyboard/shortcut-help-search";
|
||||
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
|
||||
|
||||
const SNAP_POINTS: string[] = ["70%", "92%"];
|
||||
|
||||
@@ -18,10 +23,15 @@ export function KeyboardShortcutsDialog() {
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const shortcutOs = getShortcutOs();
|
||||
const isMac = shortcutOs === "mac";
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
// Effective bindings, so a shortcut the user unassigned lists no keys here
|
||||
// instead of advertising a default that no longer fires.
|
||||
const bindings = useKeybindings();
|
||||
const sections = useMemo(() => buildShortcutSections(bindings, getDisplayPlatform()), [bindings]);
|
||||
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],
|
||||
@@ -55,14 +65,16 @@ export function KeyboardShortcutsDialog() {
|
||||
>
|
||||
<View testID="keyboard-shortcuts-dialog-content" style={styles.content}>
|
||||
{visibleSections.map((section) => (
|
||||
<View key={section.id} style={styles.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.noteKey ? <Text style={styles.rowNote}>{t(row.noteKey)}</Text> : null}
|
||||
{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>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Animated, StyleSheet, Text, View } from "react-native";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { supportsMaskedEffects } from "@/constants/platform";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerCycle } from "./sweep";
|
||||
|
||||
@@ -60,7 +61,8 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
// Without an alpha-mask compositor the band would paint as a bare white bar.
|
||||
const measured = supportsMaskedEffects && rowSize.width > 0 && rowSize.height > 0;
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
|
||||
@@ -82,7 +82,7 @@ import { HEADER_INNER_HEIGHT, useIsCompactFormFactor } from "@/constants/layout"
|
||||
import { isNative as platformIsNative } from "@/constants/platform";
|
||||
import { useOpenAddProject } from "@/hooks/use-open-add-project";
|
||||
import { useImportSession } from "@/hooks/use-import-session";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import {
|
||||
type SidebarProjectEntry,
|
||||
type SidebarWorkspaceEntry,
|
||||
@@ -453,8 +453,8 @@ function SidebarFooter({
|
||||
handleOpenHostSettings: (serverId: string) => void;
|
||||
onBeforeNavigate?: () => void;
|
||||
}) {
|
||||
const newAgentKeys = useShortcutKeys("paseo/project.open");
|
||||
const settingsKeys = useShortcutKeys("paseo/settings.toggle");
|
||||
const newAgentKeys = useShortcutKeys("new-agent");
|
||||
const settingsKeys = useShortcutKeys("toggle-settings");
|
||||
const isCompactLayout = useIsCompactFormFactor();
|
||||
const [rowWidth, setRowWidth] = useState(0);
|
||||
const handleRowLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
|
||||
@@ -61,8 +61,13 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usesDesktopPopoverSpacing } from "@/constants/presentation";
|
||||
import {
|
||||
hasSoftwareKeyboard,
|
||||
useHardwareKeyboardPresent,
|
||||
type KeyboardInputEvent,
|
||||
} from "@/keyboard";
|
||||
import {
|
||||
buildProviderQualifiedDescription,
|
||||
buildSelectedTriggerLabel,
|
||||
@@ -105,7 +110,7 @@ const DESKTOP_PROVIDER_VIEW_BASE_HEIGHT = 80;
|
||||
const DESKTOP_MODEL_ROW_HEIGHT = 40;
|
||||
|
||||
/** Fixed picker row heights so virtualized lists can mount directly at the selected row via `getItemLayout`. */
|
||||
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
|
||||
export const MODEL_PICKER_ROW_HEIGHT = usesDesktopPopoverSpacing ? 36 : 44;
|
||||
export const MODEL_PICKER_HEADING_HEIGHT = 32;
|
||||
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
|
||||
@@ -386,7 +391,7 @@ export function useModelBrowser({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch = isWeb,
|
||||
autoFocusSearch = !hasSoftwareKeyboard,
|
||||
profiles = null,
|
||||
serverId = null,
|
||||
}: ModelBrowserInput): ModelBrowserState {
|
||||
@@ -1649,7 +1654,7 @@ function ModelSearchEmptyState() {
|
||||
// React Native Web blurs the focused input on every scroll in "on-drag" mode, including wheel
|
||||
// scrolls and the scroll that reveals an arrowed-to row. That moves focus out of search, so
|
||||
// typing stops and Enter lands on the header's Back button. Only a native keyboard needs it.
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = hasSoftwareKeyboard ? "on-drag" : "none";
|
||||
|
||||
interface ModelBrowserKeyboardBinding {
|
||||
view: ModelBrowserView;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
|
||||
interface RenderErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
/** A caught error is cleared when any of these values change, so new content renders. */
|
||||
resetKeys: readonly unknown[];
|
||||
/** The error state shown in place of the children. `retry` renders the children again. */
|
||||
renderError(error: string, retry: () => void): ReactNode;
|
||||
onError(error: unknown, componentStack: string | null | undefined): void;
|
||||
}
|
||||
|
||||
interface RenderErrorBoundaryState {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
|
||||
* which replaces the whole app.
|
||||
*/
|
||||
export class RenderErrorBoundary extends Component<
|
||||
RenderErrorBoundaryProps,
|
||||
RenderErrorBoundaryState
|
||||
> {
|
||||
state: RenderErrorBoundaryState = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: ErrorInfo): void {
|
||||
this.props.onError(error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
|
||||
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
|
||||
this.retry();
|
||||
}
|
||||
}
|
||||
|
||||
retry = (): void => {
|
||||
this.setState({ error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
|
||||
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { startResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
|
||||
describe("startResizeHandleDrag", () => {
|
||||
it("previews pointer frames and commits only the final size", () => {
|
||||
@@ -29,3 +32,14 @@ describe("startResizeHandleDrag", () => {
|
||||
expect(commit.mock.calls[0]?.[0][1]).toBeCloseTo(0.4, 10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveResizeHandleInteraction", () => {
|
||||
it("uses DOM pointer events only on fine-pointer web targets, gesture pan on fine-pointer non-web targets, and touch grip on touch targets", () => {
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: true })).toBe("web-pointer");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: false })).toBe(
|
||||
"native-pointer",
|
||||
);
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: false })).toBe("touch");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: true })).toBe("touch");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,24 @@ interface StartResizeHandleDragInput {
|
||||
commit: (sizes: number[]) => void;
|
||||
}
|
||||
|
||||
export type ResizeHandleInteraction = "web-pointer" | "native-pointer" | "touch";
|
||||
|
||||
/**
|
||||
* Selects how the resize bar is hit-tested and dragged: thin pointer bar with DOM events on a
|
||||
* fine-pointer web target, thin pointer bar with gesture pan on a fine-pointer non-web target, and a
|
||||
* wide touch target with a grip pill otherwise.
|
||||
*/
|
||||
export function resolveResizeHandleInteraction({
|
||||
finePointer,
|
||||
isWeb,
|
||||
}: {
|
||||
finePointer: boolean;
|
||||
isWeb: boolean;
|
||||
}): ResizeHandleInteraction {
|
||||
if (!finePointer) return "touch";
|
||||
return isWeb ? "web-pointer" : "native-pointer";
|
||||
}
|
||||
|
||||
export interface ResizeHandleDrag {
|
||||
move: (deltaRatio: number) => void;
|
||||
finish: () => void;
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { View, type PointerEvent as RNPointerEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { startResizeHandleDrag, type ResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
type ResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import {
|
||||
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
|
||||
@@ -48,6 +53,7 @@ export function ResizeHandle({
|
||||
}: ResizeHandleProps) {
|
||||
const { theme } = useUnistyles();
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
const interaction = resolveResizeHandleInteraction({ finePointer, isWeb });
|
||||
const pointerStatesRef = useRef(new Map<number, PointerState>());
|
||||
const touchStateRef = useRef<PointerState | null>(null);
|
||||
const cursorBeforeDragRef = useRef<string | null>(null);
|
||||
@@ -225,8 +231,12 @@ export function ResizeHandle({
|
||||
...(direction === "horizontal"
|
||||
? { left: hitAreaAlignment === "end" ? 0 : -5 }
|
||||
: { top: hitAreaAlignment === "end" ? 0 : -5 }),
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
...(isWeb
|
||||
? {
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
}
|
||||
: {}),
|
||||
} as object,
|
||||
],
|
||||
[direction, hitAreaAlignment],
|
||||
@@ -254,6 +264,32 @@ export function ResizeHandle({
|
||||
[direction, highlighted, theme.colors.foreground],
|
||||
);
|
||||
|
||||
const ariaOrientation = direction === "horizontal" ? "vertical" : "horizontal";
|
||||
const separatorHitArea =
|
||||
interaction === "web-pointer" ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
collapsable={false}
|
||||
style={interaction === "native-pointer" ? hitAreaStyle : touchHitAreaStyle}
|
||||
onPointerEnter={interaction === "native-pointer" ? handlePointerEnter : undefined}
|
||||
onPointerLeave={interaction === "native-pointer" ? handlePointerLeave : undefined}
|
||||
>
|
||||
{interaction === "touch" ? <View pointerEvents="none" style={touchGripStyle} /> : null}
|
||||
</View>
|
||||
</GestureDetector>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={handleStyle} testID={testID}>
|
||||
{highlighted && (
|
||||
@@ -263,27 +299,7 @@ export function ResizeHandle({
|
||||
testID={testID ? `${testID}-highlight` : undefined}
|
||||
/>
|
||||
)}
|
||||
{finePointer ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
collapsable={false}
|
||||
style={touchHitAreaStyle}
|
||||
>
|
||||
<View pointerEvents="none" style={touchGripStyle} />
|
||||
</View>
|
||||
</GestureDetector>
|
||||
)}
|
||||
{separatorHitArea}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -135,8 +135,9 @@ 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 "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import type { PrHint } from "@/git/use-pr-status-query";
|
||||
import {
|
||||
@@ -261,6 +262,7 @@ interface ProjectHeaderRowProps {
|
||||
chevron: "expand" | "collapse" | null;
|
||||
onPress: () => void;
|
||||
worktreeTarget: SidebarProjectHostTarget | null;
|
||||
isProjectActive?: boolean;
|
||||
onWorkspacePress?: () => void;
|
||||
onWorktreeCreated?: (workspaceId: string) => void;
|
||||
shortcutNumber?: number | null;
|
||||
@@ -421,6 +423,7 @@ function ProjectRowTrailingActions({
|
||||
projectPath,
|
||||
isHovered,
|
||||
isMobileBreakpoint,
|
||||
isProjectActive,
|
||||
onBeginWorkspaceSetup,
|
||||
onRemoveProject,
|
||||
removeProjectStatus,
|
||||
@@ -432,6 +435,7 @@ function ProjectRowTrailingActions({
|
||||
projectPath: string;
|
||||
isHovered: boolean;
|
||||
isMobileBreakpoint: boolean;
|
||||
isProjectActive: boolean;
|
||||
onBeginWorkspaceSetup: () => void;
|
||||
onRemoveProject?: () => void;
|
||||
removeProjectStatus: "idle" | "pending" | "success";
|
||||
@@ -444,6 +448,7 @@ function ProjectRowTrailingActions({
|
||||
displayName={displayName}
|
||||
onPress={onBeginWorkspaceSetup}
|
||||
visible={actionsVisible}
|
||||
showShortcutHint={isProjectActive}
|
||||
testID={`sidebar-project-new-worktree-${projectViewKey}`}
|
||||
/>
|
||||
) : null}
|
||||
@@ -738,14 +743,17 @@ 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 }) => [
|
||||
@@ -797,6 +805,9 @@ function NewWorktreeButton({
|
||||
<Text style={styles.projectActionTooltipText}>
|
||||
{t("sidebar.workspace.actions.newWorkspace")}
|
||||
</Text>
|
||||
{showShortcutHint && newWorktreeKeys ? (
|
||||
<Shortcut chord={newWorktreeKeys} style={styles.projectActionTooltipShortcut} />
|
||||
) : null}
|
||||
</View>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
@@ -880,6 +891,7 @@ function ProjectHeaderRow({
|
||||
chevron,
|
||||
onPress,
|
||||
worktreeTarget,
|
||||
isProjectActive = false,
|
||||
onWorkspacePress,
|
||||
onWorktreeCreated: _onWorktreeCreated,
|
||||
shortcutNumber = null,
|
||||
@@ -979,6 +991,7 @@ function ProjectHeaderRow({
|
||||
projectPath={projectPath}
|
||||
isHovered={isHovered}
|
||||
isMobileBreakpoint={isMobileBreakpoint}
|
||||
isProjectActive={isProjectActive}
|
||||
onBeginWorkspaceSetup={handleBeginWorkspaceSetup}
|
||||
onRemoveProject={onRemoveProject}
|
||||
removeProjectStatus={removeProjectStatus}
|
||||
@@ -1333,7 +1346,7 @@ function WorkspaceRowWithMenu({
|
||||
}, [onToggleWorkspacePin, workspace]);
|
||||
const onTogglePin = canPin ? handleTogglePin : undefined;
|
||||
|
||||
const archiveShortcutKeys = useShortcutKeys("paseo/workspace.archive");
|
||||
const archiveShortcutKeys = useShortcutKeys("archive-workspace");
|
||||
const { hasClearableAttention, canMarkUnread, clearAttention, markUnread } =
|
||||
useWorkspaceReadState({
|
||||
serverId: workspace.serverId,
|
||||
@@ -1656,6 +1669,12 @@ function ProjectBlock({
|
||||
enabled: collapsed,
|
||||
});
|
||||
|
||||
const active = isProjectSelectedByRoute({
|
||||
selection: activeWorkspaceSelection,
|
||||
project,
|
||||
enabled: selectionEnabled,
|
||||
});
|
||||
|
||||
const renderWorkspaceRow = useCallback(
|
||||
(
|
||||
item: SidebarWorkspacePlacement,
|
||||
@@ -1859,6 +1878,7 @@ function ProjectBlock({
|
||||
worktreeTarget={
|
||||
rowModel.trailingAction.kind === "new_workspace" ? rowModel.trailingAction.target : null
|
||||
}
|
||||
isProjectActive={active}
|
||||
onWorkspacePress={onWorkspacePress}
|
||||
onWorktreeCreated={onWorktreeCreated}
|
||||
drag={drag}
|
||||
@@ -2872,6 +2892,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
projectActionTooltipShortcut: {},
|
||||
projectShortcutBadgeOverlay: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[2] + 1,
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { orderHostsLocalFirst } from "@/types/host-connection";
|
||||
@@ -73,8 +73,8 @@ export function SidebarFooterOverflowMenu({
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const openUsage = useOpenSidebarUsage();
|
||||
const newAgentKeys = useShortcutKeys("paseo/project.open");
|
||||
const settingsKeys = useShortcutKeys("paseo/settings.toggle");
|
||||
const newAgentKeys = useShortcutKeys("new-agent");
|
||||
const settingsKeys = useShortcutKeys("toggle-settings");
|
||||
const helpLabel = t("sidebar.help.trigger");
|
||||
const addProjectTrailing = useMemo(
|
||||
() => (newAgentKeys ? <Shortcut chord={newAgentKeys} /> : null),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { PluginSidebarItem } from "@/plugins/sidebar-items";
|
||||
import { canCreateWorktreeForProjectKind } from "@/projects/host-projects";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
|
||||
@@ -43,7 +43,7 @@ import { useWorkspaceClipboardActions } from "@/hooks/use-workspace-clipboard-ac
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -770,7 +770,7 @@ function StatusWorkspaceRowWithMenu({
|
||||
}, [onToggleWorkspacePin, workspace]);
|
||||
const onTogglePin = canPin ? handleTogglePin : undefined;
|
||||
|
||||
const archiveShortcutKeys = useShortcutKeys("paseo/workspace.archive");
|
||||
const archiveShortcutKeys = useShortcutKeys("archive-workspace");
|
||||
const { hasClearableAttention, canMarkUnread, clearAttention, markUnread } =
|
||||
useWorkspaceReadState({
|
||||
serverId: workspace.serverId,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isWeb as platformIsWeb } from "@/constants/platform";
|
||||
import { supportsTouchHaptics, usesTouchLongPressHold } from "@/constants/touch-timing";
|
||||
import { decideLongPressMove } from "@/utils/sidebar-gesture-arbitration";
|
||||
import type { useContextMenu } from "@/components/ui/context-menu";
|
||||
|
||||
@@ -59,7 +59,7 @@ export function useLongPressDragInteraction(input: {
|
||||
|
||||
const armTimers = useCallback(() => {
|
||||
clearTimers();
|
||||
if (platformIsWeb || !drag) {
|
||||
if (!usesTouchLongPressHold || !drag) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ export function useLongPressDragInteraction(input: {
|
||||
dragArmedRef.current = true;
|
||||
dragActivatedRef.current = true;
|
||||
didLongPressRef.current = true;
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
}, DRAG_ARM_DELAY_MS);
|
||||
|
||||
@@ -109,7 +109,7 @@ export function useLongPressDragInteraction(input: {
|
||||
if (distance > CONTEXT_MENU_STATIONARY_SLOP_PX) {
|
||||
return;
|
||||
}
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
openContextMenuAtStartPoint();
|
||||
}, CONTEXT_MENU_DELAY_MS);
|
||||
}, [clearTimers, drag, menuController, openContextMenuAtStartPoint]);
|
||||
|
||||
@@ -785,7 +785,11 @@ 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(
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "@getpaseo/protocol/terminal-input-mode";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useKeyboardShiftStyle } from "@/keyboard/shift";
|
||||
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -89,7 +90,6 @@ import {
|
||||
type TerminalResizeRequest,
|
||||
} from "./terminal-resize-debouncer";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useKeyboardFocusSurface } from "@/keyboard";
|
||||
import {
|
||||
applyTerminalRendererReadyChange,
|
||||
@@ -305,7 +305,10 @@ export function TerminalPane({
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}, [settings.monoFontFamily]);
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({ isNative, isCompact: isMobile });
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({
|
||||
hasSoftwareKeyboard,
|
||||
isCompact: isMobile,
|
||||
});
|
||||
const [keyBarWidth, setKeyBarWidth] = useState(0);
|
||||
const virtualKeyboardRows = resolveTerminalVirtualKeyboardRows({
|
||||
isCompact: isMobile,
|
||||
@@ -316,7 +319,7 @@ export function TerminalPane({
|
||||
const swipeGesturesEnabled = isMobile;
|
||||
const { shift: keyboardShift, style: keyboardPaddingStyle } = useKeyboardShiftStyle({
|
||||
mode: "padding",
|
||||
enabled: isNative || isMobile,
|
||||
enabled: hasSoftwareKeyboard || isMobile,
|
||||
});
|
||||
const [keyboardInset, setKeyboardInset] = useState(0);
|
||||
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
|
||||
@@ -608,7 +611,7 @@ export function TerminalPane({
|
||||
|
||||
const handleKeyboardChange = useCallback(
|
||||
(nextShift: number) => {
|
||||
setKeyboardInset(isNative || isMobile ? nextShift : 0);
|
||||
setKeyboardInset(hasSoftwareKeyboard || isMobile ? nextShift : 0);
|
||||
setIsKeyboardVisible(nextShift > 0);
|
||||
pulseKeyboardRefits();
|
||||
},
|
||||
@@ -1180,10 +1183,10 @@ export function TerminalPane({
|
||||
emulatorRef.current?.blur();
|
||||
onOpenFileExplorer();
|
||||
}, [swipeGesturesEnabled, onOpenFileExplorer]);
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ isNative });
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ hasSoftwareKeyboard });
|
||||
const showFloatingCopyAction = shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection,
|
||||
isNative,
|
||||
hasSoftwareKeyboard,
|
||||
});
|
||||
const keyboardToggleIconColor = theme.colors.foregroundMuted;
|
||||
|
||||
@@ -1332,7 +1335,9 @@ export function TerminalPane({
|
||||
<View
|
||||
style={styles.keyboardRows}
|
||||
onLayout={handleKeyBarLayout}
|
||||
testID={isNative && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined}
|
||||
testID={
|
||||
hasSoftwareKeyboard && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined
|
||||
}
|
||||
>
|
||||
{virtualKeyboardRows.map((row) => (
|
||||
<View
|
||||
|
||||
@@ -27,7 +27,7 @@ import { Keyframe, runOnJS } from "react-native-reanimated";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { FloatingScrollView, FloatingSurface } from "@/components/ui/floating";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import type { KeyboardFocusScope } from "@/keyboard";
|
||||
import type { KeyboardFocusScope } from "@/keyboard/actions";
|
||||
import { getOverlayRoot, OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
|
||||
import {
|
||||
computePosition,
|
||||
|
||||
@@ -61,7 +61,7 @@ import {
|
||||
resolveSheetCanvasStaticContentHeight,
|
||||
} from "./menu-sheet-layout";
|
||||
import type { Alignment, Placement } from "../anchor";
|
||||
import type { KeyboardFocusScope } from "@/keyboard";
|
||||
import type { KeyboardFocusScope } from "@/keyboard/actions";
|
||||
|
||||
const ThemedChevronLeft = withUnistyles(ChevronLeft);
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { WorkspaceRenameModal } from "@/workspace-rename";
|
||||
import { useActionHandler } from "@/actions";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { 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
|
||||
@@ -41,12 +44,13 @@ 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 { handled: false } as const;
|
||||
if (!fields) return false;
|
||||
cancelPendingOpen();
|
||||
openFrameRef.current = requestAnimationFrame(() => {
|
||||
openFrameRef.current = null;
|
||||
setIsOpen(true);
|
||||
});
|
||||
return true;
|
||||
}, [cancelPendingOpen, fields]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
@@ -60,8 +64,12 @@ export function WorkspaceRenameHost() {
|
||||
setIsOpen(false);
|
||||
}, [cancelPendingOpen, serverId, routeWorkspaceId]);
|
||||
|
||||
useActionHandler("paseo/workspace.rename", handle, {
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-rename-global",
|
||||
actions: WORKSPACE_RENAME_ACTIONS,
|
||||
enabled: serverId !== null && fields !== null,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
|
||||
const workspace = useMemo(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from "react";
|
||||
import { useId, 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 { useActionHandler } from "@/actions";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useComposerInput } from "@/composer/session";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { resolveNextChoiceId } from "./mode";
|
||||
@@ -89,28 +89,33 @@ export function useModelPickerShortcut(disabled: boolean) {
|
||||
const action =
|
||||
isActiveComposer && !disabled && input
|
||||
? {
|
||||
id: "paseo/message-input.model-toggle",
|
||||
id: "message-input.model-toggle" as const,
|
||||
canOpen: input.isFocused,
|
||||
}
|
||||
: undefined;
|
||||
const keys = useShortcutKeys(action ? "paseo/message-input.model-toggle" : null);
|
||||
const keys = useShortcutKeys(action ? "toggle-model-picker" : 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;
|
||||
useActionHandler(
|
||||
"paseo/message-input.effort-cycle",
|
||||
() => {
|
||||
if (!thinking || nextEffortId === null) return { handled: false };
|
||||
useKeyboardActionHandler({
|
||||
handlerId: effortHandlerId,
|
||||
actions: ["message-input.effort-cycle"],
|
||||
enabled: canCycleEffort,
|
||||
isActive: input?.isFocused,
|
||||
priority: 200,
|
||||
handle: () => {
|
||||
if (!thinking || nextEffortId === null) return false;
|
||||
thinking.onSelect(nextEffortId);
|
||||
return true;
|
||||
},
|
||||
{ enabled: () => canCycleEffort && (input?.isFocused() ?? false) },
|
||||
);
|
||||
return useShortcutKeys(canCycleEffort ? "paseo/message-input.effort-cycle" : null);
|
||||
});
|
||||
return useShortcutKeys(canCycleEffort ? "cycle-effort" : 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 "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import {
|
||||
composerToolbarGeometry,
|
||||
|
||||
@@ -3,8 +3,10 @@ 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 { ActionRegistryProvider } from "@/actions";
|
||||
import { createCoreRegistries, type CoreRegistries } from "@/core-actions";
|
||||
import {
|
||||
KeyboardActionDispatcherProvider,
|
||||
useKeyboardActionDispatcher,
|
||||
} from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { useAgentModeCycleShortcut, type AgentModeControlValue } from "./mode-control";
|
||||
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
@@ -16,7 +18,7 @@ const MODES: AgentMode[] = [
|
||||
{ id: "bypass", label: "Bypass" },
|
||||
];
|
||||
|
||||
let core: CoreRegistries | null = null;
|
||||
let dispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
|
||||
|
||||
// A composer's controls with no Mode control mounted, as a compact composer renders them while
|
||||
// its settings drawer is closed.
|
||||
@@ -27,6 +29,7 @@ function ComposerControlsProbe({
|
||||
selectedModeId: string;
|
||||
onSelectMode: (modeId: string) => void;
|
||||
}) {
|
||||
dispatcher = useKeyboardActionDispatcher();
|
||||
const modeControl = useMemo<AgentModeControlValue>(
|
||||
() => ({
|
||||
provider: "claude",
|
||||
@@ -43,9 +46,8 @@ function ComposerControlsProbe({
|
||||
|
||||
function renderComposer(input: { selectedModeId: string; isActiveComposer?: boolean }) {
|
||||
const onSelectMode = vi.fn();
|
||||
core = createCoreRegistries();
|
||||
render(
|
||||
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
|
||||
<KeyboardActionDispatcherProvider>
|
||||
<ComposerKeyboardScopeProvider
|
||||
isPaneFocused
|
||||
isActiveComposer={input.isActiveComposer ?? true}
|
||||
@@ -53,17 +55,16 @@ function renderComposer(input: { selectedModeId: string; isActiveComposer?: bool
|
||||
>
|
||||
<ComposerControlsProbe selectedModeId={input.selectedModeId} onSelectMode={onSelectMode} />
|
||||
</ComposerKeyboardScopeProvider>
|
||||
</ActionRegistryProvider>,
|
||||
</KeyboardActionDispatcherProvider>,
|
||||
);
|
||||
return onSelectMode;
|
||||
}
|
||||
|
||||
function cycleMode(): boolean {
|
||||
const registries = core;
|
||||
if (!registries) throw new Error("The composer is not rendered");
|
||||
if (!dispatcher) throw new Error("The dispatcher is not mounted");
|
||||
let handled = false;
|
||||
act(() => {
|
||||
handled = registries.actions.dispatch("paseo/message-input.mode-cycle");
|
||||
handled = dispatcher!.dispatch({ id: "message-input.mode-cycle", scope: "message-input" });
|
||||
});
|
||||
return handled;
|
||||
}
|
||||
|
||||
@@ -10,8 +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 "@/keyboard";
|
||||
import { useActionHandler } from "@/actions";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { resolveNextAgentModeId } from "@/composer/agent-controls/mode";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { useComposerControlLayout } from "@/composer/agent-controls/layout-context";
|
||||
@@ -88,7 +89,7 @@ export function AgentModeControl({
|
||||
const { presentation } = useComposerControlLayout();
|
||||
const { t } = useTranslation();
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const cycleShortcutKeys = useShortcutKeys("paseo/message-input.mode-cycle");
|
||||
const cycleShortcutKeys = useShortcutKeys("cycle-agent-mode");
|
||||
const anchorRef = useRef<View>(null);
|
||||
const openRef = useRef(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -220,23 +221,32 @@ const EMPTY_MODES: AgentMode[] = [];
|
||||
*/
|
||||
export function useAgentModeCycleShortcut(modeControl: AgentModeControlValue | null | undefined) {
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const handlerIdRef = useRef(`mode-cycle:${Math.random().toString(36).slice(2)}`);
|
||||
const modeOptions = modeControl?.modeOptions ?? EMPTY_MODES;
|
||||
const enabled =
|
||||
isActiveComposer && modeControl != null && !modeControl.disabled && modeOptions.length > 1;
|
||||
|
||||
useActionHandler(
|
||||
"paseo/message-input.mode-cycle",
|
||||
() => {
|
||||
if (!modeControl) return { handled: false };
|
||||
const handle = useCallback(
|
||||
(action: KeyboardActionDefinition): boolean => {
|
||||
if (action.id !== "message-input.mode-cycle" || !enabled || !modeControl) return false;
|
||||
const nextModeId = resolveNextAgentModeId({
|
||||
modeOptions,
|
||||
selectedMode: modeControl.selectedModeId,
|
||||
});
|
||||
if (!nextModeId) return { handled: false };
|
||||
if (!nextModeId) return false;
|
||||
modeControl.onSelectMode(nextModeId);
|
||||
return true;
|
||||
},
|
||||
{ enabled },
|
||||
[enabled, modeControl, modeOptions],
|
||||
);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: handlerIdRef.current,
|
||||
actions: ["message-input.mode-cycle"],
|
||||
enabled,
|
||||
priority: 200,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
|
||||
function compareAvailableModes(a: AgentMode[], b: AgentMode[]): boolean {
|
||||
|
||||
@@ -21,7 +21,7 @@ import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
|
||||
import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { readMeasuredWidth } from "@/hooks/use-container-width";
|
||||
import {
|
||||
toolbarContentSlot,
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
type ToolbarGlyphs,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { getAgentControlHintKey, shortModelLabel } from "./utils";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardToggle } from "@/hooks/use-keyboard-toggle";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { ComposerControls, ControlTooltipHint } from "./composer-control";
|
||||
@@ -186,7 +186,7 @@ export function CompactModelSheet({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch: isWeb && !usesBottomSheet,
|
||||
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
toolbarSlot,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
@@ -119,7 +120,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 "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { AutocompletePopover } from "@/components/ui/autocomplete-popover";
|
||||
import type { AutocompleteOption } from "@/components/ui/autocomplete";
|
||||
import { useAgentAutocomplete } from "@/hooks/use-agent-autocomplete";
|
||||
@@ -145,15 +146,10 @@ 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 {
|
||||
type ActionDeclined,
|
||||
type ActionInvocation,
|
||||
ActionScope,
|
||||
useActionHandler,
|
||||
useActionScope,
|
||||
} from "@/actions";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import { submitAgentInput } from "@/composer/submit";
|
||||
import { ComposerRecall } from "@/composer/recall";
|
||||
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
|
||||
@@ -254,8 +250,12 @@ function resolveIsVoiceModeForAgent(
|
||||
return voice?.isVoiceModeForAgent(serverId, agentId) ?? false;
|
||||
}
|
||||
|
||||
function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
|
||||
return isMessageInputFocused ? 200 : 100;
|
||||
}
|
||||
|
||||
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
|
||||
return isWeb && !isMobile;
|
||||
return !hasSoftwareKeyboard && !isMobile;
|
||||
}
|
||||
|
||||
function resolveCompactLayout(override: boolean | undefined, formFactor: boolean): boolean {
|
||||
@@ -589,18 +589,9 @@ function focusMessageInputWithPlatformStrategy(messageInputRef: {
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
interface DispatchComposerKeyboardActionArgs {
|
||||
action: KeyboardActionDefinition;
|
||||
isPaneFocused: boolean;
|
||||
messageInputRef: { current: MessageInputRef | null };
|
||||
isAgentRunning: boolean;
|
||||
isCancellingAgent: boolean;
|
||||
@@ -609,11 +600,10 @@ interface ComposerKeyboardActionArgs {
|
||||
focusMessageInputForKeyboardAction: () => void;
|
||||
}
|
||||
|
||||
function runComposerKeyboardAction(
|
||||
invocation: ActionInvocation,
|
||||
args: ComposerKeyboardActionArgs,
|
||||
): void | ActionDeclined {
|
||||
function dispatchComposerKeyboardAction(args: DispatchComposerKeyboardActionArgs): boolean {
|
||||
const {
|
||||
action,
|
||||
isPaneFocused,
|
||||
messageInputRef,
|
||||
isAgentRunning,
|
||||
isCancellingAgent,
|
||||
@@ -621,33 +611,83 @@ function runComposerKeyboardAction(
|
||||
handleCancelAgent,
|
||||
focusMessageInputForKeyboardAction,
|
||||
} = args;
|
||||
if (!isPaneFocused) return false;
|
||||
|
||||
if (invocation.actionId === "paseo/agent.interrupt") {
|
||||
if (messageInputRef.current?.runKeyboardAction("dictation-cancel")) return;
|
||||
if (!isAgentRunning || isCancellingAgent || !isConnected) return DECLINED;
|
||||
if (action.id === "agent.interrupt") {
|
||||
if (messageInputRef.current?.runKeyboardAction("dictation-cancel")) return true;
|
||||
if (!isAgentRunning || isCancellingAgent || !isConnected) return false;
|
||||
handleCancelAgent();
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (invocation.actionId === "paseo/message-input.focus") {
|
||||
if (action.id === "message-input.focus") {
|
||||
focusMessageInputForKeyboardAction();
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
const passthroughAction = resolveMessageInputPassthroughAction(invocation.actionId);
|
||||
if (!passthroughAction) return DECLINED;
|
||||
const passthroughAction = resolveMessageInputPassthroughAction(action.id);
|
||||
if (!passthroughAction) return false;
|
||||
const result = messageInputRef.current?.runKeyboardAction(passthroughAction);
|
||||
if (passthroughAction === "dictation-confirm" && result !== true) return DECLINED;
|
||||
if (passthroughAction === "send" || passthroughAction === "dictation-confirm") {
|
||||
return result ?? false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Runs the composer's keyboard actions; it sits inside the composer's action scope. */
|
||||
function ComposerKeyboardRegistration(props: ComposerKeyboardActionArgs) {
|
||||
function ComposerKeyboardRegistration({
|
||||
messageInputRef,
|
||||
isAgentRunning,
|
||||
isCancellingAgent,
|
||||
isConnected,
|
||||
handleCancelAgent,
|
||||
focusMessageInputForKeyboardAction,
|
||||
isMessageInputFocused,
|
||||
handlerId,
|
||||
}: Omit<DispatchComposerKeyboardActionArgs, "action" | "isPaneFocused"> & {
|
||||
isMessageInputFocused: boolean;
|
||||
handlerId: string;
|
||||
}) {
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
useActionHandler(
|
||||
COMPOSER_KEYBOARD_ACTIONS,
|
||||
(invocation) => runComposerKeyboardAction(invocation, props),
|
||||
{ enabled: isActiveComposer },
|
||||
const handleKeyboardAction = useCallback(
|
||||
(action: KeyboardActionDefinition): boolean =>
|
||||
dispatchComposerKeyboardAction({
|
||||
action,
|
||||
isPaneFocused: isActiveComposer,
|
||||
messageInputRef,
|
||||
isAgentRunning,
|
||||
isCancellingAgent,
|
||||
isConnected,
|
||||
handleCancelAgent,
|
||||
focusMessageInputForKeyboardAction,
|
||||
}),
|
||||
[
|
||||
focusMessageInputForKeyboardAction,
|
||||
handleCancelAgent,
|
||||
isActiveComposer,
|
||||
isAgentRunning,
|
||||
isCancellingAgent,
|
||||
isConnected,
|
||||
messageInputRef,
|
||||
],
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -660,13 +700,17 @@ function resolveMessageInputPassthroughAction(
|
||||
actionId: string,
|
||||
): MessageInputKeyboardActionKind | null {
|
||||
switch (actionId) {
|
||||
case "paseo/message-input.dictation-confirm":
|
||||
case "message-input.send":
|
||||
return "send";
|
||||
case "message-input.dictation-confirm":
|
||||
return "dictation-confirm";
|
||||
case "paseo/message-input.dictation-toggle":
|
||||
case "message-input.dictation-toggle":
|
||||
return "dictation-toggle";
|
||||
case "paseo/message-input.voice-toggle":
|
||||
case "message-input.dictation-cancel":
|
||||
return "dictation-cancel";
|
||||
case "message-input.voice-toggle":
|
||||
return "voice-toggle";
|
||||
case "paseo/message-input.voice-mute-toggle":
|
||||
case "message-input.voice-mute-toggle":
|
||||
return "voice-mute-toggle";
|
||||
default:
|
||||
return null;
|
||||
@@ -1197,23 +1241,17 @@ export function Composer({ isPaneFocused, ...props }: ComposerProps) {
|
||||
const commandCenterPanel = mobilePanelTarget === "agent-list" ? "agent" : mobilePanelTarget;
|
||||
const coveredForCommandCenter =
|
||||
isCompact && isMobilePanelCoveringHost(commandCenterPanel, paneHost);
|
||||
const isActiveComposer = isPaneFocused && !coveredByOverlayPanel;
|
||||
// Every active composer activates its own scope. The newest one, such as a
|
||||
// New workspace draft over a running agent, is innermost and takes the keys.
|
||||
const actionScope = useActionScope("paseo/composer", { active: isActiveComposer });
|
||||
return (
|
||||
<ComposerKeyboardScopeProvider
|
||||
isPaneFocused={isPaneFocused}
|
||||
isActiveComposer={isActiveComposer}
|
||||
isActiveComposer={isPaneFocused && !coveredByOverlayPanel}
|
||||
isCommandCenterTarget={isPaneFocused && !coveredForCommandCenter}
|
||||
>
|
||||
<ActionScope activation={actionScope}>
|
||||
<OverlayDismissalScope>
|
||||
<RenderProfile id="ComposerContent">
|
||||
<ComposerContent {...props} />
|
||||
</RenderProfile>
|
||||
</OverlayDismissalScope>
|
||||
</ActionScope>
|
||||
<OverlayDismissalScope>
|
||||
<RenderProfile id="ComposerContent">
|
||||
<ComposerContent {...props} />
|
||||
</RenderProfile>
|
||||
</OverlayDismissalScope>
|
||||
</ComposerKeyboardScopeProvider>
|
||||
);
|
||||
}
|
||||
@@ -1277,8 +1315,8 @@ function ComposerContentImpl({
|
||||
const toastErrorRef = useRef(toast.error);
|
||||
toastErrorRef.current = toast.error;
|
||||
const voice = useVoiceOptional();
|
||||
const voiceToggleKeys = useShortcutKeys("paseo/message-input.voice-toggle");
|
||||
const agentInterruptKeys = useShortcutKeys("paseo/agent.interrupt");
|
||||
const voiceToggleKeys = useShortcutKeys("voice-toggle");
|
||||
const agentInterruptKeys = useShortcutKeys("agent-interrupt");
|
||||
const isDictationReady = useIsDictationReady({
|
||||
serverId,
|
||||
isConnected,
|
||||
@@ -1412,6 +1450,7 @@ 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);
|
||||
@@ -1436,6 +1475,9 @@ 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 }) => {
|
||||
@@ -2436,6 +2478,7 @@ function ComposerContentImpl({
|
||||
|
||||
const handleFocusChange = useCallback(
|
||||
(focused: boolean) => {
|
||||
setIsMessageInputFocused(focused);
|
||||
if (focused) {
|
||||
onAttentionInputFocus?.();
|
||||
}
|
||||
@@ -2704,12 +2747,14 @@ function ComposerContentImpl({
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
handlerId={keyboardHandlerIdRef.current}
|
||||
messageInputRef={messageInputRef}
|
||||
isAgentRunning={isAgentRunning}
|
||||
isCancellingAgent={isCancellingAgent}
|
||||
isConnected={isConnected}
|
||||
handleCancelAgent={handleCancelAgent}
|
||||
focusMessageInputForKeyboardAction={focusMessageInputForKeyboardAction}
|
||||
isMessageInputFocused={isMessageInputFocused}
|
||||
/>
|
||||
<View
|
||||
style={
|
||||
|
||||
@@ -77,12 +77,16 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
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, isNative, isWeb } from "@/constants/platform";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { composerMinInputHeight } from "@/constants/presentation";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
@@ -115,7 +119,6 @@ import {
|
||||
runDefaultSendAction,
|
||||
runMessageInputKeyboardAction,
|
||||
stopRealtimeVoice,
|
||||
type MessageInputKeyboardActionKind,
|
||||
} from "./state";
|
||||
|
||||
const DEFAULT_SEND_KEYS: ShortcutKey[][] = [["Enter"]];
|
||||
@@ -238,11 +241,9 @@ export interface MessageInputRef {
|
||||
getNativeElement?: () => HTMLElement | null;
|
||||
}
|
||||
|
||||
const MIN_INPUT_HEIGHT_MOBILE = 30;
|
||||
const MIN_INPUT_HEIGHT_DESKTOP = 46;
|
||||
const DEFAULT_MAX_INPUT_HEIGHT = 160;
|
||||
const MAX_INPUT_VIEWPORT_RATIO = 0.5;
|
||||
const MIN_INPUT_HEIGHT = isWeb ? MIN_INPUT_HEIGHT_DESKTOP : MIN_INPUT_HEIGHT_MOBILE;
|
||||
const MIN_INPUT_HEIGHT = composerMinInputHeight;
|
||||
type WebTextInputKeyPressEvent = NativeSyntheticEvent<
|
||||
TextInputKeyPressEventData & {
|
||||
metaKey?: boolean;
|
||||
@@ -1386,9 +1387,9 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
const discGlyphSize = TOOLBAR_DISC_GLYPH_SIZES[controlSizing];
|
||||
const toast = useToast();
|
||||
const voice = useVoiceOptional();
|
||||
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 voiceMuteToggleKeys = useShortcutKeys("voice-mute-toggle");
|
||||
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
|
||||
const focusInputKeys = useShortcutKeys("focus-message-input");
|
||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
|
||||
// Web text is DOM-owned between deferred draft publications. The action button only needs
|
||||
@@ -1883,7 +1884,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
|
||||
const handleLongPressSend = useCallback(() => {
|
||||
if (alternateSendAction && isNative) {
|
||||
if (alternateSendAction && supportsTouchHaptics) {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => {});
|
||||
}
|
||||
handleAlternateSendAction();
|
||||
@@ -1910,12 +1911,12 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
[onSelectionChangeCallback],
|
||||
);
|
||||
|
||||
const shouldHandleWebKeyPress = isWeb;
|
||||
const shouldSubmitOnEnter = isWeb && !isCompact;
|
||||
const shouldHandleKeyPress = supportsConfigurableComposerSendKeys;
|
||||
const shouldSubmitOnEnter = supportsConfigurableComposerSendKeys && !isCompact;
|
||||
|
||||
const handleDesktopKeyPress = useCallback(
|
||||
(event: WebTextInputKeyPressEvent) => {
|
||||
if (!shouldHandleWebKeyPress) return;
|
||||
if (!shouldHandleKeyPress) return;
|
||||
handleDesktopKeyPressImpl(event, {
|
||||
onKeyPressCallback,
|
||||
input: getComposerInputSnapshot(
|
||||
@@ -1935,7 +1936,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
},
|
||||
[
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
onKeyPressCallback,
|
||||
shouldSubmitOnEnter,
|
||||
sendShortcut,
|
||||
@@ -2222,14 +2223,19 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
editable={!isDictating && !isRealtimeVoiceForCurrentAgent && !disabled}
|
||||
scrollEnabled={isComposerScrollEnabled}
|
||||
autoFocus={false}
|
||||
onKeyPress={shouldHandleWebKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onKeyPress={shouldHandleKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onPasteImages={onPasteImages}
|
||||
onPasteError={handlePasteError}
|
||||
fullscreen={isFullscreen}
|
||||
compact={isCompact}
|
||||
onRenderedLinesChange={setRenderedLines}
|
||||
focusHintVisible={!isFullscreen && isWeb && !isInputFocused && !hasLiveText}
|
||||
focusHintVisible={
|
||||
!isFullscreen &&
|
||||
supportsConfigurableComposerSendKeys &&
|
||||
!isInputFocused &&
|
||||
!hasLiveText
|
||||
}
|
||||
focusInputKeys={focusInputKeys}
|
||||
focusHintLabel={t("composer.input.focusHint", {
|
||||
shortcut: focusInputKeys ? formatShortcut(focusInputKeys[0], getShortcutOs()) : "",
|
||||
@@ -2253,7 +2259,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
disabled,
|
||||
isComposerScrollEnabled,
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
handleDesktopKeyPress,
|
||||
handleSelectionChange,
|
||||
onPasteImages,
|
||||
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
|
||||
@@ -97,19 +98,6 @@ 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;
|
||||
|
||||
@@ -25,6 +25,9 @@ export const isWeb = Platform.OS === "web";
|
||||
/** iOS or Android — the JS runtime is React Native. */
|
||||
export const isNative = Platform.OS !== "web";
|
||||
|
||||
/** Platforms with an alpha-mask compositor for decorative shimmer effects. */
|
||||
export const supportsMaskedEffects = ["web", "ios", "android"].includes(Platform.OS);
|
||||
|
||||
/** Development build/runtime — true in Metro dev bundles, false in production. */
|
||||
export const isDev = Boolean((globalThis as { __DEV__?: boolean }).__DEV__);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolvePresentationCapabilities } from "./presentation";
|
||||
|
||||
describe("presentation capabilities per target", () => {
|
||||
it("resolves mobile and desktop presentation answers for iOS, Android, web, and Electron", () => {
|
||||
expect(resolvePresentationCapabilities({ isNative: true, isWeb: false })).toEqual({
|
||||
allowsInlineWorkspaceRename: false,
|
||||
usesCompactBottomSheet: true,
|
||||
usesDesktopPopoverSpacing: false,
|
||||
initialUiBaseFontSize: 15,
|
||||
initialContentFontSize: 16,
|
||||
usesMobileContentFontMigration: true,
|
||||
composerMinInputHeight: 30,
|
||||
});
|
||||
expect(resolvePresentationCapabilities({ isNative: false, isWeb: true })).toEqual({
|
||||
allowsInlineWorkspaceRename: true,
|
||||
usesCompactBottomSheet: false,
|
||||
usesDesktopPopoverSpacing: true,
|
||||
initialUiBaseFontSize: 14,
|
||||
initialContentFontSize: 15,
|
||||
usesMobileContentFontMigration: false,
|
||||
composerMinInputHeight: 46,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { FONT_SIZE } from "@/styles/theme";
|
||||
import { isNative, isWeb } from "./platform";
|
||||
|
||||
export interface PresentationCapabilities {
|
||||
/** Wide sidebar rows rename in place instead of opening a rename modal. */
|
||||
allowsInlineWorkspaceRename: boolean;
|
||||
/** Compact screens present bottom sheets (`SheetFlatList` / Gorhom modal) instead of dialogs. */
|
||||
usesCompactBottomSheet: boolean;
|
||||
/** Popover lists use tight desktop row padding instead of touch-sheet spacing. */
|
||||
usesDesktopPopoverSpacing: boolean;
|
||||
/** Initial UI font size (pt) when no user preference is saved. */
|
||||
initialUiBaseFontSize: number;
|
||||
/** Initial chat content font size (pt) when no user preference is saved. */
|
||||
initialContentFontSize: number;
|
||||
/** Whether legacy 15 pt persisted content size migrates up to the mobile 16 pt default. */
|
||||
usesMobileContentFontMigration: boolean;
|
||||
/** Minimum multiline composer input height (pt). */
|
||||
composerMinInputHeight: number;
|
||||
}
|
||||
|
||||
export function resolvePresentationCapabilities(input: {
|
||||
isNative: boolean;
|
||||
isWeb: boolean;
|
||||
}): PresentationCapabilities {
|
||||
return {
|
||||
allowsInlineWorkspaceRename: input.isWeb,
|
||||
usesCompactBottomSheet: input.isNative,
|
||||
usesDesktopPopoverSpacing: input.isWeb,
|
||||
initialUiBaseFontSize: input.isNative ? 15 : FONT_SIZE.base,
|
||||
initialContentFontSize: input.isNative ? 16 : FONT_SIZE.content,
|
||||
usesMobileContentFontMigration: input.isNative,
|
||||
composerMinInputHeight: input.isWeb ? 46 : 30,
|
||||
};
|
||||
}
|
||||
|
||||
const CAPABILITIES = resolvePresentationCapabilities({ isNative, isWeb });
|
||||
|
||||
export const allowsInlineWorkspaceRename = CAPABILITIES.allowsInlineWorkspaceRename;
|
||||
export const usesCompactBottomSheet = CAPABILITIES.usesCompactBottomSheet;
|
||||
export const usesDesktopPopoverSpacing = CAPABILITIES.usesDesktopPopoverSpacing;
|
||||
export const initialUiBaseFontSize = CAPABILITIES.initialUiBaseFontSize;
|
||||
export const initialContentFontSize = CAPABILITIES.initialContentFontSize;
|
||||
export const usesMobileContentFontMigration = CAPABILITIES.usesMobileContentFontMigration;
|
||||
export const composerMinInputHeight = CAPABILITIES.composerMinInputHeight;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Platform-free: Playwright imports this through workspace-deck-retention in plain Node.
|
||||
|
||||
export interface SourceFileBudgets {
|
||||
readonly highlighted: number;
|
||||
readonly plain: number;
|
||||
}
|
||||
|
||||
export interface PlatformResourceBudgets {
|
||||
readonly workspaceDeckRetentionLimit: number;
|
||||
readonly sourceFileBudgets: SourceFileBudgets;
|
||||
}
|
||||
|
||||
const MOBILE_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
const WEB_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
/** Native phones use mobile memory budgets; web and Electron use desktop budgets. */
|
||||
export function resolveResourceBudgets(input: { isNative: boolean }): PlatformResourceBudgets {
|
||||
return input.isNative ? MOBILE_RESOURCE_BUDGETS : WEB_RESOURCE_BUDGETS;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
describe("resource budget per target", () => {
|
||||
it("resolves mobile and desktop resource budget limits for iOS, Android, web, and Electron", () => {
|
||||
expect(resolveResourceBudgets({ isNative: true })).toEqual({
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
});
|
||||
expect(resolveResourceBudgets({ isNative: false })).toEqual({
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { isNative } from "./platform";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
const RESOURCE_BUDGETS = resolveResourceBudgets({ isNative });
|
||||
|
||||
export const workspaceDeckRetentionLimit = RESOURCE_BUDGETS.workspaceDeckRetentionLimit;
|
||||
export const sourceFileBudgets = RESOURCE_BUDGETS.sourceFileBudgets;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveTouchTiming } from "./touch-timing";
|
||||
|
||||
describe("touch timing per target", () => {
|
||||
it("enables touch timing and haptics only on iOS and Android, not on web or Electron", () => {
|
||||
expect(resolveTouchTiming({ isNative: true })).toEqual({
|
||||
supportsTouchHaptics: true,
|
||||
usesTouchLongPressHold: true,
|
||||
});
|
||||
expect(resolveTouchTiming({ isNative: false })).toEqual({
|
||||
supportsTouchHaptics: false,
|
||||
usesTouchLongPressHold: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { isNative } from "./platform";
|
||||
|
||||
export interface TouchTimingCapabilities {
|
||||
/** Fire tactile `expo-haptics` feedback on touch interactions. */
|
||||
supportsTouchHaptics: boolean;
|
||||
/** Require a stationary long-press delay to arm drag or open context menus. */
|
||||
usesTouchLongPressHold: boolean;
|
||||
}
|
||||
|
||||
export function resolveTouchTiming(input: { isNative: boolean }): TouchTimingCapabilities {
|
||||
return {
|
||||
supportsTouchHaptics: input.isNative,
|
||||
usesTouchLongPressHold: input.isNative,
|
||||
};
|
||||
}
|
||||
|
||||
const TOUCH_TIMING = resolveTouchTiming({ isNative });
|
||||
|
||||
export const supportsTouchHaptics = TOUCH_TIMING.supportsTouchHaptics;
|
||||
export const usesTouchLongPressHold = TOUCH_TIMING.usesTouchLongPressHold;
|
||||
@@ -1,11 +0,0 @@
|
||||
export { CoreActionsProvider, createCoreRegistries } from "./internal/provider";
|
||||
export type { CoreRegistries } from "./internal/provider";
|
||||
export { useAppShellActions } from "./internal/app-shell-actions";
|
||||
export { buildShortcutSections } from "./internal/sections";
|
||||
export { filterShortcutHelpSections } from "./internal/help-search";
|
||||
export type { ShortcutRow, ShortcutSection } from "./internal/sections";
|
||||
export {
|
||||
getWorkspaceIndexJumpModifierKey,
|
||||
getWorkspaceSwitcherCycleKey,
|
||||
getWorkspaceSwitcherReleaseModifier,
|
||||
} from "./internal/workspace-keys";
|
||||
@@ -1,102 +0,0 @@
|
||||
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" },
|
||||
];
|
||||
@@ -1,90 +0,0 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { usePathname, useRouter } from "expo-router";
|
||||
import { useActionHandler, useActionRegistry, useActionScope } from "@/actions";
|
||||
import { getDisplayPlatform, useKeybindings } from "@/keyboard";
|
||||
import { useOpenAddProject } from "@/hooks/use-open-add-project";
|
||||
import {
|
||||
type ActiveWorkspaceSelection,
|
||||
getLastWorkspaceSelection,
|
||||
navigateToLastWorkspace,
|
||||
navigateToWorkspace,
|
||||
useActiveWorkspaceSelection,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { triggerWorkspaceSwitcherCycle } from "@/workspace-switcher";
|
||||
import { type AppShell, createAppShellRuns, returnFromSettings } from "./app-shell-runs";
|
||||
import { useCoreActionRuns } from "./provider";
|
||||
import { getWorkspaceSwitcherReleaseModifier } from "./workspace-keys";
|
||||
|
||||
/**
|
||||
* Supplies the app shell's `run` for the core actions no screen owns, and
|
||||
* takes Escape on desktop Settings.
|
||||
*/
|
||||
export function useAppShellActions({
|
||||
isMobile,
|
||||
toggleAgentList,
|
||||
cycleTheme,
|
||||
}: {
|
||||
isMobile: boolean;
|
||||
toggleAgentList: () => void;
|
||||
cycleTheme: () => void;
|
||||
}): void {
|
||||
const actions = useActionRegistry();
|
||||
const bindings = useKeybindings();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const openProjectPicker = useOpenAddProject();
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
// The workspace the last jump went to, ahead of the route catching up, so
|
||||
// repeated next/previous presses step from it.
|
||||
const jumpedWorkspaceRef = useRef<ActiveWorkspaceSelection | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeWorkspaceSelection) {
|
||||
jumpedWorkspaceRef.current = activeWorkspaceSelection;
|
||||
}
|
||||
}, [activeWorkspaceSelection]);
|
||||
|
||||
const shell: AppShell = {
|
||||
pathname: () => pathname,
|
||||
isMobile: () => isMobile,
|
||||
router: {
|
||||
push: (route) => router.push(route as Parameters<typeof router.push>[0]),
|
||||
replace: (route) => router.replace(route as Parameters<typeof router.replace>[0]),
|
||||
back: () => router.back(),
|
||||
},
|
||||
selectedWorkspace: () => jumpedWorkspaceRef.current ?? activeWorkspaceSelection,
|
||||
navigateToWorkspace: (target) => {
|
||||
jumpedWorkspaceRef.current = target;
|
||||
navigateToWorkspace(target);
|
||||
},
|
||||
navigateToLastWorkspace,
|
||||
cycleWorkspaceSwitcher: (delta) => {
|
||||
const currentWorkspace = activeWorkspaceSelection
|
||||
? (getLastWorkspaceSelection() ?? activeWorkspaceSelection)
|
||||
: null;
|
||||
const releaseModifier = getWorkspaceSwitcherReleaseModifier({
|
||||
delta,
|
||||
platform: getDisplayPlatform(),
|
||||
bindings,
|
||||
});
|
||||
return triggerWorkspaceSwitcherCycle({ delta, releaseModifier, currentWorkspace });
|
||||
},
|
||||
openProjectPicker: () => {
|
||||
void openProjectPicker();
|
||||
},
|
||||
toggleAgentList,
|
||||
cycleTheme,
|
||||
dispatch: (actionId) => actions.dispatch(actionId),
|
||||
};
|
||||
|
||||
useCoreActionRuns(createAppShellRuns(shell));
|
||||
|
||||
// Escape on desktop Settings goes back to the workspace. The workspace's
|
||||
// composer stays mounted and active under Settings, so Settings activates
|
||||
// the innermost scope while it shows.
|
||||
const isDesktopSettings = pathname.startsWith("/settings") && !isMobile;
|
||||
const settingsScope = useActionScope("paseo/settings", { active: isDesktopSettings });
|
||||
useActionHandler("paseo/agent.interrupt", () => returnFromSettings(shell), {
|
||||
scope: settingsScope,
|
||||
});
|
||||
}
|
||||
@@ -1,271 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
|
||||
import type { SidebarShortcutWorkspaceTarget } from "@/utils/sidebar-shortcuts";
|
||||
import { createAppShellRuns, type AppShell } from "./app-shell-runs";
|
||||
import { createCoreRegistries } from "./provider";
|
||||
|
||||
const SIDEBAR_TARGETS = [
|
||||
{ serverId: "srv", workspaceId: "ws-1" },
|
||||
{ serverId: "srv", workspaceId: "ws-2" },
|
||||
{ serverId: "srv", workspaceId: "ws-3" },
|
||||
{ serverId: "srv", workspaceId: "ws-4" },
|
||||
{ serverId: "srv", workspaceId: "ws-5" },
|
||||
] as const;
|
||||
|
||||
const STATUS_VISUAL_TARGETS = [
|
||||
{ serverId: "srv", workspaceId: "needs-input" },
|
||||
{ serverId: "srv", workspaceId: "running-new" },
|
||||
{ serverId: "srv", workspaceId: "running-old" },
|
||||
{ serverId: "srv", workspaceId: "done" },
|
||||
] as const;
|
||||
|
||||
interface ShellState {
|
||||
pathname?: string;
|
||||
isMobile?: boolean;
|
||||
selectedWorkspace?: SidebarShortcutWorkspaceTarget | null;
|
||||
sidebarTargets?: readonly SidebarShortcutWorkspaceTarget[];
|
||||
hasLastWorkspace?: boolean;
|
||||
switcherTakesStep?: boolean;
|
||||
projectPickerHost?: boolean;
|
||||
}
|
||||
|
||||
/** The core registries with the app shell's runs behind them, recording what the shell did. */
|
||||
function createShell(state: ShellState = {}) {
|
||||
const did: unknown[] = [];
|
||||
useKeyboardShortcutsStore.setState({
|
||||
sidebarShortcutWorkspaceTargets: [...(state.sidebarTargets ?? SIDEBAR_TARGETS)],
|
||||
});
|
||||
const shell: AppShell = {
|
||||
pathname: () => state.pathname ?? "/h/srv/workspace/ws-2",
|
||||
isMobile: () => state.isMobile ?? false,
|
||||
router: {
|
||||
push: (route) => did.push(["router-push", route]),
|
||||
replace: (route) => did.push(["router-replace", route]),
|
||||
back: () => did.push(["router-back"]),
|
||||
},
|
||||
selectedWorkspace: () => state.selectedWorkspace ?? null,
|
||||
navigateToWorkspace: (target) => did.push(["navigate-workspace", target]),
|
||||
navigateToLastWorkspace: () => {
|
||||
did.push(["navigate-last-workspace"]);
|
||||
return state.hasLastWorkspace ?? true;
|
||||
},
|
||||
cycleWorkspaceSwitcher: (delta) => {
|
||||
did.push(["workspace-switcher-cycle", delta]);
|
||||
return state.switcherTakesStep ?? true;
|
||||
},
|
||||
openProjectPicker: () => did.push(["open-project-picker"]),
|
||||
toggleAgentList: () => did.push(["toggle-agent-list"]),
|
||||
cycleTheme: () => did.push(["cycle-theme"]),
|
||||
dispatch: (actionId) => core.actions.dispatch(actionId),
|
||||
};
|
||||
const core = createCoreRegistries(createAppShellRuns(shell));
|
||||
if (state.projectPickerHost) {
|
||||
core.actions.registerHandler("paseo/workspace.project.pick", () => {
|
||||
did.push(["project-pick"]);
|
||||
});
|
||||
}
|
||||
return { actions: core.actions, did };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useKeyboardShortcutsStore.setState({
|
||||
commandCenterOpen: false,
|
||||
shortcutsDialogOpen: false,
|
||||
sidebarShortcutWorkspaceTargets: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace.navigate.index", () => {
|
||||
it("navigates to the sidebar target at index-1", () => {
|
||||
const { actions, did } = createShell();
|
||||
expect(actions.dispatch("paseo/workspace.navigate.index", { index: 4 })).toBe(true);
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-4" }]]);
|
||||
});
|
||||
|
||||
it("declines when the target index is out of range", () => {
|
||||
const { actions, did } = createShell();
|
||||
expect(actions.dispatch("paseo/workspace.navigate.index", { index: 99 })).toBe(false);
|
||||
expect(did).toEqual([]);
|
||||
});
|
||||
|
||||
it("declines when no index arrives", () => {
|
||||
const { actions, did } = createShell();
|
||||
expect(actions.dispatch("paseo/workspace.navigate.index")).toBe(false);
|
||||
expect(did).toEqual([]);
|
||||
});
|
||||
|
||||
it("declines when there are no sidebar targets", () => {
|
||||
const { actions, did } = createShell({ sidebarTargets: [] });
|
||||
expect(actions.dispatch("paseo/workspace.navigate.index", { index: 1 })).toBe(false);
|
||||
expect(did).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace.next and workspace.previous", () => {
|
||||
function step(actionId: "paseo/workspace.next" | "paseo/workspace.previous", state: ShellState) {
|
||||
const { actions, did } = createShell(state);
|
||||
const handled = actions.dispatch(actionId);
|
||||
return { handled, did };
|
||||
}
|
||||
|
||||
it("uses the retained navigation workspace selection over a stale pathname", () => {
|
||||
const { did } = step("paseo/workspace.next", {
|
||||
pathname: "/h/srv/workspace/ws-2",
|
||||
selectedWorkspace: { serverId: "srv", workspaceId: "ws-4" },
|
||||
});
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-5" }]]);
|
||||
});
|
||||
|
||||
it("moves from status row 2 to row 3 using status visual target order", () => {
|
||||
const { did } = step("paseo/workspace.next", {
|
||||
pathname: "/h/srv/workspace/ui-expose-archive-worktrees-on-merge",
|
||||
sidebarTargets: STATUS_VISUAL_TARGETS,
|
||||
selectedWorkspace: { serverId: "srv", workspaceId: "running-new" },
|
||||
});
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "running-old" }]]);
|
||||
});
|
||||
|
||||
it("moves backward from status row 2 to row 1 using status visual target order", () => {
|
||||
const { did } = step("paseo/workspace.previous", {
|
||||
pathname: "/h/srv/workspace/ui-expose-archive-worktrees-on-merge",
|
||||
sidebarTargets: STATUS_VISUAL_TARGETS,
|
||||
selectedWorkspace: { serverId: "srv", workspaceId: "running-new" },
|
||||
});
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "needs-input" }]]);
|
||||
});
|
||||
|
||||
it("moves backward from status row 3 to row 2 using status visual target order", () => {
|
||||
const { did } = step("paseo/workspace.previous", {
|
||||
pathname: "/h/srv/workspace/running-old",
|
||||
sidebarTargets: STATUS_VISUAL_TARGETS,
|
||||
selectedWorkspace: { serverId: "srv", workspaceId: "running-old" },
|
||||
});
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "running-new" }]]);
|
||||
});
|
||||
|
||||
it("falls back to the pathname workspace when no retained selection exists", () => {
|
||||
const { did } = step("paseo/workspace.previous", { pathname: "/h/srv/workspace/ws-3" });
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-2" }]]);
|
||||
});
|
||||
|
||||
it("wraps from the last target forward to the first", () => {
|
||||
const { did } = step("paseo/workspace.next", {
|
||||
selectedWorkspace: { serverId: "srv", workspaceId: "ws-5" },
|
||||
});
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-1" }]]);
|
||||
});
|
||||
|
||||
it("declines when there are no sidebar targets", () => {
|
||||
const { handled, did } = step("paseo/workspace.next", { sidebarTargets: [] });
|
||||
expect(handled).toBe(false);
|
||||
expect(did).toEqual([]);
|
||||
});
|
||||
|
||||
it("falls back to the first target when the current workspace is not in the sidebar", () => {
|
||||
const { did } = step("paseo/workspace.next", {
|
||||
pathname: "/settings/general",
|
||||
selectedWorkspace: { serverId: "other", workspaceId: "ws-x" },
|
||||
});
|
||||
expect(did).toEqual([["navigate-workspace", { serverId: "srv", workspaceId: "ws-1" }]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settings.toggle", () => {
|
||||
it("pushes to the settings root when not currently in settings", () => {
|
||||
const { actions, did } = createShell({ pathname: "/h/srv/workspace/ws-2" });
|
||||
actions.dispatch("paseo/settings.toggle");
|
||||
expect(did).toEqual([["router-push", "/settings"]]);
|
||||
});
|
||||
|
||||
it("navigates to the last workspace when leaving settings on desktop", () => {
|
||||
const { actions, did } = createShell({ pathname: "/settings/general", isMobile: false });
|
||||
actions.dispatch("paseo/settings.toggle");
|
||||
expect(did).toEqual([["navigate-last-workspace"]]);
|
||||
});
|
||||
|
||||
it("opens the project picker route when there is no workspace to return to", () => {
|
||||
const { actions, did } = createShell({
|
||||
pathname: "/settings/general",
|
||||
hasLastWorkspace: false,
|
||||
});
|
||||
actions.dispatch("paseo/settings.toggle");
|
||||
expect(did).toEqual([["navigate-last-workspace"], ["router-replace", "/open-project"]]);
|
||||
});
|
||||
|
||||
it("falls back to router.back() on mobile", () => {
|
||||
const { actions, did } = createShell({ pathname: "/settings/general", isMobile: true });
|
||||
actions.dispatch("paseo/settings.toggle");
|
||||
expect(did).toEqual([["router-back"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("callbacks and pickers", () => {
|
||||
it.each([
|
||||
["paseo/sidebar.toggle.left", "toggle-agent-list"],
|
||||
["paseo/sidebar.toggle.both", "toggle-agent-list"],
|
||||
["paseo/theme.cycle", "cycle-theme"],
|
||||
["paseo/project.open", "open-project-picker"],
|
||||
] as const)("%s → %s", (actionId, effect) => {
|
||||
const { actions, did } = createShell();
|
||||
expect(actions.dispatch(actionId)).toBe(true);
|
||||
expect(did).toEqual([[effect]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toggle dialogs", () => {
|
||||
it("opens the command center directly into the files sub-list from a workspace", () => {
|
||||
const { actions } = createShell();
|
||||
actions.dispatch("paseo/command-center.files");
|
||||
const store = useKeyboardShortcutsStore.getState();
|
||||
expect(store.commandCenterOpen).toBe(true);
|
||||
expect(store.commandCenterSublist?.id).toBe("files");
|
||||
});
|
||||
|
||||
it("leaves the file-search shortcut to the project-picker host outside a workspace", () => {
|
||||
const { actions, did } = createShell({ pathname: "/settings", projectPickerHost: true });
|
||||
expect(actions.dispatch("paseo/command-center.files")).toBe(true);
|
||||
expect(did).toEqual([["project-pick"]]);
|
||||
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("opens the command center when closed and closes it when open", () => {
|
||||
const { actions } = createShell();
|
||||
actions.dispatch("paseo/command-center.toggle");
|
||||
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(true);
|
||||
actions.dispatch("paseo/command-center.toggle");
|
||||
expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("toggles the shortcuts dialog", () => {
|
||||
const { actions } = createShell();
|
||||
actions.dispatch("paseo/shortcuts-dialog.toggle");
|
||||
expect(useKeyboardShortcutsStore.getState().shortcutsDialogOpen).toBe(true);
|
||||
actions.dispatch("paseo/shortcuts-dialog.toggle");
|
||||
expect(useKeyboardShortcutsStore.getState().shortcutsDialogOpen).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace switcher", () => {
|
||||
it("steps forward and backward", () => {
|
||||
const { actions, did } = createShell();
|
||||
actions.dispatch("paseo/workspace.switcher.next");
|
||||
actions.dispatch("paseo/workspace.switcher.previous");
|
||||
expect(did).toEqual([
|
||||
["workspace-switcher-cycle", 1],
|
||||
["workspace-switcher-cycle", -1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("declines when the switcher does not take the step", () => {
|
||||
const { actions } = createShell({ switcherTakesStep: false });
|
||||
expect(actions.dispatch("paseo/workspace.switcher.next")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown actions", () => {
|
||||
it("dispatches nothing for an id no one registered", () => {
|
||||
const { actions, did } = createShell();
|
||||
expect(actions.dispatch("totally.made.up")).toBe(false);
|
||||
expect(did).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,120 +0,0 @@
|
||||
import type { ActionDeclined } from "@/actions";
|
||||
import { COMMAND_CENTER_FILES_SUBLIST_ID } from "@/command-center/sublist";
|
||||
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
|
||||
import {
|
||||
buildOpenProjectRoute,
|
||||
buildSettingsRoute,
|
||||
parseHostWorkspaceRouteFromPathname,
|
||||
} from "@/utils/host-routes";
|
||||
import {
|
||||
getRelativeSidebarShortcutTarget,
|
||||
type SidebarShortcutWorkspaceTarget,
|
||||
} from "@/utils/sidebar-shortcuts";
|
||||
import type { CoreActionRuns } from "./provider";
|
||||
|
||||
const DECLINED: ActionDeclined = { handled: false };
|
||||
|
||||
/** What the app shell's actions act on: the route, navigation, and the shell's own toggles. */
|
||||
export interface AppShell {
|
||||
pathname(): string;
|
||||
isMobile(): boolean;
|
||||
router: {
|
||||
push(route: string): void;
|
||||
replace(route: string): void;
|
||||
back(): void;
|
||||
};
|
||||
/** The workspace navigation last selected, which can be ahead of the route. */
|
||||
selectedWorkspace(): SidebarShortcutWorkspaceTarget | null;
|
||||
navigateToWorkspace(target: SidebarShortcutWorkspaceTarget): void;
|
||||
/** Returns whether there was a workspace to go back to. */
|
||||
navigateToLastWorkspace(): boolean;
|
||||
/** Returns whether the switcher took the step. */
|
||||
cycleWorkspaceSwitcher(delta: 1 | -1): boolean;
|
||||
openProjectPicker(): void;
|
||||
toggleAgentList(): void;
|
||||
cycleTheme(): void;
|
||||
dispatch(actionId: string): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The app shell's `run` for the core actions no screen owns: navigation,
|
||||
* global toggles, and the fallbacks a focused workspace declines.
|
||||
*/
|
||||
export function createAppShellRuns(shell: AppShell): CoreActionRuns {
|
||||
function sidebarTargets(): readonly SidebarShortcutWorkspaceTarget[] {
|
||||
return useKeyboardShortcutsStore.getState().sidebarShortcutWorkspaceTargets;
|
||||
}
|
||||
|
||||
function jumpTo(target: SidebarShortcutWorkspaceTarget | null): void | ActionDeclined {
|
||||
if (!target) return DECLINED;
|
||||
shell.navigateToWorkspace({ serverId: target.serverId, workspaceId: target.workspaceId });
|
||||
}
|
||||
|
||||
function jumpRelative(delta: 1 | -1): void | ActionDeclined {
|
||||
const targets = sidebarTargets();
|
||||
if (targets.length === 0) return DECLINED;
|
||||
const current =
|
||||
shell.selectedWorkspace() ?? parseHostWorkspaceRouteFromPathname(shell.pathname());
|
||||
return jumpTo(
|
||||
getRelativeSidebarShortcutTarget({
|
||||
targets,
|
||||
currentTarget: current
|
||||
? { serverId: current.serverId, workspaceId: current.workspaceId }
|
||||
: null,
|
||||
delta,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function cycleSwitcher(delta: 1 | -1): void | ActionDeclined {
|
||||
return shell.cycleWorkspaceSwitcher(delta) ? undefined : DECLINED;
|
||||
}
|
||||
|
||||
return {
|
||||
"paseo/project.open": () => shell.openProjectPicker(),
|
||||
"paseo/settings.toggle": () => {
|
||||
if (!shell.pathname().startsWith("/settings")) {
|
||||
shell.router.push(buildSettingsRoute());
|
||||
} else if (!shell.isMobile()) {
|
||||
returnFromSettings(shell);
|
||||
} else {
|
||||
shell.router.back();
|
||||
}
|
||||
},
|
||||
"paseo/command-center.toggle": () => {
|
||||
const store = useKeyboardShortcutsStore.getState();
|
||||
store.setCommandCenterOpen(!store.commandCenterOpen);
|
||||
},
|
||||
"paseo/command-center.files": () => {
|
||||
if (!parseHostWorkspaceRouteFromPathname(shell.pathname())) {
|
||||
return shell.dispatch("paseo/workspace.project.pick") ? undefined : DECLINED;
|
||||
}
|
||||
useKeyboardShortcutsStore
|
||||
.getState()
|
||||
.setCommandCenterOpen(true, { sublistId: COMMAND_CENTER_FILES_SUBLIST_ID });
|
||||
},
|
||||
"paseo/shortcuts-dialog.toggle": () => {
|
||||
const store = useKeyboardShortcutsStore.getState();
|
||||
store.setShortcutsDialogOpen(!store.shortcutsDialogOpen);
|
||||
},
|
||||
"paseo/theme.cycle": () => shell.cycleTheme(),
|
||||
// A focused workspace takes both sidebars first; elsewhere only the agent list exists.
|
||||
"paseo/sidebar.toggle.left": () => shell.toggleAgentList(),
|
||||
"paseo/sidebar.toggle.both": () => shell.toggleAgentList(),
|
||||
"paseo/workspace.navigate.index": ({ index }) => {
|
||||
if (index === undefined) return DECLINED;
|
||||
return jumpTo(sidebarTargets()[index - 1] ?? null);
|
||||
},
|
||||
"paseo/workspace.previous": () => jumpRelative(-1),
|
||||
"paseo/workspace.next": () => jumpRelative(1),
|
||||
"paseo/workspace.switcher.next": () => cycleSwitcher(1),
|
||||
"paseo/workspace.switcher.previous": () => cycleSwitcher(-1),
|
||||
};
|
||||
}
|
||||
|
||||
/** Leaves Settings for the workspace it was opened from, or the project picker. */
|
||||
export function returnFromSettings(shell: Pick<AppShell, "navigateToLastWorkspace" | "router">) {
|
||||
if (!shell.navigateToLastWorkspace()) {
|
||||
shell.router.replace(buildOpenProjectRoute());
|
||||
}
|
||||
}
|
||||
@@ -1,588 +0,0 @@
|
||||
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,108 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
ActionRegistryProvider,
|
||||
createActionRegistry,
|
||||
createActionScopeStore,
|
||||
type ActionHandler,
|
||||
type ActionRegistry,
|
||||
type ActionScopeStore,
|
||||
} from "@/actions";
|
||||
import {
|
||||
createKeybindingRegistry,
|
||||
KeybindingRegistryProvider,
|
||||
type KeybindingRegistry,
|
||||
} from "@/keyboard";
|
||||
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
|
||||
import { CORE_ACTIONS } from "./actions";
|
||||
import { CORE_BINDINGS } from "./bindings";
|
||||
|
||||
/** The app shell's implementation of core actions that no mounted surface owns. */
|
||||
export type CoreActionRuns = Readonly<Partial<Record<string, ActionHandler>>>;
|
||||
|
||||
interface RunsSlot {
|
||||
current: CoreActionRuns;
|
||||
}
|
||||
|
||||
const DECLINED = { handled: false } as const;
|
||||
|
||||
const RunsSlotContext = createContext<RunsSlot | null>(null);
|
||||
|
||||
export interface CoreRegistries {
|
||||
scopes: ActionScopeStore;
|
||||
actions: ActionRegistry;
|
||||
keybindings: KeybindingRegistry;
|
||||
}
|
||||
|
||||
function registerCore(runs: RunsSlot): CoreRegistries {
|
||||
const scopes = createActionScopeStore();
|
||||
const actions = createActionRegistry({ scopes });
|
||||
const keybindings = createKeybindingRegistry({ actions, scopes });
|
||||
for (const definition of CORE_ACTIONS) {
|
||||
actions.registerAction({
|
||||
...definition,
|
||||
run: (invocation) => {
|
||||
const run = runs.current[definition.id];
|
||||
return run ? run(invocation) : DECLINED;
|
||||
},
|
||||
});
|
||||
}
|
||||
keybindings.registerBindings(CORE_BINDINGS);
|
||||
return { scopes, actions, keybindings };
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's registries with every `paseo/*` action and default binding, for
|
||||
* code that runs outside `CoreActionsProvider`. A core action with no entry in
|
||||
* `runs` and no mounted handler is declined.
|
||||
*/
|
||||
export function createCoreRegistries(runs: CoreActionRuns = {}): CoreRegistries {
|
||||
return registerCore({ current: runs });
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the app's action and keybinding registries and registers every
|
||||
* `paseo/*` action and default shortcut, so Settings and badges see them
|
||||
* before any surface mounts. Mount it once, at the app root.
|
||||
*/
|
||||
export function CoreActionsProvider({ children }: { children: ReactNode }) {
|
||||
const [core] = useState(() => {
|
||||
const runs: RunsSlot = { current: {} };
|
||||
return { runs, ...registerCore(runs) };
|
||||
});
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
|
||||
useEffect(() => {
|
||||
core.keybindings.setOverrides(overrides);
|
||||
}, [core, overrides]);
|
||||
|
||||
useEffect(() => () => core.keybindings.dispose(), [core]);
|
||||
|
||||
return (
|
||||
<ActionRegistryProvider actions={core.actions} scopes={core.scopes}>
|
||||
<KeybindingRegistryProvider keybindings={core.keybindings}>
|
||||
<RunsSlotContext.Provider value={core.runs}>{children}</RunsSlotContext.Provider>
|
||||
</KeybindingRegistryProvider>
|
||||
</ActionRegistryProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies the `run` of core actions from the app shell. Each one runs after
|
||||
* every mounted handler declines, and reads the latest closure.
|
||||
*/
|
||||
export function useCoreActionRuns(runs: CoreActionRuns): void {
|
||||
const slot = useContext(RunsSlotContext);
|
||||
if (!slot) {
|
||||
throw new Error("useCoreActionRuns must be used within CoreActionsProvider");
|
||||
}
|
||||
useLayoutEffect(() => {
|
||||
slot.current = runs;
|
||||
});
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
import { whenMatchesPlatform, type DisplayPlatform, type EffectiveKeybinding } from "@/keyboard";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { chordStringToShortcutKeys } from "@/keyboard/shortcut-string";
|
||||
|
||||
interface ShortcutRowDefinition {
|
||||
actionId: string;
|
||||
labelKey: string;
|
||||
noteKey?: string;
|
||||
}
|
||||
|
||||
interface ShortcutSectionDefinition {
|
||||
id: string;
|
||||
titleKey: string;
|
||||
rows: readonly ShortcutRowDefinition[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings → Shortcuts and the shortcuts dialog, in display order: sections
|
||||
* most-reached-for first, and in each section the shortcut someone opens the
|
||||
* sheet to find at the top.
|
||||
*/
|
||||
const SHORTCUT_SECTIONS: readonly ShortcutSectionDefinition[] = [
|
||||
{
|
||||
id: "general",
|
||||
titleKey: "settings.shortcuts.sections.general",
|
||||
rows: [
|
||||
{
|
||||
actionId: "paseo/command-center.toggle",
|
||||
labelKey: "settings.shortcuts.help.toggleCommandCenter",
|
||||
},
|
||||
{ actionId: "paseo/command-center.files", labelKey: "settings.shortcuts.help.searchFiles" },
|
||||
{
|
||||
actionId: "paseo/shortcuts-dialog.toggle",
|
||||
labelKey: "settings.shortcuts.help.showKeyboardShortcuts",
|
||||
noteKey: "settings.shortcuts.helpNotes.showKeyboardShortcuts",
|
||||
},
|
||||
{ actionId: "paseo/settings.toggle", labelKey: "settings.shortcuts.help.toggleSettings" },
|
||||
{ actionId: "paseo/theme.cycle", labelKey: "settings.shortcuts.help.cycleTheme" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "workspaces",
|
||||
titleKey: "settings.shortcuts.sections.workspaces",
|
||||
rows: [
|
||||
{ actionId: "paseo/project.open", labelKey: "settings.shortcuts.help.openProject" },
|
||||
{ actionId: "paseo/workspace.new", labelKey: "settings.shortcuts.help.newWorkspace" },
|
||||
{
|
||||
actionId: "paseo/workspace.switcher.next",
|
||||
labelKey: "settings.shortcuts.help.switchRecentWorkspace",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.switcher.previous",
|
||||
labelKey: "settings.shortcuts.help.switchRecentWorkspaceReverse",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.navigate.index",
|
||||
labelKey: "settings.shortcuts.help.jumpToWorkspace",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.previous",
|
||||
labelKey: "settings.shortcuts.help.previousWorkspace",
|
||||
},
|
||||
{ actionId: "paseo/workspace.next", labelKey: "settings.shortcuts.help.nextWorkspace" },
|
||||
{ actionId: "paseo/workspace.pin", labelKey: "Pin chat" },
|
||||
{ actionId: "paseo/workspace.archive", labelKey: "settings.shortcuts.help.archiveWorkspace" },
|
||||
{ actionId: "paseo/workspace.archive.undo", labelKey: "Undo archive workspace" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "tabs-panes",
|
||||
titleKey: "settings.shortcuts.sections.tabsPanes",
|
||||
rows: [
|
||||
{ actionId: "paseo/workspace.tab.menu.open", labelKey: "settings.shortcuts.help.newTab" },
|
||||
{ actionId: "paseo/workspace.tab.target.agent", labelKey: "workspace.tabs.actions.newAgent" },
|
||||
{ actionId: "paseo/workspace.terminal.new", labelKey: "settings.shortcuts.help.newTerminal" },
|
||||
{
|
||||
actionId: "paseo/workspace.tab.target.browser",
|
||||
labelKey: "workspace.tabs.actions.newBrowser",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.tab.target.changes",
|
||||
labelKey: "workspace.tabs.actions.changes",
|
||||
},
|
||||
{ actionId: "paseo/workspace.tab.target.files", labelKey: "workspace.tabs.actions.files" },
|
||||
{
|
||||
actionId: "paseo/workspace.tab.close-current",
|
||||
labelKey: "settings.shortcuts.help.closeCurrentTab",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.tab.navigate.index",
|
||||
labelKey: "settings.shortcuts.help.jumpToTab",
|
||||
},
|
||||
{ actionId: "paseo/workspace.tab.previous", labelKey: "settings.shortcuts.help.previousTab" },
|
||||
{ actionId: "paseo/workspace.tab.next", labelKey: "settings.shortcuts.help.nextTab" },
|
||||
{
|
||||
actionId: "paseo/workspace.pane.split.right",
|
||||
labelKey: "settings.shortcuts.help.splitPaneRight",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.split.down",
|
||||
labelKey: "settings.shortcuts.help.splitPaneDown",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.focus.left",
|
||||
labelKey: "settings.shortcuts.help.focusPaneLeft",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.focus.right",
|
||||
labelKey: "settings.shortcuts.help.focusPaneRight",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.focus.up",
|
||||
labelKey: "settings.shortcuts.help.focusPaneUp",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.focus.down",
|
||||
labelKey: "settings.shortcuts.help.focusPaneDown",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.move-tab.left",
|
||||
labelKey: "settings.shortcuts.help.moveTabLeft",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.move-tab.right",
|
||||
labelKey: "settings.shortcuts.help.moveTabRight",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.move-tab.up",
|
||||
labelKey: "settings.shortcuts.help.moveTabUp",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.pane.move-tab.down",
|
||||
labelKey: "settings.shortcuts.help.moveTabDown",
|
||||
},
|
||||
{ actionId: "paseo/workspace.pane.close", labelKey: "settings.shortcuts.help.closePane" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "layout",
|
||||
titleKey: "settings.shortcuts.sections.layout",
|
||||
rows: [
|
||||
{
|
||||
actionId: "paseo/sidebar.toggle.left",
|
||||
labelKey: "settings.shortcuts.help.toggleLeftSidebar",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/sidebar.toggle.right",
|
||||
labelKey: "settings.shortcuts.help.toggleRightSidebar",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/sidebar.toggle.both",
|
||||
labelKey: "settings.shortcuts.help.toggleBothSidebars",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/workspace.focus.toggle",
|
||||
labelKey: "settings.shortcuts.help.toggleFocusMode",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "agent-input",
|
||||
titleKey: "settings.shortcuts.sections.agentInput",
|
||||
rows: [
|
||||
{
|
||||
actionId: "paseo/message-input.focus",
|
||||
labelKey: "settings.shortcuts.help.focusMessageInput",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/message-input.model-toggle",
|
||||
labelKey: "settings.shortcuts.help.toggleModelPicker",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/message-input.effort-cycle",
|
||||
labelKey: "settings.shortcuts.help.cycleEffort",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/message-input.mode-cycle",
|
||||
labelKey: "settings.shortcuts.help.cycleAgentMode",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/message-input.voice-toggle",
|
||||
labelKey: "settings.shortcuts.help.toggleVoiceMode",
|
||||
},
|
||||
{
|
||||
actionId: "paseo/message-input.dictation-toggle",
|
||||
labelKey: "settings.shortcuts.help.startStopDictation",
|
||||
},
|
||||
{ actionId: "paseo/agent.interrupt", labelKey: "settings.shortcuts.help.interruptAgent" },
|
||||
{
|
||||
actionId: "paseo/message-input.voice-mute-toggle",
|
||||
labelKey: "settings.shortcuts.help.muteUnmuteVoiceMode",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export interface ShortcutRow {
|
||||
/** The action id. */
|
||||
id: string;
|
||||
labelKey: string;
|
||||
noteKey?: string;
|
||||
/** The binding a rebind edits: the action's first binding on this platform. */
|
||||
binding: EffectiveKeybinding;
|
||||
/** The keys that fire it, or `null` when the user unassigned it. */
|
||||
chord: ShortcutKey[][] | null;
|
||||
}
|
||||
|
||||
export interface ShortcutSection {
|
||||
id: string;
|
||||
titleKey: string;
|
||||
rows: ShortcutRow[];
|
||||
}
|
||||
|
||||
function rowFor(
|
||||
definition: ShortcutRowDefinition,
|
||||
bindings: readonly EffectiveKeybinding[],
|
||||
platform: DisplayPlatform,
|
||||
): ShortcutRow | null {
|
||||
const binding = bindings.find(
|
||||
(candidate) =>
|
||||
candidate.actionId === definition.actionId && whenMatchesPlatform(candidate.when, platform),
|
||||
);
|
||||
if (!binding) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: definition.actionId,
|
||||
labelKey: definition.labelKey,
|
||||
...(definition.noteKey ? { noteKey: definition.noteKey } : {}),
|
||||
binding,
|
||||
chord: binding.parsedChord.length === 0 ? null : chordStringToShortcutKeys(binding.combo),
|
||||
};
|
||||
}
|
||||
|
||||
/** The shortcut sections for this platform. A row with no binding here is left out. */
|
||||
export function buildShortcutSections(
|
||||
bindings: readonly EffectiveKeybinding[],
|
||||
platform: DisplayPlatform,
|
||||
): ShortcutSection[] {
|
||||
return SHORTCUT_SECTIONS.flatMap((section) => {
|
||||
const rows = section.rows.flatMap((row) => rowFor(row, bindings, platform) ?? []);
|
||||
return rows.length > 0 ? [{ id: section.id, titleKey: section.titleKey, rows }] : [];
|
||||
});
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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) };
|
||||
}
|
||||
@@ -94,6 +94,18 @@ describe("desktop-daemon-transport", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports socket and pipe sessions as local and Remote SSH sessions as remote", () => {
|
||||
const transportFactory = createDesktopDaemonTransportFactory(
|
||||
createFakeLocalDaemonTransportRpc(),
|
||||
);
|
||||
const open = (target: Parameters<typeof buildDesktopDaemonTransportUrl>[0]) =>
|
||||
transportFactory!({ url: buildDesktopDaemonTransportUrl(target) });
|
||||
|
||||
expect(open({ transportType: "socket", transportPath: "/tmp/paseo.sock" }).local).toBe(true);
|
||||
expect(open({ transportType: "pipe", transportPath: "\\\\.\\pipe\\paseo" }).local).toBe(true);
|
||||
expect(open({ transportType: "ssh", host: "deploy@example.com" }).local).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, 65536])("rejects an out-of-range Remote SSH port (%s)", (sshPort) => {
|
||||
const transportFactory = createDesktopDaemonTransportFactory(
|
||||
createFakeLocalDaemonTransportRpc(),
|
||||
|
||||
@@ -168,6 +168,8 @@ export function createDesktopDaemonTransportFactory(
|
||||
})();
|
||||
|
||||
const transport: DaemonTransport = {
|
||||
// Remote SSH forwards bytes across the network; sockets and pipes stay on this machine.
|
||||
local: target.transportType !== "ssh",
|
||||
send: (data) => {
|
||||
if (!didEmitOpen) {
|
||||
return;
|
||||
|
||||
@@ -73,7 +73,7 @@ type TextFilePanelProps = BuiltinFilePanelProps & {
|
||||
*/
|
||||
export function TextFilePanel(props: TextFilePanelProps) {
|
||||
const size = props.file.size;
|
||||
const presentation = selectSourcePresentation({ size, platform: isWeb ? "web" : "native" });
|
||||
const presentation = selectSourcePresentation({ size });
|
||||
if (presentation === "unsupported") return <TooLargeTextFile size={size} />;
|
||||
if (isWeb && size <= MAX_EDITABLE_BYTES) return <EditableTextFile {...props} />;
|
||||
return <ReadonlyTextFile {...props} presentation={presentation} />;
|
||||
|
||||
@@ -11,4 +11,11 @@ describe("selectSourcePresentation", () => {
|
||||
expect(selectSourcePresentation({ platform, size: budgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
}
|
||||
|
||||
it("defaults to the target resource budget limits when no platform override is passed", () => {
|
||||
const webBudgets = SOURCE_PRESENTATION_BUDGETS.web;
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted })).toBe("highlighted");
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted + 1 })).toBe("plain");
|
||||
expect(selectSourcePresentation({ size: webBudgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { sourceFileBudgets } from "@/constants/resource-budget";
|
||||
import { resolveResourceBudgets } from "@/constants/resource-budget-tables";
|
||||
|
||||
export const SOURCE_PRESENTATION_BUDGETS = {
|
||||
web: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
native: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
web: resolveResourceBudgets({ isNative: false }).sourceFileBudgets,
|
||||
native: resolveResourceBudgets({ isNative: true }).sourceFileBudgets,
|
||||
} as const;
|
||||
|
||||
export type SourcePresentation = "highlighted" | "plain" | "unsupported";
|
||||
@@ -8,9 +11,9 @@ export type SourcePlatform = keyof typeof SOURCE_PRESENTATION_BUDGETS;
|
||||
|
||||
export function selectSourcePresentation(input: {
|
||||
size: number;
|
||||
platform: SourcePlatform;
|
||||
platform?: SourcePlatform;
|
||||
}): SourcePresentation {
|
||||
const budgets = SOURCE_PRESENTATION_BUDGETS[input.platform];
|
||||
const budgets = input.platform ? SOURCE_PRESENTATION_BUDGETS[input.platform] : sourceFileBudgets;
|
||||
if (input.size <= budgets.highlighted) return "highlighted";
|
||||
if (input.size <= budgets.plain) return "plain";
|
||||
return "unsupported";
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useShortcutKeys } from "@/keyboard";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { actionsWithoutPrimary, type GitAction, type GitActions } from "@/git/policy";
|
||||
@@ -83,7 +83,7 @@ export function GitActionsSplitButton({
|
||||
const { theme } = useUnistyles();
|
||||
const { t } = useTranslation();
|
||||
const runGitAction = useGitActionRunner();
|
||||
const archiveShortcutKeys = useShortcutKeys("paseo/workspace.archive");
|
||||
const archiveShortcutKeys = useShortcutKeys("archive-workspace");
|
||||
|
||||
const getActionDisplayLabel = useCallback((action: GitAction): string => {
|
||||
if (action.status === "pending") return action.pendingLabel;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useCallback } from "react";
|
||||
import { router } from "expo-router";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspace } from "@/stores/session-store-hooks";
|
||||
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
|
||||
|
||||
const WORKTREE_NEW_ACTIONS: readonly KeyboardActionId[] = ["worktree.new"];
|
||||
|
||||
export function useActiveWorktreeNewAction() {
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
const workspaceId = selection?.workspaceId ?? null;
|
||||
const activeWorkspace = useWorkspace(serverId, workspaceId);
|
||||
const activeGitWorkspace = activeWorkspace?.projectKind === "git" ? activeWorkspace : null;
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (!serverId || !activeGitWorkspace) {
|
||||
return false;
|
||||
}
|
||||
router.navigate(
|
||||
buildNewWorkspaceRoute({
|
||||
serverId,
|
||||
sourceDirectory: activeGitWorkspace.projectRootPath,
|
||||
projectId: activeGitWorkspace.projectId,
|
||||
}) as never,
|
||||
);
|
||||
return true;
|
||||
}, [activeGitWorkspace, serverId]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "worktree-new-active",
|
||||
actions: WORKTREE_NEW_ACTIONS,
|
||||
enabled: serverId !== null && activeGitWorkspace !== null,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback } from "react";
|
||||
import { router } from "expo-router";
|
||||
import { useActionHandler } from "@/actions";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { canCreateWorktreeForProjectKind } from "@/projects/host-projects";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
@@ -8,6 +9,8 @@ import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspac
|
||||
import { useWorkspace } from "@/stores/session-store-hooks";
|
||||
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
|
||||
|
||||
const WORKSPACE_NEW_ACTIONS: readonly KeyboardActionId[] = ["workspace.new"];
|
||||
|
||||
export function useGlobalNewWorkspaceAction() {
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
@@ -22,7 +25,7 @@ export function useGlobalNewWorkspaceAction() {
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (hosts.length === 0) {
|
||||
return { handled: false } as const;
|
||||
return false;
|
||||
}
|
||||
router.navigate(
|
||||
(serverId
|
||||
@@ -37,7 +40,14 @@ export function useGlobalNewWorkspaceAction() {
|
||||
)
|
||||
: buildNewWorkspaceRoute()) as never,
|
||||
);
|
||||
return true;
|
||||
}, [activeWorkspace, canUseActiveWorkspaceContext, hosts.length, serverId]);
|
||||
|
||||
useActionHandler("paseo/workspace.new", handle, { enabled: hosts.length > 0 });
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-new-global",
|
||||
actions: WORKSPACE_NEW_ACTIONS,
|
||||
enabled: hosts.length > 0,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive";
|
||||
import { useActionHandler } from "@/actions";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
|
||||
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
|
||||
@@ -8,7 +11,11 @@ import { useActionHandler } from "@/actions";
|
||||
export function useGlobalWorkspaceArchiveAction() {
|
||||
const { canArchive, archive } = useActiveWorkspaceArchive();
|
||||
|
||||
useActionHandler("paseo/workspace.archive", () => (archive() ? undefined : { handled: false }), {
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-archive-global",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
enabled: canArchive,
|
||||
priority: 0,
|
||||
handle: archive,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useCallback } from "react";
|
||||
import { useActionHandler } from "@/actions";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useSidebarWorkspacePinController } from "@/hooks/use-sidebar-workspace-pin";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
|
||||
const WORKSPACE_PIN_ACTIONS: readonly KeyboardActionId[] = ["workspace.pin"];
|
||||
|
||||
// The pin shortcut used to live on the sidebar row, so it disappeared whenever the row was not
|
||||
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode.
|
||||
// It belongs here instead: one registration keyed on the active route selection.
|
||||
@@ -33,14 +36,14 @@ export function useGlobalWorkspacePinAction() {
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (!serverId || !fields || !canPin) {
|
||||
return { handled: false } as const;
|
||||
return false;
|
||||
}
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey({
|
||||
serverId,
|
||||
workspaceId: fields.id,
|
||||
});
|
||||
if (!workspaceKey) {
|
||||
return { handled: false } as const;
|
||||
return false;
|
||||
}
|
||||
togglePin({
|
||||
serverId,
|
||||
@@ -48,9 +51,14 @@ export function useGlobalWorkspacePinAction() {
|
||||
workspaceKey,
|
||||
pinnedAt: fields.pinnedAt,
|
||||
});
|
||||
return true;
|
||||
}, [canPin, fields, serverId, togglePin]);
|
||||
|
||||
useActionHandler("paseo/workspace.pin", handle, {
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-pin-global",
|
||||
actions: WORKSPACE_PIN_ACTIONS,
|
||||
enabled: serverId !== null && fields !== null && canPin,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import type {
|
||||
KeyboardActionDefinition,
|
||||
KeyboardActionId,
|
||||
} from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
|
||||
interface UseKeyboardActionHandlerInput {
|
||||
handlerId: string;
|
||||
actions: readonly KeyboardActionId[];
|
||||
enabled: boolean;
|
||||
priority: number;
|
||||
isActive?: () => boolean;
|
||||
handle: (action: KeyboardActionDefinition) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a keyboard action handler with the global dispatcher.
|
||||
*
|
||||
* The dispatcher is driven by a native window keydown listener and calls the
|
||||
* most-recently-registered matching handler first (see keyboard-action-dispatcher.ts).
|
||||
* Two properties must hold or handlers bound to the same action step on each other:
|
||||
*
|
||||
* 1. Stable registration order. registerHandler bumps a registration counter, so
|
||||
* re-registering on every render reshuffles which handler the dispatcher reaches
|
||||
* first. A frequently re-rendering control (e.g. a running agent's mode control)
|
||||
* would then jump ahead of another (e.g. the New Workspace draft) and consume the
|
||||
* key, silently acting on the wrong surface. So we register once per
|
||||
* (handlerId, priority, actions) and never re-register just because handle,
|
||||
* isActive, or enabled changed.
|
||||
*
|
||||
* 2. Fresh callbacks. Because we do not re-register on every render, the registered
|
||||
* entry must read the latest props at dispatch time. handle and isActive are read
|
||||
* live from a ref, and enabled is folded into isActive so the dispatcher
|
||||
* re-evaluates it fresh (the plain enabled field it filters on is captured at
|
||||
* registration and would otherwise go stale).
|
||||
*/
|
||||
export function useKeyboardActionHandler(input: UseKeyboardActionHandlerInput) {
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const inputRef = useRef(input);
|
||||
inputRef.current = input;
|
||||
|
||||
// Only these identity-affecting fields trigger a re-register. actions is compared by
|
||||
// content, not array identity, so inline literals do not churn the registration.
|
||||
const actionsKey = input.actions.join(" ");
|
||||
useEffect(() => {
|
||||
return keyboardActionDispatcher.registerHandler({
|
||||
handlerId: inputRef.current.handlerId,
|
||||
actions: inputRef.current.actions,
|
||||
// Always-on at the coarse filter; the real enable/active gate is re-checked fresh
|
||||
// inside isActive below so it can never be stale in the registry entry.
|
||||
enabled: true,
|
||||
priority: inputRef.current.priority,
|
||||
isActive: () => {
|
||||
const current = inputRef.current;
|
||||
if (!current.enabled) return false;
|
||||
return current.isActive ? current.isActive() : true;
|
||||
},
|
||||
handle: (action) => inputRef.current.handle(action),
|
||||
});
|
||||
}, [actionsKey, input.handlerId, input.priority, keyboardActionDispatcher]);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { type QueryClient, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import type { ShortcutOverrides } from "@/keyboard/shortcut-override-store";
|
||||
import type { ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
|
||||
import {
|
||||
createShortcutOverrideStore,
|
||||
type ShortcutOverrideStore,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useActionHandler } from "@/actions";
|
||||
import { useId } from "react";
|
||||
import { hasFocusedTextInput } from "@/keyboard";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
|
||||
export interface KeyboardToggleAction {
|
||||
id: string;
|
||||
id: KeyboardActionId;
|
||||
canOpen: () => boolean;
|
||||
}
|
||||
|
||||
@@ -20,10 +22,17 @@ export function useKeyboardToggle({
|
||||
searchFocused: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
useActionHandler(action ? action.id : [], onToggle, {
|
||||
enabled: () =>
|
||||
action !== undefined &&
|
||||
!disabled &&
|
||||
(action.canOpen() || (open && (searchFocused || !hasFocusedTextInput()))),
|
||||
const handlerId = useId();
|
||||
useKeyboardActionHandler({
|
||||
handlerId,
|
||||
actions: action ? [action.id] : [],
|
||||
enabled: action !== undefined && !disabled,
|
||||
priority: 200,
|
||||
isActive: () =>
|
||||
action?.canOpen() === true || (open && (searchFocused || !hasFocusedTextInput())),
|
||||
handle: () => {
|
||||
onToggle();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -23,7 +23,12 @@ import {
|
||||
isChecksHiddenByLegacyRowItem,
|
||||
type SidebarRowItems,
|
||||
} from "@/components/sidebar/display-preferences/row-items";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import {
|
||||
initialContentFontSize,
|
||||
initialUiBaseFontSize,
|
||||
resolvePresentationCapabilities,
|
||||
usesMobileContentFontMigration,
|
||||
} from "@/constants/presentation";
|
||||
import {
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
FONT_SIZE,
|
||||
@@ -60,17 +65,19 @@ export const DEFAULT_TERMINAL_SCROLLBACK_LINES = 10_000;
|
||||
export const MIN_TERMINAL_SCROLLBACK_LINES = 0;
|
||||
export const MAX_TERMINAL_SCROLLBACK_LINES = 1_000_000;
|
||||
export function defaultUiBaseFontSize(native: boolean): number {
|
||||
return native ? 15 : FONT_SIZE.base;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialUiBaseFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = defaultUiBaseFontSize(isNative);
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = initialUiBaseFontSize;
|
||||
export const MIN_UI_BASE_FONT_SIZE = 10;
|
||||
export const MAX_UI_BASE_FONT_SIZE = 21;
|
||||
export function defaultContentFontSize(native: boolean): number {
|
||||
return native ? 16 : FONT_SIZE.content;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialContentFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = defaultContentFontSize(isNative);
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = initialContentFontSize;
|
||||
export const MIN_CONTENT_FONT_SIZE = 10;
|
||||
export const MAX_CONTENT_FONT_SIZE = 21;
|
||||
export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
|
||||
@@ -410,7 +417,9 @@ export async function loadAppSettingsFromStorage(deps: SettingsDeps): Promise<Ap
|
||||
await writeAppSettings(deps.storage, read.stored, read.settings);
|
||||
}
|
||||
const { needsWrite: _needsWrite, ...stored } = read.stored;
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, { native: isNative });
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, {
|
||||
native: usesMobileContentFontMigration,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[AppSettings] Failed to load settings:", error);
|
||||
throw error;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { usesDesktopBindings } from "@/keyboard";
|
||||
import { useMemo } from "react";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { resolveShortcutKeysForAction } from "@/keyboard/keyboard-shortcuts";
|
||||
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
|
||||
/** `null` action ids are accepted so callers can keep the hook unconditional. */
|
||||
export function useShortcutKeys(actionId: string | null): ShortcutKey[][] | null {
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
const isMac = getShortcutOs() === "mac";
|
||||
|
||||
return useMemo(() => {
|
||||
if (actionId === null) return null;
|
||||
return resolveShortcutKeysForAction(actionId, overrides, {
|
||||
isMac,
|
||||
usesDesktopBindings,
|
||||
});
|
||||
}, [actionId, overrides, isMac]);
|
||||
}
|
||||
@@ -2435,6 +2435,9 @@ export const ar: TranslationResources = {
|
||||
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "تعذّر عرض هذه اللوحة",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "وكيل جديد",
|
||||
creatingAgent: "وكيل الخلق",
|
||||
|
||||
@@ -2467,6 +2467,9 @@ export const en = {
|
||||
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Unable to show this panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "New Agent",
|
||||
creatingAgent: "Creating agent",
|
||||
|
||||
@@ -2495,6 +2495,9 @@ export const es: TranslationResources = {
|
||||
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "No se puede mostrar este panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nuevo agente",
|
||||
creatingAgent: "Agente creador",
|
||||
|
||||
@@ -2491,6 +2491,9 @@ export const fr: TranslationResources = {
|
||||
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Impossible d'afficher ce panneau",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nouvel agent",
|
||||
creatingAgent: "Création de l’agent",
|
||||
|
||||
@@ -2461,6 +2461,9 @@ export const ja: TranslationResources = {
|
||||
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "このパネルを表示できません",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新しいエージェント",
|
||||
creatingAgent: "エージェントを作成中",
|
||||
|
||||
@@ -2452,6 +2452,9 @@ export const ko: TranslationResources = {
|
||||
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "이 패널을 표시할 수 없습니다",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "새 에이전트",
|
||||
creatingAgent: "에이전트 생성 중",
|
||||
|
||||
@@ -2477,6 +2477,9 @@ export const ptBR: TranslationResources = {
|
||||
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Não foi possível exibir este painel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Novo Agente",
|
||||
creatingAgent: "Criando agente",
|
||||
|
||||
@@ -2477,6 +2477,9 @@ export const ru: TranslationResources = {
|
||||
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Не удалось показать эту панель",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Новый агент",
|
||||
creatingAgent: "Создание агента",
|
||||
|
||||
@@ -2408,6 +2408,9 @@ export const zhCN: TranslationResources = {
|
||||
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "无法显示此面板",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新建 Agent",
|
||||
creatingAgent: "正在创建 Agent",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
export type KeyboardFocusScope =
|
||||
| "terminal"
|
||||
| "message-input"
|
||||
| "command-center"
|
||||
| "editable"
|
||||
| "browser"
|
||||
| "other";
|
||||
|
||||
export type MessageInputKeyboardActionKind =
|
||||
| "focus"
|
||||
| "send"
|
||||
| "dictation-toggle"
|
||||
| "dictation-cancel"
|
||||
| "dictation-confirm"
|
||||
| "voice-toggle"
|
||||
| "voice-mute-toggle"
|
||||
| "mode-cycle"
|
||||
| "model-toggle"
|
||||
| "effort-cycle";
|
||||
|
||||
export type KeyboardActionId =
|
||||
| "agent.interrupt"
|
||||
| "agent.new"
|
||||
| "workspace.tab.menu.open"
|
||||
| "workspace.tab.target.agent"
|
||||
| "workspace.tab.target.browser"
|
||||
| "workspace.tab.target.changes"
|
||||
| "workspace.tab.target.files"
|
||||
| "workspace.tab.close.current"
|
||||
| "workspace.tab.navigate.index"
|
||||
| "workspace.tab.navigate.relative"
|
||||
| "workspace.pane.split.right"
|
||||
| "workspace.pane.split.down"
|
||||
| "workspace.pane.focus.left"
|
||||
| "workspace.pane.focus.right"
|
||||
| "workspace.pane.focus.up"
|
||||
| "workspace.pane.focus.down"
|
||||
| "workspace.pane.move-tab.left"
|
||||
| "workspace.pane.move-tab.right"
|
||||
| "workspace.pane.move-tab.up"
|
||||
| "workspace.pane.move-tab.down"
|
||||
| "workspace.pane.close"
|
||||
| "workspace.navigate.index"
|
||||
| "workspace.navigate.relative"
|
||||
| "workspace.switcher.cycle"
|
||||
| "sidebar.toggle.left"
|
||||
| "sidebar.toggle.right"
|
||||
| "sidebar.toggle.both"
|
||||
| "settings.toggle"
|
||||
| "command-center.toggle"
|
||||
| "command-center.files"
|
||||
| "shortcuts.dialog.toggle"
|
||||
| "workspace.terminal.new"
|
||||
| "workspace.new"
|
||||
| "workspace.project.pick"
|
||||
| "worktree.new"
|
||||
| "workspace.archive"
|
||||
| "workspace.archive.undo"
|
||||
| "workspace.pin"
|
||||
| "view.toggle.focus"
|
||||
| "theme.cycle"
|
||||
| "message-input.action";
|
||||
|
||||
export type KeyboardShortcutPayload =
|
||||
| { index: number }
|
||||
| { delta: 1 | -1 }
|
||||
| { kind: MessageInputKeyboardActionKind }
|
||||
| null;
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHardwareKeyboardPresence } from "./internal/hardware-presence";
|
||||
import { createRecordingCoreRegistries } from "@/core-actions/testing";
|
||||
import * as webConventions from "./internal/conventions.web";
|
||||
import { createWebHardwareKeyboardPresence } from "./internal/presence.web";
|
||||
import { buildEffectiveBindings } from "./keyboard-shortcuts";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { createOverlayRegistry } from "./internal/overlays";
|
||||
import { nativeKeyboardInput } from "./internal/sources/contract";
|
||||
@@ -34,11 +36,15 @@ describe("hardware keyboard availability", () => {
|
||||
|
||||
it("routes compact Electron input independently of hint availability", () => {
|
||||
const presence = createHardwareKeyboardPresence({ read: () => false, watch: () => () => {} });
|
||||
const core = createRecordingCoreRegistries();
|
||||
const actions: string[] = [];
|
||||
const pipeline = createKeyboardPipeline({
|
||||
getContext: () => ({ isMac: true, usesDesktopBindings: true, commandCenterOpen: false }),
|
||||
keybindings: core.keybindings,
|
||||
getBindings: () => buildEffectiveBindings({}),
|
||||
isCapturing: () => false,
|
||||
dispatch: (match) => {
|
||||
actions.push(match.action);
|
||||
return true;
|
||||
},
|
||||
overlays: createOverlayRegistry(),
|
||||
});
|
||||
pipeline.keyDown(
|
||||
@@ -58,7 +64,42 @@ describe("hardware keyboard availability", () => {
|
||||
),
|
||||
);
|
||||
expect(presence.getSnapshot()).toBe(false);
|
||||
expect(core.ranIds()).toEqual(["paseo/command-center.toggle"]);
|
||||
expect(actions).toEqual(["command-center.toggle"]);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("answers keyboard presence and conventions per target", async () => {
|
||||
const nativeConventions = (await import(
|
||||
new URL("./internal/conventions.ts", import.meta.url).href
|
||||
)) as typeof webConventions & { usesDesktopBindings: boolean };
|
||||
const { hardwareKeyboardPresence: nativePresence } = (await import(
|
||||
new URL("./internal/presence.ts", import.meta.url).href
|
||||
)) as { hardwareKeyboardPresence: { getSnapshot(): boolean } };
|
||||
|
||||
expect(nativePresence.getSnapshot()).toBe(false);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: true } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: false } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(false);
|
||||
|
||||
expect({
|
||||
usesDesktopBindings: nativeConventions.usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys: nativeConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: nativeConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
usesDesktopBindings: true,
|
||||
supportsConfigurableComposerSendKeys: false,
|
||||
hasSoftwareKeyboard: true,
|
||||
});
|
||||
|
||||
expect({
|
||||
supportsConfigurableComposerSendKeys: webConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: webConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
supportsConfigurableComposerSendKeys: true,
|
||||
hasSoftwareKeyboard: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { KeyboardFocusScope } from "./internal/key-event";
|
||||
import type { KeyboardFocusScope } from "@/keyboard/actions";
|
||||
|
||||
function isElement(value: unknown): value is Element {
|
||||
return typeof Element !== "undefined" && value instanceof Element;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildWorkspaceKeyboardHandlerId } from "@/keyboard/handler-id";
|
||||
|
||||
describe("buildWorkspaceKeyboardHandlerId", () => {
|
||||
it("separates workspaces that share a pane id", () => {
|
||||
// Every workspace's default pane is called "main", and the deck keeps several
|
||||
// workspaces mounted at once. Dropping the workspace id here left the evicted
|
||||
// workspace without a keyboard.
|
||||
const left = buildWorkspaceKeyboardHandlerId({
|
||||
name: "workspace-new-tab-menu",
|
||||
serverId: "srv",
|
||||
workspaceId: "wks_a",
|
||||
paneId: "main",
|
||||
});
|
||||
const right = buildWorkspaceKeyboardHandlerId({
|
||||
name: "workspace-new-tab-menu",
|
||||
serverId: "srv",
|
||||
workspaceId: "wks_b",
|
||||
paneId: "main",
|
||||
});
|
||||
|
||||
expect(left).not.toBe(right);
|
||||
});
|
||||
|
||||
it("separates panes within a workspace", () => {
|
||||
const main = buildWorkspaceKeyboardHandlerId({
|
||||
name: "workspace-new-tab-menu",
|
||||
serverId: "srv",
|
||||
workspaceId: "wks_a",
|
||||
paneId: "main",
|
||||
});
|
||||
const explorer = buildWorkspaceKeyboardHandlerId({
|
||||
name: "workspace-new-tab-menu",
|
||||
serverId: "srv",
|
||||
workspaceId: "wks_a",
|
||||
paneId: "explorer",
|
||||
});
|
||||
|
||||
expect(main).not.toBe(explorer);
|
||||
});
|
||||
|
||||
it("omits the pane segment for workspace-wide surfaces", () => {
|
||||
expect(
|
||||
buildWorkspaceKeyboardHandlerId({
|
||||
name: "workspace-tab-actions",
|
||||
serverId: "srv",
|
||||
workspaceId: "wks_a",
|
||||
}),
|
||||
).toBe("workspace-tab-actions:srv:wks_a");
|
||||
});
|
||||
|
||||
it("treats a blank pane id as workspace-wide", () => {
|
||||
expect(
|
||||
buildWorkspaceKeyboardHandlerId({
|
||||
name: "workspace-new-tab-menu",
|
||||
serverId: "srv",
|
||||
workspaceId: "wks_a",
|
||||
paneId: " ",
|
||||
}),
|
||||
).toBe("workspace-new-tab-menu:srv:wks_a");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* A keyboard handler id is an identity, not a label.
|
||||
*
|
||||
* The dispatcher keeps one live handler per id and useKeyboardActionHandler
|
||||
* registers once per id, never re-registering when focus changes. So when two
|
||||
* mounted surfaces produce the same id, the second one evicts the first and the
|
||||
* first is left without a keyboard for the rest of its mount — silently, with no
|
||||
* symptom until someone presses the key.
|
||||
*
|
||||
* The workspace deck keeps several workspaces mounted at once, so a workspace
|
||||
* surface is only identified by its server, its workspace, and its pane. Pane
|
||||
* ids are namespaced per workspace ("main" is every workspace's default pane),
|
||||
* which is why they cannot carry the identity on their own.
|
||||
*/
|
||||
export interface WorkspaceKeyboardSurface {
|
||||
/** Stable name for the surface, e.g. "workspace-new-tab-menu". */
|
||||
name: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
/** Omit for surfaces that own the whole workspace rather than one pane. */
|
||||
paneId?: string | null;
|
||||
}
|
||||
|
||||
export function buildWorkspaceKeyboardHandlerId({
|
||||
name,
|
||||
serverId,
|
||||
workspaceId,
|
||||
paneId,
|
||||
}: WorkspaceKeyboardSurface): string {
|
||||
const trimmedPaneId = paneId?.trim();
|
||||
const paneSegment = trimmedPaneId ? `:${trimmedPaneId}` : "";
|
||||
return `${name}:${serverId}:${workspaceId}${paneSegment}`;
|
||||
}
|
||||
@@ -11,36 +11,12 @@ export { hasFocusedTextInput, registerFocusedTextInput } from "./internal/focuse
|
||||
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
|
||||
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
|
||||
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
|
||||
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
|
||||
export {
|
||||
hasSoftwareKeyboard,
|
||||
usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys,
|
||||
} from "./internal/conventions";
|
||||
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
|
||||
export { useHardwareKeyboardPresent } from "./availability";
|
||||
export { readPressModifiers } from "./internal/press-modifiers";
|
||||
export type { PressModifiers } from "./internal/press-modifiers";
|
||||
export {
|
||||
createKeybindingRegistry,
|
||||
displayKeysFor,
|
||||
DuplicateKeybindingError,
|
||||
} from "./internal/keybinding-registry";
|
||||
export type {
|
||||
DisplayPlatform,
|
||||
EffectiveKeybinding,
|
||||
KeybindingConflict,
|
||||
KeybindingDispatchResult,
|
||||
KeybindingInput,
|
||||
KeybindingRegistry,
|
||||
KeybindingRegistryOptions,
|
||||
} from "./internal/keybinding-registry";
|
||||
export { whenMatchesPlatform } from "./internal/when";
|
||||
export type { When, WhenClause } from "./internal/when";
|
||||
export type { KeyboardFocusScope } from "./internal/key-event";
|
||||
export {
|
||||
getDisplayPlatform,
|
||||
KeybindingRegistryProvider,
|
||||
useKeybindingRegistry,
|
||||
useKeybindings,
|
||||
useShortcutKeys,
|
||||
} from "./internal/react";
|
||||
export { isCaptureComplete, normalizeCapturedCombo } from "./internal/capture";
|
||||
export { createChordMatcher } from "./internal/chord-matcher";
|
||||
export type { ChordMatch, ChordMatcher } from "./internal/chord-matcher";
|
||||
export type { KeyboardShortcutContext, KeyboardShortcutInput } from "./internal/key-event";
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { EffectiveKeybinding } from "./keybinding-registry";
|
||||
import { parseBindingChord } from "./key-event";
|
||||
|
||||
/** A binding shipped on the `Digit` wildcard stands for every digit 1-9. */
|
||||
function bindsDigitWildcard(binding: EffectiveKeybinding): boolean {
|
||||
return parseBindingChord(binding.defaultCombo).at(-1)?.code === "Digit";
|
||||
}
|
||||
|
||||
/** Keeps a 1-9 binding on all nine digits when the user records a new modifier for it. */
|
||||
export function normalizeCapturedCombo(binding: EffectiveKeybinding, combo: string): string {
|
||||
return bindsDigitWildcard(binding) ? combo.replace(/(^|\+)[1-9]$/, "$1Digit") : combo;
|
||||
}
|
||||
|
||||
/** A 1-9 binding needs a final digit; earlier combos may be any chord prefix. */
|
||||
export function isCaptureComplete(
|
||||
binding: EffectiveKeybinding,
|
||||
combos: readonly string[],
|
||||
): boolean {
|
||||
const lastCombo = combos.at(-1);
|
||||
if (!lastCombo) return false;
|
||||
return !bindsDigitWildcard(binding) || /(^|\+)(Digit|[1-9])$/.test(lastCombo);
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createActionRegistry, createActionScopeStore } from "@/actions";
|
||||
import { createChordMatcher } from "./chord-matcher";
|
||||
import type { KeyboardShortcutInput } from "./key-event";
|
||||
import { createKeybindingRegistry, type EffectiveKeybinding } from "./keybinding-registry";
|
||||
|
||||
function bindings(
|
||||
entries: ReadonlyArray<{ id: string; combo: string }>,
|
||||
): readonly EffectiveKeybinding[] {
|
||||
const scopes = createActionScopeStore();
|
||||
const actions = createActionRegistry({ scopes });
|
||||
const registry = createKeybindingRegistry({ actions, scopes });
|
||||
registry.registerBindings(
|
||||
entries.map((entry) => ({ id: entry.id, actionId: `test/${entry.id}`, combo: entry.combo })),
|
||||
);
|
||||
return registry.getBindings();
|
||||
}
|
||||
|
||||
function key(input: Partial<KeyboardShortcutInput> & { key: string; code: string }) {
|
||||
return {
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
const CTRL_TAB = key({ key: "Tab", code: "Tab", ctrlKey: true });
|
||||
const CTRL_W = key({ key: "w", code: "KeyW", ctrlKey: true });
|
||||
const KEY_S = key({ key: "s", code: "KeyS" });
|
||||
const KEY_X = key({ key: "x", code: "KeyX" });
|
||||
const CONTROL = key({ key: "Control", code: "ControlLeft", ctrlKey: true });
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("createChordMatcher", () => {
|
||||
it("matches a single-step binding on its key", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([{ id: "next", combo: "Ctrl+Tab" }]);
|
||||
|
||||
expect(chord.keyDown(CTRL_TAB, table, false)).toEqual({
|
||||
kind: "matched",
|
||||
binding: table[0],
|
||||
});
|
||||
});
|
||||
|
||||
it("matches a chord across two presses", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
|
||||
|
||||
expect(chord.keyDown(CTRL_W, table, false)).toEqual({ kind: "pending" });
|
||||
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "matched", binding: table[0] });
|
||||
});
|
||||
|
||||
it("reserves a chord's first step over a single-step binding on the same keys", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([
|
||||
{ id: "close", combo: "Ctrl+W" },
|
||||
{ id: "split", combo: "Ctrl+W S" },
|
||||
]);
|
||||
|
||||
expect(chord.keyDown(CTRL_W, table, false)).toEqual({ kind: "pending" });
|
||||
expect(chord.keyDown(KEY_S, table, false)).toEqual({
|
||||
kind: "matched",
|
||||
binding: table.find((binding) => binding.id === "split"),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a chord pending while a modifier goes down between steps", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
|
||||
|
||||
chord.keyDown(CTRL_W, table, false);
|
||||
|
||||
expect(chord.keyDown(CONTROL, table, false)).toEqual({ kind: "pending" });
|
||||
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "matched", binding: table[0] });
|
||||
});
|
||||
|
||||
it("ignores a lone modifier when no chord is pending", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
|
||||
|
||||
expect(chord.keyDown(CONTROL, table, false)).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("drops the chord on a second key that continues nothing", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
|
||||
|
||||
chord.keyDown(CTRL_W, table, false);
|
||||
|
||||
expect(chord.keyDown(KEY_X, table, false)).toEqual({ kind: "none" });
|
||||
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("drops a pending chord once the timeout passes", () => {
|
||||
vi.useFakeTimers();
|
||||
const chord = createChordMatcher({ timeoutMs: 100 });
|
||||
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
|
||||
|
||||
chord.keyDown(CTRL_W, table, false);
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("drops a pending chord on reset", () => {
|
||||
const chord = createChordMatcher();
|
||||
const table = bindings([{ id: "split", combo: "Ctrl+W S" }]);
|
||||
|
||||
chord.keyDown(CTRL_W, table, false);
|
||||
chord.reset();
|
||||
|
||||
expect(chord.keyDown(KEY_S, table, false)).toEqual({ kind: "none" });
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user