Compare commits

...
31 Commits
Author SHA1 Message Date
Mohamed Boudra bfec7ac3ad chore(release): cut 0.3.1 2026-08-09 13:30:33 +02:00
Mohamed Boudra 5269c7b592 docs(release): prepare v0.3.1 2026-08-09 13:28:13 +02:00
Mohamed Boudra 05dc2022c8 Keep shared-worktree fetches proportional to ref changes (#3078)
* fix(server): bound shared-worktree fetch refreshes

* fix(server): preserve buffered git metadata events

* fix(server): cover remote ref selection changes

* fix(server): preserve narrow fetch echo routing

* fix(server): preserve ref updates during refresh

Keep normal refresh requeue semantics for watcher events that arrive while a ref-derived calculation is active, so a second same-ref movement cannot be mistaken for the original fetch echo.

* fix(server): narrow external fetch ref updates

Use authoritative fetch boundaries to separate watcher echoes from outside events, and retain remote ref names so packed-to-loose materialization from other Git clients stays narrow without weakening add/delete fallbacks.
2026-08-09 12:51:00 +02:00
Mohamed BoudraandChristoph Leiter c0daf8e066 feat(app): add running status ring and lighten status dots
Keep the animated ring phase-locked across hosts and derive its knockout surface from each host's actual interaction state. Align filled status circles at 6px while preserving the larger needs-input alert.

Co-authored-by: Christoph Leiter <christoph@leiter.io>
2026-08-09 11:33:58 +02:00
Mohamed Boudra 6ae6231d1f fix(app): prevent inline code from obscuring text
Explicit inline-code line height creates oversized painted backgrounds when mixed markdown wraps on native. Let native font metrics determine the span height so adjacent lines remain visible.
2026-08-09 11:33:58 +02:00
Mohamed Boudra c77a6761af Treat unpublished desktop updates as unavailable (#3076)
* fix(desktop): treat unpublished updates as unavailable

GitHub releases can become visible before their platform updater manifests finish publishing. Treat that specific upstream condition as an unavailable update while preserving Paseo reporting for genuine updater failures.

* refactor(desktop): inject updater runtime dependency

Exercise updater event and rejection behavior through a typed fake at the runtime boundary instead of coordinating a hoisted module singleton in tests.

* fix(desktop): preserve lazy updater initialization

* revert(desktop): drop updater runtime refactor
2026-08-09 11:20:16 +02:00
Mohamed Boudra fd9cc5d693 Restore macOS direct LAN connections (#3071)
* fix(desktop): restore direct LAN connections

Desktop 0.3.0 routed remote WebSockets through the Electron main process, causing previously working macOS LAN connections to fail with EHOSTUNREACH. Revert custom direct headers and restore the renderer WebSocket path used before the regression.

* fix(app): replace host connections by identity

Keep one connection per stable ID when TLS or password settings change. This preserves the current-main upsert invariant while the custom-header rollback removes the unrelated transport feature.
2026-08-09 15:32:31 +08:00
Mohamed Boudra 7761d122d8 Stabilize async server lifecycle tests (#3060)
* test(server): stabilize async lifecycle coverage

* test(server): name teardown dependencies
2026-08-09 14:33:38 +08:00
01a1d3b2b6 Recover daemon workers stalled by workspace Git pressure (#3033)
* fix(server): bound workspace git pipelines

* fix(server): bound workspace git watcher setup

* fix(server): recover unresponsive daemon workers

* fix(server): tolerate transient daemon heartbeat delays

A five-second watchdog threshold can replace a healthy worker during a short event-loop delay. Keep recovery bounded while allowing a 15-second heartbeat gap, and preserve process-level coverage for workers that ignore graceful termination.

* test(server): normalize workspace fixture paths

Workspace Git entry points resolve paths before invoking dependencies. Keep admission-control fixtures keyed by the same canonical paths so their assertions and deferred gates work on Windows.

---------

Co-authored-by: Timi Ajiboye <trypio00@gmail.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-08-09 03:01:34 +02:00
Mohamed Boudra 3bca9b7a92 fix(app): preserve selected list markers when copying (#3055)
Mouse drags start and end inside rendered list items, so the clipboard serializer dropped item semantics even when the visible marker was selected. Treat the marker as explicit selection intent while keeping text-only selections unmarked.
2026-08-09 08:15:45 +08:00
Mohamed Boudra 8ffe7c75d5 Keep the daemon responsive when file watching fails (#3056)
* fix(server): keep watcher failures from stalling the daemon

Native watcher teardown can block the Node main thread when an error overlaps subscription lifecycle work. Reduce lifecycle churn, abandon errored subscriptions into bounded polling, recover only after setup settles, and expose error callback frequency in runtime metrics.

* fix(server): keep watcher recovery bounded
2026-08-09 02:14:00 +02:00
Christoph Leiter 74cf1931b1 fix(shortcuts): show effective bindings in the cheat sheet (#2985)
Render and search the shortcut chord that actually fires, including rebinding default-only display tokens such as question mark and index wildcards. Unassigned rows show no empty badge, and named-key overrides use the shared display vocabulary.
2026-08-09 01:56:32 +02:00
Christoph Leiter 90aa8bbefc feat(shortcuts): allow shortcuts to be unassigned (#2510)
Allow users to clear and restore shortcut bindings, persist the explicit unassigned state, and keep shortcut displays and actions aligned with the binding that fires. Includes focused unit coverage and desktop renderer Playwright coverage.
2026-08-09 01:31:40 +02:00
shrimpandMohamed Boudra c28836b4e5 feat(app): add Pure black theme (#3012)
* feat(app): add AMOLED and all four Catppuccin themes

Add an AMOLED theme (pure black background) and the four official
Catppuccin flavors (Latte light, Frappé/Macchiato/Mocha dark) to the
appearance picker. Generalize the dark-theme builder to support a light
surface variant, register the new themes with Unistyles, and patch all
registered theme keys when applying font/syntax appearance settings.

* fix(app): localize Catppuccin + AMOLED theme labels across language packs

The initial theme commit pasted the English brand/flavor labels into every
locale. Localize them following each pack's convention: transliterate
Catppuccin and the coffee-flavor names into Arabic/Russian scripts, use
katakana/hanzi equivalents in ja/zh-CN, and standard loanwords in
fr/es/pt-BR. AMOLED is a universal acronym and stays as-is except where
the pack transliterates (Arabic).

* fix(app): make Latte terminal ANSI colors readable

* test(app): cover appearance theme picker options

* refactor(app): scope theme PR to AMOLED

* refactor(app): rename AMOLED theme to Pure Black

* fix(app): refine Pure black appearance

* test(app): wait for sidebar toggle icon

* test(app): remove hover timing race

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-08-09 01:12:53 +02:00
Mohamed Boudra 8f38d04919 Keep the active project when switching workspace hosts (#3051)
* fix(app): preserve projects across host switches

New workspace entry context retained only a host-local placement, so switching hosts could replace the selected project with the destination's first project. Hydrate that placement against canonical project identity while keeping exact clone placement separate.

* fix(app): preserve manual project choice during hydration

Keep the raw route placement key as stable selection context while hydrating the routed project to its canonical identity.
2026-08-09 00:51:07 +02:00
Mohamed Boudra ce7b3a90c0 Give every Hub execution its own workspace lifecycle (#3045)
* fix(server): archive Hub executions by workspace identity

Hub archive previously depended on backing-specific owner state and archived the agent directly, so local and reused workspaces could survive. Resolve the required workspaceId from the execution agent and let the shared workspace archive service own agent, terminal, and backing teardown.

* fix(server): preserve agent archive through workspace teardown

* test(server): keep Hub regression fixtures workspace-scoped

* fix(hub): own executions through fresh workspaces

Hub executions must own a workspace regardless of backing so archival has one lifecycle boundary for agents, terminals, and checkout cleanup. Retain the retired wire selector for parsing compatibility while removing its ownership semantics.

* fix(server): serialize archive metadata writes

* fix(server): preserve archive during reconciliation
2026-08-08 23:55:12 +02:00
Mohamed Boudra cefb71dcac Keep New workspace metadata inside the composer (#3050)
Allow desktop metadata controls to shrink so long host and starting-ref labels truncate without crossing the composer rail. Adds a real-browser regression for the combined long-label case.
2026-08-08 23:29:45 +02:00
49b257c55a fix(app): make session rename reachable in the mobile sessions dropdown (#2924)
* fix(app): make session rename reachable in the mobile sessions dropdown

The per-session actions menu in the mobile tab switcher (a gorhom bottom
sheet) opened as an anchored popover, which on native renders a second RN
Modal stacked on the sheet — the fragile nested-overlay case docs/floating-panels.md
warns about. The actions menu (incl. Rename) never appeared on native, so
sessions could not be renamed from the dropdown.

Give the menu compactMode="sheet" like every other mobile menu in the file,
so it stacks as a gorhom sheet on a gorhom sheet (the supported path). Extract
the accessory into workspace-tab-trailing-accessory.tsx and add a reachability
test that fails if the sheet presentation regresses.

* test(app): cover compact session rename via the tab switcher e2e

Adds a Playwright spec that drives the mobile-viewport sessions dropdown -> per-session actions sheet -> Rename, exercising the real gorhom sheet interaction the fix restores (the desktop rename specs only cover the right-click context menu, and the unit test mocks the menu engine).

---------

Co-authored-by: Klaude <klaude@Klaudes-MacBook-Pro.local>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-08-08 21:12:16 +00:00
1e0ce69c54 Make the sidebar resize handle usable by touch (#2953)
* fix(app): make the sidebar resize handle usable by touch

The drag handle was a 10px strip at `right: -5`, so half of it sat outside
the sidebar's bounds. Web hit-testing does not clip to the parent box, but
iOS `hitTest:` and Gesture Handler's Android traversal both do, leaving a
~5px target with no visible affordance — hover is the only cue, and hover
never fires on native.

Split the handle by input capability rather than by platform: a fine pointer
keeps the hairline straddling the border, and touch gets a 24x88 grab target
that sits fully inside the sidebar with a permanent grip. The pan gesture now
requires horizontal intent and fails on vertical drift, so a finger on the
grip still scrolls the list behind it.

`useHasFinePointer` replaces the copy of the same media query that lived in
the review surface.

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

* refactor(app): simplify touch resize handle styles

* fix(app): reveal touch resize grip while pressed

Keep the touch grip out of sidebar content while idle, then expose it for the full resize gesture lifecycle so it remains visible during an active drag.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-08-08 22:32:24 +02:00
Glen Stampoultzis b9b3a24d58 fix(desktop): restore notification sounds (#2582)
Restore desktop notification sounds by default, add a persisted Play sound setting, and group notification permission and testing in a dedicated Notifications section.
2026-08-08 22:28:37 +02:00
Sihyeon JeonandClaude Opus 5 b19db9537c fix(server): summarise Claude AskUserQuestion permission notifications (#2925)
* fix(server): summarise Claude AskUserQuestion permission notifications

Claude's handlePermissionRequest never set title or description on the
AgentPermissionRequest it emits, so buildPermissionDetails fell through to
serialising request.input. For AskUserQuestion that input is the whole question
object, and the push and in-app notifications both showed truncated JSON.

Summarise the first question the way the OMP and Pi providers already do for
their ask_user permissions: title is the question text, description is the
option labels. request.input is untouched, so the permission UI keeps rendering
the full payload.

Closes #2612

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FWY2Xdowxr562GXFdxPhjZ

* test(server): assert question permissions through the emitted request

Greptile flagged that the suite imported a production helper that was only
exported for the test, which leaves an unnecessary public export behind and
couples the tests to implementation structure.

The helper is module-private again, and every case now asserts on the
permission request the session emits and the notification body built from it.
Added a case pinning request.input so the permission UI payload stays covered,
and one for a non-question tool.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FWY2Xdowxr562GXFdxPhjZ

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 21:28:21 +02:00
HunterandClaude Opus 5 1a117652fd Fix Kimi usage refresh, 5 hour session limit, and reasoning levels (#2743)
* Refresh expired Kimi usage tokens

* Test Kimi usage token refresh

* Harden Kimi usage token refresh

Follow-up review of the refresh path added in f6ce001a.

Credential reads no longer depend on the shape of fields this provider
only writes back: declaring expires_at and friends as required numbers
meant a null or stringified value threw away the access token sitting
next to them, turning a working Kimi quota bar into "unavailable" with
no way back. Those fields are nullish and coerced now.

Refreshed tokens are merged into a re-read of the credential file rather
than the copy the request started with, so a write by Kimi Code during
the refresh round-trip survives, and a file deleted in that window stays
deleted instead of being resurrected with fresh credentials. A failed
write logs at warn: Kimi rotates the refresh token, so losing that write
silently logs the user out of Kimi Code.

Only 401 triggers a refresh. A 403 means authenticated but not entitled,
which no refresh fixes, and refreshing anyway rotated the user's refresh
token on every poll.

Also: floor expires_at to whole seconds, indent the file the way Kimi
Code does, derive the temp file name from the real basename, and split
out fetchUsageResponse, which is what puts fetchUsage back under the
complexity limit — the original passed neither lint nor the formatter.

* Keep CLI-rotated Kimi credentials during refresh

The Kimi CLI shares the credential file the quota fetcher writes. A refresh
read the file, merged its new tokens, and renamed over it, so a rotation that
landed while the refresh was in flight was replaced with stale tokens and the
CLI's session broke until credentials were recreated.

Thread the refresh token that was actually spent into the persistence step and
skip the write when the file no longer carries it.

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

* fix(kimi): normalize additional usage windows

* fix(kimi): preserve custom auth while parsing limit windows

* test(kimi): cover additional usage windows

* test(kimi): move usage-window tests into service.test.ts

Every other quota provider is tested in service.test.ts; kimi.test.ts
was the only provider with a standalone collocated test file.

* fix(kimi): resolve reasoning-effort options per model, not per catalog probe

deriveModelDefinitionsFromACP derived thinkingOptions once from whichever
model happened to be active in the one-off catalog probe session, then
copied that same array onto every model. Kimi's ACP adapter only reports
thinking levels for the currently selected model, so K2.7/K2.7-coding-fast
(boolean on/off) and K3 (off/low/medium/high) ended up with identical,
often-wrong options depending on which model the probe defaulted to.

fetchCatalog now reuses the single probe session to switch through each
candidate model and read back its real thought_level options, falling
back to the default options if an individual model's probe fails. Skips
entirely when there's one model or no thinking picker, so providers
without per-model effort levels pay no extra round trips.

* refactor(kimi): merge kimi-usage.ts back into kimi.ts

kimi.ts was the only quota provider split across two files; every
other provider (including claude.ts at 503 lines, larger than the
merged Kimi file) stays in one. Also fixes a nested-ternary lint
error surfaced by the merge.

* fix(kimi): re-validate credentials immediately before the rename

Greptile flagged that saveRefreshedCredentials read the credential file,
checked its refresh token against a stale snapshot, then did async
writeFile work before an unconditional rename — leaving a window where
the Kimi CLI could rotate the file after the check and have its newer
tokens clobbered by our stale merge. The refresh-token-only comparison
also missed a CLI access-token rotation that kept the same refresh token.

Re-read the file immediately before the rename and compare both tokens
against the snapshot the merge was built from, discarding the merge if
anything changed. Narrows the check-then-write gap to the smallest
window possible without cross-process file locking.

* refactor(acp): make per-model catalog probing an injectable resolver

Catalog discovery in ACPAgentClient.fetchCatalog ran sequential
setSessionConfigOption model switches for every multi-model ACP with a
thought_level picker, so a slow or nonconforming agent could stall any
provider's catalog probe under the shared 60s timeout.

Replace the built-in resolvePerModelThinkingOptions with an optional
ACPCatalogModelResolver injected through ACPAgentClientOptions (threaded
through GenericACPAgentClient like the existing transformer/parser deps).
The base client ships no resolver, so catalog discovery derives models
from the initial session response and never switches models. Export the
config-option helpers a resolver needs.

The base regression test pins that a plain ACPAgentClient with multiple
models and a thinking picker never calls setSessionConfigOption.

* feat(kimi): resolve per-model thinking options via KimiACPAgentClient

Kimi exposes different thinking-effort levels per model but only reports
the currently selected model's levels, so the catalog probe must switch
through each model to read them back. Move that logic off the shared ACP
adapter and onto a Kimi-specific client.

Add resolveKimiCatalogModels (the sequential setSessionConfigOption probe,
fallback, and warning) and KimiACPAgentClient, which injects it via the
new catalogModelResolver dependency. Select it for providerId "kimi" in
the registry alongside cursor/kiro/traecli, so only Kimi pays the extra
round trips; every other ACP provider skips model switching entirely.

Tests cover the four probe behaviors on KimiACPAgentClient and the
registry dispatch to it.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 21:09:26 +02:00
Mohamed Boudra 638693a5d7 fix(app): keep the crash screen readable and its retry reachable (#3043)
The root error fallback was one unbounded scroller, so on a phone the title
rendered under the status bar and a long stack trace pushed Retry off the
bottom of the screen — the one action that recovers the app was unreachable
on exactly the errors that need it most.

The screen is now a fixed shell: a safe-area message block, an independently
scrolling details region, and a Retry that stays put. `SafeAreaProvider` moved
above the boundary in the root tree because the fallback renders when the app
tree below it has already failed, and insets have to be available there.

The hand-rolled Pressable and bordered message box are replaced by the shared
`<Button>` and `<ScrollableCodeSurface>`, which gives the trace a monospace
face and horizontal scrolling instead of wrapping mid-token. On desktop the
trace is capped and the action sits with the message; a button pinned to the
bottom of a tall window reads as detached from the content it belongs to.

Dropped the "Something went wrong" kicker — it restated the title one line
above it.
2026-08-08 20:59:01 +02:00
Christoph LeiterandClaude Sonnet 5 2740c8206f fix(server): resolve exact file paths that git ignores (#3042)
Clicking a file path an agent mentioned failed with "No file found"
whenever git ignored the file, which covers anything written under a
scratch directory such as .dev/.

Backticked paths do not open directly. They resolve through the
directory-suggestions RPC, which the daemon runs with gitignore
filtering on for every workspace search. findExactEntry resolved the
path, confirmed it stayed inside the workspace root, and then discarded
it on the ignore check.

Ignore filtering belongs to discovery. It keeps build output out of the
composer's @-mention picker and out of the directory chooser, and both
of those keep it. It does not belong to retrieval of a path the caller
named exactly, where containment inside the root is the only question
left. That check is now dropped from the exact-path branch alone.

This does not widen what is readable. The file-read path applies no
ignore filtering at all; resolveScopedPath checks only root containment,
before and after resolving symlinks. Every file this surfaces was
already readable through the file explorer.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 20:47:28 +02:00
Jason@HNDandMohamed Boudra 0906d1d7bd fix(codex): omit disabled skills from slash commands (#2759)
* fix(codex): omit disabled skills from slash commands

Codex skills/list returns disabled skills with enabled:false. Filter
them out in loadSkills so Paseo matches Codex CLI/TUI and no longer
surfaces stale slash entries for skills the user disabled.

Fixes #2617

* fix(codex): preserve empty skill discovery

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-08-08 20:22:48 +02:00
Mohamed Boudra 3d420720c5 docs(hub): document workflow security boundaries (#3032)
* docs(hub): add security guidance for workflows

* docs: register Hub security guide
2026-08-08 17:22:09 +02:00
Mohamed Boudra 375d1d6fb8 Merge branch 'main' of github.com:getpaseo/paseo 2026-08-08 16:59:56 +02:00
Mohamed Boudra f0eb7cea4b feat(providers): add native options and exact MCP grants (#3025)
* feat(providers): add native options and exact MCP grants

Keep provider policy in provider-owned schemas so unattended Hub runs can grant only requested tools from injected MCP servers. Preserve the native resolved sandbox policy when a workflow override is present, including configured writable roots.

* test(hub): verify real provider tool policy

* test(app): avoid pinning transient restart status
2026-08-08 16:49:29 +02:00
Mohamed Boudra b669dad221 Add durable Paseo Hub CLI login (#3022)
* feat(cli): add durable Hub login

Keep organization-scoped human credentials separate from daemon relationship authority. Connect now exchanges explicit or stored CLI authority for a one-time enrollment token, while logout removes human access without implicitly disconnecting automation.

* fix(cli): require TLS for remote Hub credentials

Durable Hub credentials are bearer secrets, so remote origins must not receive them over cleartext HTTP. Keep literal loopback HTTP available for local Hub development.

* fix(cli): make Hub destinations explicit

Resolve optional Hub origins through one shared precedence policy so active logins remain the default context and credentials stay origin-bound. Report the selected destination before human-facing work, keep structured output auditable, and preserve login authority until requested daemon disconnection succeeds.
2026-08-08 15:27:43 +02:00
Mohamed Boudra 7ac4303d8f docs(release): streamline release workflow
Make the release document the single source of truth. ACP drift is explicit opt-in, release preparation uses one remote batch, and a heartbeat owns completion through published artifacts and store submissions. Preserve one changelog entry per beta and collapse the series on promotion.
2026-08-08 13:49:22 +02:00
paseo-ai[bot] e36842b234 fix: update lockfile signatures and Nix hash [skip ci] 2026-08-08 09:04:58 +00:00
279 changed files with 15388 additions and 3687 deletions
+2 -6
View File
@@ -1,13 +1,9 @@
---
name: release-beta
description: Cut a beta release of Paseo. Use when the user says "release beta", "cut a beta", "ship a beta", "beta release", or "/release-beta". Betas are release candidates on the beta channel — they carry an in-place changelog entry, don't move the website download target, and publish npm only on the beta dist-tag.
description: Cut a beta release of Paseo. Use when the user says "release beta", "cut a beta", "ship a beta", "beta release", or "/release-beta".
user-invocable: true
---
# Release beta
Read `docs/release.md` in the Paseo repo and follow the **Beta flow** section end-to-end. Run the **Beta release** completion checklist at the bottom of that doc.
During preparation, classify the previous-stable-to-`HEAD` diff as patch or minor and show the target version and rationale to the user. Agents never select a major version autonomously.
Each beta updates an in-place `CHANGELOG.md` entry (`## X.Y.Z-beta.N`) that gets overwritten at promotion, and npm publishes only on the explicit `beta` dist-tag.
Follow the **Beta flow** and **Beta release** completion checklist in `docs/release.md` end-to-end.
+1 -5
View File
@@ -6,8 +6,4 @@ user-invocable: true
# Release stable
Read `docs/release.md` in the Paseo repo and follow the **Standard release (stable)** flow if cutting fresh, or the **Beta flow** promotion step if promoting an existing beta. Run the **Stable release (or promotion)** completion checklist at the bottom of that doc.
For a fresh release, classify the previous-stable-to-`HEAD` diff as patch or minor and show the target version and rationale to the user. Agents never select a major version autonomously.
The doc covers the changelog, pre-release sanity check, and post-release babysit pattern. Don't skip steps.
Follow the applicable flow and the **Stable release (or promotion)** completion checklist in `docs/release.md` end-to-end.
+28
View File
@@ -1,5 +1,33 @@
# Changelog
## 0.3.1 - 2026-08-09
### Added
- Unassign keyboard shortcuts and see the effective bindings in shortcut help ([#2510](https://github.com/getpaseo/paseo/pull/2510) by [@cleiter](https://github.com/cleiter), [#2985](https://github.com/getpaseo/paseo/pull/2985) by [@cleiter](https://github.com/cleiter))
- Choose a Pure black theme ([#3012](https://github.com/getpaseo/paseo/pull/3012) by [@shrimpwtf](https://github.com/shrimpwtf))
### Improved
- Running agents use a clearer animated status ring ([c0daf8e](https://github.com/getpaseo/paseo/commit/c0daf8e066e0d7379723a2a6ddea20afc71ead20) by [@cleiter](https://github.com/cleiter))
- Workspace Git updates stay responsive under file-watcher failures, heavy Git activity, and large shared-worktree repositories ([#3056](https://github.com/getpaseo/paseo/pull/3056), [#3033](https://github.com/getpaseo/paseo/pull/3033) by [@dwyanewang](https://github.com/dwyanewang), [#3078](https://github.com/getpaseo/paseo/pull/3078))
- Kimi usage refreshes correctly and shows five-hour limits and reasoning levels ([#2743](https://github.com/getpaseo/paseo/pull/2743) by [@UnbrokenHunter](https://github.com/UnbrokenHunter))
- Resize the desktop sidebar with touch ([#2953](https://github.com/getpaseo/paseo/pull/2953) by [@colonelpanic8](https://github.com/colonelpanic8))
### Fixed
- Direct LAN connections work again on macOS ([#3071](https://github.com/getpaseo/paseo/pull/3071))
- Desktop update checks no longer report an error while platform downloads are still publishing ([#3076](https://github.com/getpaseo/paseo/pull/3076))
- Copied lists keep their markers across selection boundaries ([#3055](https://github.com/getpaseo/paseo/pull/3055))
- Switching hosts keeps the active project selected ([#3051](https://github.com/getpaseo/paseo/pull/3051))
- New Workspace keeps project and isolation controls inside the composer ([#3050](https://github.com/getpaseo/paseo/pull/3050))
- Session rename is reachable from the mobile sessions menu ([#2924](https://github.com/getpaseo/paseo/pull/2924) by [@kaspesi](https://github.com/kaspesi))
- Desktop notification sounds play again ([#2582](https://github.com/getpaseo/paseo/pull/2582) by [@gstamp](https://github.com/gstamp))
- Codex slash commands omit disabled skills ([#2759](https://github.com/getpaseo/paseo/pull/2759) by [@jasonhnd](https://github.com/jasonhnd))
- Exact ignored file paths resolve correctly ([#3042](https://github.com/getpaseo/paseo/pull/3042) by [@cleiter](https://github.com/cleiter))
- Claude question notifications summarize the requested input ([#2925](https://github.com/getpaseo/paseo/pull/2925) by [@SihyeonJeon](https://github.com/SihyeonJeon))
- The crash screen stays readable and keeps its retry action reachable ([#3043](https://github.com/getpaseo/paseo/pull/3043))
## 0.3.0 - 2026-08-08
### Added
+1
View File
@@ -57,6 +57,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
### Writing docs
+1 -1
View File
@@ -341,7 +341,7 @@ One file per schedule. ID is 8 hex characters.
### Nested: ScheduleTarget (discriminated union on `type`)
- `{ type: "agent", agentId: string }` — send to existing agent
- `{ type: "new-agent", config: { provider, cwd, modeId?, model?, thinkingOptionId?, title?, approvalPolicy?, sandboxMode?, networkAccess?, webSearch?, extra?, systemPrompt?, mcpServers? } }` — create a new agent
- `{ type: "new-agent", config: { provider, cwd, modeId?, model?, thinkingOptionId?, title?, providerOptions?, featureValues?, systemPrompt?, mcpServers? } }` — create a new agent
### Nested: ScheduleRun
+1 -1
View File
@@ -223,7 +223,7 @@ Selected state on rows in a desktop list+detail uses `surfaceSidebarHover` as th
There is exactly one token per status signal — `statusSuccess`, `statusDanger`, `statusWarning`, `statusMerged` — and every status surface uses it: PR state icons, CI check icons and pies, diff stats, file-change icons, status pills, usage bars. A surface does not get a quieter or louder variant because of where it sits. If a dense list feels loud, that is a density or weight problem; fix the density, not the color. The tokens are generated, not hand-picked — see the rule in `packages/app/src/styles/theme.ts` and regenerate rather than nudging one value. The level is set by the densest consumer, the sidebar workspace list.
Status **dots** are the one exception, and they are a family of their own — `statusDotSuccess`, `statusDotDanger`, `statusDotWarning`, `statusDotRunning`, read only by `getStatusDotColor` (`packages/app/src/utils/status-dot-color.ts`). Same hues and the same generation rule, but their own band: pushed away from the surface rather than toward it (darker in light, lighter in dark) and at 90% of gamut chroma against the status family's 55–60%. A dot is a few points of solid color with no shape to read and no label attached, and the running one pulses, so at the status band's lightness the dots read dimmer than the metadata beside them — backwards, since the dot is the row's state. All four move together; regenerate the set, never one hue.
Status **dots** are the one exception, and they are a family of their own — `statusDotSuccess`, `statusDotDanger`, `statusDotWarning`, `statusDotRunning`, read only by `getStatusDotColor` (`packages/app/src/utils/status-dot-color.ts`). Same hues and the same generation rule, but their own band: 90% of gamut chroma against the status family's 55–60%. A dot is a few points of solid color with no shape to read and no label attached, and the running one pulses, so at the status band's chroma the dots read dimmer than the metadata beside them — backwards, since the dot is the row's state. Lightness is set by hue separation rather than by distance from the surface: at 6pt four dark hues on a light surface all read as one dark blob no matter how much contrast they have. So the light band runs as bright as the contrast floor allows at L=0.62, the last step where all four clear 3:1 against the sidebar's `surface2`; the dark band sits at L=0.72, where danger turns pink above. All four move together; regenerate the set, never one hue.
Status pills are the status token as foreground on a 10%-alpha tint of the same token (`${token}1a`), with a 20% border (`${token}33`). The `<StatusBadge>` primitive (`packages/app/src/components/ui/status-badge.tsx`) is canonical; a pill never reaches into `palette`.
+36 -12
View File
@@ -2,7 +2,9 @@
Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Running a daemon does
not register it with a Hub. The relationship begins only when a user runs
`paseo hub connect <url> --token <token>` from the daemon machine.
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
## Connection and authority
@@ -44,12 +46,30 @@ daemon, execution, and agent identity with that terminal state. Paseo never stor
replays the original prompt. A duplicate create returns the existing agent without starting another
turn.
Hub creates use the same agent creation path as trusted clients. They may select any existing
worktree target shape and carry optional MCP server configuration for the agent session. The daemon
keeps that configuration in its private agent record so provider sessions can recover after a
restart; neither ordinary client snapshots and updates nor Hub projections expose session
configuration. Execution completion policy remains outside the daemon: a completed agent turn does
not imply that the Hub execution is terminal.
Every Hub execution creates a fresh Paseo workspace. The workspace owns the execution's agents and
terminals. Local checkout and worktree targets select only the workspace backing and isolation; the
Hub cannot select or reuse an existing workspace. Hub creates use the same agent creation path as
trusted clients. They may select any worktree target shape and carry optional MCP server configuration and provider-native
`providerOptions` for the agent session. The daemon keeps that configuration in its private agent
record so provider sessions can recover after a restart; neither ordinary client snapshots and
updates nor Hub projections expose session configuration. See [providers.md](providers.md) for the
supported provider keys.
Hub tool preapproval is a private, structured list of `{ kind: "mcp", server, tool }` references.
Every reference must name an MCP server injected by the same create request. The daemon translates
only those identities into the selected provider's native approval configuration. The protocol
cannot name or preapprove native tools such as Bash, Edit, or Write. Explicit local or managed ask
and deny policy takes precedence. Providers without exact MCP preapproval support reject unattended
Hub creation instead of broadening access or waiting for an invisible prompt.
When a create request includes a tool policy, a successful response includes
`toolPolicyApplied: true`; absence of that acknowledgement is not success for unattended execution.
A Hub workflow may use read-only provider settings for classifier steps. This is defense in depth,
not a security boundary: classifier labels and prompt intent do not authorize tools. Exact MCP grants
and the provider's local or managed policy remain the authorization controls.
Execution completion policy remains outside the daemon: a completed agent turn does not imply that
the Hub execution is terminal.
The Hub ends an execution by sending `hub.execution.control.request` with the durable execution ID
and either `interrupt` or `archive`. The daemon resolves the agent from the authenticated daemon
@@ -59,11 +79,11 @@ If no execution exists for that authenticated daemon and execution ID, interrupt
success because the requested stopped or archived state already holds. An execution owned by another
daemon is indistinguishable from a missing execution and is never exposed or affected.
Interrupt uses the ordinary agent cancellation lifecycle. Archive first archives the owned agent.
When that agent belongs to an active Paseo-owned worktree workspace, the daemon also archives the
workspace through the shared workspace archive service, so the backing directory is removed only
after its final active workspace reference disappears. Local and shared checkouts archive only the
execution-owned agent.
Interrupt uses the ordinary agent cancellation lifecycle. Archive resolves the execution agent's
required workspaceId and sends it through the shared workspace archive service. The service archives
that workspace's agents and terminals, then removes Paseo-owned backing directories only after their
final active workspace reference disappears. Local checkouts remain on disk; sibling workspaces
sharing a backing directory remain active.
## Disconnect and revocation
@@ -81,9 +101,13 @@ opening a Hub socket. This also covers an enrollment whose request may have succ
response was lost. `--force` removes local authority immediately and warns that remote revocation may
still be pending.
`paseo hub logout` removes only the active human CLI credential and preserves credentials for other origins. Interactive logout inspects and optionally disconnects a same-origin daemon before deleting the login; a failed requested disconnect preserves the login. JSON and noninteractive logout never prompt or disconnect implicitly.
## Cross-repository compatibility
The consumer implementation lives in Paseo Cloud. Cloud owns its copy of the Hub wire schemas and
has no Paseo runtime or build dependency. Cross-repository end-to-end verification separately builds
a Paseo source checkout and exercises the real daemon, CLI, direct WebSocket, Cloud service, and
Postgres. That compatibility fixture is not a package dependency or fallback implementation.
Its `hub-e2e` ACP provider accepts only exact tool names on the injected `hub` MCP server. Other
custom ACP providers remain unsupported for unattended preapproval.
+35
View File
@@ -2,6 +2,41 @@
This guide walks through adding a new agent provider end-to-end. There are two integration patterns, and this doc covers both.
## Provider-native session options
`AgentSessionConfig.providerOptions` carries JSON-safe configuration for the selected provider. The
names and nesting are the provider's native contract; options are not portable between providers.
Paseo validates the object with the selected provider's strict schema before constructing a session.
Unknown keys fail with their `providerOptions.*` path. Paseo-owned controls such as cwd, model,
prompt, environment, session identity, MCP transport, callbacks, and hooks cannot be passed here.
This Paseo version accepts these keys:
- **Codex:** `approval_policy`, `sandbox_mode`,
`sandbox_workspace_write.{writable_roots,network_access,exclude_slash_tmp,exclude_tmpdir_env_var}`,
`web_search`, `features.multi_agent_v2`, and `features.network_proxy`. A network proxy object may
contain `enabled`, `proxy_url`, `socks_url`, `enable_socks5`, `enable_socks5_udp`,
`allow_local_binding`, `allow_upstream_proxy`, `dangerously_allow_all_unix_sockets`,
`dangerously_allow_non_loopback_proxy`, `domains`, and `unix_sockets`. See the
[Codex configuration reference](https://developers.openai.com/codex/config-reference).
- **Claude:** `allowedTools`, `disallowedTools`, `additionalDirectories`, `sandbox`, and `settings`.
The accepted sandbox fields cover enablement, fail-if-unavailable behavior, excluded and
unsandboxed commands, filesystem read/write rules, network domain/socket/local-binding rules,
weaker nested sandboxing, ignored violations, and the ripgrep command. `settings` accepts native
`permissions.{allow,ask,deny}` and sandbox settings. See the
[Claude Agent SDK TypeScript reference](https://platform.claude.com/docs/en/agent-sdk/typescript)
and [Claude settings reference](https://code.claude.com/docs/en/settings).
- **OpenCode:** `permission`, either one `ask`/`allow`/`deny` action or the native per-tool rule
object. Supported entries are `read`, `edit`, `glob`, `grep`, `list`, `bash`, `task`,
`external_directory`, `todowrite`, `question`, `webfetch`, `websearch`, `codesearch`,
`repo_clone`, `repo_overview`, `lsp`, `doom_loop`, and `skill`. See the
[OpenCode permissions reference](https://opencode.ai/docs/permissions/). OpenCode permissions are
application policy, not an OS sandbox.
Each provider definition owns its option schema and exact MCP preapproval mapping. A new provider
must fail closed for Hub unattended execution until it can approve one exact injected MCP server
and tool identity without approving native tools.
## Two Integration Patterns
### ACP (Agent Client Protocol) -- recommended
+111 -45
View File
@@ -9,19 +9,17 @@ A release has exactly two steps. The agent does the first, the user authorizes t
**Preparation** (local, reversible — agent does this):
- format, lint, typecheck all green
- ACP provider catalog drift checked with `npm run acp:version-drift:check`;
if stale package-runner pins are intentional, say so explicitly, otherwise run
`npm run acp:version-drift:update` and commit the updated catalog
- classify the previous-stable-to-`HEAD` diff as patch or minor, then show the
- resolve the release source to one commit and confirm that commit's existing CI is green
- classify the diff from the previous stable to the release source as patch or minor, then show the
target version and rationale to the user
- draft the changelog, show it to the user, wait for review
- run the pre-release sanity check, surface findings to the user
- confirm CI is green
**Go-ahead** (user says "go ahead"):
- commit the approved changelog
- run the release
- commit the approved release inputs locally
- run the release, which publishes npm and pushes the prepared branch and tag
- create the release heartbeat immediately and babysit it to completion
Rules that apply to both steps:
@@ -31,12 +29,43 @@ Rules that apply to both steps:
- Invoking a release skill is intent to start the flow, not blanket authorization to publish.
- If the user asks for a release preview, show the prospective changelog/release contents and answer questions, but do not commit, tag, publish, or run release commands until they explicitly authorize the release.
## Release source and CI
The default release source is `origin/main`. Fetch `origin`, then record the
resolved commit. The default release checkout is a clean local `main` whose
`HEAD` equals `origin/main`.
An explicit user instruction can select another ref, such as a hotfix commit or
tag. Resolve that ref once and apply every source, diff, and CI check to that
commit instead of `origin/main`.
Before making release-preparation commits, confirm the existing CI run for the
resolved commit is green. Pending CI is watched to completion. Release
preparation then stays local through the changelog, any explicitly requested ACP
catalog update, lockfile preparation, and the version commit. After approval,
commit the prepared inputs locally and run the release command. Its branch and
tag push is the one remote release batch and starts CI for the complete release
commit.
## ACP catalog updates
ACP catalog work enters a release through an explicit user request:
- **Check ACP drift** — run `npm run acp:version-drift:check`. When drift exists,
run `npm run acp:version-drift:update`, verify the catalog, and include the
update in the local release-preparation commits.
- **Update ACP** — run `npm run acp:version-drift:update`, verify the catalog, and
include the update in the local release-preparation commits.
The release authorization covers the requested ACP commit. It ships in the same
release push as the changelog and version commit.
## Two paths
There are two supported ways to ship from `main`:
There are two supported release paths:
1. **Direct stable release**: you are ready to ship the current `main` commit to everyone immediately.
2. **Beta flow**: release candidates on the `beta` channel. Betas carry an in-place changelog entry (beta users check it), publish npm only on the explicit `beta` dist-tag, and never become the website's default download — they sit behind the Stable/Beta switch on `/download`.
2. **Beta flow**: release candidates on the `beta` channel. Each beta carries its own changelog entry, publishes npm only on the explicit `beta` dist-tag, and stays behind the Stable/Beta switch on `/download`.
Paseo has one linear release track even though npm dist-tags are independent
pointers. The npm invariant is:
@@ -48,8 +77,9 @@ pointers. The npm invariant is:
## Release version decision
Every fresh release starts by classifying the full previous-stable-to-`HEAD`
diff. The highest-impact change determines the version:
Every fresh release starts by classifying the full diff from the previous
stable to the resolved release source. The highest-impact change determines the
version:
- **Minor** — a user would experience the release as a significant upgrade. This
includes substantial new workflows, providers, forges, platforms, integrations,
@@ -72,7 +102,7 @@ as described in **Fixing a failed release build**.
Before running any stable release command:
- Make sure the intended release commit is already committed to `main` and the working tree is clean.
- Make sure the resolved release source passed CI, the approved release inputs are committed locally on the intended branch, and the working tree is clean.
- **Run `npm run format`, `npm run lint`, and `npm run typecheck` and commit any resulting changes BEFORE you start any `release:*` command.** `release:check` runs `npm install --workspaces --include-workspace-root` as part of `release:prepare`, which can mutate `package-lock.json` (e.g. churning `"dev": true` markers on optional deps). The next step, `version:all:*`, runs `npm version` which aborts when the working tree is dirty. If this happens mid-flight you have to commit the lockfile churn before retrying — and the pre-commit format hook will reject a lockfile-only commit because oxfmt internally skips `package-lock.json` while lefthook's glob still matches it. Avoid the whole mess by running format/lint/typecheck first, then `release:prepare` once on its own to absorb any lockfile churn into a normal commit, then start the release.
- Do not use a release command as a substitute for checking whether the current commit is actually ready.
@@ -133,7 +163,7 @@ npm run release:promote # Promote X.Y.Z-beta.N to stable X.Y.Z
- `release:promote` creates a fresh stable tag like `v0.1.41`; the final release never reuses the beta tag
- Desktop assets now come from the Electron package at `packages/desktop`
- Beta releases use Electron's `beta` update channel. Users on the stable channel only receive stable releases; users on the beta channel receive beta releases and the final stable release when it is published.
- **Betas carry a changelog entry.** Beta users read release notes, so each beta updates an in-place `CHANGELOG.md` entry (`## X.Y.Z-beta.N`) that `Release Notes Sync` mirrors into the prerelease body on the tag push. The entry is intermediary: promotion overwrites it in place with the final stable entry, so no `-beta.N` heading is ever left behind. See the Changelog policy section.
- **Each beta carries its own changelog entry.** `Release Notes Sync` mirrors the matching `## X.Y.Z-beta.N` entry into that prerelease body. Promotion collapses every beta entry for the version into one final stable entry. See the Changelog policy section.
Use the beta path when you need to:
@@ -291,11 +321,30 @@ Do not treat `build_ios: SUCCESS` or `submit_ios: SUCCESS` as a completed iOS re
To confirm the submission landed, inspect the EAS workflow with `npx eas workflow:view <workflow-run-id> --json`. App Store Connect (review state for the matching version/build) and the Play Console track are the final ground truth.
### Babysitting mobile after a release
## Release completion and heartbeat
The user rarely opens the Expo dashboard. A failed EAS build or submit/review job can sit silently until users complain about a stale version. After every stable release, set up a long-delay babysit that re-checks GitHub Actions, EAS builds, and the EAS `Release Mobile` workflow for the release tag. If any build is `ERRORED`/`CANCELED`, any workflow is `FAILURE`, or any required submit/review job fails, surface it immediately. If all builds are `FINISHED` and all required submit/review jobs are `SUCCESS`, confirm and stop.
A release is **in progress** after npm publication and tag push. Report it as
**shipped** only after every applicable build, publication, asset, manifest, and
store submission passes the completion checklist.
**Use `create_heartbeat`, never `create_schedule`, for release babysitting.** Babysitting fires back into the current conversation as a wake-up prompt. `create_schedule` starts a fresh agent the user has to find and read; `create_heartbeat` surfaces the build status inline in the conversation that owns the release, where it is impossible to miss. If you find yourself reaching for `create_schedule` for a release babysit, you are about to ship a status report into a void.
Immediately after every beta, stable, or promotion tag push, create a heartbeat
that resumes the release in the current conversation. Create it automatically
with `create_heartbeat`. The heartbeat owns the release until it either reaches
the completion checklist or finds a failure that needs new user authority.
Each heartbeat checks the release tag commit, all GitHub Actions runs for the
release branch and tag, npm dist-tags, the GitHub Release body and assets,
desktop updater manifests, the published Docker image, and the applicable EAS
workflow. Inspect the GitHub Release itself and confirm that the macOS, Linux,
Windows, and Android APK assets are present along with the channel manifests
(`latest-mac.yml`, `latest-linux.yml`, and `latest.yml` for stable;
`beta-mac.yml`, `beta-linux.yml`, and `beta.yml` for beta).
For stable releases, also confirm every required mobile build, upload, store
submission, and review-submission job for the release commit. For betas, confirm
the beta EAS workflow completed its TestFlight distribution and Beta App Review
path. Delete the heartbeat only after every applicable checklist item passes,
then report the release as shipped.
Pattern:
@@ -303,13 +352,16 @@ Pattern:
// mcp__paseo__create_heartbeat arguments
{
"name": "vX.Y.Z release babysit heartbeat",
"cron": "*/15 * * * *",
"maxRuns": 8, // covers ~2h of build + store-submission window
"prompt": "Heartbeat: check vX.Y.Z release. Run gh run list, eas build:list, eas workflow:runs, and eas workflow:view for the matching Release Mobile run. Report concisely. The release is not done until desktop/APK workflows are green, EAS builds are FINISHED, Android submit_android is SUCCESS, and iOS submit_ios + submit_ios_for_review are SUCCESS. Flag any ERRORED/FAILED/CANCELED/FAILURE loudly.",
"cron": "*/10 * * * *",
"timezone": "UTC",
"maxRuns": 120,
"expiresIn": "24h",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; every GitHub Actions run for the release branch and tag; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; and the matching EAS workflow. Completion requires every applicable checklist item. For stable, require build_ios, submit_ios, submit_ios_for_review, build_android, and submit_android to succeed. For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes, delete THIS heartbeat, report shipped, and stop.",
}
```
Tight cadence on purpose. The first run fires immediately, giving a near-real-time status check before the conversation closes. Subsequent runs at 15-minute intervals catch transitions quickly: a failed EAS build or failed App Store review submission at +20m should not wait until +50m to surface. Keep the prompt short — the heartbeat is a status probe, not a research task — and have it bail out as soon as every platform is actually on its store path so the remaining runs do not generate noise.
Run an immediate status check after creating the heartbeat. The heartbeat handles
later transitions and stops itself when the release is complete.
## Release notes on GitHub
@@ -322,7 +374,7 @@ The GitHub Release body is populated automatically by the `Release Notes Sync` w
- Homebrew, the Play Store, the App Store, and `app.paseo.sh` have no beta. The Beta view drops those rows, and the whole Web section, rather than showing an inert "stable only" placeholder. When a surface gains a beta path — say a public TestFlight link — add its row back in `packages/website/src/routes/download.tsx`.
- The default download target only moves when you publish the final stable release tag like `v0.1.41`.
- The public `/changelog` page renders `CHANGELOG.md` as-is, so the in-flight `-beta.N` entry shows there once it lands on `main` — that's intended, it's where beta users check what's coming. Only the **default download target** stays pinned to the latest stable; the download links read GitHub's releases API, not the changelog, so a `-beta.N` heading on top never affects them.
- The download page's "What's new" link deep-links the **minor group** anchor (`/changelog#release-0.3`), not the exact entry: promotion rewrites the `-beta.N` entry in place, so that anchor dies while the group survives. A version with no entry in the bundled changelog — a tag whose changelog commit hasn't redeployed the site yet — links the plain `/changelog` instead of a dead anchor.
- The download page's "What's new" link deep-links the **minor group** anchor (`/changelog#release-0.3`), not the exact entry: promotion collapses the beta entries into one stable entry, so the minor group remains the durable target. A version with no entry in the bundled changelog — a tag whose changelog commit hasn't redeployed the site yet — links the plain `/changelog` instead of a dead anchor.
- The website itself is deployed by `Deploy Website` (Cloudflare Workers), which redeploys on `release: published` for non-prerelease releases and on pushes to `main` that touch `CHANGELOG.md` or `packages/website/**`.
## Fixing a failed release build
@@ -403,17 +455,16 @@ No prefix (`v`), no extra text. `Release Notes Sync` matches the `## X.Y.Z` (or
## Changelog policy
- `CHANGELOG.md` includes stable releases and the current beta line.
- `CHANGELOG.md` includes stable releases and every entry in the current beta series.
- The first beta of a version inserts a top entry like `## 0.1.60-beta.1 - YYYY-MM-DD`.
- Each subsequent beta updates that same top entry in place — bump the heading (`0.1.60-beta.1` → `0.1.60-beta.2`) and fold in whatever else landed.
- Stable promotion updates that same entry in place one last time: heading to `0.1.60`, date to the promotion day.
- One entry per version line. The `-beta.N` heading is intermediary — overwrite it, never append. Don't leave stale `-beta.N` entries behind and don't create a duplicate entry per beta.
- It always covers the full diff from the previous stable tag, regardless of how many betas were cut in between.
- Each subsequent beta inserts a new top entry with the next beta number. Its notes cover the changes since the previous beta tag.
- Stable promotion replaces every beta entry for that version with one `## 0.1.60 - YYYY-MM-DD` entry.
- The promoted stable entry covers the full diff from the previous stable tag and collapses internal iterations across the beta series.
## Changelog ownership
- **The agent running the release writes the changelog entry — beta or stable.** Do not hand the changelog to another model or agent. The release agent has the release context and owns the final wording.
- Draft the entry from the previous-stable-to-`HEAD` diff, review it against the changelog policy below, show it to the user, and wait for approval before committing it. Each beta refreshes the same entry; promotion refreshes it one last time from the full previous-stable-to-`HEAD` diff.
- **The agent running the release writes the changelog entry — beta or stable.** The release context and final wording stay with that agent.
- For the first beta or a direct stable release, draft from the previous stable tag to the release source. For later betas, draft from the previous beta tag to the release source. Promotion replaces the beta series with one entry drafted from the previous stable tag to the release source. Review the result against the changelog policy below, show it to the user, and wait for approval before committing it.
## Changelog voice
@@ -434,10 +485,8 @@ The changelog is shown on the Paseo homepage. Write it for **end users**, not de
Test: would a non-developer reader recognise what changed when using the app? If they'd need an engineer to translate ("what's a remount?"), the bullet is still implementation-facing — rewrite it as the symptom the user experiences.
- **Collapse internal iterations.** If a feature was added and then fixed within the same release, just list the feature as working. Users never saw the broken version.
- **Only list changes relative to the previous stable release.** The diff is `v(previous)..HEAD`. If something was introduced and fixed between those two tags, it never shipped — don't mention the fix.
- **Common trap:** when drafting from `git log`, every commit looks like a separate bullet — including the "fix X" commits that landed on top of a brand-new feature in the same release window. Before listing a Fixed entry, check whether the thing being fixed was itself added in this same release. If so, drop the fix and fold it into the feature bullet.
- **Example:** if the release adds an in-app browser and also contains a commit "fix: browser pane keyboard handling no longer steals shortcuts", do **not** list the keyboard fix under Fixed. The browser is shipping for the first time, so users will only ever see the working version. The Added entry covers it.
- **Use the entry's release scope.** Include changes within the matching range in **Changelog scope**.
- **Collapse internal iterations within that scope.** Present a feature added and fixed in one range as working. A later beta can describe a fix to behavior delivered in an earlier beta; promotion folds the complete beta series into the final stable behavior.
- **Cut low-signal entries.** "Toolbar buttons have consistent sizing" is too granular. Combine small polish items or drop them.
## Changelog conciseness
@@ -480,7 +529,7 @@ Rules:
This returns every distinct GitHub login that authored or co-authored a commit in the PR. Use those logins for attribution. Fall back to `gh pr view N --json author` only if the commits command returns nothing (which should not happen for merged PRs).
When listing PR numbers, `git log --format='%H %s' v<previous>..HEAD | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects.
When listing PR numbers, `git log --format='%H %s' v<previous>..<release-source-sha> | grep -E '\(#[0-9]+\)$'` pulls the PR number out of squash commit subjects.
## Changelog ordering
@@ -494,51 +543,68 @@ Entries within each section (Added, Improved, Fixed) are ordered by user impact:
Before cutting a **stable** release, the release agent reviews the diff as a last line of defence against shipping bugs. Skip this for betas — the beta itself is the smoke test, and gating each beta on a code review defeats the point of using betas as fast release candidates.
Review the diff between the latest release tag and `HEAD`. Focus on:
Review the diff between the latest release tag and the resolved release source. Focus on:
1. **Breaking changes** — especially in the WebSocket protocol, agent lifecycle, and any server↔client contract.
2. **Backward compatibility** — the important direction is old app clients talking to newly updated daemons. Users update desktop and daemon first, then keep running the old app for a while. Flag anything that breaks old clients against new daemons or requires both sides to update in lockstep.
3. **Regressions** — anything that looks like it could break existing functionality.
Use `git diff <latest-release-tag>..HEAD` as the review input. This is a deep sanity check, not a full code review. If anything looks risky, investigate before proceeding and surface the finding to the user.
Use `git diff <latest-release-tag>..<release-source-sha>` as the review input. This is a deep sanity check, not a full code review. If anything looks risky, investigate before proceeding and surface the finding to the user.
## Changelog scope
The changelog always covers **previous-stable-to-`HEAD`**, beta and stable alike:
Changelog scope follows the release being described:
- **Beta release**: the entry covers `previous stable tag → HEAD`. Update the current in-place beta entry; don't start a fresh one per beta.
- **Stable promotion**: the same entry is promoted in place. It still captures the full delta from the previous stable release, not just what changed since the last beta.
- **First beta**: `previous stable tag → release source`
- **Later beta**: `previous beta tag → release source`
- **Direct stable release**: `previous stable tag → release source`
- **Stable promotion**: replace the full beta series with one entry covering `previous stable tag → release source`
Betas are checkpoints along the way; the entry is the single record for the jump from one stable version to the next, and beta users read it in the meantime.
Each beta entry records what its testers receive. Promotion produces the single stable record for the full jump from one stable version to the next.
## Completion checklist
### Beta release
- [ ] Working tree is clean and the intended commit is on `main`
- [ ] Update the in-place beta entry in `CHANGELOG.md` (heading `## X.Y.Z-beta.N - YYYY-MM-DD`), review it against the changelog policy, get approval, and commit it before cutting the release
- [ ] The previous-stable-to-`HEAD` diff is classified as patch or minor, with the target version and rationale approved
- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green
- [ ] Add a new `CHANGELOG.md` entry for this beta (heading `## X.Y.Z-beta.N - YYYY-MM-DD`), review it against the changelog policy, get approval, and commit it before cutting the release
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag
- [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully
- [ ] Every GitHub Actions run for the complete release commit and tag is green
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease exists with the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
- [ ] The GitHub prerelease contains `beta-mac.yml`, `beta-linux.yml`, and `beta.yml`
- [ ] GitHub `Android APK Release` workflow for the same tag is green
- [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest`
- [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body
- [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
### Stable release (or promotion)
- [ ] Run the pre-release sanity check (see above) and address any findings
- [ ] The previous-stable-to-`HEAD` diff is classified as patch or minor, with the target version and rationale approved
- [ ] Ensure the intended release commit is already committed and the git worktree is clean before running any release command
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] The resolved release source is the intended commit (default `origin/main`) and its existing CI is green
- [ ] Ensure the approved release inputs are committed locally and the git worktree is clean before running any release command
- [ ] Ensure local `npm run typecheck` passes on that exact commit before running any release command
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). When promoting from beta, overwrite the existing `## X.Y.Z-beta.N` heading in place (heading → `X.Y.Z`, date → promotion day) — do not add a new entry on top of the beta one
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion replaces every `## X.Y.Z-beta.N` entry in the series with one `## X.Y.Z - YYYY-MM-DD` entry covering the full release
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] Release preparation stayed local until the approved release command pushed the complete branch and tag
- [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully
- [ ] Every GitHub Actions run for the complete release commit and tag is green
- [ ] Move npm's `beta` dist-tag to the new stable version for every published package and verify both `latest` and `beta` resolve to it
- [ ] The published GitHub Release exists with the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
- [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml`
- [ ] GitHub `Android APK Release` workflow for the same tag is green
- [ ] GitHub `Docker` workflow is green and both the versioned and `latest` images are published
- [ ] GitHub `Release Notes Sync` is green and the release body matches the stable changelog entry
- [ ] EAS `Release Mobile` workflow for the same tag is green
- [ ] EAS iOS `build_ios` completes for the same tag
- [ ] EAS iOS `submit_ios` succeeds, uploading the build to App Store Connect/TestFlight
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review
- [ ] EAS Android `build_android` completes for the same tag
- [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
+1 -1
View File
@@ -345,7 +345,7 @@ Gotchas:
- **Narrow the discriminated union before spreading.** `updateTheme`'s updater returns the theme union; spreading the union widens `colorScheme` to `"light" | "dark"`, which is assignable to neither concrete member. Branch on `t.colorScheme` so each branch spreads a single narrowed theme type (no `as`).
- **`lineHeight.diff` is the code/diff line-height axis** — it is coupled to the code-font-size control (≈ `codeFontSize * 1.5`). Do NOT use it for prose. Markdown body line-height scales with the UI ramp (`Math.round(theme.fontSize.base * 1.4)`); routing prose through `lineHeight.diff` clips text at small code sizes.
- **High-churn draft values** (live-while-typing in the appearance preview) bypass the theme: apply them as inline styles marked with `inlineUnistylesStyle` so per-keystroke values don't grow the `#unistyles-web` CSS registry.
- **Mounted parsed content uses `AppearanceStyleBoundary`.** Markdown, syntax-highlighted code, and tool-call detail bodies can contain memoized/custom renderer trees that do not naturally re-run when runtime-patched appearance tokens change. Wrap the parsed surface once with `packages/app/src/components/appearance-style-boundary.tsx`; do not add local "appearance key" props at each callsite.
- **The app shell uses one `AppearanceStyleBoundary`.** Runtime-patched numeric theme values are baked into Unistyles web classes rather than CSS variables, while parsed/memoized content also does not naturally re-run when appearance tokens change. The boundary sits below stable runtime providers in `app/_layout.tsx` and remounts the visual shell once. `applyAppearance` patches the active theme before inactive registry entries so its subscribers receive the committed values in the same update. Do not add local appearance keys or nested boundaries.
- **Dynamic font tokens stay widened.** `fontFamily`, `fontSize`, and `lineHeight` on `commonTheme` are annotated `string`/`number` (not narrowed by `as const`) so the updater's return assigns; the platform default stacks live in `DEFAULT_UI_FONT_STACK` / `DEFAULT_MONO_FONT_STACK`.
## Debugging
+1 -1
View File
@@ -1 +1 @@
sha256-MDuVQQ5DmNoPlb9+LlrZYxGbP+22rYpfhcDJQxmIUsU=
sha256-RCp5Ogd8AETLmJCZaUebcgSPRk+is26nkUY7+blDb/g=
+21 -21
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.3.0",
"version": "0.3.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.3.0",
"version": "0.3.1",
"hasInstallScript": true,
"license": "AGPL-3.0-or-later",
"workspaces": [
@@ -35299,7 +35299,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -36353,12 +36353,12 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.3.0",
"@getpaseo/protocol": "0.3.0",
"@getpaseo/server": "0.3.0",
"@getpaseo/client": "0.3.1",
"@getpaseo/protocol": "0.3.1",
"@getpaseo/server": "0.3.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -36605,10 +36605,10 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"@getpaseo/protocol": "0.3.0",
"@getpaseo/relay": "0.3.0",
"@getpaseo/protocol": "0.3.1",
"@getpaseo/relay": "0.3.1",
"zod": "^4.4.3"
},
"devDependencies": {
@@ -36619,7 +36619,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.3.0",
"version": "0.3.1",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@getpaseo/cli": "*",
@@ -36862,7 +36862,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -37758,7 +37758,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"@codemirror/language": "6.12.4",
"@codemirror/legacy-modes": "^6.5.3",
@@ -37990,7 +37990,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"zod": "^4.4.3"
},
@@ -38003,7 +38003,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"base64-js": "^1.5.1",
"tweetnacl": "^1.0.3",
@@ -38221,15 +38221,15 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.220",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.3.0",
"@getpaseo/highlight": "0.3.0",
"@getpaseo/protocol": "0.3.0",
"@getpaseo/relay": "0.3.0",
"@getpaseo/client": "0.3.1",
"@getpaseo/highlight": "0.3.1",
"@getpaseo/protocol": "0.3.1",
"@getpaseo/relay": "0.3.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "^1.20.1",
"@opencode-ai/sdk": "1.14.46",
@@ -38778,7 +38778,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.3.0",
"version": "0.3.1",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.3.0",
"version": "0.3.1",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -0,0 +1,36 @@
import { expect, test } from "../support/fixtures";
import { openSettingsSection } from "../support/helpers/settings";
test("shows Pure black in the appearance picker", async ({ page }, testInfo) => {
await page.goto("/settings");
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
await openSettingsSection(page, "appearance");
const themeTrigger = page.getByLabel("Theme: System", { exact: true });
await themeTrigger.click();
await expect(page.getByText("Pure black", { exact: true })).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("appearance-theme-picker.png"),
fullPage: true,
});
});
test("applies the interface font size to settings text", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem("@paseo:app-settings", JSON.stringify({ uiFontSize: 24 }));
});
await page.goto("/settings");
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
await openSettingsSection(page, "appearance");
const sectionTitle = page.getByText("Theme", { exact: true }).first();
await expect(sectionTitle).toHaveCSS("font-size", "18px");
const fontSizeInput = page.getByLabel("Interface font size");
await expect(fontSizeInput).toHaveValue("24");
await fontSizeInput.fill("12");
await fontSizeInput.press("Tab");
await expect(fontSizeInput).toHaveValue("12");
await expect(sectionTitle).toHaveCSS("font-size", "9px");
});
@@ -118,6 +118,53 @@ async function selectAssistantText(page: Page, text: string): Promise<void> {
await selectAssistantTextRange(page, text, text);
}
async function selectAssistantListItemFromMarker(
page: Page,
listTag: "ol" | "ul",
itemText: string,
endText: string,
): Promise<void> {
const assistantMessage = page.getByTestId("assistant-message").filter({
hasText: "Direct matches:",
});
const item = assistantMessage
.locator(`[data-paseo-markdown-tag="${listTag}"]`)
.filter({ hasText: itemText })
.locator(':scope > [data-paseo-markdown-tag="li"]')
.filter({ hasText: itemText });
await item.evaluate((element, selectedEndText) => {
const marker = element.querySelector(':scope > [data-paseo-markdown-list-marker="true"]');
const markerText = marker?.firstChild;
if (!(markerText instanceof Text)) {
throw new Error("Expected rendered list marker text");
}
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
let endNode: Text | null = null;
let endOffset = -1;
while (walker.nextNode()) {
const node = walker.currentNode;
const offset = node.textContent?.indexOf(selectedEndText) ?? -1;
if (node instanceof Text && offset >= 0) {
endNode = node;
endOffset = offset + selectedEndText.length;
break;
}
}
if (!endNode) {
throw new Error(`Could not find list item selection end: ${selectedEndText}`);
}
const range = document.createRange();
range.setStart(markerText, 0);
range.setEnd(endNode, endOffset);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}, endText);
}
async function doubleClickAssistantMarkdownText(
page: Page,
tag: "code" | "strong",
@@ -405,6 +452,24 @@ test("copying an assistant selection preserves Markdown structure and links", as
'<div>- <strong><a href="https://example.com/issues/1">First issue</a></strong>',
);
await selectAssistantListItemFromMarker(page, "ul", "First issue", "failure.");
await copySelection(page);
const draggedBulletClipboard = await readRichClipboard(page);
expect(draggedBulletClipboard.plainText).toBe(
"- **[First issue](https://example.com/issues/1)**: exact `apply_patch` failure.",
);
expect(draggedBulletClipboard.html).toContain(
'<div>- <strong><a href="https://example.com/issues/1">First issue</a></strong>',
);
await selectAssistantListItemFromMarker(page, "ol", "Sixth item", "Sixth item");
await copySelection(page);
const draggedNumberClipboard = await readRichClipboard(page);
expect(draggedNumberClipboard.plainText).toBe("6. Sixth item");
expect(draggedNumberClipboard.html).toContain("<div>6. Sixth item</div>");
await selectAssistantText(page, "docs");
await copySelection(page);
@@ -13,6 +13,7 @@ import {
} from "../support/helpers/new-workspace";
import { connectSeedClient, type SeedDaemonClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { addConnectedHostsAndReload } from "../support/helpers/hosts";
import { switchWorkspaceViaSidebar } from "../support/helpers/workspace-ui";
import { createTempGitRepo } from "../support/helpers/workspace";
@@ -29,6 +30,7 @@ interface CreatedProject {
interface CrossHostProjectScenario {
contextWorkspaceId: string;
primarySharedWorkspaceId: string;
selectedProjectViewKey: string;
sharedProjectKey: string;
secondaryHost: {
@@ -149,6 +151,7 @@ const test = base.extend<{ crossHostProject: CrossHostProjectScenario }>({
await provide({
contextWorkspaceId: contextProject.workspaceId,
primarySharedWorkspaceId: primarySharedProject.workspaceId,
selectedProjectViewKey: projectPlacementViewKey(
getServerId(),
primarySharedProject.projectId,
@@ -196,4 +199,33 @@ test.describe("New workspace host project preservation", () => {
await expectNewWorkspaceProjectSelected(page, SHARED_PROJECT_NAME);
});
test("keeps the active workspace project selected when switching hosts", async ({
page,
crossHostProject,
}) => {
await openProjectDirectoryWithHosts(page, {
hosts: [crossHostProject.secondaryHost],
primaryLabel: PRIMARY_HOST_LABEL,
});
await switchWorkspaceViaSidebar({
page,
serverId: getServerId(),
workspaceId: crossHostProject.primarySharedWorkspaceId,
});
await openGlobalNewWorkspaceComposer(page);
await expectNewWorkspaceProjectSelected(page, SHARED_PROJECT_NAME);
await selectNewWorkspaceHost(page, SECONDARY_HOST_LABEL);
await expectNewWorkspaceProjectSelected(page, SHARED_PROJECT_NAME);
await addConnectedHostsAndReload(page, [crossHostProject.secondaryHost], {
primaryLabel: PRIMARY_HOST_LABEL,
});
await expectNewWorkspaceProjectSelected(page, SHARED_PROJECT_NAME);
await selectNewWorkspaceHost(page, SECONDARY_HOST_LABEL);
await expectNewWorkspaceProjectSelected(page, SHARED_PROJECT_NAME);
});
});
@@ -0,0 +1,87 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import {
openNewWorkspaceComposer,
openStartingRefPicker,
selectBranchInPicker,
selectWorkspaceIsolation,
} from "../support/helpers/new-workspace";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { seedSavedSettingsHosts } from "../support/helpers/settings";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
const LONG_HOST_NAME =
"development-macbook-pro.local-connected-through-a-very-long-private-hostname";
const LONG_BRANCH_NAME =
"feat/app/add-amoled-theme-with-a-very-long-pull-request-and-branch-description";
function measureControlRightEdges(controls: HTMLElement[]) {
const measurements: Array<{ label: string | null; right: number }> = [];
for (const control of controls) {
const rect = control.getBoundingClientRect();
measurements.push({ label: control.getAttribute("aria-label"), right: rect.right });
}
return measurements;
}
test.describe("New workspace metadata row layout", () => {
let workspace: SeededWorkspace;
test.beforeEach(async () => {
workspace = await seedWorkspace({
repoPrefix: "new-workspace-layout-",
repo: { branches: [LONG_BRANCH_NAME] },
});
});
test.afterEach(async () => {
await workspace?.cleanup();
});
test("long host and branch names stay inside the composer's right rail", async ({ page }) => {
await page.setViewportSize({ width: 2048, height: 878 });
await seedSavedSettingsHosts(page, [
{
serverId: getServerId(),
label: LONG_HOST_NAME,
endpoint: `127.0.0.1:${getE2EDaemonPort()}`,
},
{
serverId: "srv_e2e_layout_offline",
label: "Offline host",
endpoint: "127.0.0.1:9",
},
]);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectWorkspaceIsolation(page, "worktree");
await openStartingRefPicker(page);
await selectBranchInPicker(page, LONG_BRANCH_NAME);
const composer = page.locator('[data-testid="message-input-root"]:visible');
const metadataRow = page.getByTestId("new-workspace-ref-picker-row");
await expect(composer).toBeVisible();
await expect(metadataRow).toBeVisible();
const [composerBox, controlBoxes] = await Promise.all([
composer.boundingBox(),
metadataRow.getByRole("button").evaluateAll(measureControlRightEdges),
]);
expect(composerBox).not.toBeNull();
const composerRightRail = composerBox!.x + composerBox!.width;
for (const control of controlBoxes) {
expect(
control.right,
`${control.label ?? "Metadata control"} crossed the composer rail`,
).toBeLessThanOrEqual(composerRightRail + 1);
}
});
});
@@ -34,7 +34,7 @@ const cases: ProviderSubagentCase[] = [
provider: "codex",
sentinel: "CODEX_CHILD_SENTINEL",
expectedName: "Sentinel child",
providerConfig: { extra: { codex: { features: { multi_agent_v2: true } } } },
providerConfig: { providerOptions: { features: { multi_agent_v2: true } } },
prompt:
'Use the native collaboration.spawn_agent tool exactly once with task_name "sentinel_child" and fork_turns "none". Ask it to reply with exactly CODEX_CHILD_SENTINEL and do nothing else. Wait for it with collaboration.wait_agent, then reply ROOT_DONE. Do not use Paseo tools.',
},
@@ -114,16 +114,6 @@ test.describe("Settings sidebar navigation", () => {
await expectDirectHostUriHidden(page);
});
test("browser web hides direct connection custom headers", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await toggleHostAdvanced(page);
await expect(page.getByTestId("direct-header-add")).toHaveCount(0);
});
test("sidebar shows a Back to workspace row that leaves /settings", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
@@ -8,7 +8,6 @@ async function expectBorderHighlight(page: Page, testID: string) {
await expect(page.getByTestId(`${testID}-highlight`)).toHaveCount(0);
await handle.hover();
await expect(page.getByTestId(`${testID}-highlight`)).toHaveCount(0);
const highlight = page.getByTestId(`${testID}-highlight`);
await expect(highlight).toBeVisible();
@@ -304,7 +304,9 @@ test.describe("Half-screen desktop layout", () => {
await gotoAppShell(page);
const openToggle = page.getByTestId("menu-button");
const openBounds = await openToggle.locator("svg").first().boundingBox();
const openIcon = openToggle.locator("svg").first();
await expect(openIcon).toBeVisible();
const openBounds = await openIcon.boundingBox();
expect(openBounds).not.toBeNull();
expect(openBounds?.x).toBeGreaterThan(12);
@@ -312,7 +314,9 @@ test.describe("Half-screen desktop layout", () => {
await expect(page.getByTestId("sidebar-global-new-workspace")).not.toBeVisible();
const closedToggle = page.getByTestId("menu-button");
const closedBounds = await closedToggle.locator("svg").first().boundingBox();
const closedIcon = closedToggle.locator("svg").first();
await expect(closedIcon).toBeVisible();
const closedBounds = await closedIcon.boundingBox();
expect(closedBounds).not.toBeNull();
expect(closedBounds?.x).toBeCloseTo(12, 0);
expect(closedBounds?.y).toBe(openBounds?.y);
@@ -503,12 +503,16 @@ test.describe("Workspace model restart regressions", () => {
createdWorkspaceId,
]),
)
.toEqual({
[seeded.workspaceA]: "running",
.toMatchObject({
[seeded.workspaceB]: "done",
[createdWorkspaceId]: "done",
});
// The restarted provider session may settle while the browser creates the sibling. Its
// initial running status is asserted above; this phase verifies that ownership never moves.
const workspaceStatuses = await fetchWorkspaceStatuses(client, [seeded.workspaceA]);
expect(["running", "done"]).toContain(workspaceStatuses[seeded.workspaceA]);
await expectWorkspaceRowDoesNotShowIndicator(page, {
serverId,
workspaceId: seeded.workspaceB,
@@ -519,11 +523,6 @@ test.describe("Workspace model restart regressions", () => {
workspaceId: createdWorkspaceId,
indicator: "running",
});
await expectWorkspaceRowInStatusBucket(page, {
serverId,
workspaceId: seeded.workspaceA,
bucket: "running",
});
await expectWorkspaceRowInStatusBucket(page, {
serverId,
workspaceId: seeded.workspaceB,
@@ -0,0 +1,76 @@
import { randomUUID } from "node:crypto";
import { test, expect } from "../support/fixtures";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { renameModalInput, renameModalSubmit } from "../support/helpers/rename";
import type { SeedDaemonClient } from "../support/helpers/seed-client";
const MOBILE_VIEWPORT = { width: 390, height: 844 };
async function fetchAgentTitle(client: SeedDaemonClient, agentId: string): Promise<string | null> {
const result = await client.fetchAgents({ scope: "active" });
return result.entries.find((entry) => entry.agent.id === agentId)?.agent.title ?? null;
}
/**
* Compact "sessions dropdown" rename path. The desktop rename specs drive the right-click
* `workspace-tab-context-*` menu, which portals into overlay-root and was never broken. This
* exercises the tab switcher's per-session actions on a phone-sized viewport — the path that
* regressed when the actions menu presented as a popover instead of a bottom sheet.
*/
test.describe("Workspace session rename (compact tab switcher)", () => {
test("renames an agent session from the switcher's per-session actions sheet", async ({
page,
}) => {
test.setTimeout(120_000);
await page.setViewportSize(MOBILE_VIEWPORT);
const initialTitle = `switcher-rename-${randomUUID().slice(0, 8)}`;
const session = await seedMockAgentWorkspace({
repoPrefix: "workspace-switcher-rename-",
title: initialTitle,
});
try {
await openAgentRoute(page, session);
await expect(page.getByTestId("workspace-tab-switcher-trigger")).toBeVisible({
timeout: 30_000,
});
// Open the sessions dropdown (a bottom sheet on compact).
await page.getByRole("button", { name: /Switch tabs/ }).click();
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" }).first()).toBeVisible(
{
timeout: 10_000,
},
);
// Open this session's "…" actions. Before the fix this tried to open a popover-Modal
// that never surfaced over the sheet on native; it now opens as a stacked sheet.
const menuBase = `workspace-tab-menu-agent_${session.agentId}`;
const actionsTrigger = page.getByTestId(`${menuBase}-trigger`);
await expect(actionsTrigger).toBeVisible({ timeout: 15_000 });
await actionsTrigger.click();
const renameItem = page.getByTestId(`${menuBase}-rename`);
await expect(renameItem).toBeVisible({ timeout: 10_000 });
await renameItem.click();
const modalPrefix = `workspace-tab-rename-modal-agent-${session.agentId}`;
const input = renameModalInput(page, modalPrefix);
await expect(input).toBeVisible({ timeout: 10_000 });
await expect(input).toHaveValue(initialTitle);
const renamed = "Renamed from the dropdown";
await input.fill(renamed);
await renameModalSubmit(page, modalPrefix).click();
await expect(input).toHaveCount(0, { timeout: 15_000 });
await expect(page.getByTestId("workspace-tab-switcher-trigger")).toContainText(renamed, {
timeout: 15_000,
});
await expect.poll(() => fetchAgentTitle(session.client, session.agentId)).toBe(renamed);
} finally {
await session.cleanup();
}
});
});
@@ -17,6 +17,49 @@ interface PairingHostInput {
endpoint: string;
}
export async function prepareLocalPairingHost(
page: Page,
daemon: IsolatedHostDaemon | OutdatedDaemon,
additionalHosts: PairingHostInput[] = [],
): Promise<void> {
await page.addInitScript((localServerId) => {
(window as unknown as { paseoDesktop: unknown }).paseoDesktop = {
platform: "darwin",
invoke: async (command: string) => {
if (command === "desktop_daemon_status") {
return {
serverId: localServerId,
status: "running",
listen: null,
hostname: null,
pid: null,
home: "",
version: null,
desktopManaged: true,
error: null,
};
}
if (command === "get_desktop_settings") {
return {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
};
}
return null;
},
getPendingOpenProject: async () => null,
events: { on: async () => () => undefined },
opener: {
openUrl: async (url: string) => {
localStorage.setItem("@paseo:e2e-opened-url", url);
},
},
};
}, daemon.serverId);
await preparePairingHost(page, daemon, additionalHosts);
}
export async function preparePairingHost(
page: Page,
daemon: IsolatedHostDaemon | OutdatedDaemon,
@@ -160,7 +160,7 @@ export async function launchAgent(input: {
model?: string;
modeId?: string;
featureValues?: Record<string, unknown>;
extra?: { codex?: { features?: { multi_agent_v2?: boolean } } };
providerOptions?: { features?: { multi_agent_v2?: boolean } };
};
}): Promise<AgentHandle> {
execFileSync("git", ["init", "-b", "main"], { cwd: input.cwd, stdio: "ignore" });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.3.0",
"version": "0.3.1",
"private": true,
"main": "index.ts",
"scripts": {
+19 -18
View File
@@ -26,6 +26,7 @@ import { CommandCenterRootActions } from "@/command-center/root-registration";
import { CommandCenterProvider } from "@/command-center/provider";
import { CommandCenterWorkspaceActions } from "@/command-center/workspace-registration";
import { AddProjectFlowHost } from "@/components/add-project-flow-host";
import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary";
import { WorktreeSetupCalloutSource } from "@/components/worktree-setup-callout-source";
import { DownloadToast } from "@/components/download-toast";
import { QuittingOverlay } from "@/components/quitting-overlay";
@@ -643,7 +644,7 @@ function ProvidersWrapper({ children }: { children: ReactNode }) {
// Apply font / size / syntax appearance settings on mount and when they change.
// Sibling to the theme effect above; order is irrelevant because both patch all
// six registered theme keys, so the active key is always current.
// registered theme keys, so the active key is always current.
useEffect(() => {
if (settingsLoading) return;
applyAppearance({
@@ -668,7 +669,7 @@ function ProvidersWrapper({ children }: { children: ReactNode }) {
<OfferLinkListener upsertDaemonFromOfferUrl={upsertConnectionFromOfferUrl} />
<HostSessionManager />
<FaviconStatusSync />
{children}
<AppearanceStyleBoundary>{children}</AppearanceStyleBoundary>
</VoiceProvider>
);
}
@@ -954,19 +955,17 @@ function RuntimeProviders({ children }: { children: ReactNode }) {
// context and need one shared provider for sibling sheets to stack.
function RootProviders({ children }: { children: ReactNode }) {
return (
<SafeAreaProvider>
<WindowChromeProvider>
<KeyboardProvider>
<KeyboardShiftProvider>
<ToastProvider>
<PortalProvider>
<BottomSheetModalProvider>{children}</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
</KeyboardShiftProvider>
</KeyboardProvider>
</WindowChromeProvider>
</SafeAreaProvider>
<WindowChromeProvider>
<KeyboardProvider>
<KeyboardShiftProvider>
<ToastProvider>
<PortalProvider>
<BottomSheetModalProvider>{children}</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
</KeyboardShiftProvider>
</KeyboardProvider>
</WindowChromeProvider>
);
}
@@ -998,9 +997,11 @@ export default function RootLayout() {
return (
<QueryProvider>
<I18nProvider>
<RootErrorBoundary>
<RootAppTree />
</RootErrorBoundary>
<SafeAreaProvider>
<RootErrorBoundary>
<RootAppTree />
</RootErrorBoundary>
</SafeAreaProvider>
</I18nProvider>
</QueryProvider>
);
@@ -5,8 +5,8 @@ const fixture = `
<div data-testid="assistant-message">
<div data-paseo-markdown-tag="p">Prefix <span data-paseo-markdown-tag="strong">bold text</span> and <span data-paseo-markdown-tag="code">inline code</span> suffix.</div>
<div data-paseo-markdown-tag="ul">
<div data-paseo-markdown-tag="li"><span data-paseo-markdown-ignore="true">•</span><div><span>First bullet text</span></div></div>
<div data-paseo-markdown-tag="li"><span data-paseo-markdown-ignore="true">•</span><div><span>Second bullet text</span></div></div>
<div data-paseo-markdown-tag="li"><span data-paseo-markdown-ignore="true" data-paseo-markdown-list-marker="true">•</span><div><span>First bullet text</span></div></div>
<div data-paseo-markdown-tag="li"><span data-paseo-markdown-ignore="true" data-paseo-markdown-list-marker="true">•</span><div><span>Second bullet text</span></div></div>
</div>
<div data-paseo-markdown-tag="pre" data-paseo-markdown-language="ts"><span data-paseo-markdown-tag="code">const answer = true;</span></div>
</div>
@@ -203,6 +203,97 @@ describe("assistant selection copy ranges", () => {
expect(copiedMarkdown(selectNodeContents(item))).toBe("- First bullet text");
});
it("retains a bullet when a drag selects from the rendered marker through the item text", () => {
const message = mountFixture();
const marker = fixtureElement(message, '[data-paseo-markdown-list-marker="true"]');
const itemText = fixtureElement(message, '[data-paseo-markdown-tag="li"] div span');
const content = createAssistantSelectionClipboardContent(
selectRange(marker, 0, itemText, textNode(itemText).length),
);
expect(content?.plainText).toBe("- First bullet text");
expect(content?.html).toContain("<div>- First bullet text</div>");
expect(content?.html).not.toContain("<ul>");
expect(content?.html).not.toContain("<li>");
});
it("retains a bullet when a drag includes the marker and part of the item text", () => {
const message = mountFixture();
const marker = fixtureElement(message, '[data-paseo-markdown-list-marker="true"]');
const itemText = fixtureElement(message, '[data-paseo-markdown-tag="li"] div span');
expect(copiedMarkdown(selectRange(marker, 0, itemText, 5))).toBe("- First");
});
it("does not invent a bullet when a drag starts after the rendered marker", () => {
const message = mountFixture();
const marker = fixtureElement(message, '[data-paseo-markdown-list-marker="true"]');
const itemText = fixtureElement(message, '[data-paseo-markdown-tag="li"] div span');
expect(
copiedMarkdown(
selectRange(marker, textNode(marker).length, itemText, textNode(itemText).length),
),
).toBe("First bullet text");
});
it("retains every selected marker across a partial multi-item drag", () => {
const message = mountFixture();
const markerSelector = '[data-paseo-markdown-list-marker="true"]';
const textSelector = '[data-paseo-markdown-tag="li"] div span';
const firstMarker = fixtureElement(message, markerSelector);
const secondText = fixtureElement(message, textSelector, 1);
expect(copiedMarkdown(selectRange(firstMarker, 0, secondText, 6))).toBe(
"- First bullet text\n- Second",
);
});
it("retains the original number when a marker drag starts mid-list", () => {
const message = mountFixture();
const list = fixtureElement(message, '[data-paseo-markdown-tag="ul"]');
list.setAttribute("data-paseo-markdown-tag", "ol");
list.setAttribute("data-paseo-markdown-list-start", "5");
const markers = list.querySelectorAll<HTMLElement>('[data-paseo-markdown-list-marker="true"]');
markers.item(0).textContent = "5.";
markers.item(1).textContent = "6.";
const secondMarker = fixtureElement(list, '[data-paseo-markdown-list-marker="true"]', 1);
const secondText = fixtureElement(list, '[data-paseo-markdown-tag="li"] div span', 1);
expect(
copiedMarkdown(selectRange(secondMarker, 0, secondText, textNode(secondText).length)),
).toBe("6. Second bullet text");
});
it("retains nested markers when a drag includes the complete outer item", () => {
const message = mountFixture();
const firstItem = fixtureElement(message, '[data-paseo-markdown-tag="li"]');
firstItem.innerHTML = [
'<span data-paseo-markdown-ignore="true" data-paseo-markdown-list-marker="true">•</span>',
"<div>",
"<span>Outer text</span>",
'<div data-paseo-markdown-tag="ul">',
'<div data-paseo-markdown-tag="li">',
'<span data-paseo-markdown-ignore="true" data-paseo-markdown-list-marker="true">•</span>',
"<div><span>Inner text</span></div>",
"</div>",
"</div>",
"</div>",
].join("");
const outerMarker = fixtureElement(
firstItem,
':scope > [data-paseo-markdown-list-marker="true"]',
);
const innerText = fixtureElement(
firstItem,
':scope [data-paseo-markdown-tag="ul"] > [data-paseo-markdown-tag="li"] > div > span',
);
expect(copiedMarkdown(selectRange(outerMarker, 0, innerText, textNode(innerText).length))).toBe(
"- Outer text\n - Inner text",
);
});
it("preserves paragraph breaks when rich HTML flattens a loose list item", () => {
const message = mountFixture();
const item = fixtureElement(message, '[data-paseo-markdown-tag="li"]');
@@ -9,6 +9,7 @@ import {
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
MARKDOWN_COPY_LIST_START_ATTRIBUTE,
MARKDOWN_COPY_TAG_ATTRIBUTE,
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
@@ -278,7 +279,7 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean
if (tag === "p" || isTableStructure(tag)) {
return true;
}
const isSelectableSemantic = tag !== null && tag !== "ol" && tag !== "ul";
const isSelectableSemantic = tag !== null && tag !== "li" && tag !== "ol" && tag !== "ul";
if (
(isSelectableSemantic || element.tagName === "A") &&
selectionStaysInsideElement(range, element)
@@ -287,7 +288,12 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean
}
if (tag === "ol" || tag === "ul") {
const selectedItems = selectedListItems(element, range);
return selectedItems.some((item) => hasSelectedAllContents(range, item, true));
return selectedItems.some(
(item) => hasSelectedListMarker(range, item) || hasSelectedAllContents(range, item, true),
);
}
if (tag === "li" && hasSelectedListMarker(range, element)) {
return true;
}
return hasSelectedAllContents(range, element, tag === "li");
}
@@ -311,6 +317,31 @@ function selectedListItems(list: Element, range: Range): Element[] {
);
}
function hasSelectedListMarker(range: Range, item: Element): boolean {
const marker = item.querySelector(`:scope > [${MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE}]`);
if (!marker) {
return false;
}
const markerContents = document.createRange();
markerContents.selectNodeContents(marker);
const selectionEndsBeforeMarker =
range.compareBoundaryPoints(Range.END_TO_START, markerContents) >= 0;
const selectionStartsAfterMarker =
range.compareBoundaryPoints(Range.START_TO_END, markerContents) <= 0;
if (selectionEndsBeforeMarker || selectionStartsAfterMarker) {
return false;
}
if (range.compareBoundaryPoints(Range.START_TO_START, markerContents) > 0) {
markerContents.setStart(range.startContainer, range.startOffset);
}
if (range.compareBoundaryPoints(Range.END_TO_END, markerContents) < 0) {
markerContents.setEnd(range.endContainer, range.endOffset);
}
return hasMarkdownContent(markerContents.cloneContents(), true);
}
function normalizeOrderedListStart(copy: Element, original: Element, range: Range): void {
if (original.getAttribute(MARKDOWN_COPY_TAG_ATTRIBUTE) !== "ol") {
return;
@@ -1,5 +1,6 @@
export const MARKDOWN_COPY_TAG_ATTRIBUTE = "data-paseo-markdown-tag";
export const MARKDOWN_COPY_IGNORE_ATTRIBUTE = "data-paseo-markdown-ignore";
export const MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE = "data-paseo-markdown-list-marker";
export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
@@ -28,6 +29,7 @@ export const markdownCopyDataSet = {
hr: { paseoMarkdownTag: "hr" },
ignore: { paseoMarkdownIgnore: "true" },
li: { paseoMarkdownTag: "li" },
listMarker: { paseoMarkdownIgnore: "true", paseoMarkdownListMarker: "true" },
ol: { paseoMarkdownTag: "ol" },
p: { paseoMarkdownTag: "p" },
pre: { paseoMarkdownTag: "pre" },
@@ -6,7 +6,10 @@ import { supportsDesktopPaneSplits, useIsCompactFormFactor } from "@/constants/l
import { GIT_ACTION_ICONS } from "@/git/action-icons";
import { useGitActionRunner, useGitActions } from "@/git/use-actions";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { resolveShortcutKeysForAction } from "@/keyboard/keyboard-shortcuts";
import {
resolveShortcutKeysForAction,
type ShortcutOverrides,
} from "@/keyboard/keyboard-shortcuts";
import { keyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
@@ -36,9 +39,7 @@ function staticIcon(element: ReactElement | undefined): CommandCenterIcon | unde
return StaticIcon;
}
function resolveWorkspaceShortcuts(
overrides: Readonly<Record<string, string>>,
): WorkspaceCommandCenterShortcuts {
function resolveWorkspaceShortcuts(overrides: ShortcutOverrides): WorkspaceCommandCenterShortcuts {
const platform = { isMac: getShortcutOs() === "mac", isDesktop: getIsElectron() };
return {
newAgent: resolveShortcutKeysForAction("workspace-tab-new", overrides, platform) ?? undefined,
+20 -201
View File
@@ -1,10 +1,9 @@
import { useCallback, useMemo, useReducer, useRef, useState } from "react";
import { useCallback, useMemo, useReducer, useState } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Pressable, Text, View } from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { getIsElectron, isNative } from "@/constants/platform";
import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Link2, Plus, X } from "lucide-react-native";
import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Link2 } from "lucide-react-native";
import type { HostProfile } from "@/types/host-connection";
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
import {
@@ -13,11 +12,6 @@ import {
serializeConnectionUriForStorage,
} from "@/utils/daemon-endpoints";
import { DaemonConnectionTestError } from "@/utils/test-daemon-connection";
import {
prepareConnectionHeaders,
type ConnectionHeaderDraft,
type ConnectionHeaderValidationIssue,
} from "@/utils/connection-headers";
import { AdaptiveModalSheet, AdaptiveTextInput, type SheetHeader } from "./adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
@@ -129,30 +123,6 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.medium,
},
advancedContent: {
gap: theme.spacing[4],
},
headerSection: {
gap: theme.spacing[2],
},
headerTitleRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[3],
},
headerList: {
gap: theme.spacing[2],
},
headerRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
headerInput: {
flex: 1,
minWidth: 0,
},
actions: {
flexDirection: "row",
gap: theme.spacing[3],
@@ -211,94 +181,6 @@ function prepareDirectConnection(
};
}
function headerIssueMessage(
issue: ConnectionHeaderValidationIssue,
t: ReturnType<typeof useTranslation>["t"],
): string {
if (issue.type === "missingName") return t("pairing.direct.headers.errors.missingName");
if (issue.type === "invalidName") {
return t("pairing.direct.headers.errors.invalidName", { name: issue.name });
}
if (issue.type === "invalidValue") {
return t("pairing.direct.headers.errors.invalidValue", { name: issue.name });
}
return t("pairing.direct.headers.errors.duplicateName", { name: issue.name });
}
interface ConnectionHeaderRowProps {
draft: ConnectionHeaderDraft;
index: number;
disabled: boolean;
placeholderTextColor: string;
iconColor: string;
onUpdate: (id: number, field: "name" | "value", value: string) => void;
onRemove: (id: number) => void;
}
function ConnectionHeaderRow({
draft,
index,
disabled,
placeholderTextColor,
iconColor,
onUpdate,
onRemove,
}: ConnectionHeaderRowProps) {
const { t } = useTranslation();
const handleNameChange = useCallback(
(value: string) => onUpdate(draft.id, "name", value),
[draft.id, onUpdate],
);
const handleValueChange = useCallback(
(value: string) => onUpdate(draft.id, "value", value),
[draft.id, onUpdate],
);
const handleRemove = useCallback(() => onRemove(draft.id), [draft.id, onRemove]);
return (
<View style={styles.headerRow}>
<AdaptiveTextInput
testID={`direct-header-name-${index}`}
nativeID={`direct-header-name-${draft.id}`}
accessibilityLabel={t("pairing.direct.headers.name")}
initialValue={draft.name}
value={draft.name}
onChangeText={handleNameChange}
placeholder={t("pairing.direct.headers.name")}
placeholderTextColor={placeholderTextColor}
style={[styles.input, styles.headerInput]}
autoCapitalize="none"
autoCorrect={false}
editable={!disabled}
/>
<AdaptiveTextInput
testID={`direct-header-value-${index}`}
nativeID={`direct-header-value-${draft.id}`}
accessibilityLabel={t("pairing.direct.headers.value")}
initialValue={draft.value}
value={draft.value}
onChangeText={handleValueChange}
placeholder={t("pairing.direct.headers.value")}
placeholderTextColor={placeholderTextColor}
style={[styles.input, styles.headerInput]}
autoCapitalize="none"
autoCorrect={false}
editable={!disabled}
/>
<Pressable
style={styles.iconButton}
onPress={handleRemove}
disabled={disabled}
accessibilityRole="button"
accessibilityLabel={t("pairing.direct.headers.remove")}
testID={`direct-header-remove-${index}`}
>
<X size={18} color={iconColor} />
</Pressable>
</View>
);
}
function draftFromConnectionUri(uri: string): DirectConnectionDraft {
const parsed = parseConnectionUri(uri);
return {
@@ -423,8 +305,6 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
const [advancedUri, setAdvancedUri] = useState("");
const [headerDrafts, setHeaderDrafts] = useState<ConnectionHeaderDraft[]>([]);
const nextHeaderId = useRef(1);
const [inputResetKey, bumpInputResetKey] = useReducer((key: number) => key + 1, 0);
const clearInput = useCallback(() => {
@@ -435,8 +315,6 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
setIsPasswordVisible(false);
setIsAdvancedOpen(false);
setAdvancedUri("");
setHeaderDrafts([]);
nextHeaderId.current = 1;
bumpInputResetKey();
}, []);
@@ -491,18 +369,11 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
if (isSaving) return;
let connection: PreparedDirectConnection;
let headers: Record<string, string> | undefined;
try {
connection = prepareDirectConnection(
{ host, port, useTls, password },
directConnectionLabels,
);
const preparedHeaders = prepareConnectionHeaders(headerDrafts);
if (preparedHeaders.issue) {
setErrorMessage(headerIssueMessage(preparedHeaders.issue, t));
return;
}
headers = preparedHeaders.headers;
} catch (error) {
const message =
error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
@@ -518,7 +389,6 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
endpoint: connection.endpoint,
useTls: connection.useTls,
...(connection.password ? { password: connection.password } : {}),
...(headers ? { headers } : {}),
});
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
@@ -555,7 +425,6 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
daemons,
directConnectionLabels,
handleClose,
headerDrafts,
host,
isMobile,
isSaving,
@@ -584,22 +453,6 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
setIsPasswordVisible((current) => !current);
}, []);
const handleAddHeader = useCallback(() => {
const id = nextHeaderId.current;
nextHeaderId.current += 1;
setHeaderDrafts((current) => [...current, { id, name: "", value: "" }]);
}, []);
const handleUpdateHeader = useCallback((id: number, field: "name" | "value", value: string) => {
setHeaderDrafts((current) =>
current.map((draft) => (draft.id === id ? { ...draft, [field]: value } : draft)),
);
}, []);
const handleRemoveHeader = useCallback((id: number) => {
setHeaderDrafts((current) => current.filter((draft) => draft.id !== id));
}, []);
const handleToggleAdvanced = useCallback(() => {
if (!isAdvancedOpen) {
try {
@@ -756,58 +609,24 @@ export function AddHostModal({ visible, onClose, onCancel, onSaved }: AddHostMod
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
</Pressable>
{isAdvancedOpen ? (
<View style={styles.advancedContent}>
<AdaptiveTextInput
testID="direct-host-uri-input"
nativeID="direct-host-uri-input"
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
initialValue={advancedUri}
resetKey={`direct-host-uri-${inputResetKey}`}
value={advancedUri}
onChangeText={setAdvancedUri}
placeholder="tcp://localhost:6767?ssl=true"
placeholderTextColor={theme.colors.foregroundMuted}
style={styles.input}
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
editable={!isSaving}
returnKeyType="done"
onSubmitEditing={handleToggleAdvanced}
/>
{isNative || getIsElectron() ? (
<View style={styles.headerSection}>
<View style={styles.headerTitleRow}>
<Text style={styles.label}>{t("pairing.direct.headers.title")}</Text>
<Button
variant="ghost"
size="sm"
leftIcon={Plus}
onPress={handleAddHeader}
disabled={isSaving}
testID="direct-header-add"
>
{t("pairing.direct.headers.add")}
</Button>
</View>
<View style={styles.headerList}>
{headerDrafts.map((draft, index) => (
<ConnectionHeaderRow
key={draft.id}
draft={draft}
index={index}
disabled={isSaving}
placeholderTextColor={theme.colors.foregroundMuted}
iconColor={theme.colors.foregroundMuted}
onUpdate={handleUpdateHeader}
onRemove={handleRemoveHeader}
/>
))}
</View>
</View>
) : null}
</View>
<AdaptiveTextInput
testID="direct-host-uri-input"
nativeID="direct-host-uri-input"
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
initialValue={advancedUri}
resetKey={`direct-host-uri-${inputResetKey}`}
value={advancedUri}
onChangeText={setAdvancedUri}
placeholder="tcp://localhost:6767?ssl=true"
placeholderTextColor={theme.colors.foregroundMuted}
style={styles.input}
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
editable={!isSaving}
returnKeyType="done"
onSubmitEditing={handleToggleAdvanced}
/>
) : null}
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
</View>
@@ -7,6 +7,7 @@ import {
} from "@getpaseo/protocol/agent-lifecycle";
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
import { getStatusDotColor } from "@/utils/status-dot-color";
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
export function AgentStatusDot({
status,
@@ -56,8 +57,8 @@ function isAgentLifecycleStatus(value: string): value is AgentLifecycleStatus {
const styles = StyleSheet.create((theme) => ({
dot: {
width: 8,
height: 8,
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
borderRadius: theme.borderRadius.full,
},
}));
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
View,
Text,
@@ -8,6 +8,7 @@ import {
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { useAnimatedStyle, useSharedValue, runOnJS } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { Gesture } from "react-native-gesture-handler";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { X } from "lucide-react-native";
@@ -36,6 +37,10 @@ import { RetainedPanelActivity } from "@/components/retained-panel";
import { SidebarResizeHandle } from "@/components/sidebar-resize-handle";
import { buildWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
import { resolveDesktopExplorerWidth } from "@/components/desktop-sidebar-layout";
import {
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
SIDEBAR_RESIZE_FAIL_OFFSET,
} from "@/components/sidebar-resize-handle-layout";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { resolveFocusedChatTarget } from "@/composer/focused-chat-target";
@@ -167,6 +172,9 @@ export function ExplorerSidebar({
});
const startWidthRef = useRef(visibleExplorerWidth);
const resizeWidth = useSharedValue(visibleExplorerWidth);
const [resizePressed, setResizePressed] = useState(false);
const showResizeGrip = useCallback(() => setResizePressed(true), []);
const hideResizeGrip = useCallback(() => setResizePressed(false), []);
useEffect(() => {
resizeWidth.value = visibleExplorerWidth;
@@ -185,8 +193,15 @@ export function ExplorerSidebar({
Gesture.Pan()
.enabled(true)
.hitSlop({ left: 8, right: 8, top: 0, bottom: 0 })
.onStart(() => {
startWidthRef.current = visibleExplorerWidth;
.onBegin(() => {
scheduleOnRN(showResizeGrip);
})
// See the left sidebar's gesture: horizontal intent only, with the start
// width anchored to the activation translation so the threshold is free.
.activeOffsetX([-SIDEBAR_RESIZE_ACTIVATION_OFFSET, SIDEBAR_RESIZE_ACTIVATION_OFFSET])
.failOffsetY([-SIDEBAR_RESIZE_FAIL_OFFSET, SIDEBAR_RESIZE_FAIL_OFFSET])
.onStart((event) => {
startWidthRef.current = visibleExplorerWidth + event.translationX;
resizeWidth.value = visibleExplorerWidth;
})
.onUpdate((event) => {
@@ -198,8 +213,18 @@ export function ExplorerSidebar({
})
.onEnd(() => {
runOnJS(setExplorerWidth)(resizeWidth.value);
})
.onFinalize(() => {
scheduleOnRN(hideResizeGrip);
}),
[resizeWidth, setExplorerWidth, viewportWidth, visibleExplorerWidth],
[
hideResizeGrip,
resizeWidth,
setExplorerWidth,
showResizeGrip,
viewportWidth,
visibleExplorerWidth,
],
);
const resizeAnimatedStyle = useAnimatedStyle(() => ({
@@ -220,6 +245,7 @@ export function ExplorerSidebar({
<SidebarResizeHandle
edge="left"
gesture={resizeGesture}
pressed={resizePressed}
testID="explorer-sidebar-resize-handle"
/>
@@ -6,33 +6,16 @@ import { getIsElectronRuntime } from "@/constants/layout";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Shortcut } from "@/components/ui/shortcut";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { formatShortcut } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import { buildKeyboardShortcutHelpSections } from "@/keyboard/keyboard-shortcuts";
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%"];
function shortcutSearchAliases(keys: string[], shortcutOs: "mac" | "non-mac"): string {
const aliases = keys.map((key) => {
if (shortcutOs === "mac") {
if (key === "mod" || key === "meta") return ["cmd", "command"];
if (key === "alt") return ["alt", "option"];
} else {
if (key === "mod" || key === "ctrl") return ["ctrl", "control"];
if (key === "meta") return ["win", "windows"];
}
return [key];
});
const combinations = aliases.reduce<string[][]>(
(prefixes, choices) =>
prefixes.flatMap((prefix) => choices.map((choice) => [...prefix, choice])),
[[]],
);
return combinations
.flatMap((combination) => [combination.join(" "), combination.join("+")])
.join(" ");
}
export function KeyboardShortcutsDialog() {
const { t } = useTranslation();
const open = useKeyboardShortcutsStore((s) => s.shortcutsDialogOpen);
@@ -42,37 +25,18 @@ export function KeyboardShortcutsDialog() {
const shortcutOs = getShortcutOs();
const isMac = shortcutOs === "mac";
const isDesktopApp = getIsElectronRuntime();
const { overrides } = useKeyboardShortcutOverrides();
// Effective bindings, so a shortcut the user unassigned lists no keys here
// instead of advertising a default that no longer fires.
const bindings = useMemo(() => buildEffectiveBindings(overrides), [overrides]);
const sections = useMemo(
() => buildKeyboardShortcutHelpSections({ isMac, isDesktop: isDesktopApp }),
[isDesktopApp, isMac],
() => buildKeyboardShortcutHelpSections({ isMac, isDesktop: isDesktopApp }, bindings),
[bindings, isDesktopApp, isMac],
);
const visibleSections = useMemo(
() => filterShortcutHelpSections({ sections, query, translate: t, shortcutOs }),
[query, sections, shortcutOs, t],
);
const visibleSections = useMemo(() => {
const normalizedQuery = query.trim().toLocaleLowerCase();
if (!normalizedQuery) return sections;
return sections.flatMap((section) => {
const sectionTitle = t(section.titleKey);
if (sectionTitle.toLocaleLowerCase().includes(normalizedQuery)) {
return [section];
}
const rows = section.rows.filter((row) => {
const searchText = [
t(row.labelKey),
row.noteKey ? t(row.noteKey) : row.note,
row.keys.join(" "),
formatShortcut(row.keys, shortcutOs),
shortcutSearchAliases(row.keys, shortcutOs),
]
.filter(Boolean)
.join(" ")
.toLocaleLowerCase();
return searchText.includes(normalizedQuery);
});
return rows.length > 0 ? [{ ...section, rows }] : [];
});
}, [query, sections, shortcutOs, t]);
useEffect(() => {
if (!open) setQuery("");
@@ -106,14 +70,18 @@ export function KeyboardShortcutsDialog() {
<Text style={styles.sectionTitle}>{t(section.titleKey)}</Text>
<View style={styles.rows}>
{section.rows.map((row) => (
<View key={row.id} style={styles.row}>
<View key={row.id} style={styles.row} testID={`shortcut-help-row-${row.id}`}>
<View style={styles.rowText}>
<Text style={styles.rowLabel}>{t(row.labelKey)}</Text>
{row.note ? (
<Text style={styles.rowNote}>{row.noteKey ? t(row.noteKey) : row.note}</Text>
) : null}
</View>
<Shortcut keys={row.keys} style={styles.rowShortcut} />
{row.chord === null ? (
<Text style={styles.rowUnassigned}>{t("settings.shortcuts.unassigned")}</Text>
) : (
<Shortcut chord={row.chord} style={styles.rowShortcut} />
)}
</View>
))}
</View>
@@ -171,6 +139,13 @@ const styles = StyleSheet.create((theme) => ({
rowShortcut: {
alignSelf: "flex-start",
},
// Matches the settings row's unassigned label, so the two screens describe the
// same state the same way.
rowUnassigned: {
alignSelf: "flex-start",
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
empty: {
paddingVertical: theme.spacing[6],
textAlign: "center",
+30 -3
View File
@@ -22,10 +22,15 @@ import {
} from "react-native";
import { Gesture } from "react-native-gesture-handler";
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { resolveDesktopSidebarWidth } from "@/components/desktop-sidebar-layout";
import {
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
SIDEBAR_RESIZE_FAIL_OFFSET,
} from "@/components/sidebar-resize-handle-layout";
import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
@@ -771,6 +776,9 @@ function DesktopSidebar({
const startWidthRef = useRef(visibleSidebarWidth);
const resizeWidth = useSharedValue(visibleSidebarWidth);
const [resizePressed, setResizePressed] = useState(false);
const showResizeGrip = useCallback(() => setResizePressed(true), []);
const hideResizeGrip = useCallback(() => setResizePressed(false), []);
useEffect(() => {
resizeWidth.value = visibleSidebarWidth;
@@ -780,8 +788,16 @@ function DesktopSidebar({
() =>
Gesture.Pan()
.hitSlop({ left: 8, right: 8, top: 0, bottom: 0 })
.onStart(() => {
startWidthRef.current = visibleSidebarWidth;
.onBegin(() => {
scheduleOnRN(showResizeGrip);
})
// Horizontal intent only, so a finger dragging down the touch grip scrolls
// the workspace list instead of resizing. Anchoring the start width to the
// activation translation keeps the extra threshold from jumping the edge.
.activeOffsetX([-SIDEBAR_RESIZE_ACTIVATION_OFFSET, SIDEBAR_RESIZE_ACTIVATION_OFFSET])
.failOffsetY([-SIDEBAR_RESIZE_FAIL_OFFSET, SIDEBAR_RESIZE_FAIL_OFFSET])
.onStart((event) => {
startWidthRef.current = visibleSidebarWidth - event.translationX;
resizeWidth.value = visibleSidebarWidth;
})
.onUpdate((event) => {
@@ -794,8 +810,18 @@ function DesktopSidebar({
})
.onEnd(() => {
runOnJS(setSidebarWidth)(resizeWidth.value);
})
.onFinalize(() => {
scheduleOnRN(hideResizeGrip);
}),
[resizeWidth, setSidebarWidth, viewportWidth, visibleSidebarWidth],
[
hideResizeGrip,
resizeWidth,
setSidebarWidth,
showResizeGrip,
viewportWidth,
visibleSidebarWidth,
],
);
const resizeAnimatedStyle = useAnimatedStyle(() => ({
@@ -894,6 +920,7 @@ function DesktopSidebar({
<SidebarResizeHandle
edge="right"
gesture={resizeGesture}
pressed={resizePressed}
testID="left-sidebar-resize-handle"
/>
</View>
@@ -22,7 +22,6 @@ import Markdown, {
type RenderRules,
} from "react-native-markdown-display";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import { MarkdownParagraphView, MarkdownTextSpan } from "@/components/markdown-text";
import { MarkdownTableCellText } from "@/components/markdown-text-selection";
@@ -110,11 +109,7 @@ export function MarkdownRenderer({
],
);
return (
<AppearanceStyleBoundary>
<MarkdownPartList parts={parts} rendererProps={rendererProps} />
</AppearanceStyleBoundary>
);
return <MarkdownPartList parts={parts} rendererProps={rendererProps} />;
}
type MarkdownPartRendererProps = Omit<MarkdownRendererProps, "text" | "enableHtmlish"> & {
+1 -1
View File
@@ -1806,7 +1806,7 @@ export const AssistantMessage = memo(function AssistantMessage({
return (
<View key={node.key} style={styles.list_item} dataSet={markdownCopyDataSet.li}>
<Text style={iconStyle} dataSet={markdownCopyDataSet.ignore}>
<Text style={iconStyle} dataSet={markdownCopyDataSet.listMarker}>
{marker}
</Text>
<MarkdownListItemContent contentStyle={contentStyle}>
@@ -0,0 +1,95 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { JSDOM } from "jsdom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RootErrorFallback } from "./root-error-boundary";
const { runtime, theme } = vi.hoisted(() => ({
runtime: { breakpoint: "xs" },
theme: {
spacing: { 2: 8, 3: 12, 4: 16, 6: 24, 8: 32 },
borderWidth: { 1: 1 },
borderRadius: { md: 6, lg: 8, xl: 12 },
fontFamily: { ui: "system-ui", mono: "monospace" },
fontSize: { xs: 11, code: 12, sm: 13, base: 15, xl: 20 },
fontWeight: { normal: "400", medium: "500", semibold: "600" },
colors: {
accent: "#369",
accentForeground: "#fff",
border: "#333",
borderAccent: "#444",
destructive: "#c33",
foreground: "#fff",
foregroundMuted: "#aaa",
surface0: "#111",
surface1: "#181818",
surface2: "#222",
surface3: "#333",
},
opacity: { 50: 0.5 },
},
}));
vi.mock("react-native-unistyles", () => ({
StyleSheet: {
create: (factory: unknown) => (typeof factory === "function" ? factory(theme) : factory),
},
useUnistyles: () => ({ theme, rt: runtime }),
withUnistyles: (component: unknown) => component,
}));
vi.mock("react-native-safe-area-context", () => ({
useSafeAreaInsets: () => ({ top: 47, right: 3, bottom: 34, left: 5 }),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
let root: Root | null = null;
beforeEach(() => {
const dom = new JSDOM("<!doctype html><html><body></body></html>");
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("window", dom.window);
vi.stubGlobal("document", dom.window.document);
vi.stubGlobal("HTMLElement", dom.window.HTMLElement);
vi.stubGlobal("Node", dom.window.Node);
vi.stubGlobal("navigator", dom.window.navigator);
const container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root?.unmount());
root = null;
vi.unstubAllGlobals();
});
describe("RootErrorFallback", () => {
for (const breakpoint of ["xs", "lg"]) {
it(`keeps the safe-area header and retry action outside the scrollable details on ${breakpoint}`, () => {
runtime.breakpoint = breakpoint;
act(() => {
root?.render(<RootErrorFallback error={"failure\n".repeat(200)} onRetry={vi.fn()} />);
});
const screen = document.querySelector('[data-testid="root-error-boundary"]');
const header = document.querySelector('[data-testid="root-error-boundary-header"]');
const details = document.querySelector('[data-testid="root-error-boundary-details"]');
const retry = document.querySelector('[data-testid="root-error-boundary-retry"]');
expect(screen).not.toBeNull();
expect(header).not.toBeNull();
expect(details).not.toBeNull();
expect(retry).not.toBeNull();
expect(screen?.getAttribute("style")).toContain("padding: 47px 3px 34px 5px");
expect(details?.contains(header)).toBe(false);
expect(details?.contains(retry)).toBe(false);
expect(screen?.contains(retry)).toBe(true);
});
}
});
@@ -1,8 +1,11 @@
import React, { Component, Fragment, type ErrorInfo, type ReactNode } from "react";
import { Pressable, ScrollView, Text, View } from "react-native";
import type { PressableStateCallbackType, StyleProp, ViewStyle } from "react-native";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { ScrollableCodeSurface } from "@/components/ui/scrollable-code-surface";
import { useIsCompactFormFactor } from "@/constants/layout";
import { formatCaughtValue } from "./root-error-details";
interface RootErrorBoundaryProps {
@@ -48,110 +51,113 @@ export class RootErrorBoundary extends Component<RootErrorBoundaryProps, RootErr
}
}
// A stack trace is reference material, not the screen. Cap it so the message and
// the retry action stay the shape of the page; the rest scrolls.
const DETAILS_MAX_HEIGHT = 300;
interface RootErrorFallbackProps {
error: string;
onRetry: () => void;
}
function RootErrorFallback({ error, onRetry }: RootErrorFallbackProps) {
export function RootErrorFallback({ error, onRetry }: RootErrorFallbackProps) {
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const isCompact = useIsCompactFormFactor();
const retry = (
<Button variant="default" onPress={onRetry} testID="root-error-boundary-retry">
{t("common.actions.retry")}
</Button>
);
return (
<ScrollView
style={styles.container}
contentContainerStyle={styles.contentContainer}
<View
style={[
styles.container,
{
paddingTop: insets.top,
paddingRight: insets.right,
paddingBottom: insets.bottom,
paddingLeft: insets.left,
},
]}
testID="root-error-boundary"
>
<View style={styles.content}>
<Text style={styles.kicker}>{t("rootError.kicker")}</Text>
<Text style={styles.title}>{t("rootError.title")}</Text>
<Text style={styles.body}>{t("rootError.body")}</Text>
<View style={styles.messageBox}>
<Text style={styles.messageLabel}>{t("rootError.details")}</Text>
<Text style={styles.message}>{error}</Text>
<View style={styles.header} testID="root-error-boundary-header">
<Text style={styles.title}>{t("rootError.title")}</Text>
<Text style={styles.body}>{t("rootError.body")}</Text>
</View>
<Pressable
accessibilityRole="button"
onPress={onRetry}
style={retryButtonStyle}
testID="root-error-boundary-retry"
>
<Text style={styles.retryButtonText}>{t("common.actions.retry")}</Text>
</Pressable>
<View style={styles.details}>
<Text style={styles.detailsLabel}>{t("rootError.details")}</Text>
<ScrollableCodeSurface
maxHeight={isCompact ? undefined : DETAILS_MAX_HEIGHT}
style={styles.detailsSurface}
scrollStyle={styles.detailsScroll}
testID="root-error-boundary-details"
>
{error}
</ScrollableCodeSurface>
</View>
{isCompact ? null : retry}
</View>
</ScrollView>
{isCompact ? <View style={styles.footer}>{retry}</View> : null}
</View>
);
}
function retryButtonStyle({ pressed }: PressableStateCallbackType): StyleProp<ViewStyle> {
return [styles.retryButton, pressed ? styles.retryButtonPressed : null];
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
backgroundColor: theme.colors.surface0,
},
contentContainer: {
flexGrow: 1,
content: {
flex: 1,
alignSelf: "center",
width: "100%",
maxWidth: 420,
justifyContent: "center",
gap: theme.spacing[6],
paddingHorizontal: theme.spacing[6],
paddingVertical: theme.spacing[8],
},
content: {
alignSelf: "center",
width: "100%",
maxWidth: 520,
gap: theme.spacing[4],
},
kicker: {
color: theme.colors.destructive,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.semibold,
header: {
alignItems: "center",
gap: theme.spacing[2],
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.xl,
fontWeight: theme.fontWeight.semibold,
fontWeight: theme.fontWeight.medium,
textAlign: "center",
},
body: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
lineHeight: 22,
},
messageBox: {
gap: theme.spacing[2],
borderWidth: 1,
borderColor: theme.colors.borderAccent,
borderRadius: theme.borderRadius.lg,
backgroundColor: theme.colors.surface1,
padding: theme.spacing[4],
},
messageLabel: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.xs,
fontWeight: theme.fontWeight.semibold,
},
message: {
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
lineHeight: 20,
textAlign: "center",
},
retryButton: {
alignSelf: "flex-start",
minHeight: 40,
justifyContent: "center",
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.accent,
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[2],
details: {
flexShrink: 1,
gap: theme.spacing[2],
},
retryButtonPressed: {
opacity: 0.85,
detailsLabel: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.xs,
fontWeight: theme.fontWeight.medium,
},
retryButtonText: {
color: theme.colors.accentForeground,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.semibold,
detailsSurface: {
flexShrink: 1,
},
detailsScroll: {
flexShrink: 1,
},
footer: {
alignSelf: "center",
width: "100%",
maxWidth: 420,
paddingHorizontal: theme.spacing[6],
paddingBottom: theme.spacing[6],
},
}));
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { resolveSidebarResizeHandleGeometry } from "./sidebar-resize-handle-layout";
const MIN_TOUCH_TARGET = 24;
describe("resolveSidebarResizeHandleGeometry", () => {
it("keeps the touch hit area inside the sidebar so native hit-testing reaches it", () => {
const geometry = resolveSidebarResizeHandleGeometry(false);
expect(geometry.edgeOffset).toBeGreaterThanOrEqual(0);
expect(geometry.width).toBeGreaterThanOrEqual(MIN_TOUCH_TARGET);
expect(geometry.height ?? 0).toBeGreaterThanOrEqual(MIN_TOUCH_TARGET);
});
it("straddles the border for a fine pointer", () => {
const geometry = resolveSidebarResizeHandleGeometry(true);
expect(geometry.edgeOffset).toBe(-geometry.width / 2);
expect(geometry.height).toBeNull();
});
});
@@ -0,0 +1,57 @@
/**
* Geometry for the sidebar resize handle.
*
* A mouse can grab a hairline, so the pointer variant straddles the sidebar
* border — half the strip hangs outside the sidebar's own bounds, which is
* fine because web hit-testing does not clip to the parent box.
*
* Native hit-testing does clip: iOS `hitTest:` returns nil for points outside a
* view's bounds and Gesture Handler's Android traversal only recurses into
* children whose ancestors contain the point. A strip hanging outside the
* sidebar is dead on touch, and what remains is far too small for a finger.
* So the touch variant sits fully inside the sidebar and is sized for a thumb.
*/
export const POINTER_HANDLE_WIDTH = 10;
export const TOUCH_HANDLE_WIDTH = 24;
export const TOUCH_HANDLE_HEIGHT = 88;
/**
* A finger resting on the grip drifts before it commits. Requiring horizontal
* intent before the pan activates, and failing it once the drift is mostly
* vertical, leaves the sidebar's own scrolling reachable through the grip.
* A mouse press moves less than either threshold, so pointer drags are
* unaffected.
*/
export const SIDEBAR_RESIZE_ACTIVATION_OFFSET = 6;
export const SIDEBAR_RESIZE_FAIL_OFFSET = 12;
export type SidebarResizeEdge = "left" | "right";
export interface SidebarResizeHandleGeometry {
/**
* Distance from the sidebar edge to the near side of the hit area. Negative
* means the hit area overhangs the sidebar, which only touch forbids.
*/
edgeOffset: number;
width: number;
/** `null` stretches the hit area to the sidebar's full height. */
height: number | null;
}
export function resolveSidebarResizeHandleGeometry(
finePointer: boolean,
): SidebarResizeHandleGeometry {
if (finePointer) {
return {
edgeOffset: -POINTER_HANDLE_WIDTH / 2,
width: POINTER_HANDLE_WIDTH,
height: null,
};
}
return {
edgeOffset: 0,
width: TOUCH_HANDLE_WIDTH,
height: TOUCH_HANDLE_HEIGHT,
};
}
@@ -2,11 +2,17 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { Pressable, View } from "react-native";
import { GestureDetector, type GestureType } from "react-native-gesture-handler";
import { StyleSheet } from "react-native-unistyles";
import {
resolveSidebarResizeHandleGeometry,
type SidebarResizeEdge,
} from "@/components/sidebar-resize-handle-layout";
import { isWeb } from "@/constants/platform";
import { useHasFinePointer } from "@/hooks/use-fine-pointer";
interface SidebarResizeHandleProps {
edge: "left" | "right";
edge: SidebarResizeEdge;
gesture: GestureType;
pressed: boolean;
testID: string;
}
@@ -18,13 +24,29 @@ const webResizeCursorStyle = isWeb
} as object)
: null;
export function SidebarResizeHandle({ edge, gesture, testID }: SidebarResizeHandleProps) {
function edgeOffsetStyle(edge: SidebarResizeEdge, edgeOffset: number) {
return edge === "left" ? { left: edgeOffset } : { right: edgeOffset };
}
export function SidebarResizeHandle({ edge, gesture, pressed, testID }: SidebarResizeHandleProps) {
const finePointer = useHasFinePointer();
if (finePointer) {
return <PointerResizeHandle edge={edge} gesture={gesture} pressed={pressed} testID={testID} />;
}
return <TouchResizeHandle edge={edge} gesture={gesture} pressed={pressed} testID={testID} />;
}
function PointerResizeHandle({ edge, gesture, testID }: SidebarResizeHandleProps) {
const [highlighted, setHighlighted] = useState(false);
const highlightTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hitAreaStyle =
edge === "left"
? [styles.hitArea, styles.leftEdge, webResizeCursorStyle]
: [styles.hitArea, styles.rightEdge, webResizeCursorStyle];
const geometry = resolveSidebarResizeHandleGeometry(true);
const hitAreaStyle = [
styles.hitArea,
{ width: geometry.width },
edgeOffsetStyle(edge, geometry.edgeOffset),
webResizeCursorStyle,
];
const cancelHighlightTimer = useCallback(() => {
if (highlightTimerRef.current === null) return;
@@ -63,20 +85,49 @@ export function SidebarResizeHandle({ edge, gesture, testID }: SidebarResizeHand
);
}
function TouchResizeHandle({ edge, gesture, pressed, testID }: SidebarResizeHandleProps) {
const geometry = resolveSidebarResizeHandleGeometry(false);
// `box-none` keeps the full-height column out of hit-testing so only the
// grab target steals taps from the rows behind it.
const layerStyle = [
styles.touchLayer,
{ width: geometry.width },
edgeOffsetStyle(edge, geometry.edgeOffset),
];
const targetStyle = [
styles.touchTarget,
{ width: geometry.width, height: geometry.height ?? undefined },
];
const gripStyle = [
styles.grip,
edge === "left" ? styles.leftEdgeGrip : styles.rightEdgeGrip,
pressed ? styles.visibleGrip : styles.hiddenGrip,
];
return (
<View pointerEvents="box-none" style={layerStyle}>
<GestureDetector gesture={gesture}>
<View
testID={testID}
role="separator"
aria-orientation="vertical"
collapsable={false}
style={targetStyle}
>
<View pointerEvents="none" testID={`${testID}-grip`} style={gripStyle} />
</View>
</GestureDetector>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
hitArea: {
position: "absolute",
top: 0,
bottom: 0,
width: 10,
zIndex: 10,
},
leftEdge: {
left: -5,
},
rightEdge: {
right: -5,
},
highlight: {
position: "absolute",
top: 0,
@@ -86,4 +137,36 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.foreground,
opacity: 0.25,
},
touchLayer: {
position: "absolute",
top: 0,
bottom: 0,
zIndex: 10,
alignItems: "center",
justifyContent: "center",
},
touchTarget: {
alignItems: "center",
justifyContent: "center",
},
grip: {
width: 4,
height: 36,
borderRadius: 2,
backgroundColor: theme.colors.foreground,
},
hiddenGrip: {
opacity: 0,
},
visibleGrip: {
opacity: 0.3,
},
leftEdgeGrip: {
alignSelf: "flex-start",
marginLeft: theme.spacing[0.5],
},
rightEdgeGrip: {
alignSelf: "flex-end",
marginRight: theme.spacing[0.5],
},
}));
@@ -376,18 +376,21 @@ function projectKebabStyle({
function getProjectWorkspaceRowStyle({
isDragging,
isPressed,
selected,
isHovered,
}: {
isDragging: boolean;
isPressed: boolean;
selected: boolean;
isHovered: boolean;
}) {
return [
styles.workspaceRow,
isDragging && styles.workspaceRowDragging,
selected && styles.sidebarRowSelected,
isHovered && styles.workspaceRowHovered,
isDragging && styles.workspaceRowDragging,
isPressed && styles.workspaceRowPressed,
];
}
@@ -871,6 +874,7 @@ function ProjectHeaderRow({
dragHandleProps,
}: ProjectHeaderRowProps) {
const [isHovered, setIsHovered] = useState(false);
const [isPressed, setIsPressed] = useState(false);
const [contextMenuOpen, setContextMenuOpen] = useState(false);
const isMobileBreakpoint = useIsCompactFormFactor();
const localDaemonServerId = useLocalDaemonServerId();
@@ -917,6 +921,17 @@ function ProjectHeaderRow({
setContextMenuOpen(open);
if (open) setIsHovered(false);
}, []);
const handleProjectPressIn = useCallback(
(event: GestureResponderEvent) => {
setIsPressed(true);
interaction.handlePressIn(event);
},
[interaction],
);
const handleProjectPressOut = useCallback(() => {
setIsPressed(false);
interaction.handlePressOut();
}, [interaction]);
const projectRowStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
@@ -937,7 +952,7 @@ function ProjectHeaderRow({
iconDataUri={iconDataUri}
statusBucket={statusBucket}
projectViewKey={project.viewKey}
backdrop={getSidebarRowBackdrop({ isDragging, selected, isHovered })}
backdrop={getSidebarRowBackdrop({ isDragging, isPressed, selected, isHovered })}
chevron={chevron}
showChevron={isHovered && chevron !== null}
isArchiving={isArchiving}
@@ -982,10 +997,10 @@ function ProjectHeaderRow({
<PressHighlight
accessibilityRole="button"
style={projectRowStyle}
highlightStyle={styles.projectRowHovered}
onPressIn={interaction.handlePressIn}
highlightStyle={styles.projectRowPressed}
onPressIn={handleProjectPressIn}
onTouchMove={interaction.handleTouchMove}
onPressOut={interaction.handlePressOut}
onPressOut={handleProjectPressOut}
onPress={handlePress}
testID={`sidebar-project-row-${project.viewKey}`}
>
@@ -1008,10 +1023,10 @@ function ProjectHeaderRow({
enabledOnMobile={false}
accessibilityRole="button"
style={projectRowStyle}
highlightStyle={styles.projectRowHovered}
onPressIn={interaction.handlePressIn}
highlightStyle={styles.projectRowPressed}
onPressIn={handleProjectPressIn}
onTouchMove={interaction.handleTouchMove}
onPressOut={interaction.handlePressOut}
onPressOut={handleProjectPressOut}
onPress={handlePress}
testID={`sidebar-project-row-${project.viewKey}`}
>
@@ -1064,6 +1079,7 @@ function WorkspaceRowInner({
reserveIdleStatusIndicatorSpace = true,
}: WorkspaceRowInnerProps) {
const _isCompact = useIsCompactFormFactor();
const [isPressed, setIsPressed] = useState(false);
const isTouchPlatform = platformIsNative;
const interaction = useLongPressDragInteraction({
drag,
@@ -1083,6 +1099,17 @@ function WorkspaceRowInner({
}
onPress();
}, [interaction.didLongPressRef, onPress]);
const handleWorkspacePressIn = useCallback(
(event: GestureResponderEvent) => {
setIsPressed(true);
interaction.handlePressIn(event);
},
[interaction],
);
const handleWorkspacePressOut = useCallback(() => {
setIsPressed(false);
interaction.handlePressOut();
}, [interaction]);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
@@ -1093,6 +1120,7 @@ function WorkspaceRowInner({
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const workspaceRowStyle = getProjectWorkspaceRowStyle({
isDragging,
isPressed,
selected,
isHovered,
});
@@ -1127,10 +1155,10 @@ function WorkspaceRowInner({
accessibilityRole="button"
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={styles.workspaceRowHovered}
onPressIn={interaction.handlePressIn}
highlightStyle={styles.workspaceRowPressed}
onPressIn={handleWorkspacePressIn}
onTouchMove={interaction.handleTouchMove}
onPressOut={interaction.handlePressOut}
onPressOut={handleWorkspacePressOut}
onPress={handlePress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
@@ -1140,7 +1168,7 @@ function WorkspaceRowInner({
leadingProjectName={leadingProjectName}
leadingProjectIconDataUri={leadingProjectIconDataUri}
serviceSummary={serviceSummary}
backdrop={getSidebarRowBackdrop({ isDragging, selected, isHovered })}
backdrop={getSidebarRowBackdrop({ isDragging, isPressed, selected, isHovered })}
isHovered={isHovered}
isLoading={isArchiving || isCreating}
isCreating={isCreating}
@@ -12,8 +12,13 @@ import {
} from "@/utils/project-status-badge-content";
import { projectIconPlaceholderLabelFromDisplayName } from "@/utils/project-display-name";
import { getStatusDotColor } from "@/utils/status-dot-color";
import { STATUS_INDICATOR_ALERT_SIZE } from "@/utils/status-indicator-geometry";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import {
STATUS_INDICATOR_ALERT_SIZE,
STATUS_INDICATOR_FILLED_DOT_SIZE,
} from "@/utils/status-indicator-geometry";
import { StatusRing } from "@/components/status-ring";
import { getStatusRingOffset } from "@/components/status-ring/geometry";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
// Every surfaced status shares one badge shell, so the badge never changes size or position
// between states. Only the thing inside it changes.
@@ -29,7 +34,6 @@ const STATUS_BADGE_OFFSET = -4;
//
// The filled alert occupies the full badge shell so needs-input remains more prominent than
// the passive status dots.
const STATUS_BADGE_DOT_SIZE = 6;
// Matches the workspace title's lineHeight (sidebar-workspace-row-content's
// workspaceBranchText) so the icon centers on the title rather than floating above it.
const LEADING_SLOT_HEIGHT = 20;
@@ -65,7 +69,7 @@ export function ProjectLeadingVisual({
statusBucket: SidebarStateBucket | null;
projectViewKey: string;
/** The row's current background, so the status badge can knock out of it. */
backdrop: SurfaceBackdrop;
backdrop: SidebarSurfaceBackdrop;
chevron?: "expand" | "collapse" | null;
showChevron?: boolean;
isArchiving?: boolean;
@@ -116,7 +120,7 @@ export function ProjectStatusIndicator({
projectViewKey: string;
statusBucket: SidebarStateBucket | null;
/** The row's current background, so the status badge can knock out of it. */
backdrop: SurfaceBackdrop;
backdrop: SidebarSurfaceBackdrop;
loading?: boolean;
testID?: string;
}) {
@@ -164,8 +168,23 @@ function ProjectStatusBadge({
}: {
content: ProjectStatusBadgeContent;
statusBucket: SidebarStateBucket;
backdrop: SurfaceBackdrop;
backdrop: SidebarSurfaceBackdrop;
}) {
// Running skips the shell. The ring is wider than the 12pt shell and carries its own knockout,
// so nesting it inside would clip it against the very thing that was meant to separate it from
// the icon. It anchors to the same corner instead, growing around the centre the dot had.
if (content.kind === "dot" && content.bucket === "running") {
return (
<View
role="status"
accessibilityLabel={STATUS_BUCKET_LABELS[statusBucket]}
style={styles.statusRingAnchor}
testID="project-status-badge"
>
<StatusRing backdrop={backdrop} />
</View>
);
}
return (
<View
role="status"
@@ -182,14 +201,14 @@ function ProjectStatusBadge({
);
}
function getStatusBadgeBackdropStyle(backdrop: SurfaceBackdrop): ViewStyle {
function getStatusBadgeBackdropStyle(backdrop: SidebarSurfaceBackdrop): ViewStyle {
switch (backdrop) {
case "surfaceSidebar":
return styles.statusBadgeOnSidebar;
case "surfaceSidebarHover":
return styles.statusBadgeOnSidebarHover;
case "surface2":
return styles.statusBadgeOnSurface2;
default:
return styles.statusBadgeOnSidebar;
}
}
@@ -240,8 +259,8 @@ const styles = StyleSheet.create((theme) => {
// so this badge can't drift from the status dots everywhere else.
const statusDot = (bucket: ProjectStatusBadgeDotBucket) =>
({
width: STATUS_BADGE_DOT_SIZE,
height: STATUS_BADGE_DOT_SIZE,
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: getStatusDotColor({ theme, bucket }) ?? undefined,
}) as const;
@@ -282,6 +301,12 @@ const styles = StyleSheet.create((theme) => {
justifyContent: "center",
overflow: "hidden",
},
// Same corner as the shell, re-centred for the wider ring.
statusRingAnchor: {
position: "absolute",
right: getStatusRingOffset(STATUS_BADGE_OFFSET, STATUS_BADGE_SIZE),
bottom: getStatusRingOffset(STATUS_BADGE_OFFSET, STATUS_BADGE_SIZE),
},
statusBadgeOnSidebar: { backgroundColor: theme.colors.surfaceSidebar },
statusBadgeOnSidebarHover: { backgroundColor: theme.colors.surfaceSidebarHover },
statusBadgeOnSurface2: { backgroundColor: theme.colors.surface2 },
@@ -1,4 +1,4 @@
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
/**
* Which surface a sidebar row is currently painting, so anything knocking out of it — the status
@@ -9,19 +9,19 @@ import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
* here rather than three ternaries beside three stylesheets: drifting from them is how the badge
* ends up with a halo, and a halo in one grouping mode but not the other is worse than either.
*
* The pressed background is deliberately absent. It lives in a Pressable style callback and lasts
* as long as a finger is down, which is not long enough to see a mismatched ring.
*/
export function getSidebarRowBackdrop({
isDragging = false,
isPressed = false,
selected = false,
isHovered = false,
}: {
isDragging?: boolean;
isPressed?: boolean;
selected?: boolean;
isHovered?: boolean;
}): SurfaceBackdrop {
if (isDragging) return "surface2";
}): SidebarSurfaceBackdrop {
if (isDragging || isPressed) return "surface2";
if (selected || isHovered) return "surfaceSidebarHover";
return "surfaceSidebar";
}
@@ -687,12 +687,15 @@ function StatusWorkspaceRowInner({
inStatusGroup?: boolean;
}) {
const isTouchPlatform = platformIsNative;
const [isPressed, setIsPressed] = useState(false);
const trailing = useSidebarWorkspaceTrailing();
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const handlePressIn = useCallback(() => setIsPressed(true), []);
const handlePressOut = useCallback(() => setIsPressed(false), []);
return (
<SidebarWorkspaceRowFrame workspace={workspace}>
@@ -713,6 +716,7 @@ function StatusWorkspaceRowInner({
showShortcut,
});
const workspaceRowStyle = getStatusWorkspaceRowStyle({
isPressed,
selected,
isHovered,
inStatusGroup,
@@ -743,7 +747,9 @@ function StatusWorkspaceRowInner({
accessibilityRole="button"
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={styles.workspaceRowHovered}
highlightStyle={styles.workspaceRowPressed}
onPressIn={handlePressIn}
onPressOut={handlePressOut}
onPress={onPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
@@ -753,7 +759,7 @@ function StatusWorkspaceRowInner({
leadingProjectName={projectName}
leadingProjectIconDataUri={projectIconDataUri}
serviceSummary={serviceSummary}
backdrop={getSidebarRowBackdrop({ selected, isHovered })}
backdrop={getSidebarRowBackdrop({ isPressed, selected, isHovered })}
isHovered={isHovered}
isLoading={isArchiving}
shortcutNumber={shortcutNumber}
@@ -857,10 +863,12 @@ function StatusWorkspaceActionSlot({
}
function getStatusWorkspaceRowStyle({
isPressed,
selected,
isHovered,
inStatusGroup,
}: {
isPressed: boolean;
selected: boolean;
isHovered: boolean;
inStatusGroup: boolean;
@@ -870,6 +878,7 @@ function getStatusWorkspaceRowStyle({
inStatusGroup && sidebarWorkspaceRowStyles.rowIndented,
selected && styles.sidebarRowSelected,
isHovered && styles.workspaceRowHovered,
isPressed && styles.workspaceRowPressed,
];
}
@@ -4,7 +4,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import Svg, { Defs, LinearGradient as SvgLinearGradient, Rect, Stop } from "react-native-svg";
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
import {
WorkspaceMetaRow,
type WorkspaceServiceSummary,
@@ -19,12 +19,14 @@ import {
import { useAppSettings } from "@/hooks/use-settings";
import type { Theme } from "@/styles/theme";
import type { SidebarStateBucket } from "@/utils/sidebar-agent-state";
import { getStatusDotColor, isEmphasizedStatusDotBucket } from "@/utils/status-dot-color";
import { getStatusDotColor } from "@/utils/status-dot-color";
import {
STATUS_INDICATOR_ALERT_SIZE,
STATUS_INDICATOR_DOT_SIZE,
STATUS_INDICATOR_FILLED_DOT_SIZE,
} from "@/utils/status-indicator-geometry";
import { shouldRenderSyncedStatusLoader } from "@/utils/status-loader";
import { StatusRing } from "@/components/status-ring";
import { resolveSidebarWorkspacePrimaryLabel } from "@/components/sidebar/sidebar-workspace-title";
// The scrim spans more than the kebab so the fade starts left of the diff stat. Solid from
@@ -32,11 +34,6 @@ import { resolveSidebarWorkspacePrimaryLabel } from "@/components/sidebar/sideba
const SCRIM_WIDTH = 48;
const SCRIM_SOLID_OFFSET = "55%";
const DEFAULT_STATUS_DOT_SIZE = 7;
const EMPHASIZED_STATUS_DOT_SIZE = 9;
const DEFAULT_STATUS_DOT_OFFSET = 0;
const EMPHASIZED_STATUS_DOT_OFFSET = -1;
const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const needsInputColorMapping = (theme: Theme) => ({
color: theme.colors.surface0,
@@ -143,7 +140,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
leadingProjectIconDataUri?: string | null;
serviceSummary?: WorkspaceServiceSummary | null;
/** The row's current background, so the project status badge can knock out of it. */
backdrop: SurfaceBackdrop;
backdrop: SidebarSurfaceBackdrop;
isHovered: boolean;
isLoading: boolean;
isCreating?: boolean;
@@ -221,14 +218,14 @@ function WorkspaceStatusIndicator({
loading?: boolean;
reserveIdleSpace?: boolean;
}) {
// Busy is a dot here for the same reason it is on a project icon: every status in the
// sidebar is a dot, and a row with a project icon simply moves that dot onto the icon.
// A row starting up and a row working are both busy, so they share the dot and differ only
// in testID.
// Busy is the only status that moves, and it is the ring rather than a dot for the same
// reason it is a dot elsewhere: every status in the sidebar sits in this one slot, so busy
// has to fill it without displacing anything. A row starting up and a row working are both
// busy, so they share the ring and differ only in testID.
if (loading) {
return (
<View style={styles.workspaceStatusDot} testID="workspace-status-indicator-loading">
<View style={styles.standaloneRunningDot} />
<StatusRing />
</View>
);
}
@@ -236,7 +233,7 @@ function WorkspaceStatusIndicator({
if (shouldRenderSyncedStatusLoader({ bucket })) {
return (
<View style={styles.workspaceStatusDot} testID="workspace-status-indicator-running">
<View style={styles.standaloneRunningDot} />
<StatusRing />
</View>
);
}
@@ -275,50 +272,16 @@ function WorkspaceStatusIndicator({
else KindIcon = ThemedFolder;
const dotColorStyle = getStatusDotColorStyle(bucket);
const statusDotSize = isEmphasizedStatusDotBucket(bucket)
? EMPHASIZED_STATUS_DOT_SIZE
: DEFAULT_STATUS_DOT_SIZE;
const statusDotOffset =
statusDotSize === EMPHASIZED_STATUS_DOT_SIZE
? EMPHASIZED_STATUS_DOT_OFFSET
: DEFAULT_STATUS_DOT_OFFSET;
return (
<View style={styles.workspaceStatusDot} testID={`workspace-status-indicator-${bucket}`}>
<KindIcon size={14} uniProps={foregroundMutedColorMapping} />
{dotColorStyle ? (
<StatusDotOverlay
dotColorStyle={dotColorStyle}
size={statusDotSize}
offset={statusDotOffset}
/>
) : null}
{dotColorStyle ? <StatusDotOverlay dotColorStyle={dotColorStyle} /> : null}
</View>
);
}
function StatusDotOverlay({
dotColorStyle,
size,
offset,
}: {
dotColorStyle: ViewStyle;
size: number;
offset: number;
}) {
const overlayStyle = useMemo(
() => [
styles.statusDotOverlay,
dotColorStyle,
{
width: size,
height: size,
right: offset,
bottom: offset,
},
],
[dotColorStyle, offset, size],
);
return <View style={overlayStyle} />;
function StatusDotOverlay({ dotColorStyle }: { dotColorStyle: ViewStyle }) {
return <View style={[styles.statusDotOverlay, dotColorStyle]} />;
}
function getStatusDotColorStyle(bucket: SidebarStateBucket) {
@@ -569,24 +532,22 @@ const styles = StyleSheet.create((theme) => ({
},
statusDotOverlay: {
position: "absolute",
right: 0,
bottom: 0,
width: STATUS_INDICATOR_DOT_SIZE,
height: STATUS_INDICATOR_DOT_SIZE,
borderRadius: theme.borderRadius.full,
borderWidth: 1,
},
standaloneStatusDot: {
width: STATUS_INDICATOR_DOT_SIZE,
height: STATUS_INDICATOR_DOT_SIZE,
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: getStatusDotColor({ theme, bucket: "attention" }) ?? undefined,
},
standaloneRunningDot: {
width: STATUS_INDICATOR_DOT_SIZE,
height: STATUS_INDICATOR_DOT_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: getStatusDotColor({ theme, bucket: "running" }) ?? undefined,
},
idleStatusDot: {
width: 8,
height: 8,
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.foregroundExtraMuted,
opacity: 0.3,
@@ -1,6 +1,6 @@
import { memo, useCallback, useMemo, useState, type Ref } from "react";
import { useTranslation } from "react-i18next";
import { View, Text } from "react-native";
import { View, Text, type GestureResponderEvent } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useMutation } from "@tanstack/react-query";
import * as Clipboard from "expo-clipboard";
@@ -264,6 +264,7 @@ function WorkspaceRowBody({
archiveShortcutKeys,
}: WorkspaceRowBodyProps) {
const isTouchPlatform = platformIsNative;
const [isPressed, setIsPressed] = useState(false);
const trailing = useSidebarWorkspaceTrailing();
const draggable = Boolean(drag);
const interaction = useLongPressDragInteraction({
@@ -284,6 +285,17 @@ function WorkspaceRowBody({
}
onPress();
}, [interaction.didLongPressRef, onPress]);
const handleWorkspacePressIn = useCallback(
(event: GestureResponderEvent) => {
setIsPressed(true);
if (draggable) interaction.handlePressIn(event);
},
[draggable, interaction],
);
const handleWorkspacePressOut = useCallback(() => {
setIsPressed(false);
if (draggable) interaction.handlePressOut();
}, [draggable, interaction]);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
@@ -292,7 +304,12 @@ function WorkspaceRowBody({
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const workspaceRowStyle = getWorkspaceRowStyle({ isDragging, selected, isHovered });
const workspaceRowStyle = getWorkspaceRowStyle({
isDragging,
isPressed,
selected,
isHovered,
});
return (
<View
{...(draggable ? dragAttributes : {})}
@@ -325,10 +342,10 @@ function WorkspaceRowBody({
accessibilityRole="button"
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={styles.workspaceRowHovered}
onPressIn={draggable ? interaction.handlePressIn : undefined}
highlightStyle={styles.workspaceRowPressed}
onPressIn={handleWorkspacePressIn}
onTouchMove={draggable ? interaction.handleTouchMove : undefined}
onPressOut={draggable ? interaction.handlePressOut : undefined}
onPressOut={handleWorkspacePressOut}
onPress={handlePress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
@@ -336,7 +353,7 @@ function WorkspaceRowBody({
workspace={workspace}
hostBadge={hostBadge}
serviceSummary={serviceSummary}
backdrop={getSidebarRowBackdrop({ isDragging, selected, isHovered })}
backdrop={getSidebarRowBackdrop({ isDragging, isPressed, selected, isHovered })}
isHovered={isHovered}
isLoading={isArchiving || isCreating}
isCreating={isCreating}
@@ -458,18 +475,21 @@ function WorkspaceRowTrailingActions({
function getWorkspaceRowStyle({
isDragging,
isPressed,
selected,
isHovered,
}: {
isDragging: boolean;
isPressed: boolean;
selected: boolean;
isHovered: boolean;
}) {
return [
styles.workspaceRow,
isDragging && styles.workspaceRowDragging,
selected && styles.sidebarRowSelected,
isHovered && styles.workspaceRowHovered,
isDragging && styles.workspaceRowDragging,
isPressed && styles.workspaceRowPressed,
];
}
@@ -495,6 +515,9 @@ const styles = StyleSheet.create((theme) => ({
workspaceRowHovered: {
backgroundColor: theme.colors.surfaceSidebarHover,
},
workspaceRowPressed: {
backgroundColor: theme.colors.surface2,
},
workspaceRowDragging: {
backgroundColor: theme.colors.surface2,
borderWidth: 1,
@@ -710,7 +710,7 @@ function DragOverlayTabChipInner({
return (
<View style={chipStyle}>
<WorkspaceTabIcon presentation={presentation} active size={14} />
<WorkspaceTabIcon presentation={presentation} active size={14} backdrop="surface1" />
<Text numberOfLines={1} style={chipLabelStyle}>
{label}
</Text>
@@ -0,0 +1,58 @@
import { useLayoutEffect } from "react";
import { makeMutable, type SharedValue, useSharedValue } from "react-native-reanimated";
import { scheduleOnUI } from "react-native-worklets";
import { getStatusRingRotation } from "@/components/status-ring/geometry";
const sharedRotation = makeMutable(getStatusRingRotation(Date.now()));
const activeRingCount = makeMutable(0);
const clockRunning = makeMutable(false);
function advanceSharedRotation(): void {
"worklet";
if (activeRingCount.value === 0) {
clockRunning.value = false;
return;
}
sharedRotation.value = getStatusRingRotation(Date.now());
requestAnimationFrame(advanceSharedRotation);
}
function registerStatusRing(registered: SharedValue<boolean>): void {
"worklet";
if (registered.value) {
return;
}
registered.value = true;
activeRingCount.value += 1;
if (!clockRunning.value) {
clockRunning.value = true;
sharedRotation.value = getStatusRingRotation(Date.now());
requestAnimationFrame(advanceSharedRotation);
}
}
function unregisterStatusRing(registered: SharedValue<boolean>): void {
"worklet";
if (!registered.value) {
return;
}
registered.value = false;
activeRingCount.value -= 1;
}
export function useStatusRingRotation(): SharedValue<number> {
const registered = useSharedValue(false);
useLayoutEffect(() => {
scheduleOnUI(registerStatusRing, registered);
return () => {
scheduleOnUI(unregisterStatusRing, registered);
};
}, [registered]);
return sharedRotation;
}
@@ -0,0 +1,35 @@
import { useCallback, useLayoutEffect, useRef, type RefCallback } from "react";
import type { View as NativeView } from "react-native";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
const STATUS_RING_KEYFRAMES: PropertyIndexedKeyframes = {
transform: ["rotate(0deg)", "rotate(360deg)"],
};
const STATUS_RING_TIMING: KeyframeAnimationOptions = {
duration: STATUS_RING_PERIOD_MS,
easing: "linear",
iterations: Number.POSITIVE_INFINITY,
};
const STATUS_RING_TIMELINE_START_MS = 0;
export function useStatusRingAnimationRef(): RefCallback<NativeView> {
const arcElement = useRef<HTMLElement | null>(null);
const setArcElement = useCallback((instance: NativeView | null) => {
arcElement.current = instance instanceof HTMLElement ? instance : null;
}, []);
useLayoutEffect(() => {
const element = arcElement.current;
if (!element) {
return;
}
const animation = element.animate(STATUS_RING_KEYFRAMES, STATUS_RING_TIMING);
animation.startTime = STATUS_RING_TIMELINE_START_MS;
return () => {
animation.cancel();
};
}, []);
return setArcElement;
}
@@ -0,0 +1,121 @@
import type { ReactNode } from "react";
import { StyleSheet as RNStyleSheet, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import { getStatusDotColor } from "@/utils/status-dot-color";
import {
STATUS_RING_FRAME_SIZE,
STATUS_RING_HEAD_OPACITY,
STATUS_RING_SIZE,
STATUS_RING_STROKE,
STATUS_RING_TRACK_OPACITY,
} from "@/components/status-ring/geometry";
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
export interface StatusRingProps {
// The surface the ring is drawn on top of, named rather than resolved, because theme colours
// are only legible inside `StyleSheet.create` — see docs/unistyles.md. The frame fills itself
// with this so the ring reads as a hole punched in whatever it overlaps: the agent icon under a
// tab dot, the project tile under a sidebar badge. Leave it out where the ring sits on flat
// background and has nothing to knock out.
backdrop?: SurfaceBackdrop | null;
}
/**
* The static half of the running indicator: the knockout, the track, and the centre dot. The
* platform entry points supply the rotating quarter and own only how it is driven.
*
* The ring has no colour prop. It only ever means one thing — an agent is running — so it reads
* that one colour out of the theme itself. Passing the colour in would materialise it at the call
* site, outside anything Unistyles tracks, and leave the mark in the old theme until something
* incidental re-rendered the row.
*/
export function StatusRingFrame({ backdrop, children }: StatusRingProps & { children: ReactNode }) {
return (
<View style={[styles.frame, getBackdropStyle(backdrop)]}>
<View style={styles.track} />
{children}
<View style={styles.centerDot} />
</View>
);
}
function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
switch (backdrop) {
case "surface0":
return styles.backdropSurface0;
case "surface1":
return styles.backdropSurface1;
case "surfaceSidebar":
return styles.backdropSurfaceSidebar;
case "surfaceSidebarHover":
return styles.backdropSurfaceSidebarHover;
case "surface2":
return styles.backdropSurface2;
default:
return null;
}
}
// The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on
// native this style lands on a Reanimated `Animated.View`, and applying a theme-tracked style to
// one crashes when the theme changes — Unistyles and Reanimated both mutate the same native node.
// See docs/unistyles.md. The colour it needs lives on `styles.arc`, one level in, on a view
// Reanimated never touches.
export const rotatorStyles = RNStyleSheet.create({
rotator: {
position: "absolute",
width: STATUS_RING_SIZE,
height: STATUS_RING_SIZE,
},
});
export const styles = StyleSheet.create((theme) => {
const circle = {
width: STATUS_RING_SIZE,
height: STATUS_RING_SIZE,
borderRadius: theme.borderRadius.full,
borderWidth: STATUS_RING_STROKE,
} as const;
const runningColor = getStatusDotColor({ theme, bucket: "running" }) ?? undefined;
return {
frame: {
width: STATUS_RING_FRAME_SIZE,
height: STATUS_RING_FRAME_SIZE,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
backdropSurface0: { backgroundColor: theme.colors.surface0 },
backdropSurface1: { backgroundColor: theme.colors.surface1 },
backdropSurfaceSidebar: { backgroundColor: theme.colors.surfaceSidebar },
backdropSurfaceSidebarHover: { backgroundColor: theme.colors.surfaceSidebarHover },
backdropSurface2: { backgroundColor: theme.colors.surface2 },
// The closed ring the quarter runs on. Same colour rather than a grey so the indicator is one
// object at one hue; the opacity is what puts it behind the quarter instead of competing.
track: {
...circle,
position: "absolute",
borderColor: runningColor,
opacity: STATUS_RING_TRACK_OPACITY,
},
// The moving quarter. Three sides transparent leaves the top border alone, which on a fully
// rounded box is a 90° arc — the edge that makes the rotation legible against the track.
arc: {
...circle,
borderColor: "transparent",
borderTopColor: runningColor,
opacity: STATUS_RING_HEAD_OPACITY,
},
centerDot: {
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: runningColor,
},
};
});
@@ -0,0 +1,49 @@
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
// The running indicator is a status dot with a rotating ring around it, and the whole set of
// numbers below is a budget rather than four independent choices. The centre matches every other
// filled status circle; the gap and stroke grow outward from it without changing that shared size.
export const STATUS_RING_GAP = 1.5;
export const STATUS_RING_STROKE = 1.5;
// Derived outward from the dot, which means the dot is not a free variable: shrink it without
// opening the gap by the same amount and the ring closes in behind it, the whole mark scales
// down, and nothing about how the centre reads against the ring actually changes.
export const STATUS_RING_SIZE =
STATUS_INDICATOR_FILLED_DOT_SIZE + (STATUS_RING_GAP + STATUS_RING_STROKE) * 2;
// The knockout margin, and the reason the frame is wider than the ring. These indicators sit on
// the bottom-right corner of an agent or project icon, and a dot only stays readable there
// because it carries a ring of surface colour separating it from the art underneath. A ring drawn
// out to the frame's edge has no such separation and collides with the icon, so the frame is the
// knockout and the ring lives inside it.
export const STATUS_RING_HALO_INSET = 1;
export const STATUS_RING_FRAME_SIZE = STATUS_RING_SIZE + STATUS_RING_HALO_INSET * 2;
// The track and the quarter riding it are the same color and differ only here. The track is low
// enough that the quarter is unmistakably the thing moving, high enough that the ring still reads
// as a ring when the quarter is on the far side of it. The quarter is held off full so the centre
// dot stays the solid part of the mark — the ring is what the dot is doing, not a second dot.
export const STATUS_RING_TRACK_OPACITY = 0.3;
export const STATUS_RING_HEAD_OPACITY = 0.9;
// One period for every ring in the app. Each platform owns one mount-independent timeline: web
// animations share an absolute document-timeline start, while native publishes this wall-clock
// phase from one UI-thread clock. A row that appears mid-flight therefore lands in step with the
// rings already turning.
export const STATUS_RING_PERIOD_MS = 900;
export function getStatusRingRotation(nowMs: number): number {
"worklet";
return ((nowMs % STATUS_RING_PERIOD_MS) / STATUS_RING_PERIOD_MS) * 360;
}
/**
* Re-anchors a corner status dot's offset for the ring that replaces it.
*
* The dots this replaces are pinned to an icon's bottom-right corner rather than centred in a
* slot, so growing them in place would walk the indicator off the corner. Callers keep their
* existing dot offset and pass it through here to grow around the same centre point.
*/
export function getStatusRingOffset(dotOffset: number, dotSize: number): number {
return dotOffset - (STATUS_RING_FRAME_SIZE - dotSize) / 2;
}
@@ -0,0 +1,32 @@
import { memo } from "react";
import { View } from "react-native";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import {
StatusRingFrame,
type StatusRingProps,
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { useStatusRingRotation } from "@/components/status-ring/clock";
/**
* Native running indicator. The rotation is published by one shared UI-thread clock rather than
* per-instance timing, so a ring that mounts mid-flight is already in phase — see `clock.ts`.
*
* The rotated view carries no theme-tracked style; the coloured arc is nested inside it. Putting
* a Unistyles style on a Reanimated view crashes on theme change (docs/unistyles.md).
*/
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const rotation = useStatusRingRotation();
const rotatorStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${rotation.value}deg` }],
}));
return (
<StatusRingFrame backdrop={backdrop}>
<Animated.View style={[rotatorStyles.rotator, rotatorStyle]}>
<View style={styles.arc} />
</Animated.View>
</StatusRingFrame>
);
});
@@ -0,0 +1,26 @@
import { memo } from "react";
import { View } from "react-native";
import {
StatusRingFrame,
type StatusRingProps,
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { useStatusRingAnimationRef } from "@/components/status-ring/clock.web";
/**
* Web running indicator. A sidebar full of agents can hold dozens of these at once, so the browser
* drives the rotation from one absolute document-timeline epoch rather than from mount time — see
* `clock.web.ts`.
*/
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const rotatorRef = useStatusRingAnimationRef();
return (
<StatusRingFrame backdrop={backdrop}>
<View ref={rotatorRef} style={rotatorStyles.rotator}>
<View style={styles.arc} />
</View>
</StatusRingFrame>
);
});
@@ -10,7 +10,6 @@ import { ScrollView as GHScrollView } from "react-native-gesture-handler";
import { StyleSheet } from "react-native-unistyles";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary";
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
import { buildLineDiff, parseUnifiedDiff, type DiffLine } from "@/utils/tool-call-parsers";
import { highlightDiffLines } from "@/utils/diff-highlight";
@@ -741,15 +740,7 @@ function LoadingSkeleton({ containerStyle }: { containerStyle: StyleProp<ViewSty
);
}
export function ToolCallDetailsContent({ ...props }: ToolCallDetailsContentProps) {
return (
<AppearanceStyleBoundary>
<ToolCallDetailsContentInner {...props} />
</AppearanceStyleBoundary>
);
}
function ToolCallDetailsContentInner({
export function ToolCallDetailsContent({
detail,
errorText,
maxHeight,
+4 -3
View File
@@ -31,10 +31,11 @@ export function Alert({
}: AlertProps) {
const { theme } = useUnistyles();
const accentColor = resolveAccentColor(variant, theme);
const borderColor = variant === "success" ? theme.colors.border : accentColor;
const containerStyle = useMemo(
() => [styles.container, accentColor ? { borderColor: accentColor } : null],
[accentColor],
() => [styles.container, borderColor ? { borderColor } : null],
[borderColor],
);
const titleStyle = useMemo(
@@ -73,7 +74,7 @@ function resolveAccentColor(
theme: ReturnType<typeof useUnistyles>["theme"],
): string | null {
if (variant === "info") return theme.colors.palette.blue[300];
if (variant === "success") return theme.colors.palette.green[400];
if (variant === "success") return theme.colors.statusSuccess;
if (variant === "warning") return theme.colors.palette.amber[500];
if (variant === "error") return theme.colors.destructive;
return null;
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { normalizeDisplayChord } from "./normalize-display-chord";
describe("normalizeDisplayChord", () => {
it("returns null when neither keys nor chord is given", () => {
expect(normalizeDisplayChord()).toBeNull();
});
it("returns null for an empty keys array", () => {
// The trap: [] wraps to [[]], whose first element is truthy.
expect(normalizeDisplayChord(undefined, [])).toBeNull();
});
it("returns null for an empty chord", () => {
expect(normalizeDisplayChord([])).toBeNull();
});
it("returns null for a chord holding an empty combo", () => {
expect(normalizeDisplayChord([[]])).toBeNull();
expect(normalizeDisplayChord([["mod", "K"], []])).toBeNull();
});
it("wraps keys into a single-combo chord", () => {
expect(normalizeDisplayChord(undefined, ["mod", "K"])).toEqual([["mod", "K"]]);
});
it("passes a multi-step chord through unchanged", () => {
expect(normalizeDisplayChord([["mod", "K"], ["S"]])).toEqual([["mod", "K"], ["S"]]);
});
it("prefers chord over keys when both are given", () => {
expect(normalizeDisplayChord([["alt", "W"]], ["mod", "K"])).toEqual([["alt", "W"]]);
});
});
@@ -0,0 +1,28 @@
import type { ShortcutKey } from "@/utils/format-shortcut";
/**
* The combos a `Shortcut` should render, or `null` when it should render
* nothing at all.
*
* `keys={[]}` is the trap this exists to close: it wraps to `[[]]`, whose first
* element is an empty array — truthy — so a first-element check waves it
* through and an empty badge pill renders. A shortcut with no keys, whether the
* user unassigned it or it ships without a default combo, has to produce no
* element at all.
*/
export function normalizeDisplayChord(
chord?: ShortcutKey[][],
keys?: ShortcutKey[],
): ShortcutKey[][] | null {
const combos = chord ?? (keys ? [keys] : []);
if (combos.length === 0) {
return null;
}
// A chord with an empty step cannot be drawn honestly: rendering it would
// show a blank pill, and dropping the step would advertise a shorter
// sequence than the one that actually fires.
if (combos.some((combo) => combo.length === 0)) {
return null;
}
return combos;
}
@@ -9,7 +9,6 @@ import {
} from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary";
import { isWeb } from "@/constants/platform";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
@@ -56,7 +55,7 @@ export function SurfaceCard({
[bordered, style, surfaceStyle],
);
const surface = (
return (
<View
style={containerStyle}
dataSet={codeSurface ? CODE_SURFACE_DATASET : undefined}
@@ -67,7 +66,6 @@ export function SurfaceCard({
{children}
</View>
);
return <AppearanceStyleBoundary>{surface}</AppearanceStyleBoundary>;
}
export function ScrollableCodeSurface({
+7 -4
View File
@@ -2,6 +2,7 @@ import React, { useMemo, type ReactElement } from "react";
import { Text, View, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useKeyboardShortcutsAvailable } from "@/keyboard/availability";
import { normalizeDisplayChord } from "@/components/ui/normalize-display-chord";
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
@@ -17,9 +18,8 @@ export function Shortcut({
textStyle?: StyleProp<TextStyle>;
}): ReactElement | null {
const shortcutsAvailable = useKeyboardShortcutsAvailable();
const displayChord = chord ?? (keys ? [keys] : []);
const displayChord = normalizeDisplayChord(chord, keys);
const shortcutOs = getShortcutOs();
const singleCombo = displayChord[0];
const badgeStyle = useMemo(() => [styles.badge, style], [style]);
const textCombinedStyle = useMemo(() => [styles.text, textStyle], [textStyle]);
@@ -29,8 +29,11 @@ export function Shortcut({
return null;
}
if (!singleCombo) {
return <View style={style} />;
const singleCombo = displayChord?.[0];
// Render nothing, literally — an empty <View> would still consume the
// parent's `gap` and leave a phantom slot where the badge used to be.
if (!displayChord || !singleCombo) {
return null;
}
if (displayChord.length === 1) {
@@ -0,0 +1,150 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { RotateCw } from "lucide-react-native";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { DesktopPermissionRow } from "@/desktop/components/desktop-permission-row";
import { useDesktopPermissions } from "@/desktop/permissions/use-desktop-permissions";
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
import { SettingsSection } from "@/screens/settings/settings-section";
import { settingsStyles } from "@/styles/settings";
const ThemedRotateCw = withUnistyles(RotateCw, (theme) => ({
size: theme.iconSize.md,
color: theme.colors.foregroundMuted,
}));
export function DesktopNotificationsSection() {
const { t } = useTranslation();
const { settings, isSaving, updateSettings } = useDesktopSettings();
const {
isDesktopApp,
snapshot,
isRefreshing,
requestingPermission,
testNotificationState,
refreshPermissions,
requestPermission,
sendTestNotification,
} = useDesktopPermissions();
const handleRefreshPress = useCallback(() => {
void refreshPermissions();
}, [refreshPermissions]);
const handleRequestNotifications = useCallback(() => {
void requestPermission("notifications");
}, [requestPermission]);
const handlePlaySoundChange = useCallback(
(playSound: boolean) => {
void updateSettings({ notifications: { playSound } }).catch(() => {
// useDesktopSettings owns the user-visible IPC error.
});
},
[updateSettings],
);
const handleSendTestNotification = useCallback(() => {
void sendTestNotification();
}, [sendTestNotification]);
const isPermissionBusy = isRefreshing || requestingPermission !== null;
const isSendingTestNotification = testNotificationState.status === "sending";
const refreshIcon = useMemo(() => <ThemedRotateCw />, []);
const refreshButton = useMemo(
() => (
<Button
variant="ghost"
size="sm"
leftIcon={refreshIcon}
onPress={handleRefreshPress}
disabled={isPermissionBusy}
accessibilityLabel={t("settings.notifications.refreshAccessibility")}
>
{isRefreshing ? t("settings.permissions.refreshing") : t("settings.permissions.refresh")}
</Button>
),
[handleRefreshPress, isPermissionBusy, isRefreshing, refreshIcon, t],
);
const permissionLabels = useMemo(
() => ({
granted: t("settings.permissions.actions.granted"),
request: t("settings.permissions.actions.request"),
requesting: t("settings.permissions.actions.requesting"),
}),
[t],
);
if (!isDesktopApp) {
return null;
}
const notificationsGranted = snapshot?.notifications.state === "granted";
return (
<SettingsSection title={t("settings.notifications.title")} trailing={refreshButton}>
<View style={settingsStyles.card}>
<DesktopPermissionRow
title={t("settings.notifications.permission")}
status={snapshot?.notifications ?? null}
isRequesting={requestingPermission === "notifications"}
onRequest={handleRequestNotifications}
labels={permissionLabels}
/>
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.notifications.playSound")}</Text>
<Text style={settingsStyles.rowHint}>{t("settings.notifications.playSoundHint")}</Text>
</View>
<Switch
value={settings.notifications.playSound}
onValueChange={handlePlaySoundChange}
disabled={isSaving}
accessibilityLabel={t("settings.notifications.playSound")}
testID="desktop-notifications-play-sound-switch"
/>
</View>
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.notifications.test")}</Text>
<Text style={settingsStyles.rowHint}>
{notificationsGranted
? t("settings.notifications.testHint")
: t("settings.notifications.permissionRequired")}
</Text>
</View>
<Button
variant="outline"
size="sm"
onPress={handleSendTestNotification}
disabled={!notificationsGranted || isPermissionBusy || isSendingTestNotification}
>
{isSendingTestNotification
? t("settings.notifications.sending")
: t("settings.notifications.send")}
</Button>
</View>
</View>
{testNotificationState.status === "success" ? (
<Alert
variant="success"
title={t("settings.notifications.sentTitle")}
description={t("settings.notifications.sentDescription")}
testID="desktop-notifications-test-success"
/>
) : null}
{testNotificationState.status === "error" ? (
<Alert
variant="error"
title={t("settings.notifications.sendFailedTitle")}
description={testNotificationState.message}
testID="desktop-notifications-test-error"
/>
) : null}
</SettingsSection>
);
}
@@ -1,6 +1,6 @@
import { useMemo } from "react";
import { View, Text } from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Check } from "lucide-react-native";
import { Button } from "@/components/ui/button";
import { settingsStyles } from "@/styles/settings";
@@ -14,16 +14,16 @@ export interface DesktopPermissionRowProps {
granted: string;
request: string;
requesting: string;
busyExtraAction: (label: string) => string;
};
showBorder?: boolean;
onRequest: () => void;
extraActionLabel?: string;
isExtraActionBusy?: boolean;
isExtraActionDisabled?: boolean;
onExtraAction?: () => void;
}
const ThemedCheck = withUnistyles(Check, (theme) => ({
size: theme.iconSize.sm,
color: theme.colors.foregroundMuted,
}));
export function DesktopPermissionRow({
title,
status,
@@ -31,12 +31,7 @@ export function DesktopPermissionRow({
labels,
showBorder,
onRequest,
extraActionLabel,
isExtraActionBusy = false,
isExtraActionDisabled = false,
onExtraAction,
}: DesktopPermissionRowProps) {
const { theme } = useUnistyles();
const state = status?.state ?? "unknown";
const isGranted = state === "granted";
const shouldShowDetail =
@@ -58,21 +53,9 @@ export function DesktopPermissionRow({
</View>
<View style={styles.permissionRowActions}>
{isGranted ? (
<View style={styles.permissionGrantedActions}>
<View style={styles.permissionStatusPill}>
<Check size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
<Text style={styles.permissionStatusText}>{labels.granted}</Text>
</View>
{extraActionLabel && onExtraAction ? (
<Button
variant="outline"
size="sm"
onPress={onExtraAction}
disabled={isExtraActionDisabled || isExtraActionBusy}
>
{isExtraActionBusy ? labels.busyExtraAction(extraActionLabel) : extraActionLabel}
</Button>
) : null}
<View style={styles.permissionStatusPill}>
<ThemedCheck />
<Text style={styles.permissionStatusText}>{labels.granted}</Text>
</View>
) : (
<Button variant="outline" size="sm" onPress={onRequest} disabled={isRequesting}>
@@ -92,11 +75,6 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "flex-end",
gap: theme.spacing[1],
},
permissionGrantedActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
permissionStatusPill: {
flexDirection: "row",
alignItems: "center",
@@ -1,7 +1,7 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { View, Text } from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { RotateCw } from "lucide-react-native";
import { Button } from "@/components/ui/button";
import { DesktopPermissionRow } from "@/desktop/components/desktop-permission-row";
@@ -9,49 +9,33 @@ import { useDesktopPermissions } from "@/desktop/permissions/use-desktop-permiss
import { settingsStyles } from "@/styles/settings";
import { SettingsSection } from "@/screens/settings/settings-section";
const ThemedRotateCw = withUnistyles(RotateCw, (theme) => ({
size: theme.iconSize.md,
color: theme.colors.foregroundMuted,
}));
export function DesktopPermissionsSection() {
const { t } = useTranslation();
const { theme } = useUnistyles();
const {
isDesktopApp,
snapshot,
isRefreshing,
requestingPermission,
isSendingTestNotification,
testNotificationError,
refreshPermissions,
requestPermission,
sendTestNotification,
} = useDesktopPermissions();
const errorTextStyle = useMemo(
() => [styles.errorText, { color: theme.colors.destructive }],
[theme.colors.destructive],
);
const handleRefreshPress = useCallback(() => {
void refreshPermissions();
}, [refreshPermissions]);
const handleRequestNotifications = useCallback(() => {
void requestPermission("notifications");
}, [requestPermission]);
const handleRequestMicrophone = useCallback(() => {
void requestPermission("microphone");
}, [requestPermission]);
const handleSendTestNotification = useCallback(() => {
void sendTestNotification();
}, [sendTestNotification]);
const isBusy = isRefreshing || requestingPermission !== null;
const notificationsGranted = snapshot?.notifications.state === "granted";
const refreshIcon = useMemo(
() => <RotateCw size={theme.iconSize.md} color={theme.colors.foregroundMuted} />,
[theme.iconSize.md, theme.colors.foregroundMuted],
);
const refreshIcon = useMemo(() => <ThemedRotateCw />, []);
const refreshButton = useMemo(
() => (
@@ -74,7 +58,6 @@ export function DesktopPermissionsSection() {
granted: t("settings.permissions.actions.granted"),
request: t("settings.permissions.actions.request"),
requesting: t("settings.permissions.actions.requesting"),
busyExtraAction: (label: string) => t("settings.permissions.actions.busySuffix", { label }),
}),
[t],
);
@@ -86,21 +69,8 @@ export function DesktopPermissionsSection() {
return (
<SettingsSection title={t("settings.permissions.title")} trailing={refreshButton}>
<View style={settingsStyles.card}>
<DesktopPermissionRow
title={t("settings.permissions.notifications")}
status={snapshot?.notifications ?? null}
isRequesting={requestingPermission === "notifications"}
onRequest={handleRequestNotifications}
labels={permissionLabels}
extraActionLabel={t("settings.permissions.test")}
isExtraActionBusy={isSendingTestNotification}
isExtraActionDisabled={!notificationsGranted || isBusy}
onExtraAction={handleSendTestNotification}
/>
{testNotificationError ? <Text style={errorTextStyle}>{testNotificationError}</Text> : null}
<DesktopPermissionRow
title={t("settings.permissions.microphone")}
showBorder
status={snapshot?.microphone ?? null}
isRequesting={requestingPermission === "microphone"}
onRequest={handleRequestMicrophone}
@@ -110,11 +80,3 @@ export function DesktopPermissionsSection() {
</SettingsSection>
);
}
const styles = StyleSheet.create((theme) => ({
errorText: {
fontSize: theme.fontSize.xs,
paddingHorizontal: theme.spacing[4],
paddingBottom: theme.spacing[2],
},
}));
@@ -1,8 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import {
createDesktopLocalDaemonTransportFactory,
createDesktopWebSocketTransportFactory,
} from "./desktop-daemon-transport";
import { createDesktopLocalDaemonTransportFactory } from "./desktop-daemon-transport";
import { createFakeLocalDaemonTransportRpc } from "./test-local-daemon-transport-rpc";
const LOCAL_URL = "paseo+local://socket?path=%2Ftmp%2Fpaseo.sock";
@@ -46,25 +43,4 @@ describe("desktop-daemon-transport", () => {
expect(rpc.closedSessions).toEqual(["local-session-2"]);
expect(cleanup).toHaveBeenCalledTimes(1);
});
it("forwards remote WebSocket headers and protocols through the desktop bridge", () => {
const rpc = createFakeLocalDaemonTransportRpc();
const transportFactory = createDesktopWebSocketTransportFactory(rpc);
expect(transportFactory).not.toBeNull();
transportFactory!({
url: "wss://daemon.example/ws",
headers: { "X-Tenant": "acme", Authorization: "Bearer secret" },
protocols: ["paseo.bearer.secret"],
});
expect(rpc.openCalls).toEqual([
{
transportType: "websocket",
url: "wss://daemon.example/ws",
headers: { "X-Tenant": "acme", Authorization: "Bearer secret" },
protocols: ["paseo.bearer.secret"],
},
]);
});
});
@@ -2,13 +2,11 @@ import type {
DaemonTransport,
DaemonTransportFactory,
} from "@getpaseo/client/internal/daemon-client";
import type { DesktopDaemonTransportTarget, LocalTransportTarget } from "./desktop-daemon";
import type { LocalTransportTarget } from "./desktop-daemon";
import {
defaultLocalDaemonTransportRpc,
defaultWebSocketDaemonTransportRpc,
type LocalDaemonTransportRpc,
} from "./local-daemon-transport-rpc";
import { isElectronRuntime } from "@/desktop/host";
const LOCAL_TRANSPORT_SCHEME = "paseo+local:";
@@ -52,12 +50,11 @@ function parseLocalDaemonTransportUrl(url: string): LocalTransportTarget {
};
}
function createDesktopDaemonTransportFactory(
resolveTarget: (options: Parameters<DaemonTransportFactory>[0]) => DesktopDaemonTransportTarget,
rpc: LocalDaemonTransportRpc,
): DaemonTransportFactory {
return (options) => {
const target = resolveTarget(options);
export function createDesktopLocalDaemonTransportFactory(
rpc: LocalDaemonTransportRpc = defaultLocalDaemonTransportRpc,
): DaemonTransportFactory | null {
return ({ url }) => {
const target = parseLocalDaemonTransportUrl(url);
let sessionId: string | null = null;
let unlisten: (() => void) | null = null;
let disposed = false;
@@ -190,26 +187,3 @@ function createDesktopDaemonTransportFactory(
return transport;
};
}
export function createDesktopLocalDaemonTransportFactory(
rpc: LocalDaemonTransportRpc = defaultLocalDaemonTransportRpc,
): DaemonTransportFactory | null {
return createDesktopDaemonTransportFactory(({ url }) => parseLocalDaemonTransportUrl(url), rpc);
}
export function createDesktopWebSocketTransportFactory(
rpc?: LocalDaemonTransportRpc,
): DaemonTransportFactory | null {
if (!rpc && !isElectronRuntime()) {
return null;
}
return createDesktopDaemonTransportFactory(
({ url, headers, protocols }) => ({
transportType: "websocket" as const,
url,
...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
...(protocols && protocols.length > 0 ? { protocols } : {}),
}),
rpc ?? defaultWebSocketDaemonTransportRpc,
);
}
@@ -46,16 +46,6 @@ export interface LocalTransportTarget {
transportPath: string;
}
export interface WebSocketTransportTarget {
[key: string]: unknown;
transportType: "websocket";
url: string;
headers?: Record<string, string>;
protocols?: string[];
}
export type DesktopDaemonTransportTarget = LocalTransportTarget | WebSocketTransportTarget;
interface LocalTransportEventPayload {
sessionId: string;
kind: "open" | "message" | "close" | "error";
@@ -203,16 +193,6 @@ export async function openLocalTransportSession(target: LocalTransportTarget): P
return raw;
}
export async function openWebSocketTransportSession(
target: WebSocketTransportTarget,
): Promise<string> {
const raw = await invokeDesktopCommand<unknown>("open_websocket_daemon_transport", target);
if (typeof raw !== "string" || raw.trim().length === 0) {
throw new Error("Unexpected WebSocket transport session response.");
}
return raw;
}
export async function sendLocalTransportMessage(input: {
sessionId: string;
text?: string;
@@ -2,10 +2,8 @@ import {
closeLocalTransportSession,
listenToLocalTransportEvents,
openLocalTransportSession,
openWebSocketTransportSession,
sendLocalTransportMessage,
type DesktopDaemonTransportTarget,
type WebSocketTransportTarget,
type LocalTransportTarget,
} from "./desktop-daemon";
export interface LocalDaemonTransportEvent {
@@ -19,7 +17,7 @@ export interface LocalDaemonTransportEvent {
}
export interface LocalDaemonTransportRpc {
openSession(target: DesktopDaemonTransportTarget): Promise<string>;
openSession(target: LocalTransportTarget): Promise<string>;
listenToEvents(handler: (event: LocalDaemonTransportEvent) => void): Promise<() => void>;
sendMessage(input: { sessionId: string; text?: string; binaryBase64?: string }): Promise<void>;
closeSession(sessionId: string): Promise<void>;
@@ -31,10 +29,3 @@ export const defaultLocalDaemonTransportRpc: LocalDaemonTransportRpc = {
sendMessage: sendLocalTransportMessage,
closeSession: closeLocalTransportSession,
};
export const defaultWebSocketDaemonTransportRpc: LocalDaemonTransportRpc = {
openSession: (target) => openWebSocketTransportSession(target as WebSocketTransportTarget),
listenToEvents: listenToLocalTransportEvents,
sendMessage: sendLocalTransportMessage,
closeSession: closeLocalTransportSession,
};
@@ -1,4 +1,4 @@
import type { DesktopDaemonTransportTarget } from "./desktop-daemon";
import type { LocalTransportTarget } from "./desktop-daemon";
import type {
LocalDaemonTransportEvent,
LocalDaemonTransportRpc,
@@ -11,7 +11,7 @@ export interface RecordedSend {
}
export interface FakeLocalDaemonTransportRpc extends LocalDaemonTransportRpc {
readonly openCalls: DesktopDaemonTransportTarget[];
readonly openCalls: LocalTransportTarget[];
readonly recordedSends: RecordedSend[];
readonly closedSessions: string[];
resolveOpen(sessionId: string): void;
@@ -22,7 +22,7 @@ export interface FakeLocalDaemonTransportRpc extends LocalDaemonTransportRpc {
}
export function createFakeLocalDaemonTransportRpc(): FakeLocalDaemonTransportRpc {
const openCalls: DesktopDaemonTransportTarget[] = [];
const openCalls: LocalTransportTarget[] = [];
const recordedSends: RecordedSend[] = [];
const closedSessions: string[] = [];
let eventHandler: ((event: LocalDaemonTransportEvent) => void) | null = null;
@@ -14,13 +14,18 @@ export interface UseDesktopPermissionsReturn {
snapshot: DesktopPermissionSnapshot | null;
isRefreshing: boolean;
requestingPermission: DesktopPermissionKind | null;
isSendingTestNotification: boolean;
testNotificationError: string | null;
testNotificationState: TestNotificationState;
refreshPermissions: () => Promise<void>;
requestPermission: (kind: DesktopPermissionKind) => Promise<void>;
sendTestNotification: () => Promise<void>;
}
export type TestNotificationState =
| { status: "idle" }
| { status: "sending" }
| { status: "success" }
| { status: "error"; message: string };
export function useDesktopPermissions(): UseDesktopPermissionsReturn {
const { t } = useTranslation();
const isDesktopApp = shouldShowDesktopPermissionSection();
@@ -30,7 +35,9 @@ export function useDesktopPermissions(): UseDesktopPermissionsReturn {
const [requestingPermission, setRequestingPermission] = useState<DesktopPermissionKind | null>(
null,
);
const [isSendingTestNotification, setIsSendingTestNotification] = useState(false);
const [testNotificationState, setTestNotificationState] = useState<TestNotificationState>({
status: "idle",
});
useEffect(() => {
return () => {
@@ -111,28 +118,34 @@ export function useDesktopPermissions(): UseDesktopPermissionsReturn {
[isDesktopApp, refreshPermissions, t],
);
const [testNotificationError, setTestNotificationError] = useState<string | null>(null);
const sendTestNotification = useCallback(async () => {
if (!isDesktopApp) {
return;
}
setIsSendingTestNotification(true);
setTestNotificationError(null);
setTestNotificationState({ status: "sending" });
try {
const sent = await sendOsNotification({
title: t("desktop.permissions.testNotification.title"),
body: t("desktop.permissions.testNotification.body"),
});
if (!sent) {
setTestNotificationError(t("desktop.permissions.testNotification.notDelivered"));
if (!isMountedRef.current) {
return;
}
setTestNotificationState(
sent
? { status: "success" }
: {
status: "error",
message: t("desktop.permissions.testNotification.notDelivered"),
},
);
} catch {
setTestNotificationError(t("desktop.permissions.testNotification.failed"));
} finally {
if (isMountedRef.current) {
setIsSendingTestNotification(false);
setTestNotificationState({
status: "error",
message: t("desktop.permissions.testNotification.failed"),
});
}
}
}, [isDesktopApp, t]);
@@ -150,8 +163,7 @@ export function useDesktopPermissions(): UseDesktopPermissionsReturn {
snapshot,
isRefreshing,
requestingPermission,
isSendingTestNotification,
testNotificationError,
testNotificationState,
refreshPermissions,
requestPermission,
sendTestNotification,
@@ -13,6 +13,9 @@ const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
export interface DesktopSettings {
releaseChannel: ReleaseChannel;
notifications: {
playSound: boolean;
};
daemon: {
manageBuiltInDaemon: boolean;
keepRunningAfterQuit: boolean;
@@ -21,11 +24,15 @@ export interface DesktopSettings {
export interface DesktopSettingsPatch {
releaseChannel?: ReleaseChannel;
notifications?: Partial<DesktopSettings["notifications"]>;
daemon?: Partial<DesktopSettings["daemon"]>;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
releaseChannel: "stable",
notifications: {
playSound: true,
},
daemon: {
manageBuiltInDaemon: true,
keepRunningAfterQuit: false,
@@ -144,10 +151,17 @@ export async function migrateLegacyDesktopSettings(input: {
function parseDesktopSettings(raw: unknown): DesktopSettings {
const record = isRecord(raw) ? raw : {};
const notifications = isRecord(record.notifications) ? record.notifications : {};
const daemon = isRecord(record.daemon) ? record.daemon : {};
return {
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
notifications: {
playSound:
typeof notifications.playSound === "boolean"
? notifications.playSound
: DEFAULT_DESKTOP_SETTINGS.notifications.playSound,
},
daemon: {
manageBuiltInDaemon:
typeof daemon.manageBuiltInDaemon === "boolean"
@@ -167,6 +181,10 @@ function mergeDesktopSettings(
): DesktopSettings {
return {
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
notifications: {
...current.notifications,
...updates.notifications,
},
daemon: {
...current.daemon,
...updates.daemon,
@@ -177,6 +195,7 @@ function mergeDesktopSettings(
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
return {
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
...(updates.notifications ? { notifications: updates.notifications } : {}),
...(updates.daemon ? { daemon: updates.daemon } : {}),
};
}
@@ -0,0 +1,40 @@
import { useEffect, useState } from "react";
import { isWeb } from "@/constants/platform";
// A touch tablet running the desktop layout is still `isWeb === false || true`
// depending on the build, so neither platform gate answers "can this user
// hover and point precisely". Only the media query does.
const FINE_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
function getFinePointerQueryList(): MediaQueryList | null {
if (!isWeb || typeof window === "undefined" || typeof window.matchMedia !== "function") {
return null;
}
return window.matchMedia(FINE_POINTER_QUERY);
}
/** True when a mouse-like pointer drives the UI. Always false on native. */
export function hasFinePointer(): boolean {
return getFinePointerQueryList()?.matches ?? false;
}
/**
* Reactive `hasFinePointer()` — re-renders when the user switches between a
* mouse and touch (detachable keyboards, tablet mode).
*/
export function useHasFinePointer(): boolean {
const [finePointer, setFinePointer] = useState(hasFinePointer);
useEffect(() => {
const mediaQuery = getFinePointerQueryList();
if (!mediaQuery) return;
const handleChange = () => setFinePointer(mediaQuery.matches);
handleChange();
mediaQuery.addEventListener?.("change", handleChange);
return () => {
mediaQuery.removeEventListener?.("change", handleChange);
};
}, []);
return finePointer;
}
@@ -1,16 +1,21 @@
import { useCallback } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { type QueryClient, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
import {
createShortcutOverrideStore,
type ShortcutOverrideStore,
} from "@/keyboard/shortcut-override-store";
const STORAGE_KEY = "@paseo:keyboard-shortcut-overrides";
const QUERY_KEY = ["keyboard-shortcut-overrides"];
const EMPTY_OVERRIDES: Record<string, string> = {};
const EMPTY_OVERRIDES: ShortcutOverrides = {};
export interface UseKeyboardShortcutOverridesReturn {
overrides: Record<string, string>;
overrides: ShortcutOverrides;
isLoading: boolean;
setOverride: (bindingId: string, comboString: string) => Promise<void>;
clearOverride: (bindingId: string) => Promise<void>;
removeOverride: (bindingId: string) => Promise<void>;
resetAll: () => Promise<void>;
hasOverrides: boolean;
@@ -25,48 +30,55 @@ export function useKeyboardShortcutOverrides(): UseKeyboardShortcutOverridesRetu
gcTime: Infinity,
});
const setOverride = useCallback(
async (bindingId: string, comboString: string) => {
const prev = queryClient.getQueryData<Record<string, string>>(QUERY_KEY) ?? EMPTY_OVERRIDES;
const next = { ...prev, [bindingId]: comboString };
queryClient.setQueryData<Record<string, string>>(QUERY_KEY, next);
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
},
[queryClient],
);
const removeOverride = useCallback(
async (bindingId: string) => {
const prev = queryClient.getQueryData<Record<string, string>>(QUERY_KEY) ?? EMPTY_OVERRIDES;
const { [bindingId]: _, ...next } = prev;
queryClient.setQueryData<Record<string, string>>(QUERY_KEY, next);
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
},
[queryClient],
);
const resetAll = useCallback(async () => {
queryClient.setQueryData<Record<string, string>>(QUERY_KEY, EMPTY_OVERRIDES);
await AsyncStorage.removeItem(STORAGE_KEY);
}, [queryClient]);
const store = getStore(queryClient);
const overrides = data ?? EMPTY_OVERRIDES;
return {
overrides,
isLoading: isPending,
setOverride,
removeOverride,
resetAll,
setOverride: store.set,
clearOverride: store.clear,
removeOverride: store.remove,
resetAll: store.resetAll,
hasOverrides: Object.keys(overrides).length > 0,
};
}
async function loadOverridesFromStorage(): Promise<Record<string, string>> {
/**
* One store per query client. Every component that calls the hook has to share
* a single write queue -- a store per hook instance would give each its own
* queue and reintroduce the interleaving the store exists to prevent.
*/
const stores = new WeakMap<QueryClient, ShortcutOverrideStore>();
function getStore(queryClient: QueryClient): ShortcutOverrideStore {
const existing = stores.get(queryClient);
if (existing) return existing;
const created = createShortcutOverrideStore({
cache: {
read: () => queryClient.getQueryData<ShortcutOverrides>(QUERY_KEY) ?? EMPTY_OVERRIDES,
write: (next) => {
queryClient.setQueryData<ShortcutOverrides>(QUERY_KEY, next);
},
},
storage: {
write: (serialized) => AsyncStorage.setItem(STORAGE_KEY, serialized),
remove: () => AsyncStorage.removeItem(STORAGE_KEY),
},
onError: (err) => {
console.error("[KeyboardShortcutOverrides] Failed to save overrides:", err);
},
});
stores.set(queryClient, created);
return created;
}
async function loadOverridesFromStorage(): Promise<ShortcutOverrides> {
try {
const stored = await AsyncStorage.getItem(STORAGE_KEY);
if (stored) {
return JSON.parse(stored) as Record<string, string>;
return JSON.parse(stored) as ShortcutOverrides;
}
} catch (err) {
console.error("[KeyboardShortcutOverrides] Failed to load overrides:", err);
@@ -71,6 +71,7 @@ export function useKeyboardShortcuts({
const openProjectPickerAction = useOpenAddProject();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const keyboardWorkspaceSelectionRef = useRef<ActiveWorkspaceSelection | null>(null);
const badgeModifierKeyRef = useRef<string | null | undefined>(undefined);
const publishBrowserShortcutPolicy = useCallback(
(chordState?: ChordState) => {
@@ -110,7 +111,13 @@ export function useKeyboardShortcuts({
// runtime should reveal the sidebar number badges (Alt on web, Cmd on
// desktop Mac, Ctrl on desktop non-Mac). The store ORs altDown/cmdOrCtrlDown
// to drive badge visibility, so we set the flag matching this runtime.
const badgeModifierKey = getWorkspaceIndexJumpModifierKey({ isMac, isDesktop: isDesktopApp });
// Derived from the effective bindings: `null` when the user unassigned or
// rebound the jump shortcut, and no `event.key` ever equals null, so the
// badges simply never appear.
const badgeModifierKey = getWorkspaceIndexJumpModifierKey(
{ isMac, isDesktop: isDesktopApp },
bindings,
);
const setBadgeModifierDown = (down: boolean) => {
const state = useKeyboardShortcutsStore.getState();
if (isDesktopApp) {
@@ -120,6 +127,16 @@ export function useKeyboardShortcuts({
}
};
// The keyup listener matches the released key against the modifier derived
// when the effect last ran, so a modifier held while the jump binding
// changes can never be released -- the badges would stay up until a blur.
// Clear on change only: this effect also re-runs on every navigation, and
// clearing unconditionally would drop the badges mid Cmd+1, Cmd+2.
if (badgeModifierKeyRef.current !== badgeModifierKey) {
badgeModifierKeyRef.current = badgeModifierKey;
resetModifiers();
}
const shouldHandle = () => {
if (typeof document === "undefined") return false;
if (document.visibilityState !== "visible") return false;
@@ -29,6 +29,9 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
const DEFAULT_DESKTOP: DesktopSettings = {
releaseChannel: "stable",
notifications: {
playSound: true,
},
daemon: {
manageBuiltInDaemon: true,
keepRunningAfterQuit: false,
@@ -255,6 +255,7 @@ describe("loadSettingsFromStorage", () => {
isElectron: true,
settings: {
releaseChannel: "beta",
notifications: { playSound: true },
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
},
});
+3 -1
View File
@@ -246,7 +246,9 @@ describe("translation resources", () => {
expect(en.settings.shortcuts.actions.rebind).toBe("Rebind");
expect(en.settings.integrations.commandLine.title).toBe("Command line");
expect(en.settings.integrations.skills.updateAvailable).toBe("Update available");
expect(en.settings.permissions.notifications).toBe("Notifications");
expect(en.settings.notifications.playSound).toBe("Play sound");
expect(en.settings.notifications.permission).toBe("Notification permission");
expect(en.settings.notifications.sentTitle).toBe("Test notification sent");
expect(en.settings.permissions.actions.request).toBe("Request");
});
+22 -18
View File
@@ -1243,7 +1243,6 @@ export const ar: TranslationResources = {
},
},
rootError: {
kicker: "حدث خطأ",
title: "واجه Paseo مشكلة.",
body: "جرّب مرة أخرى لإعادة تحميل التطبيق. إذا استمر حدوث ذلك، فأرفق التفاصيل أدناه عند الإبلاغ عنه.",
details: "التفاصيل",
@@ -1427,19 +1426,6 @@ export const ar: TranslationResources = {
show: "عرض متقدم",
hide: "إخفاء المتقدمة",
},
headers: {
title: "رؤوس مخصصة",
add: "إضافة رأس",
name: "الاسم",
value: "القيمة",
remove: "إزالة الرأس",
errors: {
missingName: "أدخل اسمًا لكل رأس",
invalidName: "{{name}} ليس اسم رأس صالحًا",
invalidValue: "يحتوي {{name}} على فاصل أسطر غير صالح",
duplicateName: "تم إدخال {{name}} أكثر من مرة",
},
},
passwordVisibility: {
show: "إظهار كلمة المرور",
hide: "إخفاء كلمة المرور",
@@ -1704,6 +1690,7 @@ export const ar: TranslationResources = {
editor: "المحرر",
shortcuts: "الاختصارات",
integrations: "التكامل",
notifications: "الإشعارات",
permissions: "الأذونات",
diagnostics: "التشخيص",
about: "عن",
@@ -1713,6 +1700,21 @@ export const ar: TranslationResources = {
vimKeybindings: "اختصارات Vim",
vimHint: "تنطبق على ملفات المصدر في الويب وسطح المكتب.",
},
notifications: {
title: "الإشعارات",
permission: "إذن الإشعارات",
refreshAccessibility: "تحديث إذن الإشعارات",
playSound: "تشغيل صوت",
playSoundHint: "تشغيل صوت عند وصول إشعار سطح مكتب",
test: "اختبار الإشعار",
testHint: "إرسال إشعار باستخدام هذه الإعدادات",
permissionRequired: "اسمح بالوصول إلى الإشعارات قبل الاختبار",
send: "إرسال",
sending: "جارٍ الإرسال...",
sentTitle: "تم إرسال إشعار الاختبار",
sentDescription: "سلّم Paseo الإشعار إلى نظام التشغيل.",
sendFailedTitle: "تعذر إرسال إشعار الاختبار",
},
hostSections: {
projects: "المشاريع",
connections: "اتصالات",
@@ -1859,6 +1861,7 @@ export const ar: TranslationResources = {
midnight: "منتصف الليل",
claude: "كلود",
ghostty: "شبحي",
pureBlack: "أسود خالص",
auto: "نظام",
},
},
@@ -1897,11 +1900,15 @@ export const ar: TranslationResources = {
searchPlaceholder: "البحث في الاختصارات",
unavailableOnMobile: "اختصارات لوحة المفاتيح متاحة فقط على سطح المكتب",
capturePrompt: "اضغط على الاختصار...",
unassigned: "غير معين",
actions: {
menu: "إجراءات {{name}}",
done: "منتهي",
cancel: "يلغي",
bind: "ربط",
rebind: "إعادة ربط",
reset: "إعادة ضبط",
clear: "مسح",
reset: "إعادة الضبط إلى الافتراضي",
resetAll: "إعادة ضبط الكل",
},
sections: {
@@ -2007,17 +2014,14 @@ export const ar: TranslationResources = {
},
permissions: {
title: "الأذونات",
notifications: "إشعارات",
microphone: "ميكروفون",
refresh: "ينعش",
refreshing: "منعش...",
refreshAccessibility: "تحديث أذونات سطح المكتب",
test: "امتحان",
actions: {
granted: "ممنوح",
request: "طلب",
requesting: "جارٍ الطلب...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1253,7 +1253,6 @@ export const en = {
},
},
rootError: {
kicker: "Something went wrong",
title: "Paseo ran into a problem.",
body: "Try again to reload the app. If this keeps happening, include the details below when you report it.",
details: "Details",
@@ -1438,19 +1437,6 @@ export const en = {
show: "Show advanced",
hide: "Hide advanced",
},
headers: {
title: "Custom headers",
add: "Add header",
name: "Name",
value: "Value",
remove: "Remove header",
errors: {
missingName: "Enter a name for each header",
invalidName: "{{name}} is not a valid header name",
invalidValue: "{{name}} contains an invalid line break",
duplicateName: "{{name}} is entered more than once",
},
},
passwordVisibility: {
show: "Show password",
hide: "Hide password",
@@ -1715,6 +1701,7 @@ export const en = {
editor: "Editor",
shortcuts: "Shortcuts",
integrations: "Integrations",
notifications: "Notifications",
permissions: "Permissions",
diagnostics: "Diagnostics",
about: "About",
@@ -1724,6 +1711,21 @@ export const en = {
vimKeybindings: "Vim keybindings",
vimHint: "Applies to source files on web and desktop.",
},
notifications: {
title: "Notifications",
permission: "Notification permission",
refreshAccessibility: "Refresh notification permission",
playSound: "Play sound",
playSoundHint: "Play a sound when a desktop notification arrives",
test: "Test notification",
testHint: "Send a notification using these settings",
permissionRequired: "Allow notification access before testing",
send: "Send",
sending: "Sending...",
sentTitle: "Test notification sent",
sentDescription: "Paseo handed the notification to the operating system.",
sendFailedTitle: "Unable to send test notification",
},
hostSections: {
projects: "Projects",
connections: "Connections",
@@ -1869,6 +1871,7 @@ export const en = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "Pure black",
auto: "System",
},
},
@@ -1907,11 +1910,15 @@ export const en = {
searchPlaceholder: "Search shortcuts",
unavailableOnMobile: "Keyboard shortcuts are only available on desktop",
capturePrompt: "Press shortcut...",
unassigned: "Not set",
actions: {
menu: "Actions for {{name}}",
done: "Done",
cancel: "Cancel",
bind: "Bind",
rebind: "Rebind",
reset: "Reset",
clear: "Clear",
reset: "Reset to default",
resetAll: "Reset all",
},
sections: {
@@ -2018,17 +2025,14 @@ export const en = {
},
permissions: {
title: "Permissions",
notifications: "Notifications",
microphone: "Microphone",
refresh: "Refresh",
refreshing: "Refreshing...",
refreshAccessibility: "Refresh desktop permissions",
test: "Test",
actions: {
granted: "Granted",
request: "Request",
requesting: "Requesting...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1283,7 +1283,6 @@ export const es: TranslationResources = {
},
},
rootError: {
kicker: "Algo salió mal",
title: "Paseo tuvo un problema.",
body: "Vuelve a intentarlo para recargar la app. Si sigue ocurriendo, incluye los detalles de abajo al reportarlo.",
details: "Detalles",
@@ -1468,19 +1467,6 @@ export const es: TranslationResources = {
show: "Mostrar avanzado",
hide: "Ocultar avanzado",
},
headers: {
title: "Encabezados personalizados",
add: "Añadir encabezado",
name: "Nombre",
value: "Valor",
remove: "Eliminar encabezado",
errors: {
missingName: "Introduce un nombre para cada encabezado",
invalidName: "{{name}} no es un nombre de encabezado válido",
invalidValue: "{{name}} contiene un salto de línea no válido",
duplicateName: "{{name}} se ha introducido más de una vez",
},
},
passwordVisibility: {
show: "Mostrar contraseña",
hide: "Ocultar contraseña",
@@ -1747,6 +1733,7 @@ export const es: TranslationResources = {
editor: "Editor",
shortcuts: "Atajos",
integrations: "Integraciones",
notifications: "Notificaciones",
permissions: "Permisos",
diagnostics: "Diagnóstico",
about: "Acerca de",
@@ -1756,6 +1743,21 @@ export const es: TranslationResources = {
vimKeybindings: "Atajos de Vim",
vimHint: "Se aplica a archivos fuente en web y escritorio.",
},
notifications: {
title: "Notificaciones",
permission: "Permiso de notificaciones",
refreshAccessibility: "Actualizar permiso de notificaciones",
playSound: "Reproducir sonido",
playSoundHint: "Reproduce un sonido cuando llega una notificación de escritorio",
test: "Probar notificación",
testHint: "Envía una notificación con esta configuración",
permissionRequired: "Permite el acceso a las notificaciones antes de probar",
send: "Enviar",
sending: "Enviando...",
sentTitle: "Notificación de prueba enviada",
sentDescription: "Paseo entregó la notificación al sistema operativo.",
sendFailedTitle: "No se pudo enviar la notificación de prueba",
},
hostSections: {
projects: "Proyectos",
connections: "Conexiones",
@@ -1906,6 +1908,7 @@ export const es: TranslationResources = {
midnight: "Medianoche",
claude: "claudio",
ghostty: "fantasmal",
pureBlack: "Negro puro",
auto: "Sistema",
},
},
@@ -1945,11 +1948,15 @@ export const es: TranslationResources = {
searchPlaceholder: "Buscar atajos",
unavailableOnMobile: "Los atajos de teclado solo están disponibles en el escritorio",
capturePrompt: "Presione el acceso directo...",
unassigned: "Sin asignar",
actions: {
menu: "Acciones para {{name}}",
done: "Hecho",
cancel: "Cancelar",
bind: "Asignar",
rebind: "Reencuadernar",
reset: "Reiniciar",
clear: "Borrar",
reset: "Restablecer al valor predeterminado",
resetAll: "Restablecer todo",
},
sections: {
@@ -2057,17 +2064,14 @@ export const es: TranslationResources = {
},
permissions: {
title: "Permisos",
notifications: "Notificaciones",
microphone: "Micrófono",
refresh: "Refrescar",
refreshing: "Refrescante...",
refreshAccessibility: "Actualizar permisos de escritorio",
test: "Prueba",
actions: {
granted: "Otorgada",
request: "Pedido",
requesting: "Solicitando...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1286,7 +1286,6 @@ export const fr: TranslationResources = {
},
},
rootError: {
kicker: "Une erreur s'est produite",
title: "Paseo a rencontré un problème.",
body: "Réessayez pour recharger l'application. Si cela continue, joignez les détails ci-dessous au signalement.",
details: "Détails",
@@ -1472,19 +1471,6 @@ export const fr: TranslationResources = {
show: "Afficher avancé",
hide: "Masquer avancé",
},
headers: {
title: "En-têtes personnalisés",
add: "Ajouter un en-tête",
name: "Nom",
value: "Valeur",
remove: "Supprimer l'en-tête",
errors: {
missingName: "Saisissez un nom pour chaque en-tête",
invalidName: "{{name}} n'est pas un nom d'en-tête valide",
invalidValue: "{{name}} contient un saut de ligne non valide",
duplicateName: "{{name}} est saisi plusieurs fois",
},
},
passwordVisibility: {
show: "Afficher le mot de passe",
hide: "Masquer le mot de passe",
@@ -1751,6 +1737,7 @@ export const fr: TranslationResources = {
editor: "Éditeur",
shortcuts: "Raccourcis",
integrations: "Intégrations",
notifications: "Notifications",
permissions: "Autorisations",
diagnostics: "Diagnostic",
about: "À propos",
@@ -1760,6 +1747,21 @@ export const fr: TranslationResources = {
vimKeybindings: "Raccourcis Vim",
vimHint: "S’applique aux fichiers source sur le web et le bureau.",
},
notifications: {
title: "Notifications",
permission: "Autorisation des notifications",
refreshAccessibility: "Actualiser l’autorisation des notifications",
playSound: "Émettre un son",
playSoundHint: "Émet un son lorsqu’une notification de bureau arrive",
test: "Tester la notification",
testHint: "Envoie une notification avec ces réglages",
permissionRequired: "Autorisez l’accès aux notifications avant le test",
send: "Envoyer",
sending: "Envoi...",
sentTitle: "Notification de test envoyée",
sentDescription: "Paseo a transmis la notification au système d’exploitation.",
sendFailedTitle: "Impossible d’envoyer la notification de test",
},
hostSections: {
projects: "Projets",
connections: "Relations",
@@ -1909,6 +1911,7 @@ export const fr: TranslationResources = {
midnight: "Minuit",
claude: "Claude",
ghostty: "Fantôme",
pureBlack: "Noir pur",
auto: "Système",
},
},
@@ -1948,11 +1951,15 @@ export const fr: TranslationResources = {
searchPlaceholder: "Rechercher des raccourcis",
unavailableOnMobile: "Les raccourcis clavier ne sont disponibles que sur le bureau",
capturePrompt: "Appuyez sur le raccourci...",
unassigned: "Non défini",
actions: {
menu: "Actions pour {{name}}",
done: "Fait",
cancel: "Annuler",
bind: "Attribuer",
rebind: "Relier",
reset: "Réinitialiser",
clear: "Effacer",
reset: "Rétablir la valeur par défaut",
resetAll: "Tout réinitialiser",
},
sections: {
@@ -2061,17 +2068,14 @@ export const fr: TranslationResources = {
},
permissions: {
title: "Autorisations",
notifications: "Notifications",
microphone: "Microphone",
refresh: "Rafraîchir",
refreshing: "Rafraîchissant...",
refreshAccessibility: "Actualiser les autorisations du bureau",
test: "Test",
actions: {
granted: "Accordé",
request: "Demande",
requesting: "Demander...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1256,7 +1256,6 @@ export const ja: TranslationResources = {
},
},
rootError: {
kicker: "問題が発生しました",
title: "Paseo で問題が発生しました。",
body: "アプリを再読み込みするにはもう一度お試しください。繰り返し発生する場合は、以下の詳細を添えて報告してください。",
details: "詳細",
@@ -1441,19 +1440,6 @@ export const ja: TranslationResources = {
show: "詳細設定を表示",
hide: "詳細設定を非表示",
},
headers: {
title: "カスタムヘッダー",
add: "ヘッダーを追加",
name: "名前",
value: "値",
remove: "ヘッダーを削除",
errors: {
missingName: "各ヘッダーの名前を入力してください",
invalidName: "{{name}} は有効なヘッダー名ではありません",
invalidValue: "{{name}} に無効な改行が含まれています",
duplicateName: "{{name}} が複数回入力されています",
},
},
passwordVisibility: {
show: "パスワードを表示",
hide: "パスワードを非表示",
@@ -1720,6 +1706,7 @@ export const ja: TranslationResources = {
editor: "エディター",
shortcuts: "ショートカット",
integrations: "連携",
notifications: "通知",
permissions: "権限",
diagnostics: "診断",
about: "アプリ情報",
@@ -1729,6 +1716,21 @@ export const ja: TranslationResources = {
vimKeybindings: "Vim キーバインド",
vimHint: "Web とデスクトップのソースファイルに適用されます。",
},
notifications: {
title: "通知",
permission: "通知の権限",
refreshAccessibility: "通知の権限を更新",
playSound: "サウンドを再生",
playSoundHint: "デスクトップ通知が届いたときにサウンドを再生します",
test: "通知をテスト",
testHint: "現在の設定でテスト通知を送信します",
permissionRequired: "テストする前に通知へのアクセスを許可してください",
send: "送信",
sending: "送信中...",
sentTitle: "テスト通知を送信しました",
sentDescription: "Paseo が通知をオペレーティングシステムに渡しました。",
sendFailedTitle: "テスト通知を送信できません",
},
hostSections: {
projects: "プロジェクト",
connections: "接続",
@@ -1874,6 +1876,7 @@ export const ja: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "ピュアブラック",
auto: "システム",
},
},
@@ -1913,11 +1916,15 @@ export const ja: TranslationResources = {
searchPlaceholder: "ショートカットを検索",
unavailableOnMobile: "キーボードショートカットはデスクトップでのみ利用できます",
capturePrompt: "ショートカットを押してください...",
unassigned: "未設定",
actions: {
menu: "{{name}} のアクション",
done: "完了",
cancel: "キャンセル",
bind: "割り当て",
rebind: "再割り当て",
reset: "リセット",
clear: "クリア",
reset: "デフォルトに戻す",
resetAll: "すべてリセット",
},
sections: {
@@ -2026,17 +2033,14 @@ export const ja: TranslationResources = {
},
permissions: {
title: "権限",
notifications: "通知",
microphone: "マイク",
refresh: "更新",
refreshing: "更新中...",
refreshAccessibility: "デスクトップの権限を更新",
test: "テスト",
actions: {
granted: "許可済み",
request: "許可を求める",
requesting: "許可を求めています...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1252,7 +1252,6 @@ export const ko: TranslationResources = {
},
},
rootError: {
kicker: "문제가 발생했습니다.",
title: "Paseo에 문제가 발생했습니다.",
body: "앱을 다시 로드해 보세요. 이런 일이 계속 발생하면 신고할 때 아래 세부정보를 포함하세요.",
details: "세부",
@@ -1437,19 +1436,6 @@ export const ko: TranslationResources = {
show: "고급 표시",
hide: "고급 숨기기",
},
headers: {
title: "사용자 지정 헤더",
add: "헤더 추가",
name: "이름",
value: "값",
remove: "헤더 삭제",
errors: {
missingName: "각 헤더의 이름을 입력하세요",
invalidName: "{{name}}은(는) 올바른 헤더 이름이 아닙니다",
invalidValue: "{{name}}에 잘못된 줄바꿈이 있습니다",
duplicateName: "{{name}}이(가) 두 번 이상 입력되었습니다",
},
},
passwordVisibility: {
show: "비밀번호 표시",
hide: "비밀번호 숨기기",
@@ -1714,6 +1700,7 @@ export const ko: TranslationResources = {
editor: "편집기",
shortcuts: "단축키",
integrations: "통합",
notifications: "알림",
permissions: "권한",
diagnostics: "진단",
about: "정보",
@@ -1723,6 +1710,21 @@ export const ko: TranslationResources = {
vimKeybindings: "Vim 키 바인딩",
vimHint: "웹 및 데스크톱의 소스 파일에 적용됩니다.",
},
notifications: {
title: "알림",
permission: "알림 권한",
refreshAccessibility: "알림 권한 새로 고침",
playSound: "소리 재생",
playSoundHint: "데스크톱 알림이 도착하면 소리를 재생합니다",
test: "알림 테스트",
testHint: "현재 설정으로 테스트 알림을 보냅니다",
permissionRequired: "테스트하기 전에 알림 접근을 허용하세요",
send: "보내기",
sending: "보내는 중...",
sentTitle: "테스트 알림을 보냈습니다",
sentDescription: "Paseo가 알림을 운영 체제에 전달했습니다.",
sendFailedTitle: "테스트 알림을 보낼 수 없음",
},
hostSections: {
projects: "프로젝트",
connections: "연결",
@@ -1870,6 +1872,7 @@ export const ko: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "순수 검정",
auto: "시스템",
},
},
@@ -1908,11 +1911,15 @@ export const ko: TranslationResources = {
searchPlaceholder: "검색 단축키",
unavailableOnMobile: "키보드 단축키는 데스크톱에서만 사용할 수 있습니다",
capturePrompt: "단축키를 누르세요...",
unassigned: "설정되지 않음",
actions: {
menu: "{{name}} 작업",
done: "완료",
cancel: "취소",
bind: "지정",
rebind: "다시 지정",
reset: "재설정",
clear: "지우기",
reset: "기본값으로 재설정",
resetAll: "모두 재설정",
},
sections: {
@@ -2019,17 +2026,14 @@ export const ko: TranslationResources = {
},
permissions: {
title: "권한",
notifications: "알림",
microphone: "마이크",
refresh: "새로고침",
refreshing: "새로고침 중...",
refreshAccessibility: "데스크톱 권한 새로고침",
test: "테스트",
actions: {
granted: "허용됨",
request: "요청",
requesting: "요청 중...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1269,7 +1269,6 @@ export const ptBR: TranslationResources = {
},
},
rootError: {
kicker: "Algo deu errado",
title: "O Paseo encontrou um problema.",
body: "Tente novamente para recarregar o app. Se isso continuar acontecendo, inclua os detalhes abaixo ao relatar o problema.",
details: "Detalhes",
@@ -1454,19 +1453,6 @@ export const ptBR: TranslationResources = {
show: "Mostrar avançado",
hide: "Ocultar avançado",
},
headers: {
title: "Cabeçalhos personalizados",
add: "Adicionar cabeçalho",
name: "Nome",
value: "Valor",
remove: "Remover cabeçalho",
errors: {
missingName: "Digite um nome para cada cabeçalho",
invalidName: "{{name}} não é um nome de cabeçalho válido",
invalidValue: "{{name}} contém uma quebra de linha inválida",
duplicateName: "{{name}} foi inserido mais de uma vez",
},
},
passwordVisibility: {
show: "Mostrar senha",
hide: "Ocultar senha",
@@ -1733,6 +1719,7 @@ export const ptBR: TranslationResources = {
editor: "Editor",
shortcuts: "Atalhos",
integrations: "Integrações",
notifications: "Notificações",
permissions: "Permissões",
diagnostics: "Diagnósticos",
about: "Sobre",
@@ -1742,6 +1729,21 @@ export const ptBR: TranslationResources = {
vimKeybindings: "Atalhos do Vim",
vimHint: "Aplica-se a arquivos-fonte na web e no desktop.",
},
notifications: {
title: "Notificações",
permission: "Permissão de notificações",
refreshAccessibility: "Atualizar permissão de notificações",
playSound: "Reproduzir som",
playSoundHint: "Reproduz um som quando chega uma notificação da área de trabalho",
test: "Testar notificação",
testHint: "Envia uma notificação usando estas configurações",
permissionRequired: "Permita o acesso às notificações antes de testar",
send: "Enviar",
sending: "Enviando...",
sentTitle: "Notificação de teste enviada",
sentDescription: "O Paseo entregou a notificação ao sistema operacional.",
sendFailedTitle: "Não foi possível enviar a notificação de teste",
},
hostSections: {
projects: "Projetos",
connections: "Conexões",
@@ -1890,6 +1892,7 @@ export const ptBR: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "Preto puro",
auto: "Sistema",
},
},
@@ -1928,11 +1931,15 @@ export const ptBR: TranslationResources = {
searchPlaceholder: "Pesquisar atalhos",
unavailableOnMobile: "Atalhos de teclado estão disponíveis apenas no desktop",
capturePrompt: "Pressione o atalho...",
unassigned: "Não definido",
actions: {
menu: "Ações para {{name}}",
done: "Concluído",
cancel: "Cancelar",
bind: "Atribuir",
rebind: "Reatribuir",
reset: "Redefinir",
clear: "Limpar",
reset: "Redefinir para o padrão",
resetAll: "Redefinir tudo",
},
sections: {
@@ -2041,17 +2048,14 @@ export const ptBR: TranslationResources = {
},
permissions: {
title: "Permissões",
notifications: "Notificações",
microphone: "Microfone",
refresh: "Atualizar",
refreshing: "Atualizando...",
refreshAccessibility: "Atualizar permissões do desktop",
test: "Testar",
actions: {
granted: "Concedida",
request: "Solicitar",
requesting: "Solicitando...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1272,7 +1272,6 @@ export const ru: TranslationResources = {
},
},
rootError: {
kicker: "Что-то пошло не так",
title: "В Paseo возникла проблема.",
body: "Попробуйте снова перезагрузить приложение. Если это повторяется, приложите приведенные ниже подробности к отчету.",
details: "Подробности",
@@ -1459,19 +1458,6 @@ export const ru: TranslationResources = {
show: "Показать расширенные",
hide: "Скрыть расширенные",
},
headers: {
title: "Пользовательские заголовки",
add: "Добавить заголовок",
name: "Имя",
value: "Значение",
remove: "Удалить заголовок",
errors: {
missingName: "Введите имя для каждого заголовка",
invalidName: "{{name}} — недопустимое имя заголовка",
invalidValue: "{{name}} содержит недопустимый перенос строки",
duplicateName: "{{name}} введён несколько раз",
},
},
passwordVisibility: {
show: "Показать пароль",
hide: "Скрыть пароль",
@@ -1738,6 +1724,7 @@ export const ru: TranslationResources = {
editor: "Редактор",
shortcuts: "Ярлыки",
integrations: "Интеграции",
notifications: "Уведомления",
permissions: "Разрешения",
diagnostics: "Диагностика",
about: "О",
@@ -1747,6 +1734,21 @@ export const ru: TranslationResources = {
vimKeybindings: "Клавиши Vim",
vimHint: "Применяется к исходным файлам в веб- и настольной версии.",
},
notifications: {
title: "Уведомления",
permission: "Разрешение на уведомления",
refreshAccessibility: "Обновить разрешение на уведомления",
playSound: "Воспроизводить звук",
playSoundHint: "Воспроизводит звук при получении уведомления на компьютере",
test: "Проверить уведомление",
testHint: "Отправляет уведомление с текущими настройками",
permissionRequired: "Разрешите доступ к уведомлениям перед проверкой",
send: "Отправить",
sending: "Отправка...",
sentTitle: "Тестовое уведомление отправлено",
sentDescription: "Paseo передал уведомление операционной системе.",
sendFailedTitle: "Не удалось отправить тестовое уведомление",
},
hostSections: {
projects: "Проекты",
connections: "Соединения",
@@ -1895,6 +1897,7 @@ export const ru: TranslationResources = {
midnight: "Полночь",
claude: "Клод",
ghostty: "Призрачный",
pureBlack: "Чистый чёрный",
auto: "Система",
},
},
@@ -1935,11 +1938,15 @@ export const ru: TranslationResources = {
searchPlaceholder: "Поиск сочетаний клавиш",
unavailableOnMobile: "Сочетания клавиш доступны только на рабочем столе.",
capturePrompt: "Нажмите ярлык...",
unassigned: "Не задано",
actions: {
menu: "Действия для {{name}}",
done: "Сделанный",
cancel: "Отмена",
bind: "Привязать",
rebind: "Перепривязка",
reset: "Перезагрузить",
clear: "Очистить",
reset: "Сбросить к значению по умолчанию",
resetAll: "Сбросить все",
},
sections: {
@@ -2045,17 +2052,14 @@ export const ru: TranslationResources = {
},
permissions: {
title: "Разрешения",
notifications: "Уведомления",
microphone: "Микрофон",
refresh: "Обновить",
refreshing: "Освежающий...",
refreshAccessibility: "Обновить разрешения рабочего стола",
test: "Тест",
actions: {
granted: "Предоставленный",
request: "Запрос",
requesting: "Запрос...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -18
View File
@@ -1227,7 +1227,6 @@ export const zhCN: TranslationResources = {
},
},
rootError: {
kicker: "出现问题",
title: "Paseo 遇到了问题。",
body: "请重试以重新加载应用。如果问题持续发生,请在报告时附上下面的详细信息。",
details: "详情",
@@ -1410,19 +1409,6 @@ export const zhCN: TranslationResources = {
show: "显示高级选项",
hide: "隐藏高级选项",
},
headers: {
title: "自定义请求头",
add: "添加请求头",
name: "名称",
value: "值",
remove: "删除请求头",
errors: {
missingName: "请为每个请求头输入名称",
invalidName: "{{name}} 不是有效的请求头名称",
invalidValue: "{{name}} 包含无效换行符",
duplicateName: "{{name}} 输入了多次",
},
},
passwordVisibility: {
show: "显示密码",
hide: "隐藏密码",
@@ -1684,6 +1670,7 @@ export const zhCN: TranslationResources = {
editor: "编辑器",
shortcuts: "快捷键",
integrations: "集成",
notifications: "通知",
permissions: "权限",
diagnostics: "诊断",
about: "关于",
@@ -1693,6 +1680,21 @@ export const zhCN: TranslationResources = {
vimKeybindings: "Vim 键位",
vimHint: "适用于网页和桌面端的源文件。",
},
notifications: {
title: "通知",
permission: "通知权限",
refreshAccessibility: "刷新通知权限",
playSound: "播放声音",
playSoundHint: "收到桌面通知时播放声音",
test: "测试通知",
testHint: "使用当前设置发送测试通知",
permissionRequired: "测试前请允许访问通知",
send: "发送",
sending: "正在发送...",
sentTitle: "测试通知已发送",
sentDescription: "Paseo 已将通知交给操作系统。",
sendFailedTitle: "无法发送测试通知",
},
hostSections: {
projects: "项目",
connections: "连接",
@@ -1838,6 +1840,7 @@ export const zhCN: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "纯黑",
auto: "系统",
},
},
@@ -1875,11 +1878,15 @@ export const zhCN: TranslationResources = {
searchPlaceholder: "搜索快捷键",
unavailableOnMobile: "键盘快捷键仅在桌面端可用",
capturePrompt: "按下快捷键...",
unassigned: "未设置",
actions: {
menu: "{{name}} 的操作",
done: "完成",
cancel: "取消",
bind: "绑定",
rebind: "重新绑定",
reset: "重置",
clear: "清除",
reset: "重置为默认",
resetAll: "全部重置",
},
sections: {
@@ -1985,17 +1992,14 @@ export const zhCN: TranslationResources = {
},
permissions: {
title: "权限",
notifications: "通知",
microphone: "麦克风",
refresh: "刷新",
refreshing: "正在刷新...",
refreshAccessibility: "刷新桌面端权限",
test: "测试",
actions: {
granted: "已授权",
request: "请求",
requesting: "正在请求...",
busySuffix: "{{label}}...",
},
},
host: {
@@ -1,14 +1,20 @@
import { describe, expect, it, vi } from "vitest";
import { formatShortcut } from "@/utils/format-shortcut";
import {
buildKeyboardShortcutHelpSections,
buildEffectiveBindings,
getBindingIdForAction,
getDefaultKeysForAction,
getWorkspaceIndexJumpModifierKey,
parseBindingChord,
resolveKeyboardShortcut,
resolveShortcutKeysForAction,
UNASSIGNED_COMBO,
type ChordState,
type KeyboardShortcutContext,
type KeyboardShortcutInput,
type ParsedShortcutBinding,
type ShortcutOverrides,
} from "./keyboard-shortcuts";
function keyboardInput(overrides: Partial<KeyboardShortcutInput>): KeyboardShortcutInput {
@@ -640,7 +646,11 @@ describe("keyboard-shortcut help sections", () => {
"workspace-tab-new": ["mod", "T"],
"workspace-jump-index": ["mod", "1-9"],
"workspace-tab-jump-index": ["mod", "alt", "1-9"],
"workspace-tab-close-current": ["meta", "W"],
// Derived from `combo: "Cmd+W"`, so the token is `mod` where the row
// used to be hand-authored as `meta`. This binding is mac-only and
// `formatShortcut` renders both as ⌘, so the badge is unchanged — see
// the render assertion below.
"workspace-tab-close-current": ["mod", "W"],
"workspace-pane-split-right": ["mod", "\\"],
"workspace-pane-close": ["mod", "shift", "W"],
},
@@ -654,11 +664,15 @@ describe("keyboard-shortcut help sections", () => {
},
},
{
name: "uses mod+b for the left sidebar and mod+period for both sidebars on non-mac",
name: "uses ctrl+b for the left sidebar and ctrl+period for both sidebars on non-mac",
context: { isMac: false, isDesktop: false },
// Derived from `combo: "Ctrl+B"` / `"Ctrl+."`, so the token is `ctrl` where
// these rows used to be hand-authored as `mod`. Both bindings are non-mac
// only and `formatShortcut` labels either token "Ctrl" there, so the badge
// is unchanged — see the render assertion below.
expectedKeys: {
"toggle-left-sidebar": ["mod", "B"],
"toggle-both-sidebars": ["mod", "."],
"toggle-left-sidebar": ["ctrl", "B"],
"toggle-both-sidebars": ["ctrl", "."],
},
},
];
@@ -667,10 +681,104 @@ describe("keyboard-shortcut help sections", () => {
const sections = buildKeyboardShortcutHelpSections(context);
for (const [id, keys] of Object.entries(expectedKeys)) {
expect(findRow(sections, id)?.keys).toEqual(keys);
expect(findRow(sections, id)?.chord).toEqual([keys]);
}
});
describe("rows derive their keys from the binding that fires", () => {
const macDesktop = { isMac: true, isDesktop: true };
const NEW_WORKSPACE_BINDING = "workspace-new-cmd-n-mac";
const MAC_INDEX_BINDING = "workspace-navigate-index-cmd-digit-mac";
const PANE_FOCUS_LEFT_BINDING = "workspace-pane-focus-left-cmd-shift-left";
const SHOW_SHORTCUTS_BINDING = "shortcuts-dialog-toggle-question-mark";
function rowChord(overrides: ShortcutOverrides, id: string) {
const sections = buildKeyboardShortcutHelpSections(
macDesktop,
buildEffectiveBindings(overrides),
);
return findRow(sections, id)?.chord ?? null;
}
// The reported bug: the cheat sheet advertised the shipped default no matter
// what the user had rebound the shortcut to.
it("shows the override, not the shipped default", () => {
expect(rowChord({}, "new-workspace")).toEqual([["mod", "N"]]);
expect(rowChord({ [NEW_WORKSPACE_BINDING]: "Cmd+Shift+K" }, "new-workspace")).toEqual([
["mod", "shift", "K"],
]);
});
it("shows every step of a multi-step chord override", () => {
expect(rowChord({ [NEW_WORKSPACE_BINDING]: "Cmd+K Cmd+N" }, "new-workspace")).toEqual([
["mod", "K"],
["mod", "N"],
]);
});
it("reports an unassigned row as having no keys at all", () => {
expect(rowChord({ [NEW_WORKSPACE_BINDING]: UNASSIGNED_COMBO }, "new-workspace")).toBeNull();
});
it("returns to the shipped default once the override is cleared", () => {
expect(rowChord({ [NEW_WORKSPACE_BINDING]: "Cmd+Shift+K" }, "new-workspace")).toEqual([
["mod", "shift", "K"],
]);
expect(rowChord({}, "new-workspace")).toEqual([["mod", "N"]]);
});
// An arrow override used to render as the raw `ARROWLEFT` code, because the
// display path uppercased key names past the table that maps them to arrows.
it("renders an arrow override as an arrow", () => {
const chord = rowChord(
{ [PANE_FOCUS_LEFT_BINDING]: "Cmd+Alt+ArrowLeft" },
"workspace-pane-focus-left",
);
expect(chord).toEqual([["mod", "alt", "Left"]]);
expect(formatShortcut(chord?.[0] ?? [], "mac")).toBe("⌥⌘←");
});
// `1-9` and `?` are display-only tokens no combo string can spell, so these
// two rows opt out of default derivation via `help.defaultDisplayKeys`.
it("keeps the wildcard token on the index-jump row", () => {
expect(rowChord({}, "workspace-jump-index")).toEqual([["mod", "1-9"]]);
});
it("keeps the bare ? on the show-shortcuts row rather than deriving Shift+?", () => {
expect(rowChord({}, "show-shortcuts")).toEqual([["?"]]);
});
it("replaces the default-only wildcard when the index jump is rebound", () => {
expect(rowChord({ [MAC_INDEX_BINDING]: "Ctrl+Digit" }, "workspace-jump-index")).toEqual([
["ctrl", "Digit"],
]);
});
it("replaces the default-only ? when show shortcuts is rebound", () => {
expect(rowChord({ [SHOW_SHORTCUTS_BINDING]: "Cmd+K" }, "show-shortcuts")).toEqual([
["mod", "K"],
]);
});
// The authored row said `meta`, the derived row says `mod`. Both render ⌘ on
// mac and this binding is mac-only, so nothing the user sees moved.
it("still renders close-tab as ⌘W after switching to the derived token", () => {
const sections = buildKeyboardShortcutHelpSections(macDesktop);
const chord = findRow(sections, "workspace-tab-close-current")?.chord;
expect(formatShortcut(chord?.[0] ?? [], "mac")).toBe("⌘W");
});
// Same story on the other side: these rows said `mod`, the non-mac combos
// say `Ctrl`, and non-mac labels both as "Ctrl".
it("still renders the sidebar toggles as Ctrl+B and Ctrl+. on non-mac", () => {
const sections = buildKeyboardShortcutHelpSections({ isMac: false, isDesktop: false });
const left = findRow(sections, "toggle-left-sidebar")?.chord;
const both = findRow(sections, "toggle-both-sidebars")?.chord;
expect(formatShortcut(left?.[0] ?? [], "non-mac")).toBe("Ctrl+B");
expect(formatShortcut(both?.[0] ?? [], "non-mac")).toBe("Ctrl+.");
});
});
it("returns stable i18n keys for section titles and help rows", () => {
const sections = buildKeyboardShortcutHelpSections({ isMac: true, isDesktop: true });
const projects = sections.find((section) => section.id === "projects");
@@ -702,6 +810,8 @@ describe("keyboard-shortcut help sections", () => {
});
describe("getWorkspaceIndexJumpModifierKey", () => {
const MAC_INDEX_BINDING = "workspace-navigate-index-cmd-digit-mac";
it("uses Alt on web, regardless of OS", () => {
expect(getWorkspaceIndexJumpModifierKey({ isMac: true, isDesktop: false })).toBe("Alt");
expect(getWorkspaceIndexJumpModifierKey({ isMac: false, isDesktop: false })).toBe("Alt");
@@ -714,4 +824,265 @@ describe("getWorkspaceIndexJumpModifierKey", () => {
it("uses Ctrl on desktop non-Mac, not Meta or Alt", () => {
expect(getWorkspaceIndexJumpModifierKey({ isMac: false, isDesktop: true })).toBe("Control");
});
it("derives the modifier from the effective binding, not the platform", () => {
const bindings = buildEffectiveBindings({ [MAC_INDEX_BINDING]: "Alt+Digit" });
expect(getWorkspaceIndexJumpModifierKey({ isMac: true, isDesktop: true }, bindings)).toBe(
"Alt",
);
});
it("suppresses the badges when the jump shortcut is unassigned", () => {
const bindings = buildEffectiveBindings({ [MAC_INDEX_BINDING]: UNASSIGNED_COMBO });
expect(getWorkspaceIndexJumpModifierKey({ isMac: true, isDesktop: true }, bindings)).toBeNull();
});
it("suppresses the badges when the jump shortcut is rebound to one concrete digit", () => {
// Capture can only ever produce a concrete digit, never the 1-9 wildcard,
// so the badges would advertise eight workspaces that no longer respond.
const bindings = buildEffectiveBindings({ [MAC_INDEX_BINDING]: "Cmd+3" });
expect(getWorkspaceIndexJumpModifierKey({ isMac: true, isDesktop: true }, bindings)).toBeNull();
});
it("suppresses the badges for a multi-step chord", () => {
const bindings = buildEffectiveBindings({ [MAC_INDEX_BINDING]: "Cmd+K Cmd+Digit" });
expect(getWorkspaceIndexJumpModifierKey({ isMac: true, isDesktop: true }, bindings)).toBeNull();
});
it("suppresses the badges when the combo needs a second modifier", () => {
const bindings = buildEffectiveBindings({ [MAC_INDEX_BINDING]: "Cmd+Shift+Digit" });
expect(getWorkspaceIndexJumpModifierKey({ isMac: true, isDesktop: true }, bindings)).toBeNull();
});
});
function parseUnknownBindingChord() {
return parseBindingChord("Ctrl+Nonsense");
}
/**
* Effective bindings with one help row rewritten to ship without a default
* combo, standing in for a binding authored as `combo: ""`. `help.keys` is left
* as authored so the empty parsed chord is the only signal.
*/
function withoutDefaultCombo(helpId: string): ParsedShortcutBinding[] {
const bindings: ParsedShortcutBinding[] = [];
for (const binding of buildEffectiveBindings({})) {
if (binding.help?.id === helpId) {
bindings.push(Object.assign({}, binding, { combo: "", parsedChord: [] }));
} else {
bindings.push(binding);
}
}
return bindings;
}
describe("unassigned shortcuts", () => {
const TAB_NEW_BINDING = "workspace-tab-new-ctrl-t-non-mac";
const desktopNonMac = { isMac: false, isDesktop: true };
function findRow(sections: ReturnType<typeof buildKeyboardShortcutHelpSections>, id: string) {
for (const section of sections) {
const row = section.rows.find((candidate) => candidate.id === id);
if (row) {
return row;
}
}
return null;
}
describe("parseBindingChord", () => {
it("yields an empty chord for a binding that ships without a default combo", () => {
expect(parseBindingChord("")).toEqual([]);
});
it("parses a normal combo into one step", () => {
expect(parseBindingChord("Ctrl+T")).toHaveLength(1);
});
it("parses a chord into one step per combo", () => {
expect(parseBindingChord("Ctrl+W S")).toHaveLength(2);
});
it("still throws on an unparseable combo", () => {
expect(parseUnknownBindingChord).toThrow();
});
});
describe("matching", () => {
it("stops matching a shortcut the user unassigned", () => {
const bindings = buildEffectiveBindings({ [TAB_NEW_BINDING]: UNASSIGNED_COMBO });
const result = resolveShortcut({
event: { key: "t", code: "KeyT", ctrlKey: true },
context: desktopNonMac,
bindings,
});
expect(result.match).toBeNull();
});
it("leaves other shortcuts firing when one is unassigned", () => {
const bindings = buildEffectiveBindings({ [TAB_NEW_BINDING]: UNASSIGNED_COMBO });
const result = resolveShortcut({
event: { key: "t", code: "KeyT", ctrlKey: true, shiftKey: true },
context: desktopNonMac,
bindings,
});
expect(result.match?.action).toBe("workspace.terminal.new");
});
it("restores the default when the override is removed", () => {
const bindings = buildEffectiveBindings({});
const result = resolveShortcut({
event: { key: "t", code: "KeyT", ctrlKey: true },
context: desktopNonMac,
bindings,
});
expect(result.match?.action).toBe("workspace.tab.new");
});
it("treats a stored empty combo as unassigned too", () => {
const bindings = buildEffectiveBindings({ [TAB_NEW_BINDING]: "" });
const result = resolveShortcut({
event: { key: "t", code: "KeyT", ctrlKey: true },
context: desktopNonMac,
bindings,
});
expect(result.match).toBeNull();
});
it("keeps rebinding to a real combo working", () => {
const bindings = buildEffectiveBindings({ [TAB_NEW_BINDING]: "Ctrl+Y" });
expect(
resolveShortcut({
event: { key: "y", code: "KeyY", ctrlKey: true },
context: desktopNonMac,
bindings,
}).match?.action,
).toBe("workspace.tab.new");
expect(
resolveShortcut({
event: { key: "t", code: "KeyT", ctrlKey: true },
context: desktopNonMac,
bindings,
}).match,
).toBeNull();
});
it("falls back to the default for a non-string stored value", () => {
// Storage is unvalidated JSON, so a corrupt value must not throw.
const overrides = { [TAB_NEW_BINDING]: 42 } as unknown as ShortcutOverrides;
const bindings = buildEffectiveBindings(overrides);
const result = resolveShortcut({
event: { key: "t", code: "KeyT", ctrlKey: true },
context: desktopNonMac,
bindings,
});
expect(result.match?.action).toBe("workspace.tab.new");
});
});
describe("resolveShortcutKeysForAction", () => {
// `ctrl`, not `mod`: these keys are derived from the non-mac binding's
// `combo: "Ctrl+T"` rather than hand-authored. `formatShortcut` labels both
// tokens "Ctrl" off mac, and this binding is non-mac only.
it("returns the default keys when there is no override", () => {
expect(resolveShortcutKeysForAction("workspace-tab-new", {}, desktopNonMac)).toEqual([
["ctrl", "T"],
]);
});
it("returns null when the user unassigned the shortcut", () => {
expect(
resolveShortcutKeysForAction(
"workspace-tab-new",
{ [TAB_NEW_BINDING]: UNASSIGNED_COMBO },
desktopNonMac,
),
).toBeNull();
});
it("returns the override keys when the shortcut is rebound", () => {
expect(
resolveShortcutKeysForAction(
"workspace-tab-new",
{ [TAB_NEW_BINDING]: "Ctrl+Y" },
desktopNonMac,
),
).toEqual([["ctrl", "Y"]]);
});
it("falls back to the default keys for an unparseable override", () => {
// Matching falls back to the default here, so the display has to as well
// or it would advertise keys that do nothing.
expect(
resolveShortcutKeysForAction(
"workspace-tab-new",
{ [TAB_NEW_BINDING]: "Ctrl+Nonsense" },
desktopNonMac,
),
).toEqual([["ctrl", "T"]]);
});
it("falls back to the default keys for a non-string stored value", () => {
const overrides = { [TAB_NEW_BINDING]: 42 } as unknown as ShortcutOverrides;
expect(resolveShortcutKeysForAction("workspace-tab-new", overrides, desktopNonMac)).toEqual([
["ctrl", "T"],
]);
});
it("returns null for an action with no binding on this platform", () => {
expect(resolveShortcutKeysForAction("message-input-send", {}, desktopNonMac)).toBeNull();
});
});
describe("help rows", () => {
it("lists no keys for an unassigned shortcut", () => {
const bindings = buildEffectiveBindings({ [TAB_NEW_BINDING]: UNASSIGNED_COMBO });
const sections = buildKeyboardShortcutHelpSections(desktopNonMac, bindings);
expect(findRow(sections, "workspace-tab-new")?.chord).toBeNull();
});
it("keeps the row so the shortcut stays rebindable", () => {
const bindings = buildEffectiveBindings({ [TAB_NEW_BINDING]: UNASSIGNED_COMBO });
const sections = buildKeyboardShortcutHelpSections(desktopNonMac, bindings);
expect(findRow(sections, "workspace-tab-new")).not.toBeNull();
expect(getBindingIdForAction("workspace-tab-new", desktopNonMac)).toBe(TAB_NEW_BINDING);
});
it("still lists the default keys when nothing is overridden", () => {
const sections = buildKeyboardShortcutHelpSections(desktopNonMac);
expect(findRow(sections, "workspace-tab-new")?.chord).toEqual([["ctrl", "T"]]);
expect(getDefaultKeysForAction("workspace-tab-new", desktopNonMac)).toEqual([["ctrl", "T"]]);
});
// A binding authored with `combo: ""` has no default. The settings row uses
// this to hide Reset, which would otherwise be a dead button landing on the
// same "Not set" state Clear already produced. The empty parsed chord is what
// marks the binding default-less.
it("reports no default keys for a binding that ships without a combo", () => {
const bindings = withoutDefaultCombo("workspace-tab-new");
expect(getDefaultKeysForAction("workspace-tab-new", desktopNonMac, bindings)).toBeNull();
});
it("lists no help keys for a binding that ships without a combo", () => {
const bindings = withoutDefaultCombo("workspace-tab-new");
const sections = buildKeyboardShortcutHelpSections(desktopNonMac, bindings);
expect(findRow(sections, "workspace-tab-new")?.chord).toBeNull();
});
});
});
+158 -94
View File
@@ -5,8 +5,11 @@ import type {
KeyboardShortcutPayload,
MessageInputKeyboardActionKind,
} from "@/keyboard/actions";
import { type KeyCombo, parseChordString } from "@/keyboard/shortcut-string";
import { chordStringToShortcutKeys } from "@/keyboard/shortcut-string";
import {
chordStringToShortcutKeys,
type KeyCombo,
parseChordString,
} from "@/keyboard/shortcut-string";
export type { KeyCombo } from "@/keyboard/shortcut-string";
@@ -40,7 +43,8 @@ export interface KeyboardShortcutHelpRow {
id: string;
label: string;
labelKey: string;
keys: ShortcutKey[];
/** The keys that actually fire this action, or `null` when it has none. */
chord: ShortcutKey[][] | null;
note?: string;
noteKey?: string;
}
@@ -85,7 +89,14 @@ interface ShortcutHelp {
id: string;
section: ShortcutSectionId;
label: string;
keys: ShortcutKey[];
/**
* Display keys to show instead of the combo. Set this only when the combo
* cannot express what the row means — the `Digit` wildcard, which stands for
* any of 1-9, and `Shift+?`, whose Shift is implied by the character itself.
* Every other row derives its keys from `combo`, so a rebound shortcut shows
* what it now does rather than what it shipped as.
*/
defaultDisplayKeys?: ShortcutKey[];
note?: string;
}
@@ -191,7 +202,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "new-agent",
section: "projects",
label: "Open project",
keys: ["mod", "O"],
},
},
{
@@ -203,7 +213,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "new-agent",
section: "projects",
label: "Open project",
keys: ["mod", "O"],
},
},
@@ -217,7 +226,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "new-workspace",
section: "projects",
label: "New workspace",
keys: ["mod", "N"],
},
},
{
@@ -229,7 +237,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "new-workspace",
section: "projects",
label: "New workspace",
keys: ["mod", "N"],
},
},
@@ -243,7 +250,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "switch-project",
section: "projects",
label: "Switch project",
keys: ["mod", "P"],
},
},
{
@@ -255,7 +261,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "switch-project",
section: "projects",
label: "Switch project",
keys: ["mod", "P"],
},
},
@@ -271,7 +276,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "archive-workspace",
section: "projects",
label: "Archive workspace",
keys: ["mod", "shift", "Backspace"],
},
},
{
@@ -285,7 +289,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "archive-workspace",
section: "projects",
label: "Archive workspace",
keys: ["mod", "shift", "Backspace"],
},
},
@@ -299,7 +302,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "pin-workspace",
section: "projects",
label: "Pin chat",
keys: ["mod", "shift", "P"],
},
},
{
@@ -311,7 +313,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "pin-workspace",
section: "projects",
label: "Pin chat",
keys: ["mod", "shift", "P"],
},
},
@@ -325,7 +326,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-new",
section: "tabs-panes",
label: "New tab",
keys: ["mod", "T"],
},
},
{
@@ -337,7 +337,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-new",
section: "tabs-panes",
label: "New tab",
keys: ["mod", "T"],
},
},
{
@@ -349,7 +348,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-close-current",
section: "tabs-panes",
label: "Close current tab",
keys: ["meta", "W"],
},
},
{
@@ -361,7 +359,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-close-current",
section: "tabs-panes",
label: "Close current tab",
keys: ["ctrl", "W"],
},
},
{
@@ -373,7 +370,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-close-current",
section: "tabs-panes",
label: "Close current tab",
keys: ["alt", "shift", "W"],
},
},
@@ -388,7 +384,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-jump-index",
section: "navigation",
label: "Jump to workspace",
keys: ["mod", "1-9"],
defaultDisplayKeys: ["mod", "1-9"],
},
},
{
@@ -401,7 +397,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-jump-index",
section: "navigation",
label: "Jump to workspace",
keys: ["mod", "1-9"],
defaultDisplayKeys: ["mod", "1-9"],
},
},
{
@@ -414,7 +410,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-jump-index",
section: "navigation",
label: "Jump to workspace",
keys: ["alt", "1-9"],
defaultDisplayKeys: ["alt", "1-9"],
},
},
@@ -429,7 +425,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-jump-index",
section: "navigation",
label: "Jump to tab",
keys: ["mod", "alt", "1-9"],
defaultDisplayKeys: ["mod", "alt", "1-9"],
},
},
{
@@ -442,7 +438,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-jump-index",
section: "navigation",
label: "Jump to tab",
keys: ["alt", "1-9"],
defaultDisplayKeys: ["alt", "1-9"],
},
},
{
@@ -455,7 +451,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-jump-index",
section: "navigation",
label: "Jump to tab",
keys: ["alt", "shift", "1-9"],
defaultDisplayKeys: ["alt", "shift", "1-9"],
},
},
@@ -470,7 +466,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-prev",
section: "navigation",
label: "Previous workspace",
keys: ["mod", "["],
},
},
{
@@ -483,7 +478,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-prev",
section: "navigation",
label: "Previous workspace",
keys: ["mod", "["],
},
},
{
@@ -496,7 +490,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-next",
section: "navigation",
label: "Next workspace",
keys: ["mod", "]"],
},
},
{
@@ -509,7 +502,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-next",
section: "navigation",
label: "Next workspace",
keys: ["mod", "]"],
},
},
{
@@ -522,7 +514,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-prev",
section: "navigation",
label: "Previous workspace",
keys: ["alt", "["],
},
},
{
@@ -535,7 +526,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-next",
section: "navigation",
label: "Next workspace",
keys: ["alt", "]"],
},
},
@@ -550,7 +540,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-prev",
section: "navigation",
label: "Previous tab",
keys: ["alt", "shift", "["],
},
},
{
@@ -563,7 +552,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-tab-next",
section: "navigation",
label: "Next tab",
keys: ["alt", "shift", "]"],
},
},
@@ -577,7 +565,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-split-right",
section: "tabs-panes",
label: "Split pane right",
keys: ["mod", "\\"],
},
},
{
@@ -589,7 +576,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-split-down",
section: "tabs-panes",
label: "Split pane down",
keys: ["mod", "shift", "\\"],
},
},
{
@@ -601,7 +587,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-focus-left",
section: "tabs-panes",
label: "Focus pane left",
keys: ["mod", "shift", "Left"],
},
},
{
@@ -613,7 +598,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-focus-right",
section: "tabs-panes",
label: "Focus pane right",
keys: ["mod", "shift", "Right"],
},
},
{
@@ -625,7 +609,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-focus-up",
section: "tabs-panes",
label: "Focus pane up",
keys: ["mod", "shift", "Up"],
},
},
{
@@ -637,7 +620,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-focus-down",
section: "tabs-panes",
label: "Focus pane down",
keys: ["mod", "shift", "Down"],
},
},
{
@@ -649,7 +631,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-move-tab-left",
section: "tabs-panes",
label: "Move tab left",
keys: ["mod", "shift", "alt", "Left"],
},
},
{
@@ -661,7 +642,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-move-tab-right",
section: "tabs-panes",
label: "Move tab right",
keys: ["mod", "shift", "alt", "Right"],
},
},
{
@@ -673,7 +653,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-move-tab-up",
section: "tabs-panes",
label: "Move tab up",
keys: ["mod", "shift", "alt", "Up"],
},
},
{
@@ -685,7 +664,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-move-tab-down",
section: "tabs-panes",
label: "Move tab down",
keys: ["mod", "shift", "alt", "Down"],
},
},
{
@@ -697,7 +675,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-pane-close",
section: "tabs-panes",
label: "Close pane",
keys: ["mod", "shift", "W"],
},
},
@@ -711,7 +688,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-terminal-new",
section: "panels",
label: "New terminal",
keys: ["mod", "shift", "T"],
},
},
{
@@ -723,7 +699,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "workspace-terminal-new",
section: "panels",
label: "New terminal",
keys: ["mod", "shift", "T"],
},
},
@@ -737,7 +712,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-command-center",
section: "panels",
label: "Toggle command center",
keys: ["mod", "K"],
},
},
{
@@ -749,7 +723,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-command-center",
section: "panels",
label: "Toggle command center",
keys: ["mod", "K"],
},
},
@@ -764,7 +737,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "show-shortcuts",
section: "panels",
label: "Show keyboard shortcuts",
keys: ["?"],
defaultDisplayKeys: ["?"],
note: "Available when focus is not in a text field or terminal.",
},
},
@@ -779,7 +752,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-left-sidebar",
section: "panels",
label: "Toggle left sidebar",
keys: ["mod", "B"],
},
},
{
@@ -791,7 +763,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-left-sidebar",
section: "panels",
label: "Toggle left sidebar",
keys: ["mod", "B"],
},
},
{
@@ -803,7 +774,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-right-sidebar",
section: "panels",
label: "Toggle right sidebar",
keys: ["mod", "E"],
},
},
{
@@ -815,7 +785,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-right-sidebar",
section: "panels",
label: "Toggle right sidebar",
keys: ["mod", "E"],
},
},
{
@@ -835,7 +804,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-both-sidebars",
section: "panels",
label: "Toggle both sidebars",
keys: ["mod", "."],
},
},
{
@@ -847,7 +815,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-both-sidebars",
section: "panels",
label: "Toggle both sidebars",
keys: ["mod", "."],
},
},
@@ -861,7 +828,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-settings",
section: "panels",
label: "Toggle settings",
keys: ["mod", ","],
},
},
{
@@ -873,7 +839,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-settings",
section: "panels",
label: "Toggle settings",
keys: ["mod", ","],
},
},
@@ -887,7 +852,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-focus",
section: "panels",
label: "Toggle focus mode",
keys: ["mod", "shift", "F"],
},
},
{
@@ -899,7 +863,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "toggle-focus",
section: "panels",
label: "Toggle focus mode",
keys: ["mod", "shift", "F"],
},
},
@@ -913,7 +876,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "cycle-theme",
section: "panels",
label: "Cycle theme",
keys: ["mod", "alt", "T"],
},
},
{
@@ -925,7 +887,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "cycle-theme",
section: "panels",
label: "Cycle theme",
keys: ["mod", "alt", "T"],
},
},
@@ -940,7 +901,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "focus-message-input",
section: "agent-input",
label: "Focus message input",
keys: ["mod", "L"],
},
},
{
@@ -953,7 +913,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "focus-message-input",
section: "agent-input",
label: "Focus message input",
keys: ["mod", "L"],
},
},
{
@@ -967,7 +926,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "cycle-agent-mode",
section: "agent-input",
label: "Cycle agent mode",
keys: ["shift", "Tab"],
},
},
{
@@ -981,7 +939,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "voice-toggle",
section: "agent-input",
label: "Toggle voice mode",
keys: ["mod", "shift", "D"],
},
},
{
@@ -995,7 +952,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "voice-toggle",
section: "agent-input",
label: "Toggle voice mode",
keys: ["mod", "shift", "D"],
},
},
{
@@ -1008,7 +964,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "dictation-toggle",
section: "agent-input",
label: "Start/stop dictation",
keys: ["mod", "D"],
},
},
{
@@ -1021,7 +976,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "dictation-toggle",
section: "agent-input",
label: "Start/stop dictation",
keys: ["mod", "D"],
},
},
{
@@ -1035,7 +989,6 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "agent-interrupt",
section: "agent-input",
label: "Interrupt agent",
keys: ["Esc"],
},
},
{
@@ -1057,15 +1010,36 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
id: "voice-mute-toggle",
section: "agent-input",
label: "Mute/unmute voice mode",
keys: ["Space"],
},
},
];
// --- Parse bindings at module load ---
/**
* The stored value meaning "the user deliberately unassigned this shortcut".
* Distinct from a missing key, which means "no override, use the default".
*/
export const UNASSIGNED_COMBO = null;
/**
* Parse a binding's combo string into a chord.
*
* An empty combo yields an empty chord, which never matches any event — the
* matcher skips bindings whose first combo is missing. That is how both a
* user-unassigned shortcut and a binding authored without a default combo are
* represented: one state, not two. Authors who want a default-less binding
* write `combo: ""` and nothing else.
*/
export function parseBindingChord(combo: string): KeyCombo[] {
if (combo === "") {
return [];
}
return parseChordString(combo);
}
function parseBinding(binding: ShortcutBinding): ParsedShortcutBinding {
const parsedChord = parseChordString(binding.combo);
const parsedChord = parseBindingChord(binding.combo);
const lastCombo = parsedChord.at(-1);
if (binding.repeat === false && lastCombo) {
lastCombo.repeat = false;
@@ -1076,15 +1050,21 @@ function parseBinding(binding: ShortcutBinding): ParsedShortcutBinding {
export const DEFAULT_BINDINGS: readonly ParsedShortcutBinding[] =
SHORTCUT_BINDINGS.map(parseBinding);
export function buildEffectiveBindings(overrides: Record<string, string>): ParsedShortcutBinding[] {
export type ShortcutOverrides = Record<string, string | null>;
export function buildEffectiveBindings(overrides: ShortcutOverrides): ParsedShortcutBinding[] {
return DEFAULT_BINDINGS.map(function (binding) {
const override = overrides[binding.id];
if (override === undefined) {
if (override === UNASSIGNED_COMBO) {
return { ...binding, combo: "", parsedChord: [] };
}
// Storage is unvalidated JSON, so anything can turn up here.
if (typeof override !== "string") {
return binding;
}
let parsedChord: KeyCombo[];
try {
parsedChord = parseChordString(override);
parsedChord = parseBindingChord(override);
} catch {
return binding;
}
@@ -1092,7 +1072,11 @@ export function buildEffectiveBindings(overrides: Record<string, string>): Parse
if (binding.repeat === false && lastCombo) {
lastCombo.repeat = false;
}
return { ...binding, combo: override, parsedChord };
if (!binding.help?.defaultDisplayKeys) {
return { ...binding, combo: override, parsedChord };
}
const { defaultDisplayKeys: _defaultDisplayKeys, ...help } = binding.help;
return { ...binding, combo: override, parsedChord, help };
});
}
@@ -1391,48 +1375,128 @@ export function getBindingIdForAction(
return null;
}
/**
* The keys to display for one binding, derived from the combo that actually
* fires so a rebound shortcut never advertises the keys it shipped with.
*
* `help.defaultDisplayKeys` wins where it is set, but only on the shipped
* binding. Effective bindings discard it when an override replaces the combo,
* so rebound rows still derive the keys that now fire.
* `parsedChord` is the single source of truth for "has no keys": it is derived
* from `combo`, so it covers both a user-unassigned shortcut and a binding
* authored without a default.
*/
function displayChordForBinding(binding: ParsedShortcutBinding): ShortcutKey[][] | null {
if (binding.parsedChord.length === 0) {
return null;
}
const displayKeys = binding.help?.defaultDisplayKeys;
if (displayKeys) {
return [displayKeys];
}
return chordStringToShortcutKeys(binding.combo);
}
export function getDefaultKeysForAction(
actionId: string,
platform: { isMac: boolean; isDesktop: boolean },
): ShortcutKey[] | null {
for (const binding of DEFAULT_BINDINGS) {
bindings: readonly ParsedShortcutBinding[] = DEFAULT_BINDINGS,
): ShortcutKey[][] | null {
for (const binding of bindings) {
if (binding.help?.id !== actionId) {
continue;
}
if (!helpMatchesPlatform(binding.when, platform)) {
continue;
}
return binding.help.keys;
return displayChordForBinding(binding);
}
return null;
}
/**
* The keys to display for a shortcut: the user's override if they set one,
* the default otherwise, and `null` when the shortcut has no keys at all —
* either the user unassigned it or it ships without a default combo.
*
* The single resolver behind every display surface (hint badges, the command
* palette, and the settings rows). It validates an override the same way
* matching does, so what is shown is always what actually fires.
*/
export function resolveShortcutKeysForAction(
actionId: string,
overrides: Readonly<Record<string, string>>,
overrides: ShortcutOverrides,
platform: { isMac: boolean; isDesktop: boolean },
): ShortcutKey[][] | null {
const bindingId = getBindingIdForAction(actionId, platform);
if (!bindingId) return null;
if (bindingId === null) {
return null;
}
const defaultChord = getDefaultKeysForAction(actionId, platform);
const override = overrides[bindingId];
if (override) return chordStringToShortcutKeys(override);
const defaultKeys = getDefaultKeysForAction(actionId, platform);
return defaultKeys ? [defaultKeys] : null;
if (override === UNASSIGNED_COMBO || override === "") {
return null;
}
// Storage is unvalidated JSON: a missing key and a corrupt value both mean
// "fall back to the default".
if (typeof override !== "string") {
return defaultChord;
}
try {
parseBindingChord(override);
} catch {
// Matching falls back to the default for an unparseable override, so the
// display has to as well or it would advertise keys that do nothing.
return defaultChord;
}
return chordStringToShortcutKeys(override);
}
/**
* The `KeyboardEvent.key` whose hold reveals the sidebar workspace-jump number
* badges. It must match the modifier of the active `workspace.navigate.index`
* binding for this runtime, otherwise the badges appear for a modifier that
* does not actually jump: Alt on web, Cmd (Meta) on desktop Mac, Ctrl on
* desktop non-Mac.
* badges, or `null` when no badges should appear.
*
* It must match the modifier of the active `workspace.navigate.index` binding
* for this runtime, otherwise the badges appear for a modifier that does not
* actually jump. That binding is parameterized — its key is the `Digit`
* wildcard, which stands for any of 1-9 — so the badges are only honest when
* the effective binding is still a single combo built on that wildcard.
* Anything else (unassigned, rebound to one concrete digit, or a multi-step
* chord) yields `null`, because the 1-9 badges would be advertising more than
* the shortcut delivers.
*/
export function getWorkspaceIndexJumpModifierKey(platform: {
isMac: boolean;
isDesktop: boolean;
}): "Alt" | "Meta" | "Control" {
if (!platform.isDesktop) return "Alt";
return platform.isMac ? "Meta" : "Control";
export function getWorkspaceIndexJumpModifierKey(
platform: { isMac: boolean; isDesktop: boolean },
bindings: readonly ParsedShortcutBinding[] = DEFAULT_BINDINGS,
): "Alt" | "Meta" | "Control" | null {
const binding = bindings.find(function (candidate) {
return (
candidate.action === "workspace.navigate.index" &&
helpMatchesPlatform(candidate.when, platform)
);
});
if (!binding || binding.parsedChord.length !== 1) {
return null;
}
const combo = binding.parsedChord[0];
if (!combo || combo.code !== "Digit") {
return null;
}
// Exactly one modifier: holding it is what reveals the badges, so a combo
// needing a second one would show badges the user cannot act on.
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;
}
export function buildKeyboardShortcutHelpSections(
@@ -1470,7 +1534,7 @@ export function buildKeyboardShortcutHelpSections(
id: help.id,
label: help.label,
labelKey: SHORTCUT_HELP_LABEL_KEYS[help.id] ?? help.label,
keys: help.keys,
chord: displayChordForBinding(binding),
...(help.note ? { note: help.note } : {}),
...(SHORTCUT_HELP_NOTE_KEYS[help.id] ? { noteKey: SHORTCUT_HELP_NOTE_KEYS[help.id] } : {}),
});
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import {
buildEffectiveBindings,
buildKeyboardShortcutHelpSections,
UNASSIGNED_COMBO,
type ShortcutOverrides,
} from "./keyboard-shortcuts";
import { filterShortcutHelpSections, shortcutSearchText } from "./shortcut-help-search";
const MAC_DESKTOP = { isMac: true, isDesktop: true };
const NEW_WORKSPACE_BINDING = "workspace-new-cmd-n-mac";
/**
* The i18n port, filled with the real English strings the rows use. Translation
* is the only dependency the filter cannot compute, so it is injected rather
* than mocked.
*/
const EN: Record<string, string> = {
"settings.shortcuts.sections.projects": "Projects",
"settings.shortcuts.help.newWorkspace": "New workspace",
"settings.shortcuts.help.openProject": "Open project",
};
function translate(key: string): string {
return EN[key] ?? key;
}
function filter(query: string, overrides: ShortcutOverrides = {}) {
return filterShortcutHelpSections({
sections: buildKeyboardShortcutHelpSections(MAC_DESKTOP, buildEffectiveBindings(overrides)),
query,
translate,
shortcutOs: "mac",
});
}
function matchedRowIds(query: string, overrides: ShortcutOverrides = {}): string[] {
return filter(query, overrides).flatMap((section) => section.rows.map((row) => row.id));
}
describe("shortcutSearchText", () => {
it("covers the tokens, the rendered badge, and the modifier aliases", () => {
const text = shortcutSearchText([["mod", "N"]], "mac");
expect(text).toContain("mod N");
expect(text).toContain("⌘N");
expect(text).toContain("cmd+N");
expect(text).toContain("command+N");
});
// The alias expansion is combinatorial, so a flattened chord would multiply
// the two combos together and invent spellings for keys never pressed at once.
it("keeps a multi-step chord's combos apart", () => {
const text = shortcutSearchText(
[
["mod", "K"],
["mod", "N"],
],
"mac",
);
expect(text).toContain("cmd+K");
expect(text).toContain("cmd+N");
expect(text).not.toContain("cmd+K+cmd+N");
});
});
describe("filterShortcutHelpSections", () => {
it("returns every section for a blank query", () => {
expect(filter(" ")).toHaveLength(buildKeyboardShortcutHelpSections(MAC_DESKTOP).length);
});
it("matches a row by its label", () => {
expect(matchedRowIds("new workspace")).toContain("new-workspace");
});
it("matches a row by the rendered badge", () => {
expect(matchedRowIds("⌘n")).toContain("new-workspace");
});
it("matches a row by a spelled-out modifier", () => {
expect(matchedRowIds("command+n")).toContain("new-workspace");
});
// The reported bug, from the search side: the cheat sheet has to stop finding
// a row by keys the user has rebound away from.
it("finds a rebound row by its new keys and not by the superseded default", () => {
const overrides = { [NEW_WORKSPACE_BINDING]: "Cmd+Shift+K" };
expect(matchedRowIds("cmd+shift+k", overrides)).toContain("new-workspace");
expect(matchedRowIds("cmd+n", overrides)).not.toContain("new-workspace");
});
it("still finds an unassigned row by its label", () => {
const overrides = { [NEW_WORKSPACE_BINDING]: UNASSIGNED_COMBO };
expect(matchedRowIds("new workspace", overrides)).toContain("new-workspace");
expect(matchedRowIds("cmd+n", overrides)).not.toContain("new-workspace");
});
it("keeps every row of a section whose own title matches", () => {
const projects = filter("projects").find((section) => section.id === "projects");
const allProjects = buildKeyboardShortcutHelpSections(MAC_DESKTOP).find(
(section) => section.id === "projects",
);
expect(projects?.rows).toHaveLength(allProjects?.rows.length ?? 0);
});
it("drops a section whose rows all miss", () => {
expect(filter("no shortcut spells this")).toEqual([]);
});
});
@@ -0,0 +1,90 @@
import type { KeyboardShortcutHelpSection } from "@/keyboard/keyboard-shortcuts";
import { formatShortcut, type ShortcutKey, type ShortcutOs } from "@/utils/format-shortcut";
/** Resolves an i18n key to display text. The caller's `t`, injected. */
export type TranslateHelpKey = (key: string) => string;
/**
* Alternative spellings for one combo, so searching "cmd k" and "command+k" both
* find ⌘K. The modifier a user types rarely matches the token the binding
* stores, and never matches the symbol the badge renders.
*/
export function shortcutSearchAliases(
keys: readonly ShortcutKey[],
shortcutOs: ShortcutOs,
): string {
const aliases = keys.map((key) => {
if (shortcutOs === "mac") {
if (key === "mod" || key === "meta") return ["cmd", "command"];
if (key === "alt") return ["alt", "option"];
} else {
if (key === "mod" || key === "ctrl") return ["ctrl", "control"];
if (key === "meta") return ["win", "windows"];
}
return [key];
});
const combinations = aliases.reduce<string[][]>(
(prefixes, choices) =>
prefixes.flatMap((prefix) => choices.map((choice) => [...prefix, choice])),
[[]],
);
return combinations
.flatMap((combination) => [combination.join(" "), combination.join("+")])
.join(" ");
}
/**
* Search text for one row's keys. Built per combo and joined, never over a
* flattened chord: the alias expansion is combinatorial, so flattening a
* multi-step chord into one key list both explodes the combination count and
* invents aliases for combos the user never has to press together.
*/
export function shortcutSearchText(chord: ShortcutKey[][], shortcutOs: ShortcutOs): string {
return chord
.flatMap((combo) => [
combo.join(" "),
formatShortcut(combo, shortcutOs),
shortcutSearchAliases(combo, shortcutOs),
])
.join(" ");
}
/**
* The cheat sheet's sections narrowed to a query, matching on the row's label,
* its note, and every spelling of the keys that actually fire it. A section
* whose own title matches keeps all of its rows.
*/
export function filterShortcutHelpSections({
sections,
query,
translate,
shortcutOs,
}: {
sections: readonly KeyboardShortcutHelpSection[];
query: string;
translate: TranslateHelpKey;
shortcutOs: ShortcutOs;
}): KeyboardShortcutHelpSection[] {
const normalizedQuery = query.trim().toLocaleLowerCase();
if (!normalizedQuery) return [...sections];
return sections.flatMap((section) => {
if (translate(section.titleKey).toLocaleLowerCase().includes(normalizedQuery)) {
return [section];
}
const rows = section.rows.filter((row) => {
const searchText = [
translate(row.labelKey),
row.noteKey ? translate(row.noteKey) : row.note,
row.chord ? shortcutSearchText(row.chord, shortcutOs) : null,
]
.filter(Boolean)
.join(" ")
.toLocaleLowerCase();
return searchText.includes(normalizedQuery);
});
return rows.length > 0 ? [{ ...section, rows }] : [];
});
}
@@ -0,0 +1,183 @@
import { describe, expect, it } from "vitest";
import type { ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
import {
createShortcutOverrideStore,
type ShortcutOverrideStore,
} from "@/keyboard/shortcut-override-store";
interface Harness {
store: ShortcutOverrideStore;
/** What the UI would render. */
cached(): ShortcutOverrides;
/** What a relaunch would load. */
persisted(): ShortcutOverrides | null;
errors: unknown[];
/** Cache and storage transitions in the order they happened. */
events: string[];
}
/**
* @param failWrites 1-based indexes of `storage.write` calls that reject.
*/
function createHarness(
options: { seed?: ShortcutOverrides; failWrites?: number[]; failRemove?: boolean } = {},
): Harness {
const failWrites = new Set(options.failWrites ?? []);
let cache: ShortcutOverrides = options.seed ?? {};
let stored: string | null = options.seed ? JSON.stringify(options.seed) : null;
let writeCount = 0;
const errors: unknown[] = [];
const events: string[] = [];
const store = createShortcutOverrideStore({
cache: {
read: () => cache,
write: (next) => {
cache = next;
events.push(`cache ${JSON.stringify(next)}`);
},
},
storage: {
write: async (serialized) => {
writeCount += 1;
const failed = failWrites.has(writeCount);
await settle(1);
if (failed) {
events.push(`write-failed ${serialized}`);
throw new Error("storage unavailable");
}
stored = serialized;
events.push(`write ${serialized}`);
},
// Slower than a write, so an unserialized reset would land last and
// delete whatever was written after it.
remove: async () => {
await settle(3);
if (options.failRemove) {
events.push("remove-failed");
throw new Error("storage unavailable");
}
stored = null;
events.push("remove");
},
},
onError: (err) => errors.push(err),
});
return {
store,
cached: () => cache,
persisted: () => (stored === null ? null : (JSON.parse(stored) as ShortcutOverrides)),
errors,
events,
};
}
/** Deterministic stand-in for storage latency: yield `ticks` microtasks. */
async function settle(ticks: number): Promise<void> {
for (let i = 0; i < ticks; i += 1) await Promise.resolve();
}
describe("createShortcutOverrideStore", () => {
it("persists a rebind", async () => {
const h = createHarness();
await h.store.set("new-workspace", "Mod+Shift+N");
expect(h.cached()).toEqual({ "new-workspace": "Mod+Shift+N" });
expect(h.persisted()).toEqual({ "new-workspace": "Mod+Shift+N" });
expect(h.errors).toEqual([]);
});
it("distinguishes unassigned from absent", async () => {
const h = createHarness();
await h.store.clear("new-workspace");
expect(h.persisted()).toEqual({ "new-workspace": null });
await h.store.remove("new-workspace");
expect(h.persisted()).toEqual({});
expect(h.cached()).not.toHaveProperty("new-workspace");
});
it("reverts the cache and reports when the write fails", async () => {
const h = createHarness({ seed: { "new-workspace": "Mod+1" }, failWrites: [1] });
await h.store.clear("new-workspace");
expect(h.cached()).toEqual({ "new-workspace": "Mod+1" });
expect(h.persisted()).toEqual({ "new-workspace": "Mod+1" });
expect(h.errors).toHaveLength(1);
});
it("drops the whole map on reset", async () => {
const h = createHarness({ seed: { "new-workspace": "Mod+1" } });
await h.store.resetAll();
expect(h.cached()).toEqual({});
expect(h.persisted()).toBeNull();
});
it("restores the map when the reset fails", async () => {
const h = createHarness({ seed: { "new-workspace": "Mod+1" }, failRemove: true });
await h.store.resetAll();
expect(h.cached()).toEqual({ "new-workspace": "Mod+1" });
expect(h.persisted()).toEqual({ "new-workspace": "Mod+1" });
expect(h.errors).toHaveLength(1);
});
it("keeps the later of two changes to the same binding when the earlier write fails", async () => {
const h = createHarness({ failWrites: [1] });
// Both dispatched before either settles -- the settings row fires these
// without awaiting.
const first = h.store.set("new-workspace", "Mod+1");
const second = h.store.set("new-workspace", "Mod+2");
await Promise.all([first, second]);
// The failed write must not roll its own stale value back over the one
// that landed, or the row would show Mod+1 and the relaunch would fire
// Mod+2.
expect(h.cached()).toEqual({ "new-workspace": "Mod+2" });
expect(h.persisted()).toEqual({ "new-workspace": "Mod+2" });
expect(h.errors).toHaveLength(1);
});
it("keeps a rebind made after Reset all", async () => {
const h = createHarness({ seed: { "new-workspace": "Mod+1" } });
const reset = h.store.resetAll();
const rebind = h.store.set("open-settings", "Mod+2");
await Promise.all([reset, rebind]);
// The removal must not land after the write, or the new binding is gone on
// the next launch while the row still shows it.
expect(h.cached()).toEqual({ "open-settings": "Mod+2" });
expect(h.persisted()).toEqual({ "open-settings": "Mod+2" });
});
it("finishes each operation before starting the next", async () => {
const h = createHarness();
await Promise.all([h.store.set("a", "Mod+1"), h.store.set("b", "Mod+2")]);
expect(h.events).toEqual([
'cache {"a":"Mod+1"}',
'write {"a":"Mod+1"}',
'cache {"a":"Mod+1","b":"Mod+2"}',
'write {"a":"Mod+1","b":"Mod+2"}',
]);
});
it("keeps running after a failed operation", async () => {
const h = createHarness({ failWrites: [1] });
await h.store.set("a", "Mod+1");
await h.store.set("b", "Mod+2");
expect(h.persisted()).toEqual({ b: "Mod+2" });
});
});
@@ -0,0 +1,116 @@
import { UNASSIGNED_COMBO, type ShortcutOverrides } from "@/keyboard/keyboard-shortcuts";
const EMPTY_OVERRIDES: ShortcutOverrides = {};
/** A binding's stored value, or `undefined` to drop its override entirely. */
export type ShortcutOverrideValue = ShortcutOverrides[string] | undefined;
/** Where the override map is persisted. Async and able to fail. */
export interface ShortcutOverrideStorage {
write(serialized: string): Promise<void>;
remove(): Promise<void>;
}
/** What the UI renders from. Synchronous and always succeeds. */
export interface ShortcutOverrideCache {
read(): ShortcutOverrides;
write(next: ShortcutOverrides): void;
}
export interface ShortcutOverrideStore {
set(bindingId: string, comboString: string): Promise<void>;
/** Unassign the shortcut: it keeps a row in Settings but matches nothing. */
clear(bindingId: string): Promise<void>;
/** Drop the override entirely, restoring the binding's default combo. */
remove(bindingId: string): Promise<void>;
resetAll(): Promise<void>;
}
export interface CreateShortcutOverrideStoreOptions {
storage: ShortcutOverrideStorage;
cache: ShortcutOverrideCache;
onError(err: unknown): void;
}
/**
* Applies override changes to the cache optimistically and persists them,
* reverting the cache if the write fails.
*
* Operations are serialized: each one runs to completion before the next
* starts. Two things go wrong without that ordering, and both end with the
* user's shortcut changing on its own after a restart. Two changes to the same
* binding can interleave so the earlier one's failure rolls back a value the
* later one already persisted; and a Reset all can delete a rebind the user
* made after it, because `remove` and `write` race. Serializing also makes the
* rollback a whole-map restore again — nothing else can have touched the cache
* while the write was in flight.
*
* The cost is that the second of two rapid changes waits one storage
* round-trip before its row updates. Every change here comes from a settings
* row the user has to click through, so that queue is never more than a couple
* of operations deep.
*/
export function createShortcutOverrideStore({
storage,
cache,
onError,
}: CreateShortcutOverrideStoreOptions): ShortcutOverrideStore {
let tail: Promise<void> = Promise.resolve();
function enqueue(operation: () => Promise<void>): Promise<void> {
const run = tail.then(operation);
// A rejected tail would wedge every later operation, so the chain that the
// next caller waits on swallows failures. The returned promise does not.
tail = run.then(noop, noop);
return run;
}
function commit(bindingId: string, value: ShortcutOverrideValue): Promise<void> {
return enqueue(async () => {
const prev = cache.read();
const next = withOverride(prev, bindingId, value);
cache.write(next);
try {
await storage.write(JSON.stringify(next));
} catch (err) {
cache.write(prev);
onError(err);
}
});
}
return {
set: (bindingId, comboString) => commit(bindingId, comboString),
clear: (bindingId) => commit(bindingId, UNASSIGNED_COMBO),
remove: (bindingId) => commit(bindingId, undefined),
resetAll: () =>
enqueue(async () => {
const prev = cache.read();
cache.write(EMPTY_OVERRIDES);
try {
await storage.remove();
} catch (err) {
cache.write(prev);
onError(err);
}
}),
};
}
/**
* `null` (unassigned) and absent (use the default) are distinct states, so
* dropping an override cannot go through a spread.
*/
export function withOverride(
overrides: ShortcutOverrides,
bindingId: string,
value: ShortcutOverrideValue,
): ShortcutOverrides {
if (value === undefined) {
const { [bindingId]: _removed, ...rest } = overrides;
return rest;
}
return { ...overrides, [bindingId]: value };
}
function noop(): void {}
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
import { formatShortcut } from "@/utils/format-shortcut";
import {
comboStringToShortcutKeys,
keyComboToString,
keyboardEventToComboString,
parseShortcutString,
SHORTCUT_KEY_NAMES,
} from "./shortcut-string";
function keyboardEvent(overrides: Partial<KeyboardEvent>): KeyboardEvent {
@@ -68,3 +71,40 @@ describe("parseShortcutString round-trips punctuation keys", () => {
expect(keyComboToString(combo)).toBe("Cmd+-");
});
});
describe("comboStringToShortcutKeys", () => {
it("maps every modifier spelling onto its display token", () => {
expect(comboStringToShortcutKeys("Cmd+Ctrl+Alt+Shift+K")).toEqual([
"mod",
"ctrl",
"alt",
"shift",
"K",
]);
// `parseShortcutString` accepts `Mod` as well, so the display path has to.
expect(comboStringToShortcutKeys("Mod+K")).toEqual(["mod", "K"]);
});
it("hands named keys to the display table under the names it uses", () => {
expect(comboStringToShortcutKeys("Cmd+Shift+ArrowLeft")).toEqual(["mod", "shift", "Left"]);
expect(formatShortcut(comboStringToShortcutKeys("Cmd+Shift+ArrowLeft"), "mac")).toBe(
"Shift+⌘+←",
);
expect(formatShortcut(comboStringToShortcutKeys("Escape"), "mac")).toBe("Esc");
expect(formatShortcut(comboStringToShortcutKeys("Backspace"), "mac")).toBe("⌫");
});
// The whole class, not just the arrows: uppercasing key names used to push
// every multi-character name past `KEY_DISPLAY`, so an override on one of them
// rendered as a shouty raw code — `ARROWLEFT`, `ESCAPE`, `PAGEDOWN`.
it("never emits a shouty raw code for any key the capture path can produce", () => {
for (const name of SHORTCUT_KEY_NAMES) {
// `F1` and the digits are already all-caps, so only names that contain a
// lowercase letter can exhibit the bug.
if (name === name.toUpperCase()) continue;
const [key] = comboStringToShortcutKeys(name);
const rendered = formatShortcut([key], "non-mac");
expect(rendered, `${name} renders as ${rendered}`).not.toBe(name.toUpperCase());
}
});
});
+31 -1
View File
@@ -74,6 +74,13 @@ for (let i = 1; i <= 12; i++) {
KEY_MAP[`F${i}`] = { code: `F${i}` };
}
/**
* Every key name a combo string can carry. Exported so the display path can be
* driven over the whole vocabulary instead of a hand-copied sample that goes
* stale the moment `KEY_MAP` gains an entry.
*/
export const SHORTCUT_KEY_NAMES: readonly string[] = Object.keys(KEY_MAP);
const CODE_TO_KEY: Record<string, string> = {};
for (const [humanKey, mapping] of Object.entries(KEY_MAP)) {
if (!CODE_TO_KEY[mapping.code]) {
@@ -177,6 +184,21 @@ const MODIFIER_CODES = new Set([
"ShiftRight",
]);
/**
* Key names as combo strings spell them, mapped to the names `KEY_DISPLAY` in
* `format-shortcut` is keyed on. The two vocabularies were never reconciled:
* `keyboardEventToComboString` emits `ArrowLeft` and `Escape` (from `KEY_MAP`),
* while the display table only knows `Left` and `Esc`. Without this bridge an
* override on a named key renders as a raw code — `ARROWLEFT`, not `←`.
*/
const DISPLAY_KEY_ALIASES: Record<string, string> = {
ArrowLeft: "Left",
ArrowRight: "Right",
ArrowUp: "Up",
ArrowDown: "Down",
Escape: "Esc",
};
export function comboStringToShortcutKeys(comboString: string): ShortcutKey[] {
const parts = comboString.split("+");
const keys: ShortcutKey[] = [];
@@ -185,6 +207,11 @@ export function comboStringToShortcutKeys(comboString: string): ShortcutKey[] {
case "Cmd":
keys.push("mod");
break;
// `parseShortcutString` accepts `Mod`, so the display path has to as well
// or a combo it can match would render the literal word.
case "Mod":
keys.push("mod");
break;
case "Ctrl":
keys.push("ctrl");
break;
@@ -195,7 +222,10 @@ export function comboStringToShortcutKeys(comboString: string): ShortcutKey[] {
keys.push("shift");
break;
default:
keys.push(part.toUpperCase());
// Pass the key through unchanged. `normalizeKey` already uppercases
// single characters, and uppercasing here is what used to push
// multi-character names past `KEY_DISPLAY` into raw output.
keys.push(DISPLAY_KEY_ALIASES[part] ?? part);
break;
}
}
@@ -71,7 +71,7 @@ export function hostProjectFromWorkspace(input: {
serverId: input.serverId,
projectId,
}),
projectKey: null,
projectKey: input.workspace.project?.projectKey ?? null,
projectName: input.workspace.projectDisplayName || projectId,
projectKind: input.workspace.projectKind,
iconWorkingDir,
@@ -6,7 +6,9 @@ import {
getHostProjectSourceDirectory,
getWorktreeSupportForHostProject,
hostProjectFromRoute,
hostProjectFromWorkspace,
} from "./host-project-model";
import { normalizeWorkspaceDescriptor } from "@/stores/session-store";
function project(): HostProjectListItem {
return {
@@ -95,4 +97,42 @@ describe("host project lookups", () => {
hosts: [{ serverId: "host-a", projectId: "prj_a" }],
});
});
test("keeps canonical equivalence identity separate from host placement identity", () => {
const workspace = normalizeWorkspaceDescriptor({
id: "workspace-a",
projectId: "project-a",
projectDisplayName: "App",
projectRootPath: "/repo/app",
workspaceDirectory: "/repo/app",
projectKind: "git",
workspaceKind: "local_checkout",
name: "main",
archivingAt: null,
status: "done",
statusEnteredAt: null,
activityAt: null,
diffStat: null,
scripts: [],
project: {
projectKey: "remote:github.com/acme/app",
projectName: "App",
checkout: {
cwd: "/repo/app",
isGit: true,
currentBranch: "main",
remoteUrl: "https://github.com/acme/app.git",
worktreeRoot: "/repo/app",
isPaseoOwnedWorktree: false,
mainRepoRoot: null,
},
},
});
expect(hostProjectFromWorkspace({ serverId: "host-a", workspace })).toMatchObject({
viewKey: JSON.stringify(["host-a", "project-a"]),
projectKey: "remote:github.com/acme/app",
hosts: [{ serverId: "host-a", projectId: "project-a" }],
});
});
});
+2 -28
View File
@@ -16,6 +16,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { Shortcut } from "@/components/ui/shortcut";
import { isWeb } from "@/constants/platform";
import { useHasFinePointer } from "@/hooks/use-fine-pointer";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import type { Theme } from "@/styles/theme";
import type { ShortcutKey } from "@/utils/format-shortcut";
@@ -46,33 +47,6 @@ function getWebTextInputElement(input: TextInput | null): HTMLElement | null {
return element instanceof HTMLElement ? element : null;
}
function getCanShowReviewKeyboardHints(): boolean {
if (!isWeb || typeof window === "undefined" || typeof window.matchMedia !== "function") {
return false;
}
return window.matchMedia("(hover: hover) and (pointer: fine)").matches;
}
function useCanShowReviewKeyboardHints(): boolean {
const [canShowHints, setCanShowHints] = useState(getCanShowReviewKeyboardHints);
useEffect(() => {
if (!isWeb || typeof window === "undefined" || typeof window.matchMedia !== "function") {
return;
}
const mediaQuery = window.matchMedia("(hover: hover) and (pointer: fine)");
const handleChange = () => setCanShowHints(mediaQuery.matches);
handleChange();
mediaQuery.addEventListener?.("change", handleChange);
return () => {
mediaQuery.removeEventListener?.("change", handleChange);
};
}, []);
return canShowHints;
}
export const INLINE_REVIEW_COMMENT_HEIGHT = 72;
export const INLINE_REVIEW_EDITOR_HEIGHT = 132;
const INLINE_REVIEW_GAP = 6;
@@ -533,7 +507,7 @@ export function InlineReviewEditor({
const { t } = useTranslation();
const inputRef = useRef<TextInput | null>(null);
const focus = useWorkspaceFocusRestoration();
const canShowKeyboardHints = useCanShowReviewKeyboardHints();
const canShowKeyboardHints = useHasFinePointer();
const [body, setBody] = useState(initialBody);
const [isFocused, setIsFocused] = useState(false);
const trimmedBody = body.trim();
@@ -3042,7 +3042,7 @@ describe("HostRuntimeStore", () => {
}
});
it("upsertDirectConnection stores SSL, password, and custom header settings", async () => {
it("upsertDirectConnection stores SSL and password settings", async () => {
const store = new HostRuntimeStore({
deps: {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
@@ -3060,7 +3060,6 @@ describe("HostRuntimeStore", () => {
endpoint: "example.paseo.test:7443",
useTls: true,
password: "shared-secret",
headers: { "X-Tenant": "acme" },
label: "tls host",
});
@@ -3072,7 +3071,6 @@ describe("HostRuntimeStore", () => {
endpoint: "example.paseo.test:7443",
useTls: true,
password: "shared-secret",
headers: { "X-Tenant": "acme" },
},
]);
+1 -12
View File
@@ -36,7 +36,6 @@ import {
import {
buildLocalDaemonTransportUrl,
createDesktopLocalDaemonTransportFactory,
createDesktopWebSocketTransportFactory,
} from "@/desktop/daemon/desktop-daemon-transport";
import { getDesktopHost } from "@/desktop/host";
import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities";
@@ -479,10 +478,7 @@ function createDefaultDeps(): HostRuntimeControllerDeps {
return {
createClient: ({ host, connection, clientId, runtimeGeneration }) => {
const localTransportFactory = createDesktopLocalDaemonTransportFactory();
const webSocketTransportFactory = createDesktopWebSocketTransportFactory();
const webSocketConfig = webSocketTransportFactory
? { transportFactory: webSocketTransportFactory }
: { webSocketFactory: createAppWebSocketFactory() };
const webSocketConfig = { webSocketFactory: createAppWebSocketFactory() };
const base = {
suppressSendErrors: true,
clientId,
@@ -510,7 +506,6 @@ function createDefaultDeps(): HostRuntimeControllerDeps {
useTls: connection.useTls ?? false,
}),
...(connection.password ? { password: connection.password } : {}),
...(connection.headers ? { headers: connection.headers } : {}),
});
}
return new DaemonClient({
@@ -1651,7 +1646,6 @@ export class HostRuntimeStore {
endpoint: string;
useTls?: boolean;
password?: string;
headers?: Record<string, string>;
label?: string;
existingClient?: DaemonClient;
}): Promise<HostProfile> {
@@ -1666,7 +1660,6 @@ export class HostRuntimeStore {
endpoint,
useTls: input.useTls ?? false,
...(password ? { password } : {}),
...(input.headers ? { headers: input.headers } : {}),
},
existingClient: input.existingClient,
});
@@ -1708,7 +1701,6 @@ export class HostRuntimeStore {
endpoint: string;
useTls?: boolean;
password?: string;
headers?: Record<string, string>;
label?: string;
}): Promise<{ profile: HostProfile; serverId: string; hostname: string | null }> {
const endpoint = normalizeHostPort(input.endpoint);
@@ -1721,7 +1713,6 @@ export class HostRuntimeStore {
endpoint,
useTls: input.useTls ?? false,
...(password ? { password } : {}),
...(input.headers ? { headers: input.headers } : {}),
},
});
}
@@ -2463,14 +2454,12 @@ export interface HostMutations {
endpoint: string;
useTls?: boolean;
password?: string;
headers?: Record<string, string>;
label?: string;
}) => Promise<HostProfile>;
probeAndUpsertDirectConnection: (input: {
endpoint: string;
useTls?: boolean;
password?: string;
headers?: Record<string, string>;
label?: string;
}) => Promise<{ profile: HostProfile; serverId: string; hostname: string | null }>;
upsertRelayConnection: (input: {

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