Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 3a3751f1bf test(server): distinguish Hub execution sessions 2026-08-09 02:39:21 +02:00
Mohamed Boudra cb4976289b test(server): exclude internal sessions from Hub counts 2026-08-09 02:26:55 +02:00
Mohamed Boudra 2668f31e07 fix(nix): refresh npm dependency hash 2026-08-09 02:06:43 +02:00
Mohamed Boudra be523e09e9 feat(plugins): add Linear attachment source 2026-08-09 01:53:55 +02:00
Mohamed Boudra 1c41ba0bee feat(plugins): add local plugin surfaces and RPCs
Keep plugin execution scoped to its daemon while allowing one local TypeScript entry point to contribute validated RPCs and native client surfaces. Paseo owns host selection, navigation chrome, and per-installation query caches.
2026-08-09 01:53:55 +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
244 changed files with 14548 additions and 2107 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.
+2
View File
@@ -40,6 +40,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/providers.md](docs/providers.md) | Adding a new agent provider end-to-end |
| [docs/forge-providers.md](docs/forge-providers.md) | Adding a git forge: registry/manifest, drop-in checklist, self-host/GHES, the two facts tiers |
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
| [docs/service-proxy.md](docs/service-proxy.md) | Service proxy: exposing workspace scripts at public URLs, DNS setup, reverse proxy config |
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
@@ -57,6 +58,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
+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.
+135
View File
@@ -0,0 +1,135 @@
# Local plugins
Local plugins contribute daemon RPCs, native app surfaces, and composer attachment sources from one
`index.tsx`. Paseo executes the server contribution in a subprocess and evaluates the client
contribution in the app runtime. Plugin code is trusted code; this first slice does not sandbox it.
## Configure a directory source
Add the plugin to the root `plugins` object in `$PASEO_HOME/config.json`:
```json
{
"plugins": {
"my-plugin": {
"source": "directory",
"path": "/absolute/path/to/my-plugin"
}
}
}
```
The directory contains an identity-only manifest and one entry point:
```text
my-plugin/
paseo-plugin.json
index.tsx
```
```json
{
"id": "my-plugin"
}
```
The manifest ID must match the config key. Restart the development daemon after changing plugin
source or configuration; directory watching is outside the first slice.
## Contribute behavior and UI
Default export one contribution function. Paseo calls it with a plugin-scoped context. The compiler
removes UI registrations from the server bundle and RPC registrations from the client bundle before
resolving dependencies.
```tsx
import { Text } from "react-native";
import { useQuery } from "@tanstack/react-query";
import { z } from "zod";
import { defineRpc, type PluginContext, useRpc } from "@paseo/plugin";
const greetRpc = defineRpc({
name: "greet",
input: z.object({ name: z.string() }),
output: z.object({ message: z.string() }),
});
function Greeting() {
const greet = useRpc(greetRpc);
const query = useQuery({
queryKey: ["greeting", "Paseo"],
queryFn: () => greet({ name: "Paseo" }),
});
return <Text>{query.data?.message}</Text>;
}
export default function contribute(plugin: PluginContext) {
plugin.handle(greetRpc, async ({ name }) => ({ message: `Hello, ${name}` }));
plugin.addSurface("main", Greeting);
plugin.addSidebarItem({
id: "main",
title: "Greeting",
icon: "MessageCircle",
surface: "main",
});
}
```
Paseo owns the route, screen header, Lucide icon validation, close action, theme DTO, layout facts,
and render error boundary. The contributed component owns the complete body below the header.
RPC contracts validate inputs and outputs in both the app and plugin subprocess. `useRpc` returns a
typed async function. Use the host-provided `@tanstack/react-query` for request state and caching;
Paseo gives each plugin installation its own query client.
When the same plugin contribution exists on multiple hosts, Paseo shows it once in the sidebar and
adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and
query cache. Plugin code cannot address another host.
## Contribute composer attachments
Register a declarative attachment source backed by a plugin RPC. Paseo owns the attachment menu,
search picker, drafts, selected pill, and submission. The plugin returns complete text snapshots;
credentials and vendor API calls stay in the daemon handler.
```tsx
const searchIssues = defineRpc({
name: "issues.search",
input: z.object({ query: z.string() }),
output: z.object({
items: z.array(
z.object({
id: z.string(),
identifier: z.string(),
title: z.string(),
subtitle: z.string().optional(),
url: z.string().url(),
text: z.string(),
resourceType: z.string(),
}),
),
}),
});
const issues = defineAttachmentSource({
id: "issues",
title: "Acme issue",
icon: "CircleDot",
pickerTitle: "Attach Acme issue",
searchPlaceholder: "Search by identifier or title",
search: searchIssues,
});
export default function contribute(plugin: PluginContext) {
plugin.handle(searchIssues, ({ query }) => searchAcmeIssues(query));
plugin.addAttachmentSource(issues);
}
```
Attachment sources stay scoped to the composer's host. Unlike sidebar contributions, equal sources
on several hosts are not coalesced. The selected snapshot submits as a text attachment with neutral
external-resource presentation, so it remains readable if the plugin is removed or an older peer
drops the optional presentation fields.
See `examples/local-plugin` for a native surface and `extensions/linear` for a complete official
attachment-source extension.
+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
+74
View File
@@ -0,0 +1,74 @@
import React, { useCallback, useMemo } from "react";
import { Pressable, Text, View } from "react-native";
import { useMutation } from "@tanstack/react-query";
import { z } from "zod";
import { defineRpc, type PluginContext, useRpc } from "@paseo/plugin";
const incrementRpc = defineRpc({
name: "increment",
input: z.object({ value: z.number() }),
output: z.object({ value: z.number(), handledBy: z.string() }),
});
interface ExampleTheme {
colors: {
surface0: string;
foreground: string;
foregroundMuted: string;
accent: string;
accentForeground: string;
statusDanger: string;
};
}
function ExampleSurface({ theme }: { theme: ExampleTheme }) {
const callIncrement = useRpc(incrementRpc);
const { data, error, isPending, mutate } = useMutation({ mutationFn: callIncrement });
const value = data?.value ?? 0;
const styles = useMemo(
() => ({
screen: { flex: 1, padding: 24, gap: 16, backgroundColor: theme.colors.surface0 },
title: { color: theme.colors.foreground, fontSize: 24 },
detail: { color: theme.colors.foregroundMuted },
button: { padding: 14, borderRadius: 10, backgroundColor: theme.colors.accent },
buttonText: { color: theme.colors.accentForeground, textAlign: "center" },
error: { color: theme.colors.statusDanger },
}),
[theme.colors],
);
const handleIncrement = useCallback(() => {
mutate({ value });
}, [mutate, value]);
return (
<View style={styles.screen}>
<Text style={styles.title}>Native plugin surface</Text>
<Text style={styles.detail}>{data?.handledBy ?? "The RPC has not run yet."}</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Increment plugin counter, currently ${value}`}
onPress={handleIncrement}
style={styles.button}
>
<Text style={styles.buttonText}>
{isPending ? "Calling daemon…" : `RPC counter: ${value}`}
</Text>
</Pressable>
{error ? <Text style={styles.error}>{error.message}</Text> : null}
</View>
);
}
export default function contribute(plugin: PluginContext) {
plugin.handle(incrementRpc, async (input) => ({
value: input.value + 1,
handledBy: "plugin subprocess",
}));
plugin.addSurface("main", ExampleSurface);
plugin.addSidebarItem({
id: "main",
title: "Local plugin",
icon: "Blocks",
surface: "main",
});
}
+3
View File
@@ -0,0 +1,3 @@
{
"id": "local-example"
}
+32
View File
@@ -0,0 +1,32 @@
# Linear
The official Linear extension adds `Attach Linear issue` to the composer. Search by issue identifier
or title, then send a stable issue snapshot to the agent.
Set a personal API key in the daemon environment:
```bash
export LINEAR_API_KEY="lin_api_..."
```
Register the extension in `$PASEO_HOME/config.json`:
```json
{
"plugins": {
"linear": {
"source": "directory",
"path": "/absolute/path/to/paseo/extensions/linear"
}
}
}
```
Restart the development daemon after changing its environment or plugin configuration.
The entry point demonstrates the complete attachment-source pattern:
- define one validated search RPC;
- handle it in the daemon subprocess;
- register a declarative attachment source for the client;
- keep credentials and vendor API calls out of the client bundle.
+45
View File
@@ -0,0 +1,45 @@
import { z } from "zod";
import {
defineAttachmentSource,
defineRpc,
type PluginAttachmentSearchPayload,
type PluginContext,
} from "@paseo/plugin";
import { createLinearIssueSearch } from "./linear";
const SearchPayloadSchema = z.object({
items: z.array(
z.object({
id: z.string(),
identifier: z.string(),
title: z.string(),
subtitle: z.string().optional(),
url: z.string().url(),
text: z.string(),
resourceType: z.string(),
}),
),
});
const searchIssues = defineRpc({
name: "issues.search",
input: z.object({ query: z.string() }),
output: SearchPayloadSchema,
});
const issueAttachments = defineAttachmentSource({
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search by identifier or title",
search: searchIssues,
});
export default function contribute(plugin: PluginContext) {
plugin.handle(searchIssues, async ({ query }): Promise<PluginAttachmentSearchPayload> => {
const linear = createLinearIssueSearch({ apiKey: process.env.LINEAR_API_KEY ?? "" });
return linear.search(query);
});
plugin.addAttachmentSource(issueAttachments);
}
+135
View File
@@ -0,0 +1,135 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
import { describe, expect, it } from "vitest";
import { createLinearIssueSearch } from "./linear";
const issue = {
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
description: "Let extensions attach external context.",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
priorityLabel: "High",
state: { name: "In Progress" },
assignee: { name: "Mohamed" },
project: { name: "Paseo" },
labels: { nodes: [{ name: "Feature" }] },
};
interface CapturedRequest {
authorization: string | undefined;
body: { query: string; variables: Record<string, unknown> };
}
async function readRequest(request: IncomingMessage): Promise<CapturedRequest> {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
return {
authorization: request.headers.authorization,
body: JSON.parse(Buffer.concat(chunks).toString("utf8")) as CapturedRequest["body"],
};
}
async function withLinearServer<T>(
respond: (request: CapturedRequest, response: ServerResponse) => void,
run: (endpoint: string) => Promise<T>,
): Promise<T> {
const server = createServer((request, response) => {
void readRequest(request).then((captured) => respond(captured, response));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as AddressInfo;
try {
return await run(`http://127.0.0.1:${address.port}/graphql`);
} finally {
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
}
function sendJson(response: ServerResponse, body: unknown): void {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(body));
}
describe("Linear issue search", () => {
it("resolves an exact issue identifier and formats its agent snapshot", async () => {
const result = await withLinearServer(
(request, response) => {
expect(request.authorization).toBe("lin_api_test");
expect(request.body.variables).toEqual({ id: "ENG-123" });
sendJson(response, { data: { issue } });
},
async (endpoint) => {
const linear = createLinearIssueSearch({ apiKey: "lin_api_test", endpoint });
return linear.search("eng-123");
},
);
expect(result).toEqual({
items: [
{
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
subtitle: "In Progress · Mohamed",
url: issue.url,
resourceType: "issue",
text: [
"Linear issue ENG-123: Plugin attachments",
`URL: ${issue.url}`,
"Status: In Progress",
"Priority: High",
"Assignee: Mohamed",
"Project: Paseo",
"Labels: Feature",
"",
"Let extensions attach external context.",
].join("\n"),
},
],
});
});
it("searches issue titles through a case-insensitive filter", async () => {
const result = await withLinearServer(
(request, response) => {
expect(request.body.variables).toEqual({
filter: { title: { containsIgnoreCase: "plugin" } },
});
sendJson(response, { data: { issues: { nodes: [issue] } } });
},
async (endpoint) => {
const linear = createLinearIssueSearch({ apiKey: "lin_api_test", endpoint });
return linear.search(" plugin ");
},
);
expect(result.items.map((item) => item.identifier)).toEqual(["ENG-123"]);
});
it("surfaces GraphQL errors even when HTTP succeeds", async () => {
await expect(
withLinearServer(
(_request, response) => sendJson(response, { errors: [{ message: "Token expired" }] }),
async (endpoint) => {
const linear = createLinearIssueSearch({ apiKey: "lin_api_test", endpoint });
return linear.search("ENG-123");
},
),
).rejects.toThrow("Token expired");
});
it("requires a daemon-side API key", () => {
expect(() => createLinearIssueSearch({ apiKey: "" })).toThrow(
"Set LINEAR_API_KEY in the daemon environment",
);
});
});
+183
View File
@@ -0,0 +1,183 @@
import { z } from "zod";
const LinearIssueSchema = z.object({
id: z.string(),
identifier: z.string(),
title: z.string(),
description: z.string().nullable(),
url: z.string(),
priorityLabel: z.string(),
state: z.object({ name: z.string() }),
assignee: z.object({ name: z.string() }).nullable(),
project: z.object({ name: z.string() }).nullable(),
labels: z.object({ nodes: z.array(z.object({ name: z.string() })) }),
});
const LinearGraphqlErrorSchema = z.object({ message: z.string() }).passthrough();
const ExactIssueResponseSchema = z.object({
data: z.object({ issue: LinearIssueSchema.nullable() }).nullable().optional(),
errors: z.array(LinearGraphqlErrorSchema).optional(),
});
const IssueSearchResponseSchema = z.object({
data: z
.object({ issues: z.object({ nodes: z.array(LinearIssueSchema) }) })
.nullable()
.optional(),
errors: z.array(LinearGraphqlErrorSchema).optional(),
});
const ISSUE_FIELDS = `
id
identifier
title
description
url
priorityLabel
state { name }
assignee { name }
project { name }
labels { nodes { name } }
`;
const EXACT_ISSUE_QUERY = `
query PaseoLinearIssue($id: String!) {
issue(id: $id) { ${ISSUE_FIELDS} }
}
`;
const SEARCH_ISSUES_QUERY = `
query PaseoLinearIssues($filter: IssueFilter) {
issues(first: 20, filter: $filter, orderBy: updatedAt) {
nodes { ${ISSUE_FIELDS} }
}
}
`;
const LINEAR_IDENTIFIER = /^[A-Z][A-Z0-9]+-\d+$/i;
export interface LinearAttachmentItem {
id: string;
identifier: string;
title: string;
subtitle?: string;
url: string;
text: string;
resourceType: string;
}
export interface LinearIssueSearch {
search(query: string): Promise<{ items: LinearAttachmentItem[] }>;
}
interface LinearIssueSearchOptions {
apiKey: string;
endpoint?: string;
request?: typeof fetch;
}
interface GraphqlRequest {
query: string;
variables: Record<string, unknown>;
}
class LinearApiError extends Error {
constructor(message: string) {
super(message);
this.name = "LinearApiError";
}
}
function issueSubtitle(issue: z.infer<typeof LinearIssueSchema>): string | undefined {
const parts = [issue.state.name, issue.assignee?.name].filter(
(part): part is string => typeof part === "string" && part.length > 0,
);
return parts.length > 0 ? parts.join(" · ") : undefined;
}
function issueText(issue: z.infer<typeof LinearIssueSchema>): string {
const labels = issue.labels.nodes.map((label) => label.name).join(", ");
const lines = [
`Linear issue ${issue.identifier}: ${issue.title}`,
`URL: ${issue.url}`,
`Status: ${issue.state.name}`,
`Priority: ${issue.priorityLabel}`,
];
if (issue.assignee) lines.push(`Assignee: ${issue.assignee.name}`);
if (issue.project) lines.push(`Project: ${issue.project.name}`);
if (labels) lines.push(`Labels: ${labels}`);
lines.push("", issue.description ?? "No description.");
return lines.join("\n");
}
function toAttachmentItem(issue: z.infer<typeof LinearIssueSchema>): LinearAttachmentItem {
const subtitle = issueSubtitle(issue);
return {
id: issue.id,
identifier: issue.identifier,
title: issue.title,
...(subtitle ? { subtitle } : {}),
url: issue.url,
text: issueText(issue),
resourceType: "issue",
};
}
function describeHttpFailure(status: number): string {
if (status === 401 || status === 403) return "Linear rejected LINEAR_API_KEY";
if (status === 429) return "Linear rate limit reached. Try again shortly";
return `Linear API request failed with HTTP ${status}`;
}
function throwGraphqlErrors(errors: Array<{ message: string }> | undefined): void {
if (!errors || errors.length === 0) return;
throw new LinearApiError(errors.map((error) => error.message).join("; "));
}
export function createLinearIssueSearch(options: LinearIssueSearchOptions): LinearIssueSearch {
const apiKey = options.apiKey.trim();
if (!apiKey) throw new LinearApiError("Set LINEAR_API_KEY in the daemon environment");
const endpoint = options.endpoint ?? "https://api.linear.app/graphql";
const request = options.request ?? fetch;
async function graphql(body: GraphqlRequest): Promise<unknown> {
const response = await request(endpoint, {
method: "POST",
headers: {
Authorization: apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new LinearApiError(describeHttpFailure(response.status));
return response.json();
}
async function findExact(identifier: string): Promise<LinearAttachmentItem[]> {
const response = ExactIssueResponseSchema.parse(
await graphql({ query: EXACT_ISSUE_QUERY, variables: { id: identifier } }),
);
throwGraphqlErrors(response.errors);
return response.data?.issue ? [toAttachmentItem(response.data.issue)] : [];
}
async function searchTitles(query: string): Promise<LinearAttachmentItem[]> {
const filter = query ? { title: { containsIgnoreCase: query } } : null;
const response = IssueSearchResponseSchema.parse(
await graphql({ query: SEARCH_ISSUES_QUERY, variables: { filter } }),
);
throwGraphqlErrors(response.errors);
if (!response.data) throw new LinearApiError("Linear returned no issue data");
return response.data.issues.nodes.map(toAttachmentItem);
}
return {
async search(query: string) {
const normalized = query.trim();
if (LINEAR_IDENTIFIER.test(normalized)) {
return { items: await findExact(normalized.toUpperCase()) };
}
const items = await searchTitles(normalized);
return { items };
},
};
}
+3
View File
@@ -0,0 +1,3 @@
{
"id": "linear"
}
+1 -1
View File
@@ -1 +1 @@
sha256-MDuVQQ5DmNoPlb9+LlrZYxGbP+22rYpfhcDJQxmIUsU=
sha256-BfRbfVUFaHQEMtDOsWAo49txz+cueRpe/7Qxltg+HSg=
+531
View File
@@ -2291,6 +2291,15 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/standalone": {
"version": "7.29.1",
"resolved": "https://registry.npmjs.org/@babel/standalone/-/standalone-7.29.1.tgz",
"integrity": "sha512-z42abD0C6fiHfgLyCWw8PYv6FCJ0IGVtSCxXk/NPykWO5LNIEGfdLDJ3HdYqlPcAhwtQ3oKH1PvNj2JGpTxQKg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
"version": "7.28.6",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
@@ -12503,6 +12512,21 @@
"@babel/types": "^7.0.0"
}
},
"node_modules/@types/babel__standalone": {
"version": "7.1.9",
"resolved": "https://registry.npmjs.org/@types/babel__standalone/-/babel__standalone-7.1.9.tgz",
"integrity": "sha512-IcCNPLqpevUD7UpV8QB0uwQPOyoOKACFf0YtYWRHcmxcakaje4Q7dbG2+jMqxw/I8Zk0NHvEps66WwS7z/UaaA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.25.6",
"@babel/types": "^7.25.6",
"@types/babel__core": "^7.20.5",
"@types/babel__generator": "^7.6.8",
"@types/babel__template": "^7.4.4",
"@types/babel__traverse": "^7.20.6"
}
},
"node_modules/@types/babel__template": {
"version": "7.4.4",
"resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
@@ -35301,6 +35325,7 @@
"name": "@getpaseo/app",
"version": "0.3.0",
"dependencies": {
"@babel/standalone": "^7.29.1",
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
"@codemirror/search": "6.7.1",
@@ -35393,6 +35418,7 @@
"@playwright/test": "^1.56.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.2",
"@types/babel__standalone": "^7.1.9",
"@types/markdown-it": "^14.1.2",
"@types/qrcode": "^1.5.6",
"@types/react": "~19.2.0",
@@ -38226,6 +38252,7 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.220",
"@anthropic-ai/sdk": "^0.104.2",
"@babel/parser": "^7.29.8",
"@getpaseo/client": "0.3.0",
"@getpaseo/highlight": "0.3.0",
"@getpaseo/protocol": "0.3.0",
@@ -38239,6 +38266,7 @@
"ajv": "^8.20.0",
"bcryptjs": "^3.0.3",
"dotenv": "^17.2.3",
"esbuild": "^0.25.12",
"express": "^4.18.2",
"fast-deep-equal": "^3.1.3",
"lru-cache": "^11.5.1",
@@ -38402,6 +38430,468 @@
"win32"
]
},
"packages/server/node_modules/@babel/helper-string-parser": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"packages/server/node_modules/@babel/helper-validator-identifier": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"packages/server/node_modules/@babel/parser": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
"integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.8"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"packages/server/node_modules/@babel/types": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/android-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/android-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/android-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/darwin-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/darwin-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/freebsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/freebsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-loong64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
"cpu": [
"loong64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-mips64el": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
"cpu": [
"mips64el"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-riscv64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
"cpu": [
"riscv64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-s390x": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
"cpu": [
"s390x"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/linux-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/netbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/openbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/openharmony-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/sunos-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/win32-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/win32-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@esbuild/win32-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"packages/server/node_modules/@isaacs/ttlcache": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@isaacs/ttlcache/-/ttlcache-2.1.4.tgz",
@@ -38556,6 +39046,47 @@
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"packages/server/node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.25.12",
"@esbuild/android-arm": "0.25.12",
"@esbuild/android-arm64": "0.25.12",
"@esbuild/android-x64": "0.25.12",
"@esbuild/darwin-arm64": "0.25.12",
"@esbuild/darwin-x64": "0.25.12",
"@esbuild/freebsd-arm64": "0.25.12",
"@esbuild/freebsd-x64": "0.25.12",
"@esbuild/linux-arm": "0.25.12",
"@esbuild/linux-arm64": "0.25.12",
"@esbuild/linux-ia32": "0.25.12",
"@esbuild/linux-loong64": "0.25.12",
"@esbuild/linux-mips64el": "0.25.12",
"@esbuild/linux-ppc64": "0.25.12",
"@esbuild/linux-riscv64": "0.25.12",
"@esbuild/linux-s390x": "0.25.12",
"@esbuild/linux-x64": "0.25.12",
"@esbuild/netbsd-arm64": "0.25.12",
"@esbuild/netbsd-x64": "0.25.12",
"@esbuild/openbsd-arm64": "0.25.12",
"@esbuild/openbsd-x64": "0.25.12",
"@esbuild/openharmony-arm64": "0.25.12",
"@esbuild/sunos-x64": "0.25.12",
"@esbuild/win32-arm64": "0.25.12",
"@esbuild/win32-ia32": "0.25.12",
"@esbuild/win32-x64": "0.25.12"
}
},
"packages/server/node_modules/isexe": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
@@ -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");
});
@@ -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.',
},
@@ -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();
}
});
});
@@ -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" });
+2
View File
@@ -32,6 +32,7 @@
"build:terminal-webview": "node ./scripts/build-terminal-webview-html.mjs"
},
"dependencies": {
"@babel/standalone": "^7.29.1",
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
"@codemirror/search": "6.7.1",
@@ -124,6 +125,7 @@
"@playwright/test": "^1.56.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.2",
"@types/babel__standalone": "^7.1.9",
"@types/markdown-it": "^14.1.2",
"@types/qrcode": "^1.5.6",
"@types/react": "~19.2.0",
+22 -19
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";
@@ -123,6 +124,7 @@ import {
} from "@/utils/host-routes";
import { buildNotificationRoute, resolveNotificationTarget } from "@/utils/notification-routing";
import { navigateToAgent } from "@/utils/navigate-to-agent";
import { PluginCatalogSync } from "@/plugins/catalog-sync";
import {
ensureOsNotificationPermission,
WEB_NOTIFICATION_CLICK_EVENT,
@@ -265,7 +267,7 @@ function ManagedDaemonSession({ daemon }: { daemon: HostProfile }) {
return (
<SessionProvider key={daemon.serverId} serverId={daemon.serverId} client={client}>
{null}
<PluginCatalogSync serverId={daemon.serverId} client={client} />
</SessionProvider>
);
}
@@ -643,7 +645,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 +670,7 @@ function ProvidersWrapper({ children }: { children: ReactNode }) {
<OfferLinkListener upsertDaemonFromOfferUrl={upsertConnectionFromOfferUrl} />
<HostSessionManager />
<FaviconStatusSync />
{children}
<AppearanceStyleBoundary>{children}</AppearanceStyleBoundary>
</VoiceProvider>
);
}
@@ -891,6 +893,7 @@ function RootStack() {
return (
<ThemedStack screenOptions={ROOT_STACK_SCREEN_OPTIONS}>
<Stack.Screen name="index" />
<Stack.Screen name="runtime-component" />
<Stack.Protected guard={storeReady}>
<Stack.Screen name="welcome" />
<Stack.Screen name="settings/index" />
@@ -954,19 +957,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 +999,11 @@ export default function RootLayout() {
return (
<QueryProvider>
<I18nProvider>
<RootErrorBoundary>
<RootAppTree />
</RootErrorBoundary>
<SafeAreaProvider>
<RootErrorBoundary>
<RootAppTree />
</RootErrorBoundary>
</SafeAreaProvider>
</I18nProvider>
</QueryProvider>
);
@@ -41,6 +41,7 @@ function KnownHostRoute() {
<Stack.Screen name="sessions" />
<Stack.Screen name="open-project" />
<Stack.Screen name="settings" />
<Stack.Screen name="plugin/[pluginId]/[surfaceId]" />
</ThemedStack>
);
@@ -0,0 +1,5 @@
import { PluginSurfaceScreen } from "@/plugins/surface-screen";
export default function PluginSurfaceRoute() {
return <PluginSurfaceScreen />;
}
@@ -0,0 +1,5 @@
import { RuntimeComponentPrototypeScreen } from "@/runtime-component/prototype-screen";
export default function RuntimeComponentRoute() {
return <RuntimeComponentPrototypeScreen />;
}
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import { getAgentAttachmentPillContent } from "./attachment-pill-content";
describe("agent attachment pill content", () => {
it("presents external resources with their provider identity", () => {
const content = getAgentAttachmentPillContent(
{
type: "text",
mimeType: "text/plain",
title: "ENG-123 Plugin attachments",
text: "Linear issue ENG-123: Plugin attachments",
externalResource: {
provider: "linear",
providerLabel: "Linear issue",
resourceType: "issue",
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
},
},
i18n.t,
);
expect(content.title).toBe("Plugin attachments");
expect(content.subtitle).toBe("Linear issue ENG-123");
});
});
@@ -1,5 +1,6 @@
import type { ReactNode } from "react";
import type { TFunction } from "i18next";
import React from "react";
import {
CircleDot,
FileText,
@@ -86,6 +87,13 @@ export function getAgentAttachmentPillContent(
subtitle: `Issue #${attachment.number}`,
};
case "text":
if (attachment.externalResource) {
return {
icon: attachmentGithubIssueIcon,
title: attachment.externalResource.title,
subtitle: `${attachment.externalResource.providerLabel} ${attachment.externalResource.identifier}`,
};
}
return {
icon: attachmentFileIcon,
title: attachment.title ?? t("message.attachments.textAttachment"),
+2
View File
@@ -3,6 +3,7 @@ import type {
ForgeSearchItem,
UploadedFileAttachment,
} from "@getpaseo/protocol/messages";
import type { PluginResourceComposerAttachment } from "@/plugins/attachments/model";
export type AttachmentStorageType = "web-indexeddb" | "desktop-file" | "native-file";
@@ -106,6 +107,7 @@ export type UserComposerAttachment =
| { kind: "image"; metadata: AttachmentMetadata }
| { kind: "file"; attachment: UploadedFileAttachment }
| WorkspaceFileComposerAttachment
| PluginResourceComposerAttachment
| { kind: "forge_issue"; item: ForgeSearchItem }
| { kind: "forge_change_request"; item: ForgeSearchItem }
// COMPAT(githubAttachmentKinds): added in v0.1.106, remove after 2026-12-28 once daemon floor >= v0.1.106
@@ -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,
@@ -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"
/>
@@ -8,7 +8,11 @@ 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 { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
const SNAP_POINTS: string[] = ["70%", "92%"];
@@ -42,9 +46,13 @@ 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(() => {
const normalizedQuery = query.trim().toLocaleLowerCase();
+33 -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";
@@ -69,6 +74,7 @@ import type { ShortcutKey } from "@/utils/format-shortcut";
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
import { SidebarWorkspaceList } from "./sidebar-workspace-list";
import { PluginSidebarItems } from "@/plugins/sidebar-items";
type SidebarTheme = ReturnType<typeof useUnistyles>["theme"];
@@ -673,6 +679,7 @@ function MobileSidebar({
testID="sidebar-schedules"
variant="compact"
/>
<PluginSidebarItems onBeforeNavigate={closeSidebar} />
</View>
<WindowChromeSafeArea placement="inline" style={styles.mobileCloseButtonRow}>
<Pressable
@@ -771,6 +778,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 +790,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 +812,18 @@ function DesktopSidebar({
})
.onEnd(() => {
runOnJS(setSidebarWidth)(resizeWidth.value);
})
.onFinalize(() => {
scheduleOnRN(hideResizeGrip);
}),
[resizeWidth, setSidebarWidth, viewportWidth, visibleSidebarWidth],
[
hideResizeGrip,
resizeWidth,
setSidebarWidth,
showResizeGrip,
viewportWidth,
visibleSidebarWidth,
],
);
const resizeAnimatedStyle = useAnimatedStyle(() => ({
@@ -857,6 +885,7 @@ function DesktopSidebar({
testID="sidebar-schedules"
variant="compact"
/>
<PluginSidebarItems />
</View>
</View>
@@ -894,6 +923,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"> & {
@@ -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],
},
}));
@@ -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) {
+29
View File
@@ -863,6 +863,35 @@ describe("openComposerAttachment", () => {
});
expect(externalUrlCalls).toEqual([issueItem.url]);
});
it("opens plugin resource URLs through the external url opener", () => {
const externalUrlCalls: string[] = [];
openComposerAttachment({
attachment: {
kind: "plugin_resource",
pluginId: "linear",
sourceId: "issues",
sourceTitle: "Linear issue",
sourceIcon: "CircleDot",
item: {
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
text: "Linear issue ENG-123: Plugin attachments",
resourceType: "issue",
},
},
setLightboxMetadata: () => {
throw new Error("unexpected lightbox call");
},
openWorkspaceAttachment: () => false,
openExternalUrl: (url) => {
externalUrlCalls.push(url);
},
});
expect(externalUrlCalls).toEqual(["https://linear.app/acme/issue/ENG-123/plugin-attachments"]);
});
});
describe("toggleGithubAttachment", () => {
@@ -10,6 +10,7 @@ import {
buildLegacyGitHubAttachmentFromSearchItem,
} from "@/utils/review-attachments";
import { workspaceFileAttachmentToAgentAttachment } from "@/attachments/workspace-file";
import { pluginResourceAttachmentToAgentAttachment } from "@/plugins/attachments/model";
export type ComposerAttachmentSubmitFormat = "forge" | "legacy-github";
@@ -55,6 +56,11 @@ export function splitComposerAttachmentsForSubmit(
continue;
}
if (attachment.kind === "plugin_resource") {
agentAttachments.push(pluginResourceAttachmentToAgentAttachment(attachment));
continue;
}
if (isWorkspaceAttachment(attachment)) {
if (attachment.kind === "browser_element" && attachment.attachment.screenshot) {
images.push(attachment.attachment.screenshot);
+34 -1
View File
@@ -125,6 +125,8 @@ import { getForgePresentation } from "@/git/forge";
import { ForgeBrandIcon } from "@/git/forge-icon";
import { useComposerGithubAutoAttach } from "./github/auto-attach";
import { readClipboardImage } from "./clipboard-image";
import { usePluginAttachmentPicker } from "@/plugins/attachments/picker";
import { PluginResourceAttachmentPill } from "@/plugins/attachments/pill";
import { resolveClientSlashCommand, type ClientSlashCommand } from "@/client-slash-commands";
import {
appendWorkspaceFileAttachment,
@@ -440,6 +442,20 @@ function renderComposerAttachmentPill(args: RenderComposerAttachmentPillArgs): R
onRemove,
});
}
if (attachment.kind === "plugin_resource") {
return (
<PluginResourceAttachmentPill
key={`${attachment.pluginId}:${attachment.sourceId}:${attachment.item.id}`}
attachment={attachment}
index={index}
disabled={disabled}
onOpen={onOpen}
onRemove={onRemove}
openLabel={labels.openGithub}
removeLabel={labels.removeGithub}
/>
);
}
return (
<GithubAttachmentPill
key={`${attachment.item.kind}:${attachment.item.number}`}
@@ -1158,6 +1174,14 @@ export function Composer({
const [lightboxMetadata, setLightboxMetadata] = useState<AttachmentMetadata | null>(null);
const attachButtonRef = useRef<View | null>(null);
const messageInputRef = useRef<MessageInputRef>(null);
const pluginAttachments = usePluginAttachmentPicker({
serverId,
client,
connected: isConnected,
attachments,
onChangeAttachments: setSelectedAttachments,
anchorRef: attachButtonRef,
});
const isComposerLocked = resolveIsComposerLocked(submitBehavior, isSubmitLoading);
const keyboardHandlerIdRef = useRef(
`message-input:${serverId}:${agentId}:${Math.random().toString(36).slice(2)}`,
@@ -1922,6 +1946,7 @@ export function Composer({
setIsGithubPickerOpen(true);
},
},
...pluginAttachments.menuItems,
{
id: "file",
label: t("composer.attachments.addFile"),
@@ -1932,7 +1957,14 @@ export function Composer({
},
);
return items;
}, [forgePresentation, handlePasteImage, handlePickFile, handlePickImage, t]);
}, [
forgePresentation,
handlePasteImage,
handlePickFile,
handlePickImage,
pluginAttachments.menuItems,
t,
]);
const handleToggleGithubItem = useCallback(
(item: ForgeSearchItem) => {
@@ -2189,6 +2221,7 @@ export function Composer({
emptyText={githubEmptyText}
renderOption={renderGithubPickerOption}
/>
{pluginAttachments.picker}
</View>
</View>
</View>
@@ -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],
},
}));
@@ -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 -5
View File
@@ -1243,7 +1243,6 @@ export const ar: TranslationResources = {
},
},
rootError: {
kicker: "حدث خطأ",
title: "واجه Paseo مشكلة.",
body: "جرّب مرة أخرى لإعادة تحميل التطبيق. إذا استمر حدوث ذلك، فأرفق التفاصيل أدناه عند الإبلاغ عنه.",
details: "التفاصيل",
@@ -1704,6 +1703,7 @@ export const ar: TranslationResources = {
editor: "المحرر",
shortcuts: "الاختصارات",
integrations: "التكامل",
notifications: "الإشعارات",
permissions: "الأذونات",
diagnostics: "التشخيص",
about: "عن",
@@ -1713,6 +1713,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 +1874,7 @@ export const ar: TranslationResources = {
midnight: "منتصف الليل",
claude: "كلود",
ghostty: "شبحي",
pureBlack: "أسود خالص",
auto: "نظام",
},
},
@@ -1897,11 +1913,15 @@ export const ar: TranslationResources = {
searchPlaceholder: "البحث في الاختصارات",
unavailableOnMobile: "اختصارات لوحة المفاتيح متاحة فقط على سطح المكتب",
capturePrompt: "اضغط على الاختصار...",
unassigned: "غير معين",
actions: {
menu: "إجراءات {{name}}",
done: "منتهي",
cancel: "يلغي",
bind: "ربط",
rebind: "إعادة ربط",
reset: "إعادة ضبط",
clear: "مسح",
reset: "إعادة الضبط إلى الافتراضي",
resetAll: "إعادة ضبط الكل",
},
sections: {
@@ -2007,17 +2027,14 @@ export const ar: TranslationResources = {
},
permissions: {
title: "الأذونات",
notifications: "إشعارات",
microphone: "ميكروفون",
refresh: "ينعش",
refreshing: "منعش...",
refreshAccessibility: "تحديث أذونات سطح المكتب",
test: "امتحان",
actions: {
granted: "ممنوح",
request: "طلب",
requesting: "جارٍ الطلب...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -5
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",
@@ -1715,6 +1714,7 @@ export const en = {
editor: "Editor",
shortcuts: "Shortcuts",
integrations: "Integrations",
notifications: "Notifications",
permissions: "Permissions",
diagnostics: "Diagnostics",
about: "About",
@@ -1724,6 +1724,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 +1884,7 @@ export const en = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "Pure black",
auto: "System",
},
},
@@ -1907,11 +1923,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 +2038,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 -5
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",
@@ -1747,6 +1746,7 @@ export const es: TranslationResources = {
editor: "Editor",
shortcuts: "Atajos",
integrations: "Integraciones",
notifications: "Notificaciones",
permissions: "Permisos",
diagnostics: "Diagnóstico",
about: "Acerca de",
@@ -1756,6 +1756,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 +1921,7 @@ export const es: TranslationResources = {
midnight: "Medianoche",
claude: "claudio",
ghostty: "fantasmal",
pureBlack: "Negro puro",
auto: "Sistema",
},
},
@@ -1945,11 +1961,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 +2077,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 -5
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",
@@ -1751,6 +1750,7 @@ export const fr: TranslationResources = {
editor: "Éditeur",
shortcuts: "Raccourcis",
integrations: "Intégrations",
notifications: "Notifications",
permissions: "Autorisations",
diagnostics: "Diagnostic",
about: "À propos",
@@ -1760,6 +1760,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 +1924,7 @@ export const fr: TranslationResources = {
midnight: "Minuit",
claude: "Claude",
ghostty: "Fantôme",
pureBlack: "Noir pur",
auto: "Système",
},
},
@@ -1948,11 +1964,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 +2081,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 -5
View File
@@ -1256,7 +1256,6 @@ export const ja: TranslationResources = {
},
},
rootError: {
kicker: "問題が発生しました",
title: "Paseo で問題が発生しました。",
body: "アプリを再読み込みするにはもう一度お試しください。繰り返し発生する場合は、以下の詳細を添えて報告してください。",
details: "詳細",
@@ -1720,6 +1719,7 @@ export const ja: TranslationResources = {
editor: "エディター",
shortcuts: "ショートカット",
integrations: "連携",
notifications: "通知",
permissions: "権限",
diagnostics: "診断",
about: "アプリ情報",
@@ -1729,6 +1729,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 +1889,7 @@ export const ja: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "ピュアブラック",
auto: "システム",
},
},
@@ -1913,11 +1929,15 @@ export const ja: TranslationResources = {
searchPlaceholder: "ショートカットを検索",
unavailableOnMobile: "キーボードショートカットはデスクトップでのみ利用できます",
capturePrompt: "ショートカットを押してください...",
unassigned: "未設定",
actions: {
menu: "{{name}} のアクション",
done: "完了",
cancel: "キャンセル",
bind: "割り当て",
rebind: "再割り当て",
reset: "リセット",
clear: "クリア",
reset: "デフォルトに戻す",
resetAll: "すべてリセット",
},
sections: {
@@ -2026,17 +2046,14 @@ export const ja: TranslationResources = {
},
permissions: {
title: "権限",
notifications: "通知",
microphone: "マイク",
refresh: "更新",
refreshing: "更新中...",
refreshAccessibility: "デスクトップの権限を更新",
test: "テスト",
actions: {
granted: "許可済み",
request: "許可を求める",
requesting: "許可を求めています...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -5
View File
@@ -1252,7 +1252,6 @@ export const ko: TranslationResources = {
},
},
rootError: {
kicker: "문제가 발생했습니다.",
title: "Paseo에 문제가 발생했습니다.",
body: "앱을 다시 로드해 보세요. 이런 일이 계속 발생하면 신고할 때 아래 세부정보를 포함하세요.",
details: "세부",
@@ -1714,6 +1713,7 @@ export const ko: TranslationResources = {
editor: "편집기",
shortcuts: "단축키",
integrations: "통합",
notifications: "알림",
permissions: "권한",
diagnostics: "진단",
about: "정보",
@@ -1723,6 +1723,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 +1885,7 @@ export const ko: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "순수 검정",
auto: "시스템",
},
},
@@ -1908,11 +1924,15 @@ export const ko: TranslationResources = {
searchPlaceholder: "검색 단축키",
unavailableOnMobile: "키보드 단축키는 데스크톱에서만 사용할 수 있습니다",
capturePrompt: "단축키를 누르세요...",
unassigned: "설정되지 않음",
actions: {
menu: "{{name}} 작업",
done: "완료",
cancel: "취소",
bind: "지정",
rebind: "다시 지정",
reset: "재설정",
clear: "지우기",
reset: "기본값으로 재설정",
resetAll: "모두 재설정",
},
sections: {
@@ -2019,17 +2039,14 @@ export const ko: TranslationResources = {
},
permissions: {
title: "권한",
notifications: "알림",
microphone: "마이크",
refresh: "새로고침",
refreshing: "새로고침 중...",
refreshAccessibility: "데스크톱 권한 새로고침",
test: "테스트",
actions: {
granted: "허용됨",
request: "요청",
requesting: "요청 중...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -5
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",
@@ -1733,6 +1732,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 +1742,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 +1905,7 @@ export const ptBR: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "Preto puro",
auto: "Sistema",
},
},
@@ -1928,11 +1944,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 +2061,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 -5
View File
@@ -1272,7 +1272,6 @@ export const ru: TranslationResources = {
},
},
rootError: {
kicker: "Что-то пошло не так",
title: "В Paseo возникла проблема.",
body: "Попробуйте снова перезагрузить приложение. Если это повторяется, приложите приведенные ниже подробности к отчету.",
details: "Подробности",
@@ -1738,6 +1737,7 @@ export const ru: TranslationResources = {
editor: "Редактор",
shortcuts: "Ярлыки",
integrations: "Интеграции",
notifications: "Уведомления",
permissions: "Разрешения",
diagnostics: "Диагностика",
about: "О",
@@ -1747,6 +1747,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 +1910,7 @@ export const ru: TranslationResources = {
midnight: "Полночь",
claude: "Клод",
ghostty: "Призрачный",
pureBlack: "Чистый чёрный",
auto: "Система",
},
},
@@ -1935,11 +1951,15 @@ export const ru: TranslationResources = {
searchPlaceholder: "Поиск сочетаний клавиш",
unavailableOnMobile: "Сочетания клавиш доступны только на рабочем столе.",
capturePrompt: "Нажмите ярлык...",
unassigned: "Не задано",
actions: {
menu: "Действия для {{name}}",
done: "Сделанный",
cancel: "Отмена",
bind: "Привязать",
rebind: "Перепривязка",
reset: "Перезагрузить",
clear: "Очистить",
reset: "Сбросить к значению по умолчанию",
resetAll: "Сбросить все",
},
sections: {
@@ -2045,17 +2065,14 @@ export const ru: TranslationResources = {
},
permissions: {
title: "Разрешения",
notifications: "Уведомления",
microphone: "Микрофон",
refresh: "Обновить",
refreshing: "Освежающий...",
refreshAccessibility: "Обновить разрешения рабочего стола",
test: "Тест",
actions: {
granted: "Предоставленный",
request: "Запрос",
requesting: "Запрос...",
busySuffix: "{{label}}...",
},
},
host: {
+22 -5
View File
@@ -1227,7 +1227,6 @@ export const zhCN: TranslationResources = {
},
},
rootError: {
kicker: "出现问题",
title: "Paseo 遇到了问题。",
body: "请重试以重新加载应用。如果问题持续发生,请在报告时附上下面的详细信息。",
details: "详情",
@@ -1684,6 +1683,7 @@ export const zhCN: TranslationResources = {
editor: "编辑器",
shortcuts: "快捷键",
integrations: "集成",
notifications: "通知",
permissions: "权限",
diagnostics: "诊断",
about: "关于",
@@ -1693,6 +1693,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 +1853,7 @@ export const zhCN: TranslationResources = {
midnight: "Midnight",
claude: "Claude",
ghostty: "Ghostty",
pureBlack: "纯黑",
auto: "系统",
},
},
@@ -1875,11 +1891,15 @@ export const zhCN: TranslationResources = {
searchPlaceholder: "搜索快捷键",
unavailableOnMobile: "键盘快捷键仅在桌面端可用",
capturePrompt: "按下快捷键...",
unassigned: "未设置",
actions: {
menu: "{{name}} 的操作",
done: "完成",
cancel: "取消",
bind: "绑定",
rebind: "重新绑定",
reset: "重置",
clear: "清除",
reset: "重置为默认",
resetAll: "全部重置",
},
sections: {
@@ -1985,17 +2005,14 @@ export const zhCN: TranslationResources = {
},
permissions: {
title: "权限",
notifications: "通知",
microphone: "麦克风",
refresh: "刷新",
refreshing: "正在刷新...",
refreshAccessibility: "刷新桌面端权限",
test: "测试",
actions: {
granted: "已授权",
request: "请求",
requesting: "正在请求...",
busySuffix: "{{label}}...",
},
},
host: {
@@ -3,12 +3,17 @@ 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 {
@@ -702,6 +707,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 +721,263 @@ 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", () => {
it("returns the default keys when there is no override", () => {
expect(resolveShortcutKeysForAction("workspace-tab-new", {}, desktopNonMac)).toEqual([
["mod", "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([["mod", "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([
["mod", "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")?.keys).toEqual([]);
});
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")?.keys).toEqual(["mod", "T"]);
expect(getDefaultKeysForAction("workspace-tab-new", desktopNonMac)).toEqual(["mod", "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. `help.keys` stays populated
// on purpose: it is hand-authored, so the empty parsed chord alone has to be
// 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")?.keys).toEqual([]);
});
});
});
+120 -23
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";
@@ -1064,8 +1067,30 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
// --- 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 +1101,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;
}
@@ -1394,45 +1425,110 @@ export function getBindingIdForAction(
export function getDefaultKeysForAction(
actionId: string,
platform: { isMac: boolean; isDesktop: boolean },
bindings: readonly ParsedShortcutBinding[] = DEFAULT_BINDINGS,
): ShortcutKey[] | null {
for (const binding of DEFAULT_BINDINGS) {
for (const binding of bindings) {
if (binding.help?.id !== actionId) {
continue;
}
if (!helpMatchesPlatform(binding.when, platform)) {
continue;
}
// `help.keys` is hand-authored, so it cannot be trusted to be empty for a
// binding that ships without a default combo. The parsed chord is derived
// from `combo`, so it is the single source of truth for "has no keys".
if (binding.parsedChord.length === 0) {
return null;
}
return binding.help.keys;
}
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;
const override = overrides[bindingId];
if (override) return chordStringToShortcutKeys(override);
if (bindingId === null) {
return null;
}
const defaultKeys = getDefaultKeysForAction(actionId, platform);
return defaultKeys ? [defaultKeys] : null;
const defaultChord = defaultKeys ? [defaultKeys] : null;
const override = overrides[bindingId];
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 +1566,8 @@ export function buildKeyboardShortcutHelpSections(
id: help.id,
label: help.label,
labelKey: SHORTCUT_HELP_LABEL_KEYS[help.id] ?? help.label,
keys: help.keys,
// An empty chord has no keys to show, whatever `help.keys` was authored as.
keys: binding.parsedChord.length === 0 ? [] : help.keys,
...(help.note ? { note: help.note } : {}),
...(SHORTCUT_HELP_NOTE_KEYS[help.id] ? { noteKey: SHORTCUT_HELP_NOTE_KEYS[help.id] } : {}),
});
@@ -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 {}
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vitest";
import {
createPluginResourceAttachment,
PluginResourceComposerAttachmentSchema,
pluginResourceAttachmentToAgentAttachment,
togglePluginResourceAttachment,
} from "./model";
import { splitComposerAttachmentsForSubmit } from "@/composer/attachments/submit";
const source = {
pluginId: "linear",
sourceId: "issues",
sourceTitle: "Linear issue",
sourceIcon: "CircleDot",
};
const item = {
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
subtitle: "In progress · Mohamed",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
text: "Linear issue ENG-123: Plugin attachments\nStatus: In progress",
resourceType: "issue",
};
describe("plugin resource attachments", () => {
it("creates a draft-safe composer attachment", () => {
const attachment = createPluginResourceAttachment(source, item);
expect(PluginResourceComposerAttachmentSchema.parse(attachment)).toEqual({
kind: "plugin_resource",
...source,
item,
});
});
it("toggles one resource by plugin, source, and stable item id", () => {
const attachment = createPluginResourceAttachment(source, item);
expect(togglePluginResourceAttachment([], attachment)).toEqual([attachment]);
expect(togglePluginResourceAttachment([attachment], attachment)).toEqual([]);
});
it("submits through the backward-compatible text attachment", () => {
const attachment = createPluginResourceAttachment(source, item);
const agentAttachment = pluginResourceAttachmentToAgentAttachment(attachment);
expect(agentAttachment).toEqual({
type: "text",
mimeType: "text/plain",
title: "ENG-123 Plugin attachments",
text: item.text,
externalResource: {
provider: "linear",
providerLabel: "Linear issue",
resourceType: "issue",
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
url: item.url,
},
});
expect(splitComposerAttachmentsForSubmit([attachment])).toEqual({
images: [],
attachments: [agentAttachment],
});
});
});
@@ -0,0 +1,70 @@
import { z } from "zod";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import type { UserComposerAttachment } from "@/attachments/types";
import { PluginAttachmentItemSchema, type PluginAttachmentItem } from "./schema";
export const PluginResourceComposerAttachmentSchema = z.object({
kind: z.literal("plugin_resource"),
pluginId: z.string().min(1),
sourceId: z.string().min(1),
sourceTitle: z.string().min(1),
sourceIcon: z.string().min(1),
item: PluginAttachmentItemSchema,
});
export type PluginResourceComposerAttachment = z.infer<
typeof PluginResourceComposerAttachmentSchema
>;
export interface PluginResourceSourceIdentity {
pluginId: string;
sourceId: string;
sourceTitle: string;
sourceIcon: string;
}
export function createPluginResourceAttachment(
source: PluginResourceSourceIdentity,
item: PluginAttachmentItem,
): PluginResourceComposerAttachment {
return {
kind: "plugin_resource",
...source,
item,
};
}
export function togglePluginResourceAttachment(
current: UserComposerAttachment[],
attachment: PluginResourceComposerAttachment,
): UserComposerAttachment[] {
const matches = (candidate: UserComposerAttachment) =>
candidate.kind === "plugin_resource" &&
candidate.pluginId === attachment.pluginId &&
candidate.sourceId === attachment.sourceId &&
candidate.item.id === attachment.item.id;
if (current.some(matches)) {
return current.filter((candidate) => !matches(candidate));
}
return [...current, attachment];
}
export function pluginResourceAttachmentToAgentAttachment(
attachment: PluginResourceComposerAttachment,
): AgentAttachment {
return {
type: "text",
mimeType: "text/plain",
title: `${attachment.item.identifier} ${attachment.item.title}`,
text: attachment.item.text,
externalResource: {
provider: attachment.pluginId,
providerLabel: attachment.sourceTitle,
resourceType: attachment.item.resourceType,
id: attachment.item.id,
identifier: attachment.item.identifier,
title: attachment.item.title,
url: attachment.item.url,
},
};
}
@@ -0,0 +1,176 @@
import { useCallback, useMemo, useState, type ReactElement, type RefObject } from "react";
import { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { LucideIcon } from "lucide-react-native";
import type { UserComposerAttachment } from "@/attachments/types";
import type { AttachmentMenuItem } from "@/composer/input/input";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import { useFetchQuery } from "@/data/query";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { resolvePluginIcon } from "../icons";
import { useInstalledPlugins } from "../registry";
import { searchPluginAttachments } from "../sdk";
import type { InstalledPlugin, PluginAttachmentSourceContribution } from "../types";
import { createPluginResourceAttachment, togglePluginResourceAttachment } from "./model";
import type { PluginAttachmentItem } from "./schema";
const SEARCH_STALE_TIME_MS = 30_000;
const EMPTY_ATTACHMENT_ITEMS: PluginAttachmentItem[] = [];
const iconColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
function SourceIcon({ Icon, color = "" }: { Icon: LucideIcon; color?: string }) {
return <Icon size={ICON_SIZE.md} color={color} />;
}
const ThemedSourceIcon = withUnistyles(SourceIcon);
interface InstalledAttachmentSource {
plugin: InstalledPlugin;
source: PluginAttachmentSourceContribution;
key: string;
}
interface PluginAttachmentPickerInput {
serverId: string;
client: DaemonClient | null;
connected: boolean;
attachments: UserComposerAttachment[];
onChangeAttachments: (attachments: UserComposerAttachment[]) => void;
anchorRef: RefObject<View | null>;
}
interface PluginAttachmentPickerBinding {
menuItems: AttachmentMenuItem[];
picker: ReactElement | null;
}
function searchEmptyText(error: unknown, isFetching: boolean): string {
if (error instanceof Error) return error.message;
if (error) return String(error);
return isFetching ? "Searching..." : "No results";
}
function installedAttachmentSources(
plugins: InstalledPlugin[],
serverId: string,
): InstalledAttachmentSource[] {
return plugins
.filter((plugin) => plugin.serverId === serverId)
.flatMap((plugin) =>
plugin.attachmentSources.map((source) => ({
plugin,
source,
key: `${plugin.id}/${source.id}`,
})),
);
}
function attachmentOptions(items: PluginAttachmentItem[]): ComboboxOption[] {
return items.map((item) => ({
id: item.id,
label: `${item.identifier} ${item.title}`,
description: item.subtitle,
}));
}
export function usePluginAttachmentPicker(
input: PluginAttachmentPickerInput,
): PluginAttachmentPickerBinding {
const plugins = useInstalledPlugins();
const sources = useMemo(
() => installedAttachmentSources(plugins, input.serverId),
[input.serverId, plugins],
);
const [activeKey, setActiveKey] = useState<string | null>(null);
const [query, setQuery] = useState("");
const active = sources.find((candidate) => candidate.key === activeKey) ?? null;
const trimmedQuery = query.trim();
const search = useFetchQuery({
queryKey: [
"plugin-attachment-search",
input.serverId,
active?.plugin.id ?? "",
active?.source.id ?? "",
trimmedQuery,
],
queryFn: async () => {
if (!input.client || !active) throw new Error("Plugin host is offline");
const client = input.client;
return searchPluginAttachments(
active.source,
(method, rpcInput) => client.invokePluginRpc(active.plugin.id, method, rpcInput),
trimmedQuery,
);
},
enabled: input.connected && active !== null,
dataShape: "list",
staleTimeMs: SEARCH_STALE_TIME_MS,
});
const items = search.error
? EMPTY_ATTACHMENT_ITEMS
: (search.data?.items ?? EMPTY_ATTACHMENT_ITEMS);
const options = useMemo(() => attachmentOptions(items), [items]);
const close = useCallback(() => {
setActiveKey(null);
setQuery("");
}, []);
const handleOpenChange = useCallback(
(open: boolean) => {
if (!open) close();
},
[close],
);
const handleSelect = useCallback(
(itemId: string) => {
if (!active) return;
const item = items.find((candidate) => candidate.id === itemId);
if (!item) return;
const attachment = createPluginResourceAttachment(
{
pluginId: active.plugin.id,
sourceId: active.source.id,
sourceTitle: active.source.title,
sourceIcon: active.source.icon,
},
item,
);
input.onChangeAttachments(togglePluginResourceAttachment(input.attachments, attachment));
close();
},
[active, close, input, items],
);
const menuItems = useMemo(
() =>
sources.map(({ key, source }) => {
const Icon = resolvePluginIcon(source.icon);
return {
id: `plugin:${key}`,
label: `Attach ${source.title}`,
icon: <ThemedSourceIcon Icon={Icon} uniProps={iconColorMapping} />,
onSelect: () => setActiveKey(key),
};
}),
[sources],
);
if (!active) return { menuItems, picker: null };
return {
menuItems,
picker: (
<Combobox
options={options}
value=""
onSelect={handleSelect}
searchable
searchPlaceholder={active.source.searchPlaceholder}
title={active.source.pickerTitle}
open
onOpenChange={handleOpenChange}
onSearchQueryChange={setQuery}
desktopPlacement="top-start"
anchorRef={input.anchorRef}
emptyText={searchEmptyText(search.error, search.isFetching)}
/>
),
};
}
@@ -0,0 +1,65 @@
import { useCallback, useMemo } from "react";
import { withUnistyles } from "react-native-unistyles";
import { AttachmentLabel, AttachmentPill } from "@/components/attachment-pill";
import type { ComposerAttachment } from "@/attachments/types";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { resolvePluginIcon } from "../icons";
import type { PluginResourceComposerAttachment } from "./model";
const iconColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
function ResourceIcon({
Icon,
color = "",
}: {
Icon: ReturnType<typeof resolvePluginIcon>;
color?: string;
}) {
return <Icon size={ICON_SIZE.sm} color={color} />;
}
const ThemedResourceIcon = withUnistyles(ResourceIcon);
interface PluginResourceAttachmentPillProps {
attachment: PluginResourceComposerAttachment;
index: number;
disabled: boolean;
onOpen: (attachment: ComposerAttachment) => void;
onRemove: (index: number) => void;
openLabel: (kind: string, identifier: string) => string;
removeLabel: (kind: string, identifier: string) => string;
}
export function PluginResourceAttachmentPill({
attachment,
index,
disabled,
onOpen,
onRemove,
openLabel,
removeLabel,
}: PluginResourceAttachmentPillProps) {
const Icon = resolvePluginIcon(attachment.sourceIcon);
const handleOpen = useCallback(() => onOpen(attachment), [attachment, onOpen]);
const handleRemove = useCallback(() => onRemove(index), [index, onRemove]);
const icon = useMemo(
() => <ThemedResourceIcon Icon={Icon} uniProps={iconColorMapping} />,
[Icon],
);
return (
<AttachmentPill
testID="composer-plugin-resource-attachment-pill"
onOpen={handleOpen}
onRemove={handleRemove}
openAccessibilityLabel={openLabel(attachment.sourceTitle, attachment.item.identifier)}
removeAccessibilityLabel={removeLabel(attachment.sourceTitle, attachment.item.identifier)}
disabled={disabled}
>
<AttachmentLabel
icon={icon}
title={attachment.item.title}
subtitle={`${attachment.sourceTitle} ${attachment.item.identifier}`}
/>
</AttachmentPill>
);
}
@@ -0,0 +1,18 @@
import { z } from "zod";
export const PluginAttachmentItemSchema = z.object({
id: z.string().min(1),
identifier: z.string().min(1),
title: z.string().min(1),
subtitle: z.string().min(1).optional(),
url: z.string().url(),
text: z.string().min(1),
resourceType: z.string().min(1),
});
export const PluginAttachmentSearchPayloadSchema = z.object({
items: z.array(PluginAttachmentItemSchema),
});
export type PluginAttachmentItem = z.infer<typeof PluginAttachmentItemSchema>;
export type PluginAttachmentSearchPayload = z.infer<typeof PluginAttachmentSearchPayloadSchema>;
+43
View File
@@ -0,0 +1,43 @@
import { useEffect } from "react";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { pluginRegistry } from "./registry";
export function PluginCatalogSync({
serverId,
client,
}: {
serverId: string;
client: DaemonClient;
}) {
const connected = useHostRuntimeIsConnected(serverId);
const supported = useHostFeature(serverId, "plugins");
useEffect(() => {
let cancelled = false;
if (!supported) {
pluginRegistry.removeHost(serverId);
return;
}
if (!connected) return;
void client
.getPluginCatalog()
.then((catalog) => {
if (!cancelled) pluginRegistry.installCatalog(serverId, catalog);
return undefined;
})
.catch((error) => {
if (!cancelled) {
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
}
return undefined;
});
return () => {
cancelled = true;
};
}, [client, connected, serverId, supported]);
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
return null;
}
+93
View File
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { evaluatePluginClientBundle } from "./evaluate";
function bundle(body: string): string {
return `(function() {
const module = { exports: {} };
module.exports.default = function(plugin) { ${body} };
return module.exports;
})`;
}
describe("evaluatePluginClientBundle", () => {
it("collects a surface and its sidebar placement", () => {
const plugin = evaluatePluginClientBundle(
"example",
bundle(`
function Surface() { return null; }
plugin.addSurface("main", Surface);
plugin.addSidebarItem({ id: "main", title: "Example", icon: "Blocks", surface: "main" });
`),
);
expect(plugin.id).toBe("example");
expect(plugin.surfaces.map((surface) => surface.id)).toEqual(["main"]);
expect(plugin.sidebarItems).toEqual([
{ id: "main", title: "Example", icon: "Blocks", surface: "main" },
]);
});
it("collects a declarative attachment source", () => {
const plugin = evaluatePluginClientBundle(
"linear",
bundle(`
plugin.addAttachmentSource({
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search by identifier or title",
search: { name: "issues.search", input: {}, output: {} },
});
`),
);
expect(plugin.attachmentSources).toEqual([
{
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search by identifier or title",
search: { name: "issues.search", input: {}, output: {} },
},
]);
});
it("rejects duplicate attachment source ids", () => {
expect(() =>
evaluatePluginClientBundle(
"linear",
bundle(`
const source = {
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search",
search: { name: "issues.search", input: {}, output: {} },
};
plugin.addAttachmentSource(source);
plugin.addAttachmentSource(source);
`),
),
).toThrow("Duplicate attachment source: issues");
});
it("rejects a sidebar placement whose surface does not exist", () => {
expect(() =>
evaluatePluginClientBundle(
"example",
bundle(`
plugin.addSidebarItem({ id: "main", title: "Example", icon: "Blocks", surface: "missing" });
`),
),
).toThrow("references missing surface missing");
});
it("rejects a bundle without a default contribution function", () => {
expect(() => evaluatePluginClientBundle("example", `(function() { return {}; })`)).toThrow(
"must default export a function",
);
});
});
+125
View File
@@ -0,0 +1,125 @@
import * as React from "react";
import * as ReactJsxRuntime from "react/jsx-runtime";
import * as ReactNative from "react-native";
// eslint-disable-next-line no-restricted-imports -- plugin bundles receive TanStack's real runtime, not Paseo's query wrappers.
import * as ReactQuery from "@tanstack/react-query";
import * as Zod from "zod";
import {
createPluginContext,
defineAttachmentSource,
defineRpc,
type PluginRegistrationCollector,
useRpc,
} from "./sdk";
import type {
EvaluatedPlugin,
PluginAttachmentSourceContribution,
PluginSidebarContribution,
PluginSurfaceProps,
} from "./types";
import type { ComponentType } from "react";
import { resolvePluginIcon } from "./icons";
const CONTRIBUTION_ID = /^[a-z][a-z0-9-]*$/;
function requireId(value: string, label: string): string {
const id = value.trim();
if (!CONTRIBUTION_ID.test(id)) throw new Error(`Invalid ${label}: ${value}`);
return id;
}
export function evaluatePluginClientBundle(id: string, bundle: string): EvaluatedPlugin {
const collector: PluginRegistrationCollector = {
surfaces: [],
sidebarItems: [],
attachmentSources: [],
};
const surfaceIds = new Set<string>();
const sidebarItemIds = new Set<string>();
const attachmentSourceIds = new Set<string>();
const pluginContext = createPluginContext({
addSurface(surfaceId: string, Component: ComponentType<PluginSurfaceProps>) {
const normalizedId = requireId(surfaceId, "surface id");
if (surfaceIds.has(normalizedId)) throw new Error(`Duplicate surface: ${normalizedId}`);
if (typeof Component !== "function")
throw new Error(`Surface ${normalizedId} is not a component`);
surfaceIds.add(normalizedId);
collector.surfaces.push({ id: normalizedId, Component });
},
addSidebarItem(contribution: PluginSidebarContribution) {
const normalizedId = requireId(contribution.id, "sidebar item id");
if (sidebarItemIds.has(normalizedId))
throw new Error(`Duplicate sidebar item: ${normalizedId}`);
if (!contribution.title.trim()) throw new Error(`Sidebar item ${normalizedId} has no title`);
if (!contribution.icon.trim()) throw new Error(`Sidebar item ${normalizedId} has no icon`);
resolvePluginIcon(contribution.icon.trim());
sidebarItemIds.add(normalizedId);
collector.sidebarItems.push({
id: normalizedId,
title: contribution.title.trim(),
icon: contribution.icon.trim(),
surface: requireId(contribution.surface, "sidebar surface id"),
});
},
addAttachmentSource(contribution: PluginAttachmentSourceContribution) {
const normalizedId = requireId(contribution.id, "attachment source id");
if (attachmentSourceIds.has(normalizedId)) {
throw new Error(`Duplicate attachment source: ${normalizedId}`);
}
const title = contribution.title.trim();
const icon = contribution.icon.trim();
const pickerTitle = contribution.pickerTitle.trim();
const searchPlaceholder = contribution.searchPlaceholder.trim();
const method = contribution.search.name.trim();
if (!title) throw new Error(`Attachment source ${normalizedId} has no title`);
if (!icon) throw new Error(`Attachment source ${normalizedId} has no icon`);
if (!pickerTitle) throw new Error(`Attachment source ${normalizedId} has no picker title`);
if (!searchPlaceholder) {
throw new Error(`Attachment source ${normalizedId} has no search placeholder`);
}
if (!method) throw new Error(`Attachment source ${normalizedId} has no search RPC`);
resolvePluginIcon(icon);
attachmentSourceIds.add(normalizedId);
collector.attachmentSources.push({
id: normalizedId,
title,
icon,
pickerTitle,
searchPlaceholder,
search: { ...contribution.search, name: method },
});
},
});
const runtimeRequire = (name: string): unknown => {
if (name === "react") return React;
if (name === "react/jsx-runtime") return ReactJsxRuntime;
if (name === "react-native") return ReactNative;
if (name === "@paseo/plugin") return { defineAttachmentSource, defineRpc, useRpc };
if (name === "@tanstack/react-query") return ReactQuery;
if (name === "zod") return Zod;
throw new Error(`Module "${name}" is not available in plugin client code`);
};
const evaluate: (source: string) => unknown = globalThis.eval;
const factory = evaluate(bundle);
if (typeof factory !== "function")
throw new Error(`Plugin ${id} client bundle is not executable`);
const exports = factory(runtimeRequire);
const setup =
exports !== null && typeof exports === "object" ? Reflect.get(exports, "default") : undefined;
if (typeof setup !== "function") {
throw new Error(`Plugin ${id} must default export a function`);
}
setup(pluginContext);
for (const item of collector.sidebarItems) {
if (!surfaceIds.has(item.surface)) {
throw new Error(`Sidebar item ${item.id} references missing surface ${item.surface}`);
}
}
return {
id,
surfaces: collector.surfaces,
sidebarItems: collector.sidebarItems,
attachmentSources: collector.attachmentSources,
};
}
+11
View File
@@ -0,0 +1,11 @@
import * as LucideIcons from "lucide-react-native";
import type { LucideIcon } from "lucide-react-native";
export function resolvePluginIcon(name: string): LucideIcon {
const candidate = Reflect.get(LucideIcons, name);
const isComponent =
typeof candidate === "function" ||
(typeof candidate === "object" && candidate !== null && "$$typeof" in candidate);
if (!isComponent) throw new Error(`Unknown Lucide icon: ${name}`);
return candidate as LucideIcon;
}
+57
View File
@@ -0,0 +1,57 @@
import { afterEach, describe, expect, it } from "vitest";
import { pluginRegistry } from "./registry";
function bundle(marker: string): string {
return `(function() {
const module = { exports: {} };
module.exports.default = function(plugin) {
function Surface() { return ${JSON.stringify(marker)}; }
plugin.addSurface("main", Surface);
plugin.addSidebarItem({ id: "main", title: "Example", icon: "Blocks", surface: "main" });
};
return module.exports;
})`;
}
afterEach(() => {
pluginRegistry.removeHost("host-a");
pluginRegistry.removeHost("host-b");
});
describe("PluginRegistry", () => {
it("preserves a plugin query cache when the same bundle reconnects", () => {
const clientBundle = bundle("one");
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }]);
const first = pluginRegistry.getSnapshot()[0];
first?.queryClient.setQueryData(["counter"], 3);
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }]);
const second = pluginRegistry.getSnapshot()[0];
expect(second?.queryClient).toBe(first?.queryClient);
expect(second?.queryClient.getQueryData(["counter"])).toBe(3);
});
it("replaces the query cache when the plugin bundle changes", () => {
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle: bundle("one") }]);
const first = pluginRegistry.getSnapshot()[0];
first?.queryClient.setQueryData(["counter"], 3);
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle: bundle("two") }]);
const second = pluginRegistry.getSnapshot()[0];
expect(second?.queryClient).not.toBe(first?.queryClient);
expect(second?.queryClient.getQueryData(["counter"])).toBeUndefined();
expect(first?.queryClient.getQueryData(["counter"])).toBeUndefined();
});
it("isolates query caches between hosts", () => {
const clientBundle = bundle("same");
pluginRegistry.installCatalog("host-a", [{ id: "example", clientBundle }]);
pluginRegistry.installCatalog("host-b", [{ id: "example", clientBundle }]);
const [hostA, hostB] = pluginRegistry.getSnapshot();
hostA?.queryClient.setQueryData(["counter"], 3);
expect(hostB?.queryClient.getQueryData(["counter"])).toBeUndefined();
});
});
+91
View File
@@ -0,0 +1,91 @@
import { useSyncExternalStore } from "react";
import { QueryClient } from "@tanstack/react-query";
import { evaluatePluginClientBundle } from "./evaluate";
import type { InstalledPlugin } from "./types";
interface CatalogPlugin {
id: string;
clientBundle: string;
}
class PluginRegistry {
private readonly byHost = new Map<string, InstalledPlugin[]>();
private readonly listeners = new Set<() => void>();
private snapshot: InstalledPlugin[] = [];
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
getSnapshot = (): InstalledPlugin[] => this.snapshot;
installCatalog(serverId: string, catalog: CatalogPlugin[]): void {
const previous = this.byHost.get(serverId) ?? [];
const installed = catalog.flatMap((entry) => {
try {
const existing = previous.find(
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
);
const queryClient = existing?.queryClient ?? new QueryClient();
return [
{
...evaluatePluginClientBundle(entry.id, entry.clientBundle),
serverId,
clientBundle: entry.clientBundle,
queryClient,
},
];
} catch (error) {
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
return [];
}
});
for (const plugin of previous) {
if (!installed.some((candidate) => candidate.queryClient === plugin.queryClient)) {
plugin.queryClient.clear();
}
}
this.byHost.set(serverId, installed);
this.publish();
}
removeHost(serverId: string): void {
const installed = this.byHost.get(serverId);
if (!installed) return;
for (const plugin of installed) plugin.queryClient.clear();
this.byHost.delete(serverId);
this.publish();
}
private publish(): void {
this.snapshot = [...this.byHost.values()]
.flat()
.sort((left, right) =>
`${left.serverId}/${left.id}`.localeCompare(`${right.serverId}/${right.id}`),
);
for (const listener of this.listeners) listener();
}
}
export const pluginRegistry = new PluginRegistry();
export function useInstalledPlugins(): InstalledPlugin[] {
return useSyncExternalStore(
pluginRegistry.subscribe,
pluginRegistry.getSnapshot,
pluginRegistry.getSnapshot,
);
}
export function useInstalledPlugin(serverId: string, pluginId: string): InstalledPlugin | null {
return (
useInstalledPlugins().find(
(plugin) => plugin.serverId === serverId && plugin.id === pluginId,
) ?? null
);
}
export function usePluginInstallations(pluginId: string): InstalledPlugin[] {
return useInstalledPlugins().filter((plugin) => plugin.id === pluginId);
}
+17
View File
@@ -0,0 +1,17 @@
export function buildPluginSurfaceRoute(
serverId: string,
pluginId: string,
contributionId: string,
): `/h/${string}/plugin/${string}/${string}` {
return `/h/${encodeURIComponent(serverId)}/plugin/${encodeURIComponent(pluginId)}/${encodeURIComponent(contributionId)}`;
}
export function hostIdFromPathname(pathname: string): string | null {
const encoded = /^\/h\/([^/]+)/.exec(pathname)?.[1];
if (!encoded) return null;
try {
return decodeURIComponent(encoded);
} catch {
return null;
}
}
+110
View File
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { callPluginRpc, defineAttachmentSource, defineRpc, searchPluginAttachments } from "./sdk";
const contract = defineRpc({
name: "increment",
input: z.unknown().pipe(z.object({ value: z.number() })),
output: z.object({ value: z.number() }),
});
describe("plugin RPC contracts", () => {
it("validates input before invoking the daemon", async () => {
let invocations = 0;
const invoke = async () => {
invocations += 1;
return { value: 2 };
};
await expect(callPluginRpc(contract, invoke, { value: "wrong" })).rejects.toBeInstanceOf(
z.ZodError,
);
expect(invocations).toBe(0);
});
it("validates output before resolving", async () => {
const invoke = async () => ({ value: "wrong" });
await expect(callPluginRpc(contract, invoke, { value: 1 })).rejects.toBeInstanceOf(z.ZodError);
});
it("returns parsed output for a valid invocation", async () => {
const invoke = async (method: string, input: unknown) => ({
value: method === "increment" && typeof input === "object" ? 2 : 0,
});
await expect(callPluginRpc(contract, invoke, { value: 1 })).resolves.toEqual({ value: 2 });
});
});
describe("plugin attachment sources", () => {
const search = defineRpc({
name: "issues.search",
input: z.object({ query: z.string() }),
output: z.object({
items: z.array(
z.object({
id: z.string(),
identifier: z.string(),
title: z.string(),
subtitle: z.string().optional(),
url: z.string(),
text: z.string(),
resourceType: z.string(),
}),
),
}),
});
it("searches through the declared RPC and validates the standard result", async () => {
const source = defineAttachmentSource({
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search",
search,
});
const payload = await searchPluginAttachments(
source,
async (method, input) => ({
items: [
{
id: "issue-1",
identifier: `${method}:${String(Reflect.get(input as object, "query"))}`,
title: "Plugin attachments",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
text: "Linear issue ENG-123: Plugin attachments",
resourceType: "issue",
},
],
}),
"ENG-123",
);
expect(payload.items[0]).toEqual({
id: "issue-1",
identifier: "issues.search:ENG-123",
title: "Plugin attachments",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
text: "Linear issue ENG-123: Plugin attachments",
resourceType: "issue",
});
});
it("rejects a malformed standard search result", async () => {
const source = defineAttachmentSource({
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search",
search,
});
await expect(
searchPluginAttachments(source, async () => ({ items: [{ id: "issue-1" }] }), "issue"),
).rejects.toBeInstanceOf(z.ZodError);
});
});
+138
View File
@@ -0,0 +1,138 @@
import {
createContext,
useCallback,
useContext,
useMemo,
type ComponentType,
type ReactNode,
} from "react";
import type { ZodType, output as ZodOutput, input as ZodInput } from "zod";
import {
PluginAttachmentSearchPayloadSchema,
type PluginAttachmentSearchPayload,
} from "./attachments/schema";
import type {
PluginAttachmentSourceContribution,
PluginSidebarContribution,
PluginSurfaceContribution,
PluginSurfaceProps,
} from "./types";
interface PluginCollector {
addSurface(id: string, Component: ComponentType<PluginSurfaceProps>): void;
addSidebarItem(contribution: PluginSidebarContribution): void;
addAttachmentSource(contribution: PluginAttachmentSourceContribution): void;
}
interface PluginRpcContextValue {
invoke(method: string, input: unknown): Promise<unknown>;
}
export interface PluginRpcContract<
InputSchema extends ZodType = ZodType,
OutputSchema extends ZodType = ZodType,
> {
name: string;
input: InputSchema;
output: OutputSchema;
}
export interface PluginContext {
handle<InputSchema extends ZodType, OutputSchema extends ZodType>(
contract: PluginRpcContract<InputSchema, OutputSchema>,
handler: (
input: ZodOutput<InputSchema>,
) => ZodInput<OutputSchema> | Promise<ZodInput<OutputSchema>>,
): void;
addSurface(id: string, Component: ComponentType<PluginSurfaceProps>): void;
addSidebarItem(contribution: PluginSidebarContribution): void;
addAttachmentSource(contribution: PluginAttachmentSourceContribution): void;
}
interface RpcDefinition<InputSchema extends ZodType, OutputSchema extends ZodType> {
name: string;
input: InputSchema;
output: OutputSchema;
}
const RPC_NAME = /^[a-z][a-z0-9._-]*$/;
export function defineRpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
definition: RpcDefinition<InputSchema, OutputSchema>,
): PluginRpcContract<InputSchema, OutputSchema> {
const name = definition.name.trim();
if (!RPC_NAME.test(name)) throw new Error(`Invalid plugin RPC method: ${definition.name}`);
return { ...definition, name };
}
export type { PluginAttachmentItem, PluginAttachmentSearchPayload } from "./attachments/schema";
export function defineAttachmentSource(
definition: PluginAttachmentSourceContribution,
): PluginAttachmentSourceContribution {
return definition;
}
const PluginRpcContext = createContext<PluginRpcContextValue | null>(null);
export function PluginRpcProvider({
children,
invoke,
}: {
children: ReactNode;
invoke(method: string, input: unknown): Promise<unknown>;
}) {
const value = useMemo(() => ({ invoke }), [invoke]);
return <PluginRpcContext.Provider value={value}>{children}</PluginRpcContext.Provider>;
}
export function createPluginContext(collector: PluginCollector) {
return {
addSurface(id: string, Component: ComponentType<PluginSurfaceProps>) {
collector.addSurface(id, Component);
},
addSidebarItem(contribution: PluginSidebarContribution) {
collector.addSidebarItem(contribution);
},
addAttachmentSource(contribution: PluginAttachmentSourceContribution) {
collector.addAttachmentSource(contribution);
},
};
}
export async function searchPluginAttachments(
source: PluginAttachmentSourceContribution,
invoke: (method: string, input: unknown) => Promise<unknown>,
query: string,
): Promise<PluginAttachmentSearchPayload> {
const output = await callPluginRpc(source.search, invoke, { query });
return PluginAttachmentSearchPayloadSchema.parseAsync(output);
}
export function useRpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
contract: PluginRpcContract<InputSchema, OutputSchema>,
): (input: ZodInput<InputSchema>) => Promise<ZodOutput<OutputSchema>> {
const context = useContext(PluginRpcContext);
if (!context) throw new Error("useRpc must run inside a contributed plugin surface");
return useCallback(
(input: ZodInput<InputSchema>) => callPluginRpc(contract, context.invoke, input),
[context, contract],
);
}
export async function callPluginRpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
contract: PluginRpcContract<InputSchema, OutputSchema>,
invoke: (method: string, input: unknown) => Promise<unknown>,
input: ZodInput<InputSchema>,
): Promise<ZodOutput<OutputSchema>> {
const parsedInput = await contract.input.parseAsync(input);
const output = await invoke(contract.name, parsedInput);
return contract.output.parseAsync(output);
}
export interface PluginRegistrationCollector {
surfaces: PluginSurfaceContribution[];
sidebarItems: PluginSidebarContribution[];
attachmentSources: PluginAttachmentSourceContribution[];
}
@@ -0,0 +1,44 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import type { InstalledPlugin } from "./types";
import { groupPluginSidebarContributions } from "./sidebar-groups";
function installed(serverId: string, contributionId = "main"): InstalledPlugin {
return {
id: "example",
serverId,
clientBundle: serverId,
queryClient: new QueryClient(),
surfaces: [{ id: "surface", Component: () => null }],
sidebarItems: [
{
id: contributionId,
title: "Example",
icon: "Blocks",
surface: "surface",
},
],
attachmentSources: [],
};
}
describe("groupPluginSidebarContributions", () => {
it("coalesces the same plugin contribution across hosts", () => {
const groups = groupPluginSidebarContributions([installed("host-a"), installed("host-b")]);
expect(groups).toHaveLength(1);
expect(groups[0]?.targets.map((target) => target.plugin.serverId)).toEqual([
"host-a",
"host-b",
]);
});
it("keeps different contribution ids separate", () => {
const groups = groupPluginSidebarContributions([
installed("host-a", "main"),
installed("host-b", "settings"),
]);
expect(groups.map((group) => group.key)).toEqual(["example/main", "example/settings"]);
});
});
@@ -0,0 +1,48 @@
import type { InstalledPlugin, PluginSidebarContribution } from "./types";
const preferredHosts = new Map<string, string>();
export interface PluginSidebarTarget {
plugin: InstalledPlugin;
item: PluginSidebarContribution;
}
export interface PluginSidebarGroup {
key: string;
pluginId: string;
contributionId: string;
title: string;
icon: string;
targets: PluginSidebarTarget[];
}
export function groupPluginSidebarContributions(plugins: InstalledPlugin[]): PluginSidebarGroup[] {
const groups = new Map<string, PluginSidebarGroup>();
for (const plugin of plugins) {
for (const item of plugin.sidebarItems) {
const key = `${plugin.id}/${item.id}`;
const existing = groups.get(key);
if (existing) {
existing.targets.push({ plugin, item });
} else {
groups.set(key, {
key,
pluginId: plugin.id,
contributionId: item.id,
title: item.title,
icon: item.icon,
targets: [{ plugin, item }],
});
}
}
}
return [...groups.values()];
}
export function getPreferredPluginContributionHost(groupKey: string): string | null {
return preferredHosts.get(groupKey) ?? null;
}
export function rememberPluginContributionHost(groupKey: string, serverId: string): void {
preferredHosts.set(groupKey, serverId);
}
@@ -0,0 +1,80 @@
import { router, usePathname } from "expo-router";
import { useCallback, useMemo } from "react";
import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
import { resolvePluginIcon } from "./icons";
import { useInstalledPlugins } from "./registry";
import { buildPluginSurfaceRoute, hostIdFromPathname } from "./routes";
import {
groupPluginSidebarContributions,
getPreferredPluginContributionHost,
rememberPluginContributionHost,
type PluginSidebarGroup,
type PluginSidebarTarget,
} from "./sidebar-groups";
function selectTarget(
group: PluginSidebarGroup,
currentHostId: string | null,
): PluginSidebarTarget {
const current = group.targets.find((target) => target.plugin.serverId === currentHostId);
if (current) return current;
const rememberedHostId = getPreferredPluginContributionHost(group.key);
const remembered = group.targets.find((target) => target.plugin.serverId === rememberedHostId);
return remembered ?? group.targets[0];
}
export function PluginSidebarItems({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) {
const plugins = useInstalledPlugins();
const pathname = usePathname();
const groups = useMemo(() => groupPluginSidebarContributions(plugins), [plugins]);
const currentHostId = hostIdFromPathname(pathname);
return groups.map((group) => (
<PluginSidebarItemRow
key={group.key}
group={group}
currentHostId={currentHostId}
pathname={pathname}
onBeforeNavigate={onBeforeNavigate}
/>
));
}
function PluginSidebarItemRow({
group,
currentHostId,
pathname,
onBeforeNavigate,
}: {
group: PluginSidebarGroup;
currentHostId: string | null;
pathname: string;
onBeforeNavigate?: () => void;
}) {
const target = selectTarget(group, currentHostId);
const route = buildPluginSurfaceRoute(
target.plugin.serverId,
group.pluginId,
group.contributionId,
);
const isActive = group.targets.some(
(candidate) =>
pathname ===
buildPluginSurfaceRoute(candidate.plugin.serverId, group.pluginId, group.contributionId),
);
const navigate = useCallback(() => {
rememberPluginContributionHost(group.key, target.plugin.serverId);
onBeforeNavigate?.();
router.push(route);
}, [group.key, onBeforeNavigate, route, target.plugin.serverId]);
return (
<SidebarHeaderRow
icon={resolvePluginIcon(group.icon)}
label={group.title}
onPress={navigate}
isActive={isActive}
testID={`plugin-sidebar-${group.pluginId}-${group.contributionId}`}
variant="compact"
/>
);
}
+297
View File
@@ -0,0 +1,297 @@
import { router, useLocalSearchParams } from "expo-router";
import { QueryClientProvider } from "@tanstack/react-query";
import { ChevronDown, X } from "lucide-react-native";
import {
Component,
useCallback,
useMemo,
useRef,
useState,
type ComponentType,
type ErrorInfo,
type ReactNode,
} from "react";
import { Platform, Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HeaderIconBadge } from "@/components/headers/header-icon-badge";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { ScreenHeader } from "@/components/headers/screen-header";
import { ScreenTitle } from "@/components/headers/screen-title";
import { HostPicker } from "@/components/hosts/host-picker";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { resolvePluginIcon } from "./icons";
import { useInstalledPlugin, usePluginInstallations } from "./registry";
import { buildPluginSurfaceRoute } from "./routes";
import { rememberPluginContributionHost } from "./sidebar-groups";
import { PluginRpcProvider } from "./sdk";
import type { PluginSurfaceProps } from "./types";
const EMPTY_SHORTCUT_KEYS: ShortcutKey[] = [];
const EMPTY_THEME_DTO: Record<string, unknown> = {};
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const pluginThemeMapping = (theme: Theme) => ({
themeDto: JSON.parse(JSON.stringify(theme)) as Record<string, unknown>,
});
const ThemedX = withUnistyles(X);
const ThemedChevronDown = withUnistyles(ChevronDown);
function routeParam(value: string | string[] | undefined): string {
return typeof value === "string" ? value : "";
}
function PluginHeaderIcon({
Icon,
color = "",
}: {
Icon: ReturnType<typeof resolvePluginIcon>;
color?: string;
}) {
return <Icon size={16} color={color} />;
}
const ThemedPluginHeaderIcon = withUnistyles(PluginHeaderIcon);
function SurfaceRenderer({
Surface,
invoke,
plugin,
layout,
host,
themeDto = EMPTY_THEME_DTO,
}: {
Surface: ComponentType<PluginSurfaceProps>;
invoke(method: string, input: unknown): Promise<unknown>;
plugin: NonNullable<ReturnType<typeof useInstalledPlugin>>;
layout: PluginSurfaceProps["layout"];
host: PluginSurfaceProps["host"];
themeDto?: Record<string, unknown>;
}) {
return (
<QueryClientProvider client={plugin.queryClient}>
<PluginRpcProvider invoke={invoke}>
<Surface theme={themeDto} host={host} layout={layout} />
</PluginRpcProvider>
</QueryClientProvider>
);
}
const ThemedSurfaceRenderer = withUnistyles(SurfaceRenderer);
interface SurfaceErrorBoundaryState {
error: string | null;
}
class SurfaceErrorBoundary extends Component<{ children: ReactNode }, SurfaceErrorBoundaryState> {
state: SurfaceErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.warn("[Plugins] Surface render failed", error, info.componentStack);
}
render() {
if (this.state.error) {
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
}
return this.props.children;
}
}
function resolvePlatform(): PluginSurfaceProps["layout"]["platform"] {
if (Platform.OS === "ios") return "ios";
if (Platform.OS === "android") return "android";
return "web";
}
function PluginHostSwitcher({
serverId,
pluginId,
contributionId,
serverIds,
}: {
serverId: string;
pluginId: string;
contributionId: string;
serverIds: string[];
}) {
const allHosts = useHosts();
const hosts = useMemo(
() => allHosts.filter((host) => serverIds.includes(host.serverId)),
[allHosts, serverIds],
);
const [open, setOpen] = useState(false);
const anchorRef = useRef<View | null>(null);
const selectedLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
const selectHost = useCallback(
(nextServerId: string) => {
rememberPluginContributionHost(`${pluginId}/${contributionId}`, nextServerId);
router.replace(buildPluginSurfaceRoute(nextServerId, pluginId, contributionId));
},
[contributionId, pluginId],
);
const openPicker = useCallback(() => setOpen(true), []);
const show = serverIds.length > 1 && hosts.length > 1;
if (!show) return null;
return (
<HostPicker
hosts={hosts}
value={serverId}
onSelect={selectHost}
open={open}
onOpenChange={setOpen}
anchorRef={anchorRef}
title="Choose plugin host"
desktopPlacement="bottom-start"
>
<View ref={anchorRef} collapsable={false}>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Plugin host: ${selectedLabel}`}
testID="plugin-host-switcher"
onPress={openPicker}
style={styles.hostSwitcher}
>
<Text numberOfLines={1} style={styles.hostSwitcherText}>
{selectedLabel}
</Text>
<ThemedChevronDown size={14} uniProps={mutedColorMapping} />
</Pressable>
</View>
</HostPicker>
);
}
export function PluginSurfaceScreen() {
const params = useLocalSearchParams<{
serverId?: string | string[];
pluginId?: string | string[];
surfaceId?: string | string[];
}>();
const serverId = routeParam(params.serverId);
const pluginId = routeParam(params.pluginId);
const contributionId = routeParam(params.surfaceId);
const plugin = useInstalledPlugin(serverId, pluginId);
const installations = usePluginInstallations(pluginId);
const hosts = useHosts();
const client = useHostRuntimeClient(serverId);
const compact = useIsCompactFormFactor();
const sidebarItem = plugin?.sidebarItems.find((entry) => entry.id === contributionId) ?? null;
const surface = plugin?.surfaces.find((entry) => entry.id === sidebarItem?.surface) ?? null;
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
const contributionServerIds = useMemo(
() =>
installations
.filter((entry) => entry.sidebarItems.some((item) => item.id === contributionId))
.map((entry) => entry.serverId),
[contributionId, installations],
);
const title = sidebarItem?.title ?? (pluginId || "Plugin");
const Icon = sidebarItem ? resolvePluginIcon(sidebarItem.icon) : null;
const invoke = useCallback(
async (method: string, input: unknown) => {
if (!client) throw new Error("Plugin host is offline");
return client.invokePluginRpc(pluginId, method, input);
},
[client, pluginId],
);
const close = useCallback(() => {
if (router.canGoBack()) router.back();
else router.replace(`/h/${encodeURIComponent(serverId)}`);
}, [serverId]);
const layout = useMemo(() => ({ compact, platform: resolvePlatform() }), [compact]);
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
const headerLeft = useMemo(
() => (
<>
{Icon ? (
<HeaderIconBadge>
<ThemedPluginHeaderIcon Icon={Icon} uniProps={mutedColorMapping} />
</HeaderIconBadge>
) : null}
<ScreenTitle>{title}</ScreenTitle>
</>
),
[Icon, title],
);
const headerRight = useMemo(
() => (
<>
<PluginHostSwitcher
serverId={serverId}
pluginId={pluginId}
contributionId={contributionId}
serverIds={contributionServerIds}
/>
<HeaderToggleButton
accessibilityLabel="Close plugin"
onPress={close}
testID="plugin-surface-close"
tooltipKeys={EMPTY_SHORTCUT_KEYS}
tooltipLabel="Close"
tooltipSide="bottom"
>
<ThemedX size={18} uniProps={mutedColorMapping} />
</HeaderToggleButton>
</>
),
[close, contributionId, contributionServerIds, pluginId, serverId],
);
return (
<View style={styles.screen}>
<ScreenHeader left={headerLeft} right={headerRight} />
<View style={styles.body}>
{plugin && surface ? (
<SurfaceErrorBoundary key={`${serverId}/${pluginId}/${contributionId}`}>
<ThemedSurfaceRenderer
Surface={surface.Component}
invoke={invoke}
plugin={plugin}
host={host}
layout={layout}
uniProps={pluginThemeMapping}
/>
</SurfaceErrorBoundary>
) : (
<Text style={styles.errorText}>This plugin surface is unavailable.</Text>
)}
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
screen: {
flex: 1,
backgroundColor: theme.colors.surface0,
},
body: {
flex: 1,
},
errorText: {
color: theme.colors.statusDanger,
padding: theme.spacing[4],
},
hostSwitcher: {
maxWidth: 180,
minHeight: 32,
paddingHorizontal: theme.spacing[2],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface1,
},
hostSwitcherText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
}));
+49
View File
@@ -0,0 +1,49 @@
import type { ComponentType } from "react";
import type { QueryClient } from "@tanstack/react-query";
import type { PluginRpcContract } from "./sdk";
export interface PluginSurfaceProps {
theme: Record<string, unknown>;
host: {
id: string;
label: string;
};
layout: {
compact: boolean;
platform: "ios" | "android" | "web";
};
}
export interface PluginSurfaceContribution {
id: string;
Component: ComponentType<PluginSurfaceProps>;
}
export interface PluginSidebarContribution {
id: string;
title: string;
icon: string;
surface: string;
}
export interface PluginAttachmentSourceContribution {
id: string;
title: string;
icon: string;
pickerTitle: string;
searchPlaceholder: string;
search: PluginRpcContract;
}
export interface EvaluatedPlugin {
id: string;
surfaces: PluginSurfaceContribution[];
sidebarItems: PluginSidebarContribution[];
attachmentSources: PluginAttachmentSourceContribution[];
}
export interface InstalledPlugin extends EvaluatedPlugin {
serverId: string;
clientBundle: string;
queryClient: QueryClient;
}
@@ -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();

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