Compare commits

...
Author SHA1 Message Date
Xu Kang fb32ab924f fix(server): contain Codex app-server stdin errors (#11847) 2026-12-03 05:12:39 +00:00
Mohamed Boudra 183aea75aa Import session from New workspace creates a new workspace (#11845)
* feat: import from New workspace into a new workspace

Import session on the New workspace screen now creates a fresh workspace for
the session's directory instead of joining the workspace already open there.

import_agent_request gains an optional newWorkspace flag. The daemon creates a
directory workspace (inheriting a managed worktree's repository project) and
removes it again if the import fails. Requests without the flag keep the
existing find-or-create placement, and older daemons ignore the field.

* fix(server): keep a new import workspace in its directory's project

A new workspace for an imported session now joins the project of the workspace
already at that directory, so a session in an external git worktree stays under
its repository's project. Split the active and archived placement tests and drop
the component-mounting sheet test; the view-model and Playwright tests cover it.
2026-12-03 12:10:15 +07:00
Mohamed Boudra 142c880af9 Let horizontal scroll views keep sideways swipes from the mobile panels (#11841)
* fix(app): let horizontal scroll views keep swipes from the mobile panels

Outside a sheet, the shared ScrollView and FlatList rendered a plain React
Native scroller on iOS and Android. The panel pans on the page activated
first, so a sideways swipe on a plugin table or code block opened or closed
a side panel instead of scrolling. Only sheets wrapped horizontal scrollers
in a gesture that kept the touch.

Every native horizontal ScrollView and FlatList now runs under the
panel-aware Native gesture the composer track already used: it blocks the
provider's open and close pans and the nearest explorer close pan, and
disallows interruption so a sheet's pan cannot take a scrolling touch. A
sheet sits outside the panels provider, so the hook blocks no panel there.

Web keeps the plain React Native scroller: the browser scrolls an overflow
container itself and cancels the page's pointer stream.

* fix(app): give the root error screen its own gesture root

The error fallback replaces the app tree above the app's
GestureHandlerRootView. Its details now scroll sideways under a
GestureDetector, which RNGH rejects in native dev builds without a root
view above it, so the fallback threw instead of showing the error.

* fix(app): give every native modal its own gesture root

A React Native Modal is a separate window above the app's
GestureHandlerRootView. A plugin popover on wide layouts renders in one,
so a horizontal SDK ScrollView there mounted a GestureDetector with no
root view: RNGH throws in native dev builds, and on Android gestures in
that window are not recognized.

The shared Modal now wraps its native content in a GestureHandlerRootView,
so the combobox and attachment lightbox drop their own copies.
2026-12-03 11:59:14 +07:00
Mohamed Boudra ffe8f77b0f Stop hardcoding Paseo versions in the plugin skill (#11838)
* Stop hardcoding Paseo versions in the plugin skill and fix 0.18.3 doc notes

* Use 0.19.0 in the workspace layout example and its runtime test
2026-12-03 11:36:04 +07:00
Mohamed Boudra 25a3fba211 Show Logits as a Paseo sponsor on the website and READMEs (#11843)
* feat(website): add Logits as a company sponsor

Add Logits alongside Hoplite and Encore on paseo.sh and the four READMEs using the official on-light and on-dark SVGs and tagline. Tighten the homepage sponsors row gap and caption max-width so all three sponsors and the Become a sponsor invitation stay on one desktop row instead of stranding the button on a second row.

* feat(website): arrange sponsors in two columns on mobile

Use a 2-column grid with compact mobile logo heights (h-7) and captions on screens below sm across both the homepage Sponsors section and the footer/docs Sponsors band so all sponsors stay visible without tall single-column stacking, switching back to the desktop flex-wrap layout at sm and wider.
2026-12-03 11:07:50 +07:00
paseo-bot[bot]andMichael Wu 0910e25441 fix(server): release idle Codex runtimes after disconnect (#11839)
A disposed app-server cannot answer inventory requests. Let idle cleanup close the stale session through the usual lifecycle while keeping sessions that are reconnecting.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Michael Wu <michaelmwu@gmail.com>
2026-12-03 03:42:40 +00:00
paseo-bot[bot]andClaude Opus 5.5 661fd6a7a5 Start the dev daemon after the dependency watchers finish their first build (#11820)
* fix(server): start the dev daemon after the dependency watchers build

tsc --watch rewrites every dist file on its first build. The dev runner
started the daemon worker at the same time, so the worker could import a
half-written protocol module and exit with a missing-export SyntaxError.
The runner now waits for both watchers to report their first build.

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

* fix(server): keep the dev runner shape the supervision parity test checks

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

* test(cli): check the dev worker start against whole output lines in order

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 03:29:25 +00:00
Mohamed Boudra bcab3c7850 fix(desktop): deny browser webview permissions by default (#11837)
* fix(desktop): deny browser webview permissions by default

* fix(desktop): consolidate webview permission install and assert exact denial errors
2026-12-03 09:57:11 +07:00
Mohamed Boudra d59e2bd17c Use browser profiles on host-proxied desktop tabs (#11772)
* Let browser profiles work on host-proxied tabs

A browser tab's Electron partition is now the pair (route, profile).
Host-proxied tabs show the profile picker, and each profile on a host
gets its own persistent partition bound to that host's one SOCKS5 server
and tunnel. Clear, Remove, and startup pruning cover every route.

One module, browser-partition.ts, owns the partition names. The existing
local and host Default names are unchanged.

* Ignore inherited object keys when reading bound host profile partitions
2026-12-03 09:33:45 +07:00
Mohamed Boudra 08e26ebbec fix(app): steer when Send now is used with the queue send behavior (#11827) 2026-12-03 09:33:08 +07:00
KiritoXD a0c5522a71 fix(cli): allow model-only schedule updates (#11796) 2026-12-03 02:12:43 +00:00
paseo-bot[bot] 37c5f74586 fix(app): prevent middle-click tab closes from pasting (#11818)
Closing a tab restores terminal focus before Chromium pastes the Linux primary selection. Cancel the middle-button release on the tab so closing it cannot type into the terminal.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 00:12:43 +00:00
paseo-bot[bot]andDaniel JB Clark a7d2593744 Deliver approved answers to Pi permission prompts (#11814)
* fix(pi): honor selectedActionId on allow and steer user denial reasons

Two Pi extension UI permission bugs tracked in getpaseo/paseo#8326:

1. Allow with selectedActionId (or bare allow) cancelled the dialog:
   - Extract shared resolveAllowedExtensionUiAnswer and PiPermissionResponseError
     into providers/pi/extension-ui-answer.ts and use it across core agent.ts,
     pi-ask-user, and rpiv-ask-user-question.
   - Accept selectedActionId when it matches an offered option label, and throw
     a bounded, shell-safe error (without consuming the pending request) when an
     allow names no valid option.
   - Rethrow PiPermissionResponseError in PiExtensionHost.respondToPermission
     while preserving fault isolation for unexpected adapter errors.

2. Denial reasons (response.message) were discarded on deny:
   - Because Pi extension_ui_response { cancelled: true } has no reason field,
     steer user-supplied denial reasons (excluding fixed Paseo dismissal strings
     and interrupt denials) BEFORE sending the cancel reply while Pi is parked
     in tool execution.
   - Gate steering on a live agent loop (activeTurnStarted or activeToolCalls),
     clear activeToolCalls on turn boundaries/startTurn/interrupt/prompt-error/exit,
     bound the steer RPC with a 5 s timeout, cap steered reasons at 2048 chars
     with a provenance label, pre-register clientMessageId: null in
     pendingSteerSubmissions before awaiting steer, and wrap MCP agent callers
     in an agent-message envelope via optional internal callerAgentId/Title.

Closes getpaseo/paseo#8326

* fix(pi): preserve active tool calls and denial steering across autonomous startTurn

* Keep the Pi permission fix focused on approvals

Leave denial reason delivery for a separate decision about how Pi should receive it. Preserve the existing cancellation path and keep approval validation inside the Pi provider.

Co-authored-by: Daniel JB Clark <djbclark@gmail.com>

* Stabilize diff fallback and website search CI checks

---------

Co-authored-by: Daniel JB Clark <djbclark@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 23:43:03 +00:00
paseo-bot[bot] bb0a541338 fix(app): keep keys typed right after the Find shortcut (#11812)
React Native Web runs selectTextOnFocus in a timer after focus. Find
already selects its query when it takes focus, so the later timer
selected the keys typed in between and the next key replaced them.
Typing "a.b" right after Cmd+F gave ".b". This made chat-find
composer tests flaky on CI.

Select the query once when the widget mounts and drop
selectTextOnFocus. The chat-find test now presses the shortcut and
types in one task, which failed every time before the fix.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 21:46:05 +00:00
paseo-bot[bot] c37a407bc8 fix(claude): remove the terminal shortcut from Stop hook warnings (#11792)
The chat warning told users to open the Claude Code transcript with Ctrl+O. In Paseo on Linux, that shortcut opens Add project. Remove the terminal hint at the Claude notification boundary.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 21:12:50 +00:00
paseo-bot[bot] ef8de256ce fix(app): release replaced plugin installations (#11800)
The current plugin’s RPC closure kept the previous catalog alive after a reload. Create each plugin installation outside the catalog update scope so the previous installation can be collected.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 20:13:31 +00:00
KiritoXD 68a1cd9a33 fix(cli): resolve terminal workspaces beyond the first ten (#11799) 2026-12-02 20:13:09 +00:00
d4d8441f06 Preserve a follow-up draft while an earlier send settles (#11448)
* Preserve a follow-up draft while an earlier send settles

* Guard composer submission with the shared draft version

* Cover attachments added from Changes during a pending send

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 20:12:48 +00:00
515392cd7b fix(app): mount a web popover's content once per open (#11748)
* fix(app): mount a web popover's content once per open

An anchored menu surface renders off-screen until its anchor and content
are measured, then changed its key from "measuring" to "placed". The key
change remounted the surface and everything inside it, so a plugin
popover's Content mounted, unmounted and mounted again on every open:
effects and requests ran twice and the first mount's state was lost.

Web plays its entering animation through the Web Animations API when the
surface is placed, so the remount did nothing there. The key now stays
stable on web. Native still remounts, because Reanimated's `entering`
only runs on mount.

Fixes #9103

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

* docs(menus): only native remounts an anchored surface on placement

Web keeps the surface mounted and starts its entering animation when it is
placed, so a popover's content mounts once per open.

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

* ci: retrigger checks for the popover fix

* Wait for the desktop device menu before clicking a preset

---------

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 19:12:50 +00:00
paseo-bot[bot] 230037c03b test(app): keep the plugin-buttons still check polling when the subject remounts (#11801)
expectStill polled locator.screenshot() inside expect.poll. A screenshot of an
element that detaches while Playwright waits for it to be stable throws, and
expect.poll does not retry a callback that throws, so one remount of the
Workspace actions toolbar failed the test at once. Treat a detached subject as
not still yet and keep polling.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 18:50:01 +00:00
paseo-bot[bot] 0d9e960d10 fix(app): open outside folder links without trailing slashes (#11786)
Absolute Markdown paths skipped the directory probe and sent existing folders to the file viewer. Use the same host path as file preview so the directory check stays outside the workspace Files listing.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 17:12:55 +00:00
122 changed files with 4021 additions and 826 deletions
+1 -1
View File
@@ -60,7 +60,7 @@
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></td>
<td align="center" width="33%"><a href="https://logits.com/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/logits-on-dark.svg"><img src="packages/website/public/sponsors/logits-on-light.svg" alt="Logits" height="40"></picture></a><br><sub>Optimized intelligence per token, second, dollar.</sub></td>
</tr>
</table>
+1 -1
View File
@@ -54,7 +54,7 @@
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></td>
<td align="center" width="33%"><a href="https://logits.com/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/logits-on-dark.svg"><img src="packages/website/public/sponsors/logits-on-light.svg" alt="Logits" height="40"></picture></a><br><sub>Optimized intelligence per token, second, dollar.</sub></td>
</tr>
</table>
+1 -1
View File
@@ -59,7 +59,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="56"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
<td align="center" width="33%"><a href="https://logits.com/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/logits-on-dark.svg"><img src="packages/website/public/sponsors/logits-on-light.svg" alt="Logits" height="56"></picture></a><br><sub>Optimized intelligence per token, second, dollar.</sub></td>
</tr>
</table>
+1 -1
View File
@@ -60,7 +60,7 @@
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
<td align="center" width="33%"><a href="https://logits.com/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/logits-on-dark.svg"><img src="packages/website/public/sponsors/logits-on-light.svg" alt="Logits" height="40"></picture></a><br><sub>Optimized intelligence per token, second, dollar.</sub></td>
</tr>
</table>
+1 -1
View File
@@ -450,7 +450,7 @@ the message is queued, so any device can open a row's attachments.
Rows take these commands:
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
- **Send now** promotes the row as `interrupt` when your send behavior setting is `interrupt`, and as `steer` otherwise (including `queue`, where the row is already waiting and Send now should not cancel the turn).
- **Edit** is offered on your own messages only. It withdraws the row, then replaces the composer
draft with its text and attachments, and stages the row's provider switch again. If the host
already started sending the row, the draft stays as it is.
+8 -1
View File
@@ -219,7 +219,14 @@ file after the daemon confirms persistence.
> **Window-state v1 limitation:** only the _first_ window of a session restores and persists saved geometry (size/position/maximized). Windows opened via ⌘⇧N / second-instance / "Open in new window" open at the default size, OS-cascaded, and do not persist — this avoids every window stacking on the same restored bounds and fighting over the single window-state store. Lifting this needs per-window state keys.
>
> **In-app browser profiles.** Each local browser tab runs in a persistent Electron partition and can switch profiles at any time; switching replaces the `<webview>` under the new partition and reloads the current URL in that profile's session. Partition names are the identity: `persist:paseo-browser` is **Default** and preserves cookies from before profiles; `persist:paseo-profile-<slug>` is a named profile. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a profile's name or color keeps sign-ins intact and updates open tabs live. Main admits only `persist:paseo-browser`, `persist:paseo-profile-<slug>`, and active host-proxy partitions (`persist:paseo-browser-host-<16hex>`) at `will-attach-webview`. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id, and main accepts it only when that guest belongs to the calling renderer and its session matches the partition. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles: clearing a profile clears its storage/cache and reloads its open tabs; removing a named profile closes its open tabs, removes it from the catalog, clears its session, and deletes its `Partitions/paseo-profile-<slug>` directory from disk. Default cannot be removed.
> **In-app browser profiles.** A browser tab's Electron partition is the pair (route, profile). The route is local, or a host's browser proxy. The profile is **Default** or a named profile. Electron sets the proxy per session (`session.setProxy`), not per `<webview>`, so the route is part of the partition name. Partition names are the identity, and `packages/desktop/src/features/browser-partition.ts` owns them:
>
> | Route | Default | Named profile |
> | ----- | ------------------------------------ | --------------------------------------------------- |
> | Local | `persist:paseo-browser` | `persist:paseo-profile-<slug>` |
> | Host | `persist:paseo-browser-host-<16hex>` | `persist:paseo-browser-host-<16hex>-profile-<slug>` |
>
> `persist:paseo-browser` keeps cookies from before profiles, and the host Default name predates profiles; do not rename either. A host runs one loopback SOCKS5 server and one tunnel. Every profile session on that host points `setProxy` at the same port, so a new profile never opens a second tunnel. Main binds a host profile's session when the renderer calls `ensureHostProxy` with its slug, and verifies it with `resolveProxy`. The status snapshot lists bound sessions in `profilePartitions`, and the tab mounts only after its profile appears there. A tab can switch profile and route at any time: the `<webview>` is replaced under the new partition and reloads the current URL. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a name or color keeps sign-ins intact and updates open tabs live. At `will-attach-webview`, main admits local partitions and only those host partitions whose session it bound. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id. Main accepts it only when that guest belongs to the calling renderer and its session matches the partition, and for a host partition, only when the session is bound to the proxy. Registration is repeated on purpose, because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles on every route: clearing a profile clears its storage and cache on the local route and on each host, then reloads its open tabs. Removing a named profile closes its open tabs, removes it from the catalog, clears its sessions, and deletes each of its `Partitions/` directories. Startup deletes the directories of profiles that are no longer in the catalog. Default cannot be removed.
>
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs and inherit the opener tab's browser profile. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the opener’s browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
>
+5 -3
View File
@@ -216,9 +216,11 @@ its own.
grew once its data arrived left the menu clipped, or hanging over its anchor, until it moved
again. `AnchoredSurface` plays the same keyframes through the Web Animations API on web, which
leaves no inline style; native keeps the Reanimated `Keyframe`.
- **Animate only once placed.** `AnchoredSurface` remounts the surface when its position resolves,
so the entering animation runs at the final position rather than ending unseen at the
off-screen measuring position.
- **Animate only once placed.** The entering animation must run at the final position, not end
unseen at the off-screen measuring position. Native remounts the surface when its position
resolves, because Reanimated's `entering` runs only on mount. Web keeps the surface mounted and
starts its Web Animations entering animation on placement, so a popover's content mounts once
per open.
- **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is
rarely the height of the page before it. A fill page is the one exception.
- **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds
+8 -1
View File
@@ -104,7 +104,14 @@ definition, no longer eligible to begin.
## Integration rules
- Callers request semantic targets through `panel-store`; they never write shared values.
- Gesture behavior comes from the four explicit hooks in `mobile-panels/gestures.ts`.
- Gesture behavior comes from the explicit hooks in `mobile-panels/gestures.ts`.
- A horizontal scroller keeps the touches that start on it: no panel opens or closes under it. Use
`ScrollView` or `FlatList` from `components/ui/scroll-view` with `horizontal`; plugins get the same
components from `@getpaseo/plugin/client/ui`. An `Animated.ScrollView` puts
`usePanelAwareHorizontalScrollGesture` on its own `GestureDetector`. The gesture blocks the
provider's pans and the nearest explorer close pan. Browsers scroll an overflow container
themselves and cancel the page's pointer stream, so the web `ScrollView` needs no gesture. The diff
document's scroller differs on purpose: at its leading edge it waits for the explorer close pan.
- Navigation gestures accept touch pointers only. Mouse and pen fail at touch-down, so dragging a
mouse to select text on a hybrid laptop never moves a panel. Browsers without a touch screen
(`hooks/pointer-capabilities`) never enable them.
@@ -1,5 +1,8 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { gateNextAgentMessage } from "../support/helpers/agent-message-gate";
import { expectComposerDraft, submitMessage } from "../support/helpers/composer";
import { expectAgentIdle } from "../support/helpers/agent-stream";
import { test, expect, type Page } from "../support/fixtures";
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
import { openChangesPanel, openChangesTreePanel } from "../support/helpers/workspace-tabs";
@@ -55,3 +58,45 @@ for (const width of [1400, 390]) {
}
});
}
async function addChangedFileToChat(page: Page) {
await openChangesPanel(page);
await page.getByTestId("diff-file-0-toggle").click({ button: "right" });
await page.getByTestId("diff-file-0-add-to-chat").click();
}
async function expectFollowUpAttachment(page: Page) {
await expect(page.getByTestId("composer-workspace-file-attachment-pill")).toContainText(
"follow-up.ts",
);
}
test("keeps a file added from Changes when an earlier send fails", async ({ page }) => {
const gate = await gateNextAgentMessage(page);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "attachment-during-send-",
title: "Target chat",
featureValues: { mockPromptRejections: 1 },
});
try {
await writeFile(path.join(workspace.cwd, "follow-up.ts"), "export const followUp = true;\n");
await workspace.client.checkoutRefresh(workspace.cwd);
await openAgentRoute(page, workspace);
await expectAgentIdle(page);
await submitMessage(page, "Send this first.");
await gate.waitForRequest();
await addChangedFileToChat(page);
await expectFollowUpAttachment(page);
gate.accept();
await expect(
page.getByRole("alert").filter({ hasText: "Requested mock prompt rejection" }),
).toBeVisible();
await expectFollowUpAttachment(page);
await expectComposerDraft(page, "");
} finally {
await workspace.cleanup();
}
});
@@ -1219,6 +1219,30 @@ test.describe("Agent message submission", () => {
await retryRestoredSubmission(page, prompt);
});
test("keeps a follow-up draft after the earlier send is rejected", async ({ page }, testInfo) => {
const gate = await gateNextAgentMessage(page);
const agent = await seedMockAgentWorkspace({
repoPrefix: `pending-rejection-${testInfo.workerIndex}-`,
title: "Pending rejection",
model: "ten-second-stream",
featureValues: { mockPromptRejections: 1 },
});
try {
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
await expectAgentIdle(page);
await submitMessage(page, "Send this first.");
await gate.waitForRequest();
await fillComposerDraft(page, "Keep this follow-up.");
gate.accept();
await expect(
page.getByRole("alert").filter({ hasText: "Requested mock prompt rejection" }),
).toBeVisible();
await expectComposerDraft(page, "Keep this follow-up.");
} finally {
await agent.cleanup();
}
});
test("restores an ambiguous Steer failure without retrying or interrupting", async ({
page,
}, testInfo) => {
@@ -606,6 +606,35 @@ async function refocusFindAndReplaceQuery(page: Page, shortcut: string) {
await page.keyboard.type("a.b");
await expect(query(page)).toHaveValue("a.b");
await expectHighlight(page, "a.b");
await typeInTheSameTaskAsShortcut(page, shortcut, "x");
await page.keyboard.type(".y");
await expect(query(page)).toHaveValue("x.y");
}
/**
* A fast typist's first key can land before the browser runs any timer queued
* by the shortcut. Pressing the shortcut and typing in one task makes that
* ordering certain instead of left to CI speed.
*/
async function typeInTheSameTaskAsShortcut(page: Page, shortcut: string, text: string) {
await composerLocator(page).click();
await expectComposerFocused(page);
await composerLocator(page).evaluate(
(element, { metaKey, typed }) => {
element.dispatchEvent(
new KeyboardEvent("keydown", {
key: "f",
metaKey,
ctrlKey: !metaKey,
bubbles: true,
cancelable: true,
}),
);
document.execCommand("insertText", false, typed);
},
{ metaKey: shortcut.startsWith("Meta"), typed: text },
);
await expect(query(page)).toBeFocused();
}
async function expectCommandCenterOwnsFindShortcut(page: Page, shortcut: string) {
@@ -4,6 +4,7 @@ import {
attachComposerTestImage,
cancelAgent,
composerLocator,
configureComposerQueueSend,
expectAttachmentPill,
expectComposerDraft,
expectComposerVisible,
@@ -102,6 +103,27 @@ test.describe("Composer queue", () => {
}
});
test("Send now with the queue send behavior steers instead of interrupting", async ({ page }) => {
const prompt = "Fold this into the running turn.";
await configureComposerQueueSend(page);
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-steer-", title: "Queue steer" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await sendQueuedMessageNow(page, prompt);
await expectDeliveredOnce(page, prompt);
// Steering keeps the open turn, so its plan approval is still waiting. An interrupt
// would have replaced the turn and dropped it.
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
expect(fetched?.agent.pendingPermissions).toHaveLength(1);
} finally {
await agent.cleanup();
}
});
test("the host delivers a queued prompt with every client closed", async ({ page }) => {
const prompt = "Continue while I am away.";
const agent = await seedAgentWithOpenTurn({
@@ -294,6 +294,22 @@ test("Import Session keeps listings tied to their host during a switch and a pen
}
});
test("New workspace imports a session into a new workspace beside the one open at its directory", async ({
page,
}, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
await flow.openGlobally();
await flow.importSession("fixture-root-07");
await flow.expectImportedIntoNewWorkspace({
existingWorkspaceId: scenario.project.workspaceId,
userText: "Review fixture item 7",
});
await page.screenshot({ path: testInfo.outputPath("new-workspace-import.png") });
});
test("captures the compact import-session journey", async ({ page }, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 390, height: 844 });
@@ -1,5 +1,10 @@
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import {
clickNewTerminal,
gotoWorkspace,
openNewTabMenuWithShortcut,
} from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
@@ -30,3 +35,44 @@ test("web switches to the previous and next tab with Alt+Shift+[ and ]", async (
await workspace.cleanup();
}
});
async function openBlankTabAfterTerminal(page: Page) {
await clickNewTerminal(page);
await page.getByRole("button", { name: "Terminal 1", exact: true }).focus();
await openNewTabMenuWithShortcut(page);
return page
.getByRole("button", { name: "New tab", exact: true })
.and(page.locator('[aria-selected="true"]'));
}
async function middleClickWithoutDefaultMouseUp(tab: Locator) {
const release = await tab.evaluateHandle((element) => {
const result = { event: null as Event | null };
element.addEventListener(
"mouseup",
(event) => {
result.event = event;
},
{ once: true },
);
return result;
});
await tab.click({ button: "middle" });
await expect(tab).toHaveCount(0);
// Chromium uses the mouseup default action to paste the X11 selection.
expect(await release.evaluate(({ event }) => event?.defaultPrevented)).toBe(true);
}
test("middle-clicking a tab cancels the mouse release before returning to a terminal", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace({ prefix: "tab-middle-click-" });
await workspace.navigateTo();
const tab = await openBlankTabAfterTerminal(page);
await test.step("close the blank tab without the browser's default middle-button action", async () => {
await middleClickWithoutDefaultMouseUp(tab);
await expect(page.getByRole("textbox", { name: "Terminal input" })).toBeFocused();
});
});
@@ -1,5 +1,5 @@
import { expect, type Page } from "@playwright/test";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
import { buildHostWorkspaceRoute, parseHostWorkspaceRouteFromPathname } from "@/utils/host-routes";
import { gotoAppShell } from "./app";
import { openCommandCenter } from "./command-center";
import { openGlobalNewWorkspaceComposer } from "./new-workspace";
@@ -194,6 +194,30 @@ export class ImportSessionFlow {
userText,
);
}
/** The import opened in a workspace of its own, listed in the sidebar beside `existingWorkspaceId`. */
async expectImportedIntoNewWorkspace(input: {
existingWorkspaceId: string;
userText: string;
}): Promise<string> {
await expect
.poll(
() => {
const workspaceId = this.currentWorkspaceId();
return workspaceId !== null && workspaceId !== input.existingWorkspaceId;
},
{ timeout: 30_000 },
)
.toBe(true);
const importedWorkspaceId = this.currentWorkspaceId();
if (!importedWorkspaceId) throw new Error("The import left the workspace route");
await this.expectImportedIntoWorkspace(importedWorkspaceId, input.userText);
for (const id of [input.existingWorkspaceId, importedWorkspaceId]) {
await expect(
this.page.getByTestId(`sidebar-workspace-row-${getServerId()}:${id}`),
).toBeVisible();
}
return importedWorkspaceId;
}
async close() {
await this.page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0);
@@ -218,6 +242,11 @@ export class ImportSessionFlow {
timeout: 30_000,
});
}
private currentWorkspaceId(): string | null {
return (
parseHostWorkspaceRouteFromPathname(new URL(this.page.url()).pathname)?.workspaceId ?? null
);
}
private async rowIds() {
return await this.page
.locator('[data-testid^="import-session-session-claude-"]')
@@ -45,6 +45,9 @@ function Details({ workspaceId, theme, layout, close }) {
owner.subscribe({ snapshot(value) { setOwnerId(value.subscriptionId); }, update() { setUpdates((n) => n + 1); } });
return () => { void owner.release(); };
}, [paseo]);
React.useEffect(() => {
globalThis.__buttonContentMounts = (globalThis.__buttonContentMounts ?? 0) + 1;
}, []);
const rpc = useRpc(summary);
const query = useQuery({ queryKey: ["summary"], queryFn: () => rpc({}) });
if (failed) throw new Error("Button content failed");
@@ -198,6 +201,13 @@ async function expectDetails(page: Page) {
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
}
/** How many times button content has mounted on the page, counted by the content itself. */
async function contentMounts(page: Page): Promise<number> {
return page.evaluate(
() => (globalThis as { __buttonContentMounts?: number }).__buttonContentMounts ?? 0,
);
}
// The details render before the daemon answers their event subscription, and reopened
// details show the cached summary at once, so wait for the subscription id to arrive.
async function readContentObservation(page: Page): Promise<string> {
@@ -231,14 +241,17 @@ async function expectCompactDetails(page: Page) {
await expect(menu.getByText("Presentation: compact", { exact: true })).toBeVisible();
}
/** Resolves once `subject` renders the same pixels twice in a row: entering animations are done. */
/**
* Resolves once `subject` renders the same pixels twice in a row: entering animations are done.
* A remount detaches the element mid-screenshot; that is not still yet, so the poll starts over.
*/
async function expectStill(subject: Locator) {
let previous: Buffer | null = null;
await expect
.poll(
async () => {
const current = await subject.screenshot();
const still = previous !== null && current.equals(previous);
const current = await screenshotAttached(subject);
const still = previous !== null && current !== null && current.equals(previous);
previous = current;
return still;
},
@@ -247,6 +260,17 @@ async function expectStill(subject: Locator) {
.toBe(true);
}
async function screenshotAttached(subject: Locator): Promise<Buffer | null> {
try {
return await subject.screenshot();
} catch (error) {
if (error instanceof Error && error.message.includes("Element is not attached to the DOM")) {
return null;
}
throw error;
}
}
/** Attaches the screen once per colour scheme, for review alongside the run. */
async function captureSchemes(page: Page, info: TestInfo, name: string, subject: Locator) {
for (const colorScheme of ["light", "dark"] as const) {
@@ -360,15 +384,18 @@ export async function withButtonShowcase(
await run({
verifyObservationLifetime: () =>
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
const mountsBefore = await contentMounts(page);
await press(page, "Header status");
await expectDetails(page);
const first = await readContentObservation(page);
expect(await contentMounts(page)).toBe(mountsBefore + 1);
await press(page, "Close deployment details");
await expect.poll(() => released.has(first)).toBe(true);
await press(page, "Composer status");
await expectDetails(page);
const second = await readContentObservation(page);
expect(second).not.toBe(first);
expect(await contentMounts(page)).toBe(mountsBefore + 2);
await workspace.client.renameProject(workspace.projectId, "Observer control");
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
await press(page, "Fail button content");
@@ -55,6 +55,47 @@ it("keeps unavailable probes and external paths on the existing file-open path",
}
});
it("opens an existing absolute folder outside the workspace without a trailing slash", async () => {
const root = await mkdtemp(path.join(tmpdir(), "outside-folder-link-"));
roots.push(root);
const workspaceRoot = path.join(root, "workspace");
const folder = path.join(root, "reports").split(path.sep).join("/");
const file = path.join(root, "notes.txt").split(path.sep).join("/");
await mkdir(workspaceRoot);
await mkdir(folder);
await writeFile(file, "notes");
const { classifyForResolution } = await import("./resolver");
const { resolveInlinePathDestination } = await import("./path-open");
const client = {
listDirectory: (cwd: string, requestedPath: string) => {
const absolute = path.resolve(cwd, requestedPath);
if (path.relative(cwd, absolute).split(path.sep)[0] === "..") {
throw new Error("Access outside of workspace is not allowed");
}
return readdir(absolute);
},
getDirectorySuggestions: async () => ({ entries: [], error: null }),
};
const destination = async (href: string) => {
const resolution = classifyForResolution({ href, text: "Open path" }, { workspaceRoot });
if (resolution.kind !== "resolved" || resolution.value.kind !== "file") {
throw new Error("Expected an explicit path link");
}
return resolveInlinePathDestination({ target: resolution.value.target, workspaceRoot, client });
};
await expect(destination(file)).resolves.toMatchObject({
kind: "file",
location: { path: file },
});
await expect(destination(folder + "/")).resolves.toEqual({
kind: "outsideDirectory",
path: folder,
});
await expect(destination(folder)).resolves.toEqual({ kind: "outsideDirectory", path: folder });
});
it("ignores an older probe after a newer file link opens", async () => {
const { createInlinePathOpener } = await import("./path-open");
let rejectProbe!: (error: Error) => void;
@@ -4,6 +4,7 @@ import {
type WorkspaceFileLocation,
type OpenFileDisposition,
} from "@/workspace/file-open";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { isAbsolutePath } from "@/utils/path";
import { resolveMissingNestedRelativeFile, type GetDirectorySuggestions } from "./resolver";
@@ -26,27 +27,30 @@ function isOutsideWorkspacePath(pathValue: string): boolean {
return isAbsolutePath(pathValue) || pathValue === "~" || pathValue.startsWith("~/");
}
/** Resolve workspace folders from filesystem facts, including names that contain dots. */
/** Resolve folders from filesystem facts, including names that contain dots. */
export async function resolveInlinePathOpen(input: PathOpenInput): Promise<PathOpenTarget> {
if (!input.file) {
return isOutsideWorkspacePath(input.directory)
? { kind: "outsideDirectory", directoryPath: input.directory }
: { kind: "directory", directoryPath: input.directory };
}
if (
input.lineStart !== undefined ||
isAbsolutePath(input.file) ||
!input.workspaceRoot.trim() ||
!input.client
) {
if (input.lineStart !== undefined || !input.workspaceRoot.trim() || !input.client) {
return { kind: "file" };
}
const outside = isOutsideWorkspacePath(input.file);
const probe = outside
? resolveFilePreviewReadTarget({ path: input.file, workspaceRoot: input.workspaceRoot })
: { cwd: input.workspaceRoot, path: input.file };
if (!probe) return { kind: "file" };
try {
await input.client.listDirectory(input.workspaceRoot, input.file);
await input.client.listDirectory(probe.cwd, probe.path);
} catch {
return { kind: "file" };
}
return { kind: "directory", directoryPath: input.file };
return {
kind: outside ? "outsideDirectory" : "directory",
directoryPath: input.file,
};
}
export type InlinePathDestination =
@@ -2,7 +2,6 @@ import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
import { Modal } from "@/components/ui/modal";
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { Pressable, Text, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { StyleSheet } from "react-native-unistyles";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { X } from "lucide-react-native";
@@ -12,7 +11,6 @@ import {
type AttachmentPreviewUrl,
useAttachmentPreviewUrl,
} from "@/attachments/use-attachment-preview-url";
import { isNative } from "@/constants/platform";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { SPACING } from "@/styles/theme";
import { WindowChromeRootRegion } from "@/utils/desktop-window";
@@ -30,7 +28,6 @@ interface AttachmentLightboxProps {
onClose: () => void;
}
const ModalRoot = isNative ? GestureHandlerRootView : View;
const LIGHTBOX_FIT = { padding: SPACING[4], maxWidth: 960, maxHeight: 640 };
export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps) {
@@ -95,7 +92,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
return (
<Modal transparent animationType="fade" statusBarTranslucent visible onRequestClose={onClose}>
<ModalRoot style={styles.root}>
<View style={styles.root}>
{/* The modal draws over the whole window: its insets are the window's, not the ones left
where the image was opened (inside a sheet tab, the bottom one is already spent). */}
<WindowSafeArea>
@@ -129,7 +126,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
</View>
</WindowChromeRootRegion>
</WindowSafeArea>
</ModalRoot>
</View>
</Modal>
);
}
+6 -3
View File
@@ -10,8 +10,11 @@ import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { getCodeInsets } from "./code-insets";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
import { isWeb } from "@/constants/platform";
import { ScrollView } from "@/components/ui/scroll-view";
const ScrollView = isWeb ? RNScrollView : GHScrollView;
// Horizontal code scrolls through the shared ScrollView, which keeps its swipes from the mobile
// panels. Vertical section scrolling keeps its own scroller.
const SectionScrollView = isWeb ? RNScrollView : GHScrollView;
interface DiffViewerProps {
diffLines: DiffLine[];
@@ -182,14 +185,14 @@ export function DiffViewer({
if (!fillAvailableHeight) return horizontalScroll;
const content = (
<ScrollView
<SectionScrollView
style={outerScrollStyle}
contentContainerStyle={webVerticalContentStyle}
nestedScrollEnabled
showsVerticalScrollIndicator
>
{horizontalScroll}
</ScrollView>
</SectionScrollView>
);
return content;
@@ -371,6 +371,12 @@ describe("resolveImportTarget", () => {
).toEqual({ crossWorkspace: true });
});
it("asks for a new workspace when the sheet was opened to create one", () => {
expect(
resolveImportTarget({ entryCwd: "/repo/paseo", isScopedListing: false, newWorkspace: true }),
).toEqual({ newWorkspace: true, crossWorkspace: true });
});
it("treats a sheet with no workspace as cross-workspace", () => {
expect(resolveImportTarget({ entryCwd: "/repo/paseo", isScopedListing: false })).toEqual({
crossWorkspace: true,
@@ -215,6 +215,8 @@ export interface ImportTarget {
* rejects an import whose cwd does not match the requested workspace.
*/
workspaceId?: string;
/** The host creates a fresh workspace for the row's directory. */
newWorkspace?: true;
/**
* The agent lands in a workspace other than the one the sheet was opened from,
* so the caller has to open that workspace instead of adding a tab here.
@@ -229,7 +231,12 @@ export function resolveImportTarget(input: {
workspaceId?: string | null;
/** The listed rows came from a fetch scoped to `workspaceCwd`. */
isScopedListing: boolean;
/** The sheet was opened to create a workspace, so every import gets its own. */
newWorkspace?: boolean;
}): ImportTarget {
if (input.newWorkspace) {
return { newWorkspace: true, crossWorkspace: true };
}
if (!input.workspaceId || !input.workspaceCwd) {
return { crossWorkspace: true };
}
@@ -73,6 +73,8 @@ interface ImportSessionSheetProps {
serverId: string | null;
cwd?: string | null;
workspaceId?: string | null;
/** Each import gets a fresh workspace instead of joining the one open at its directory. */
newWorkspace?: boolean;
onClose: () => void;
/** The agent belongs to the workspace the sheet was opened from; open it here. */
onImportedAgent?: (agentId: string) => void;
@@ -507,6 +509,7 @@ export function ImportSessionSheet({
serverId,
cwd,
workspaceId,
newWorkspace = false,
onClose,
onImportedAgent,
onImported,
@@ -710,12 +713,14 @@ export function ImportSessionSheet({
workspaceCwd: cwd,
workspaceId,
isScopedListing: scopeCwd !== null,
newWorkspace,
});
const agent = await client.importAgent({
providerId: entry.providerId,
providerHandleId: entry.providerHandleId,
cwd: entry.cwd,
...(target.workspaceId ? { workspaceId: target.workspaceId } : {}),
...(target.newWorkspace ? { newWorkspace: true } : {}),
});
// A pending import keeps the listing and navigation from the host it was sent to.
void queryClient.invalidateQueries({
@@ -1,5 +1,6 @@
import React, { Component, type ErrorInfo, type ReactNode } from "react";
import { Text, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
@@ -63,8 +64,10 @@ export function RootErrorFallback({ error, onReload }: RootErrorFallbackProps) {
</Button>
);
// The fallback replaces the app tree, so it sits above the app's gesture root and needs its own:
// the details scroll sideways under a gesture detector on native.
return (
<View
<GestureHandlerRootView
style={[
styles.container,
{
@@ -95,7 +98,7 @@ export function RootErrorFallback({ error, onReload }: RootErrorFallbackProps) {
{isCompact ? null : reload}
</View>
{isCompact ? <View style={styles.footer}>{reload}</View> : null}
</View>
</GestureHandlerRootView>
);
}
@@ -26,8 +26,11 @@ import { HighlightedLines } from "./highlighted-content";
import { DiffViewer } from "./diff-viewer";
import { getCodeInsets } from "./code-insets";
import { isWeb } from "@/constants/platform";
import { ScrollView } from "@/components/ui/scroll-view";
const ScrollView = isWeb ? RNScrollView : GHScrollView;
// Horizontal code scrolls through the shared ScrollView, which keeps its swipes from the mobile
// panels. Vertical section scrolling keeps its own scroller.
const SectionScrollView = isWeb ? RNScrollView : GHScrollView;
// A capped detail scrolls as a whole. Only full-height sheets need section scrollers.
function DetailSectionBody({
@@ -40,9 +43,13 @@ function DetailSectionBody({
const bodyStyle = useMemo(() => [style, contentContainerStyle], [style, contentContainerStyle]);
if (fillAvailableHeight) {
return (
<ScrollView {...scrollProps} style={style} contentContainerStyle={contentContainerStyle}>
<SectionScrollView
{...scrollProps}
style={style}
contentContainerStyle={contentContainerStyle}
>
{children}
</ScrollView>
</SectionScrollView>
);
}
return <View style={bodyStyle}>{children}</View>;
@@ -576,13 +583,13 @@ export function ToolCallDetailsContent({
if (resolvedMaxHeight !== undefined) {
return (
<ScrollView
<SectionScrollView
style={inlineUnistylesStyle({ maxHeight: resolvedMaxHeight })}
contentContainerStyle={ds.fullBleedContainerStyle}
nestedScrollEnabled
>
{sections}
</ScrollView>
</SectionScrollView>
);
}
return <View style={ds.fullBleedContainerStyle}>{sections}</View>;
+1 -3
View File
@@ -32,7 +32,6 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { BottomSheetScrollView, type BottomSheetBackgroundProps } from "@gorhom/bottom-sheet";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { Check, File, Folder, Search } from "lucide-react-native";
import {
flip,
@@ -1410,8 +1409,7 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
visible={props.isOpen}
onRequestClose={props.handleClose}
>
{/* Android Modal opens a separate window outside the app's gesture root. */}
<GestureHandlerRootView style={styles.desktopOverlay}>{overlay}</GestureHandlerRootView>
{overlay}
</Modal>
);
}
@@ -120,6 +120,27 @@ describe("anchored menu surface on web", () => {
},
);
it("mounts its content once per open", async () => {
const lifecycle: string[] = [];
function RecordsMounts() {
useEffect(() => {
lifecycle.push("mount");
return () => {
lifecycle.push("unmount");
};
}, []);
return <View testID="body" style={SHORT} />;
}
mountMenuAbovePill(<RecordsMounts />);
await wait(SETTLE_MS);
expect(element("panel").getBoundingClientRect().bottom).toBeLessThanOrEqual(
element("pill").getBoundingClientRect().top,
);
expect(lifecycle).toEqual(["mount"]);
});
it("widens when its content widens after the entering animation", async () => {
mountMenuAbovePill(<GrowsAfterOpen afterMs={GROWS_BEFORE_CLEANUP_MS} from={SHORT} to={WIDE} />);
@@ -284,9 +284,12 @@ export function AnchoredSurface({
// The surface is placed once both measurements land. Until then it sits off-screen so it can
// be measured, and it must not animate: an entering animation that ran there would be over
// before anyone saw the menu. Remounting on placement starts the native animation from the
// final position; web starts its own animation on placement.
// before anyone saw the menu. Native remounts the surface on placement so Reanimated's
// `entering` starts from the final position. Web keeps it mounted and starts its own animation
// on placement: a remount would mount the content twice per open, running its effects and
// requests again and dropping its first state.
const placed = position !== null;
const surfaceKey = isWeb || placed ? "placed" : "measuring";
useWebContentEntering({ placed, surfaceNativeID });
@@ -365,7 +368,7 @@ export function AnchoredSurface({
) : null}
<View pointerEvents="box-none" style={frame.holder}>
<FloatingSurface
key={placed ? "placed" : "measuring"}
key={surfaceKey}
collapsable={false}
tabIndex={-1}
nativeID={surfaceNativeID}
+17 -2
View File
@@ -3,9 +3,12 @@ import {
Modal as NativeModal,
Platform,
useWindowDimensions,
StyleSheet,
type ModalProps as NativeModalProps,
} from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
import { isNative } from "@/constants/platform";
// React Native defaults iPhone modals to portrait even when the app supports rotation.
const orientations: NonNullable<NativeModalProps["supportedOrientations"]> = [
@@ -22,14 +25,26 @@ type ModalProps = Omit<NativeModalProps, "onRequestClose"> & {
function noClose() {}
export function Modal(props: ModalProps) {
export function Modal({ children, ...props }: ModalProps) {
const { visible = true, onRequestClose, style } = props;
useDismissibleOverlay(visible && onRequestClose !== undefined, onRequestClose ?? noClose);
const windowFrame = useAndroidWindowFrame();
const containerStyle = useMemo(() => [windowFrame, style], [windowFrame, style]);
return <NativeModal supportedOrientations={orientations} {...props} style={containerStyle} />;
return (
<NativeModal supportedOrientations={orientations} {...props} style={containerStyle}>
{isNative ? (
<GestureHandlerRootView style={styles.gestureRoot}>{children}</GestureHandlerRootView>
) : (
children
)}
</NativeModal>
);
}
// A native modal is a separate window above the app's gesture root. Its content gets its own, so
// gestures recognize there and gesture detectors (a horizontal ScrollView) can mount.
const styles = StyleSheet.create({ gestureRoot: { flex: 1 } });
/**
* On Android, React Native lays out a modal's first frames at the screen size minus the status and
* navigation bars, then grows it to the full window once the dialog reports its size. The app draws
@@ -0,0 +1,229 @@
import React, { act, createRef, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import {
ScrollView as ReactNativeScrollView,
View,
type FlatList as ReactNativeFlatList,
} from "react-native";
import { GestureDetector } from "react-native-gesture-handler";
import { afterEach, describe, expect, it } from "vitest";
import { cdp } from "vitest/browser";
import {
FileExplorerCloseGestureContext,
useCloseFileExplorerGesture,
useOpenFileExplorerGesture,
} from "@/mobile-panels/gestures";
import { MobilePanelsProvider } from "@/mobile-panels/provider";
import { usePanelStore } from "@/stores/panel-store";
import { FlatList, ScrollView } from "./scroll-view.native";
import { ScrollView as WebScrollView } from "./scroll-view.web";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
const initialPanelState = usePanelStore.getState();
let root: Root | null = null;
let host: HTMLDivElement | null = null;
let explorerOpens = 0;
function recordExplorerOpen(): void {
explorerOpens += 1;
}
afterEach(async () => {
await act(async () => root?.unmount());
host?.remove();
root = null;
host = null;
usePanelStore.setState(initialPanelState, true);
explorerOpens = 0;
});
const FILL = { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 } as const;
const ROW = { height: 120 } as const;
const WIDE_CONTENT = { width: 2000, height: 120 } as const;
const ITEMS = ["one", "two", "three"];
const WIDE_ITEM = { width: 800, height: 120 } as const;
async function mount(node: ReactNode): Promise<void> {
host = document.createElement("div");
host.style.cssText = "position: fixed; inset: 0;";
document.body.appendChild(host);
const created = createRoot(host);
root = created;
await act(async () => created.render(<MobilePanelsProvider>{node}</MobilePanelsProvider>));
}
function byTestID(testID: string): HTMLElement {
const element = document.querySelector(`[data-testid="${testID}"]`);
if (!(element instanceof HTMLElement)) throw new Error(`${testID} did not render`);
return element;
}
/** Converts a point in the test frame to the top page, which draws the frame scaled to fit. */
function toPage(x: number, y: number): { x: number; y: number } {
const frame = window.frameElement?.getBoundingClientRect();
const scale = frame ? frame.width / window.innerWidth : 1;
return { x: x * scale, y: y * scale };
}
function horizontalPath(direction: "left" | "right"): [number, number] {
const width = window.innerWidth;
return direction === "left" ? [width - 8, 20] : [20, width - 8];
}
/**
* A drag across the row with real pointer input. A browser does not scroll an overflow container
* for a mouse drag, so the row reports only what the gesture handlers decide between themselves:
* the arbitration iOS and Android run for a touch.
*/
async function dragAcross(row: HTMLElement, direction: "left" | "right"): Promise<void> {
const session = cdp();
const y = row.getBoundingClientRect().top + 60;
const [fromX, toX] = horizontalPath(direction);
const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number) =>
session.send("Input.dispatchMouseEvent", {
type,
...toPage(x, y),
button: "left",
buttons: type === "mouseReleased" ? 0 : 1,
clickCount: 1,
});
await mouse("mousePressed", fromX);
const steps = 12;
for (let step = 1; step <= steps; step += 1) {
await mouse("mouseMoved", fromX + ((toX - fromX) * step) / steps);
}
await mouse("mouseReleased", toX);
await new Promise((resolve) => setTimeout(resolve, 100));
}
function ExplorerOpenSurface({ children }: { children: ReactNode }) {
const gesture = useOpenFileExplorerGesture({ enabled: true, onOpen: recordExplorerOpen });
return (
<GestureDetector gesture={gesture} touchAction="pan-y">
<View style={FILL}>{children}</View>
</GestureDetector>
);
}
function ExplorerCloseSurface({ children }: { children: ReactNode }) {
const { gesture, gestureRef } = useCloseFileExplorerGesture(true);
return (
<FileExplorerCloseGestureContext value={gestureRef}>
<GestureDetector gesture={gesture} touchAction="pan-y">
<View style={FILL}>{children}</View>
</GestureDetector>
</FileExplorerCloseGestureContext>
);
}
function wideItem() {
return <View style={WIDE_ITEM} />;
}
const rows = {
plain: () => <View testID="row" style={ROW} />,
verticalScrollView: () => (
<ScrollView testID="row" style={ROW}>
<View style={WIDE_CONTENT} />
</ScrollView>
),
horizontalScrollView: () => (
<ScrollView testID="row" style={ROW} horizontal>
<View style={WIDE_CONTENT} />
</ScrollView>
),
horizontalFlatList: () => (
<FlatList testID="row" style={ROW} horizontal data={ITEMS} renderItem={wideItem} />
),
};
describe("native ScrollView and FlatList beside the mobile panels", () => {
async function swipeToOpenExplorer(row: () => ReactNode): Promise<number> {
await mount(<ExplorerOpenSurface>{row()}</ExplorerOpenSurface>);
await dragAcross(byTestID("row"), "left");
return explorerOpens;
}
it("opens a panel from a swipe on content that does not scroll sideways", async () => {
expect(await swipeToOpenExplorer(rows.plain)).toBe(1);
});
it("leaves a sideways swipe on a vertical ScrollView to the panel", async () => {
expect(await swipeToOpenExplorer(rows.verticalScrollView)).toBe(1);
});
it("keeps a sideways swipe on a horizontal ScrollView from opening a panel", async () => {
expect(await swipeToOpenExplorer(rows.horizontalScrollView)).toBe(0);
});
it("keeps a sideways swipe on a horizontal FlatList from opening a panel", async () => {
expect(await swipeToOpenExplorer(rows.horizontalFlatList)).toBe(0);
});
async function swipeToCloseExplorer(row: () => ReactNode): Promise<string> {
usePanelStore.setState({ mobilePanel: { target: "file-explorer", revision: 1 } });
await mount(<ExplorerCloseSurface>{row()}</ExplorerCloseSurface>);
await dragAcross(byTestID("row"), "right");
return usePanelStore.getState().mobilePanel.target;
}
it("closes an open panel from a swipe on content that does not scroll sideways", async () => {
expect(await swipeToCloseExplorer(rows.plain)).toBe("agent");
});
it("keeps a sideways swipe on a horizontal ScrollView from closing the panel it is in", async () => {
expect(await swipeToCloseExplorer(rows.horizontalScrollView)).toBe("file-explorer");
});
it("forwards refs to the React Native scroll view and list", async () => {
const scrollRef = createRef<ReactNativeScrollView>();
const listRef = createRef<ReactNativeFlatList<string>>();
await mount(
<>
<ScrollView ref={scrollRef} horizontal>
<View style={WIDE_CONTENT} />
</ScrollView>
<FlatList ref={listRef} horizontal data={ITEMS} renderItem={wideItem} />
</>,
);
expect(typeof scrollRef.current?.scrollTo).toBe("function");
expect(typeof listRef.current?.scrollToOffset).toBe("function");
});
});
/** A one-finger swipe with real touch input; the browser scrolls overflow containers for it. */
async function touchSwipeAcross(row: HTMLElement, direction: "left" | "right"): Promise<void> {
const session = cdp();
await session.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
const y = row.getBoundingClientRect().top + 60;
const [fromX, toX] = horizontalPath(direction);
const touch = (type: "touchStart" | "touchMove", x: number) =>
session.send("Input.dispatchTouchEvent", { type, touchPoints: [toPage(x, y)] });
await touch("touchStart", fromX);
const steps = 12;
for (let step = 1; step <= steps; step += 1) {
await touch("touchMove", fromX + ((toX - fromX) * step) / steps);
await new Promise((resolve) => setTimeout(resolve, 16));
}
await session.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await new Promise((resolve) => setTimeout(resolve, 200));
}
describe("web ScrollView beside the mobile panels", () => {
// The browser scrolls a horizontal overflow container itself and cancels the page's pointer
// stream, so the plain React Native ScrollView already keeps the swipe on web.
it("scrolls a horizontal ScrollView under a real touch swipe instead of opening a panel", async () => {
await mount(
<ExplorerOpenSurface>
<WebScrollView testID="row" style={ROW} horizontal>
<View style={WIDE_CONTENT} />
</WebScrollView>
</ExplorerOpenSurface>,
);
await touchSwipeAcross(byTestID("row"), "left");
expect(byTestID("row").scrollLeft).toBeGreaterThan(0);
expect(explorerOpens).toBe(0);
});
});
@@ -0,0 +1,64 @@
import { forwardRef, type ReactElement, type Ref } from "react";
import {
ScrollView as NativeScrollView,
FlatList as NativeFlatList,
type ScrollViewProps,
type FlatListProps,
} from "react-native";
import { BottomSheetScrollView, BottomSheetFlatList } from "@gorhom/bottom-sheet";
import { GestureDetector } from "react-native-gesture-handler";
import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures";
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
import { withContentDrag } from "./content-drag";
// Gorhom forwards to the RN FlatList and ScrollView instances. Its published ref types disagree
// about getScrollResponder; keep that type discrepancy at this boundary.
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
/** The presentation owns gesture integration; callers keep the React Native API. */
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
if (props.horizontal) {
return (
<HorizontalScrollGesture>
<NativeScrollView {...props} ref={ref} />
</HorizontalScrollGesture>
);
}
if (inSheet) return <SheetScrollView {...props} ref={ref} />;
return <PageScrollView {...props} ref={ref} />;
},
);
/** Sideways scrolling looks the same in a sheet and on a page: the scroller keeps its touches. */
function HorizontalScrollGesture({ children }: { children: ReactElement }) {
const gesture = usePanelAwareHorizontalScrollGesture();
return <GestureDetector gesture={gesture}>{children}</GestureDetector>;
}
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
SheetScroll,
useAttachSheetContentDrag,
);
function PresentationFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
const inSheet = useIsInsideBottomSheet();
if (props.horizontal) {
return (
<HorizontalScrollGesture>
<NativeFlatList {...props} ref={ref} />
</HorizontalScrollGesture>
);
}
if (inSheet) return <SheetFlatList {...props} ref={ref} />;
return <NativeFlatList {...props} ref={ref} />;
}
// forwardRef erases the item generic. Both implementations expose the RN list methods.
export const FlatList = forwardRef(PresentationFlatList) as <Item>(
props: FlatListProps<Item> & { ref?: Ref<NativeFlatList<Item>> },
) => ReactElement;
+2 -66
View File
@@ -1,66 +1,2 @@
import { forwardRef, type Ref } from "react";
import {
ScrollView as NativeScrollView,
FlatList as NativeFlatList,
type ScrollViewProps,
type FlatListProps,
} from "react-native";
import { BottomSheetScrollView, BottomSheetFlatList } from "@gorhom/bottom-sheet";
import {
ScrollView as GestureScrollView,
FlatList as GestureFlatList,
type NativeViewGestureHandlerProps,
} from "react-native-gesture-handler";
import { isNative } from "@/constants/platform";
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
import { withContentDrag } from "./content-drag";
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
// disagree about getScrollResponder (Gorhom) and include the component function
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
) => React.ReactElement;
/** The presentation owns gesture integration; callers keep the React Native API. */
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
if (props.horizontal) {
return isNative ? (
<GestureScrollView {...props} ref={ref} disallowInterruption />
) : (
<NativeScrollView {...props} ref={ref} />
);
}
return <SheetScrollView {...props} ref={ref} />;
},
);
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
SheetScroll,
useAttachSheetContentDrag,
);
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
const inSheet = useIsInsideBottomSheet();
if (!inSheet) return <NativeFlatList {...props} ref={ref} />;
if (props.horizontal) {
return isNative ? (
<HorizontalFlatList {...props} ref={ref} disallowInterruption />
) : (
<NativeFlatList {...props} ref={ref} />
);
}
return <SheetFlatList {...props} ref={ref} />;
}
// forwardRef erases the item generic. All three implementations expose the RN list methods.
export const FlatList = forwardRef(SheetAwareFlatList) as <Item>(
props: FlatListProps<Item> & { ref?: Ref<NativeFlatList<Item>> },
) => React.ReactElement;
// Metro loads scroll-view.native.tsx or scroll-view.web.tsx; TypeScript checks callers against native.
export { ScrollView, FlatList } from "./scroll-view.native";
@@ -467,6 +467,7 @@ export function WorkspaceSetupDialog() {
attachments={chatDraft.attachments}
onChangeAttachments={chatDraft.setAttachments}
cwd={sourceDirectory}
getDraftRevision={chatDraft.getRevision}
clearDraft={chatDraft.clear}
autoFocus
commandDraft={composerState?.commandDraft}
@@ -68,6 +68,7 @@ export interface AgentInputDraft {
textReplacement: TextReplacement;
attachments: UserComposerAttachment[];
setAttachments: (updater: AttachmentUpdater) => void;
getRevision: () => number;
clear: (lifecycle: "sent" | "abandoned") => void;
isHydrated: boolean;
attachmentFocusRequestId: number;
@@ -195,6 +196,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
[draftKey],
);
const getRevision = useCallback(
() => useDraftStore.getState().getDraftRevision(draftKey),
[draftKey],
);
const clear = useCallback(
(lifecycle: "sent" | "abandoned") => {
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
@@ -381,6 +387,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -587,6 +587,7 @@ export function WorkspaceDraftComposer({
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={draftInput.setAttachments}
cwd={composerState.workingDir}
getDraftRevision={draftInput.getRevision}
clearDraft={draftInput.clear}
editingSession={editingSession}
autoFocus={shouldAutoFocusWorkspaceDraftComposer({ isPaneFocused, isSubmitting })}
+4
View File
@@ -952,6 +952,7 @@ interface ComposerProps {
onForgeChangeRequestDetected?: () => void;
onForgeChangeRequestAutoAttach?: (item: ForgeSearchItem) => void;
cwd: string;
getDraftRevision: () => number;
clearDraft: (lifecycle: "sent" | "abandoned") => void;
/** When true, auto-focuses the text input on web. */
autoFocus?: boolean;
@@ -1280,6 +1281,7 @@ function ComposerContentImpl({
onForgeChangeRequestDetected,
onForgeChangeRequestAutoAttach,
cwd,
getDraftRevision,
clearDraft,
autoFocus = false,
autoFocusKey,
@@ -1882,6 +1884,7 @@ function ComposerContentImpl({
await submitMessage(submitText, submitAttachments);
},
clearDraft,
getDraftRevision,
setUserInput: replaceUserInput,
setAttachments: (nextAttachments) => {
setSelectedAttachments(composerWorkspaceAttachment.userAttachmentsOnly(nextAttachments));
@@ -1904,6 +1907,7 @@ function ComposerContentImpl({
clearDraft,
completeSubmit,
enqueueMessage,
getDraftRevision,
hasExternalContent,
isAgentRunning,
supportsQueue,
@@ -133,7 +133,7 @@ describe("sendQueuedMessageNow", () => {
it.each([
["steer", "a:steer"],
["interrupt", "a:interrupt"],
["queue", "a:interrupt"],
["queue", "a:steer"],
] as const)("with the %s send behavior promotes as %s", async (sendBehavior, expected) => {
const queue = await queueHolding(queued);
+1 -1
View File
@@ -51,6 +51,6 @@ export async function sendQueuedMessageNow(input: {
}): Promise<void> {
await input.model.promote(
input.messageId,
input.sendBehavior === "steer" ? "steer" : "interrupt",
input.sendBehavior === "interrupt" ? "interrupt" : "steer",
);
}
+1 -1
View File
@@ -49,7 +49,7 @@ const QUEUE_MAX_HEIGHT_COMPACT = 140;
interface ComposerQueueTrackProps {
serverId: string;
agentId: string;
/** The user's send behavior setting. Send now steers or interrupts accordingly. */
/** The user's send behavior setting. Send now interrupts only when it is `interrupt`; otherwise it steers. */
sendBehavior: SendBehavior;
providerLabel: (provider: string) => string;
onRestore: (message: RestoredQueuedMessage) => void;
+53
View File
@@ -35,6 +35,7 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
@@ -59,6 +60,53 @@ describe("submitAgentInput", () => {
expect(clearDraft).toHaveBeenCalledWith("sent");
});
it.each([
{ delivery: "send", outcome: "failed" },
{ delivery: "send", outcome: "submitted" },
{ delivery: "queue", outcome: "failed" },
{ delivery: "queue", outcome: "queued" },
] as const)(
"preserves edits made while a $delivery is pending ($outcome)",
async ({ delivery, outcome }) => {
let revision = 0;
let text = "first message";
let attachments = ["first.txt"];
const setUserInput = (next: string) => {
text = next;
revision++;
};
const setAttachments = (next: string[]) => {
attachments = next;
revision++;
};
const deferred = createDeferredPromise<void>();
const result = submitAgentInput({
message: text,
attachments,
isAgentRunning: delivery === "queue",
canSubmit: true,
queueMessage: () => deferred.promise,
submitMessage: () => deferred.promise,
clearDraft: () => {
setUserInput("");
setAttachments([]);
},
setUserInput,
setAttachments,
getDraftRevision: () => revision,
setSendError: vi.fn(),
setIsProcessing: vi.fn(),
});
setUserInput("follow-up");
setAttachments(["second.txt"]);
if (outcome === "failed") deferred.reject(new Error("offline"));
else deferred.resolve();
expect(await result).toBe(outcome);
expect(text).toBe("follow-up");
expect(attachments).toEqual(["second.txt"]);
},
);
it("preserves the composer before an in-flight submit resolves when requested", async () => {
const deferred = createDeferredPromise<void>();
const attachments = [{ id: "img-1" }];
@@ -80,6 +128,7 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
@@ -123,6 +172,7 @@ describe("submitAgentInput", () => {
submitMessage: async ({ message }) => {
sent.push(message);
},
getDraftRevision: () => 0,
clearDraft: (lifecycle) => {
composer.draft = lifecycle;
},
@@ -193,6 +243,7 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
@@ -232,6 +283,7 @@ describe("submitAgentInput", () => {
submitMessage: async () => {
throw error;
},
getDraftRevision: () => 0,
clearDraft: vi.fn(),
setUserInput,
setAttachments,
@@ -265,6 +317,7 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
+6 -2
View File
@@ -17,6 +17,7 @@ export interface AgentInputSubmitActionInput<TAttachment> {
clearDraft: (lifecycle: "sent" | "abandoned") => void;
setUserInput: (text: string) => void;
setAttachments: (attachments: TAttachment[]) => void;
getDraftRevision: () => number;
setSendError: (message: string | null) => void;
setIsProcessing: (isProcessing: boolean) => void;
onSubmitError?: (error: unknown) => void;
@@ -50,18 +51,21 @@ export async function submitAgentInput<TAttachment>(
input.setUserInput("");
input.setAttachments([]);
}
const submittedRevision = shouldClearOnSubmit ? input.getDraftRevision() : null;
input.setSendError(null);
input.setIsProcessing(true);
try {
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
await deliver({ message: trimmedMessage, attachments });
input.clearDraft("sent");
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
input.clearDraft("sent");
}
input.setIsProcessing(false);
return shouldQueue ? "queued" : "submitted";
} catch (error) {
input.onSubmitError?.(error);
if (shouldClearOnSubmit) {
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
input.setUserInput(trimmedMessage);
input.setAttachments(attachments);
}
@@ -1,8 +1,4 @@
import {
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserProfilePartition,
useBrowserProfileCatalog,
} from "../profiles";
import { DEFAULT_BROWSER_PROFILE_SLUG, useBrowserProfileCatalog } from "../profiles";
import { ProfileSelector } from "./profile-selector.electron";
import {
useCallback,
@@ -831,16 +827,12 @@ export function BrowserPane({
const updateBrowser = useBrowserStore((state) => state.updateBrowser);
const setBrowserViewport = useBrowserStore((state) => state.setBrowserViewport);
const setBrowserRoutingMode = useBrowserStore((state) => state.setBrowserRoutingMode);
const proxyState = useHostBrowserProxy({ serverId, routingMode: browser?.routingMode });
const isLocalProfileMode =
proxyState.kind === "ready" && proxyState.effectiveRoutingMode === "local";
let activePartition: string | null = null;
if (proxyState.kind === "ready") {
activePartition =
proxyState.effectiveRoutingMode === "host"
? proxyState.partition
: getBrowserProfilePartition(profileSlug);
}
const proxyState = useHostBrowserProxy({
serverId,
routingMode: browser?.routingMode,
profileSlug,
});
const activePartition = proxyState.kind === "ready" ? proxyState.partition : null;
const browserViewport = browser?.viewport ?? RESPONSIVE_BROWSER_VIEWPORT;
const browserViewportRef = useRef(browserViewport);
browserViewportRef.current = browserViewport;
@@ -1813,15 +1805,13 @@ export function BrowserPane({
initialValue={draftUrl}
/>
</View>
{isLocalProfileMode ? (
<ProfileSelector
selectedSlug={profileSlug}
catalog={catalog.data ?? []}
triggerStyle={profileTriggerStyle}
onSelect={selectProfile}
refresh={refreshProfiles}
/>
) : null}
<ProfileSelector
selectedSlug={profileSlug}
catalog={catalog.data ?? []}
triggerStyle={profileTriggerStyle}
onSelect={selectProfile}
refresh={refreshProfiles}
/>
<View style={styles.chromeRight}>
<DeviceSizeMenu
selectedId={selectedDeviceSizeId}
@@ -1,4 +1,5 @@
import { getIsElectron } from "@/constants/platform";
import { DEFAULT_BROWSER_PROFILE_SLUG } from "@/desktop/browser/profiles";
import {
getDesktopHost,
type DesktopBrowserProxyStatusSnapshot,
@@ -35,13 +36,18 @@ function notifyStatusListeners(serverId: string): void {
}
}
function hasSameProfilePartitions(a: Record<string, string>, b: Record<string, string>): boolean {
const slugs = Object.keys(a);
return slugs.length === Object.keys(b).length && slugs.every((slug) => a[slug] === b[slug]);
}
function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
const existing = statusByServerId.get(snapshot.serverId);
if (
existing &&
existing.status === snapshot.status &&
existing.error === snapshot.error &&
existing.partition === snapshot.partition &&
hasSameProfilePartitions(existing.profilePartitions, snapshot.profilePartitions) &&
existing.socksPort === snapshot.socksPort
) {
return;
@@ -53,9 +59,12 @@ function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
function isStatusSnapshot(value: unknown): value is DesktopBrowserProxyStatusSnapshot {
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
const record = value as Record<string, unknown>;
const profilePartitions = record.profilePartitions;
return (
typeof record.serverId === "string" &&
typeof record.partition === "string" &&
typeof profilePartitions === "object" &&
profilePartitions !== null &&
Object.values(profilePartitions).every((partition) => typeof partition === "string") &&
typeof record.status === "string"
);
}
@@ -268,6 +277,7 @@ export function subscribeBrowserProxyStatus(serverId: string, listener: () => vo
export async function ensureHostBrowserProxy(input: {
serverId: string;
target: SupportedTarget;
profileSlug?: string;
forceReconnect?: boolean;
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
installBrowserProxyRendererBridge();
@@ -345,14 +355,15 @@ export async function prepareHostBrowserPartition(
message: "Browser proxy bridge is unavailable in this desktop build.",
};
}
if (status.status !== "ready") {
const partition = status.profilePartitions[DEFAULT_BROWSER_PROFILE_SLUG];
if (status.status !== "ready" || !partition) {
return {
ok: false,
reason: "proxy_error",
message: status.error ?? "Unable to connect browser proxy.",
};
}
return { ok: true, partition: status.partition, isRemoteHost: true };
return { ok: true, partition, isRemoteHost: true };
} catch (error) {
return {
ok: false,
@@ -9,7 +9,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_connecting" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: null,
ensureError: null,
@@ -27,11 +27,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "connecting",
error: null,
socksPort: null,
@@ -50,7 +50,7 @@ describe("resolveBrowserProxyPaneState", () => {
it("keeps the prepared host partition mounted across transient host disconnects and reconnects", () => {
const preparedSnapshot = {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "ready" as const,
error: null,
socksPort: 41234,
@@ -60,7 +60,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: preparedSnapshot,
ensureError: null,
@@ -68,7 +68,7 @@ describe("resolveBrowserProxyPaneState", () => {
}),
).toEqual({
kind: "ready",
partition: preparedSnapshot.partition,
partition: preparedSnapshot.profilePartitions.default,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
@@ -79,7 +79,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_connecting" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: preparedSnapshot,
ensureError: null,
@@ -87,7 +87,7 @@ describe("resolveBrowserProxyPaneState", () => {
}),
).toEqual({
kind: "ready",
partition: preparedSnapshot.partition,
partition: preparedSnapshot.profilePartitions.default,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
@@ -106,11 +106,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "error",
error: "Host disconnected",
socksPort: 41234,
@@ -133,11 +133,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "ready",
error: null,
socksPort: 41234,
@@ -159,11 +159,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "error",
error: "Unable to create ticket",
socksPort: null,
@@ -185,7 +185,7 @@ describe("resolveBrowserProxyPaneState", () => {
const routedTarget = { via: "unix:///tmp/paseo.sock", serverId: "srv-dev" };
const input = {
effectiveRoutingMode: "host" as const,
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "dev",
ensureError: null,
onRetry: noop,
@@ -212,7 +212,7 @@ describe("resolveBrowserProxyPaneState", () => {
routing,
proxyStatusSnapshot: {
serverId: "srv-dev",
partition: "persist:paseo-browser-host-dev",
profilePartitions: { default: "persist:paseo-browser-host-dev" },
status: "ready",
error: null,
socksPort: 41000,
@@ -250,7 +250,7 @@ describe("resolveBrowserProxyPaneState", () => {
routing: { kind: "remote", support: "host_connecting" },
proxyStatusSnapshot: {
serverId: "srv-dev",
partition: "persist:paseo-browser-host-dev",
profilePartitions: { default: "persist:paseo-browser-host-dev" },
status: "ready",
error: null,
socksPort: 41000,
@@ -259,4 +259,102 @@ describe("resolveBrowserProxyPaneState", () => {
).toMatchObject({ kind: "ready", proxyStatus: "reconnecting" });
});
});
describe("browser profiles", () => {
const hostDefault = "persist:paseo-browser-host-0123456789abcdef";
const hostWork = `${hostDefault}-profile-work`;
const supportedRouting = {
kind: "remote" as const,
support: "supported" as const,
target: "tcp://10.0.0.5:6767",
};
const base = {
hostLabel: "devbox",
ensureError: null,
onRetry: noop,
};
it("mounts the local partition of the tab's profile when routing locally", () => {
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "local",
profileSlug: "work",
proxyStatusSnapshot: null,
}),
).toMatchObject({ kind: "ready", partition: "persist:paseo-profile-work" });
});
it("waits for the host to bind the profile's session instead of mounting another profile", () => {
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "work",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: hostDefault },
status: "ready",
error: null,
socksPort: 41234,
},
}),
).toMatchObject({ kind: "connecting", effectiveRoutingMode: "host" });
});
it("waits for a profile whose slug matches an Object property name", () => {
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "constructor",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: hostDefault },
status: "ready",
error: null,
socksPort: 41234,
},
}),
).toMatchObject({ kind: "connecting", effectiveRoutingMode: "host" });
});
it("mounts the host partition of the tab's profile once it is bound", () => {
const snapshot = {
serverId: "srv-remote",
profilePartitions: { default: hostDefault, work: hostWork },
status: "ready" as const,
error: null,
socksPort: 41234,
};
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "work",
proxyStatusSnapshot: snapshot,
}),
).toEqual({
kind: "ready",
partition: hostWork,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
proxyStatus: "ready",
});
expect(
resolveBrowserProxyPaneState({
...base,
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
profileSlug: "work",
proxyStatusSnapshot: snapshot,
}),
).toMatchObject({ kind: "ready", partition: hostWork, proxyStatus: "reconnecting" });
});
});
});
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { getIsElectron } from "@/constants/platform";
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
import type { DesktopBrowserProxyStatus } from "@/desktop/host";
import { getBrowserProfilePartition } from "@/desktop/browser/profiles";
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
import { useHosts } from "@/runtime/host-runtime";
import { normalizeHostLabel } from "@/types/host-connection";
@@ -51,29 +52,35 @@ export type BrowserProxyPaneState =
retry: () => void;
};
function hasPreparedHostPartition(
/** The profile's host partition, once main has bound its session to the host's SOCKS5 port. */
function readPreparedHostPartition(
snapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
): snapshot is NonNullable<ReturnType<typeof getCachedBrowserProxyStatus>> & {
partition: string;
socksPort: number;
} {
return Boolean(snapshot?.partition && snapshot.socksPort !== null);
profileSlug: string,
): string | null {
if (
!snapshot ||
snapshot.socksPort === null ||
!Object.hasOwn(snapshot.profilePartitions, profileSlug)
) {
return null;
}
return snapshot.profilePartitions[profileSlug] ?? null;
}
function resolveRemoteUnavailablePaneState(
support: Exclude<Extract<HostBrowserRouting, { kind: "remote" }>["support"], "supported">,
hostLabel: string,
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
preparedPartition: string | null,
): BrowserProxyPaneState {
// Once Electron main has verified and bound this host's fixed SOCKS5 partition,
// keep the webview mounted across transient host disconnects/reconnects so SPA
// state, forms, scroll, and DevTools survive. Requests still fail closed at the
// local SOCKS5 listener while the tunnel is down.
// Once Electron main has verified and bound this profile's session to the host's
// fixed SOCKS5 port, keep the webview mounted across transient host
// disconnects/reconnects so SPA state, forms, scroll, and DevTools survive.
// Requests still fail closed at the local SOCKS5 listener while the tunnel is down.
const isTransientDisconnect = support === "host_connecting" || support === "host_offline";
if (isTransientDisconnect && hasPreparedHostPartition(proxyStatusSnapshot)) {
if (isTransientDisconnect && preparedPartition) {
return {
kind: "ready",
partition: proxyStatusSnapshot.partition,
partition: preparedPartition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel,
@@ -109,7 +116,7 @@ function resolvePreparedHostPaneStatus(
export function resolveBrowserProxyPaneState(input: {
routing: HostBrowserRouting;
effectiveRoutingMode: BrowserRoutingMode;
localPartition: string;
profileSlug: string;
hostLabel: string;
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>;
ensureError: string | null;
@@ -118,7 +125,7 @@ export function resolveBrowserProxyPaneState(input: {
const {
routing,
effectiveRoutingMode,
localPartition,
profileSlug,
hostLabel,
proxyStatusSnapshot,
ensureError,
@@ -128,7 +135,7 @@ export function resolveBrowserProxyPaneState(input: {
if (routing.kind === "local" || effectiveRoutingMode === "local") {
return {
kind: "ready",
partition: localPartition,
partition: getBrowserProfilePartition(profileSlug),
isRemoteHost: routing.kind === "remote",
effectiveRoutingMode: "local",
hostLabel,
@@ -136,17 +143,18 @@ export function resolveBrowserProxyPaneState(input: {
};
}
const preparedPartition = readPreparedHostPartition(proxyStatusSnapshot, profileSlug);
if (routing.support !== "supported") {
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, proxyStatusSnapshot);
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, preparedPartition);
}
// Once the fixed-port SOCKS5 session partition is verified (socksPort !== null),
// keep the webview mounted even if a background poll (e.g. HMR) left the cached
// tunnel status in "error" or "reconnecting" while the host reconnects.
if (hasPreparedHostPartition(proxyStatusSnapshot)) {
// Once the profile's session is bound to the fixed-port SOCKS5 proxy, keep the
// webview mounted even if a background poll (e.g. HMR) left the cached tunnel
// status in "error" or "reconnecting" while the host reconnects.
if (proxyStatusSnapshot && preparedPartition) {
return {
kind: "ready",
partition: proxyStatusSnapshot.partition,
partition: preparedPartition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel,
@@ -179,8 +187,9 @@ export function resolveBrowserProxyPaneState(input: {
export function useHostBrowserProxy(input: {
serverId: string;
routingMode?: BrowserRoutingMode;
profileSlug: string;
}): BrowserProxyPaneState {
const { serverId, routingMode } = input;
const { serverId, routingMode, profileSlug } = input;
const hosts = useHosts();
const host = useMemo(
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
@@ -200,6 +209,9 @@ export function useHostBrowserProxy(input: {
);
const [retryCounter, setRetryCounter] = useState(0);
// A retry replaces the host tunnel once. Later runs (another profile on the same host)
// reuse the tunnel that other tabs on this host share.
const reconnectedRetryRef = useRef(0);
const [ensureError, setEnsureError] = useState<string | null>(null);
const effectiveRoutingMode = resolveBrowserRoutingMode(
@@ -225,10 +237,13 @@ export function useHostBrowserProxy(input: {
installBrowserProxyRendererBridge();
setEnsureError(null);
const forceReconnect = retryCounter > reconnectedRetryRef.current;
reconnectedRetryRef.current = retryCounter;
void ensureHostBrowserProxy({
serverId,
target: supportedTarget,
forceReconnect: retryCounter > 0,
profileSlug,
forceReconnect,
})
.then((snapshot) => {
if (cancelled) return undefined;
@@ -249,13 +264,12 @@ export function useHostBrowserProxy(input: {
};
// targetKey serializes supportedTarget deterministically.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [effectiveRoutingMode, retryCounter, serverId, targetKey]);
}, [effectiveRoutingMode, profileSlug, retryCounter, serverId, targetKey]);
const localPartition = getDesktopHost()?.browser?.profilePartition ?? "persist:paseo-browser";
return resolveBrowserProxyPaneState({
routing,
effectiveRoutingMode,
localPartition,
profileSlug,
hostLabel,
proxyStatusSnapshot,
ensureError,
+3 -1
View File
@@ -177,7 +177,8 @@ export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "recon
export interface DesktopBrowserProxyStatusSnapshot {
serverId: string;
partition: string;
/** Profile slug -> partition, for every profile session bound to this host's proxy. */
profilePartitions: Record<string, string>;
status: DesktopBrowserProxyStatus;
error: string | null;
socksPort: number | null;
@@ -218,6 +219,7 @@ export interface DesktopBrowserBridge {
ensureHostProxy?: (input: {
serverId: string;
target: HostTransportSpec;
profileSlug?: string;
forceReconnect?: boolean;
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
@@ -10,6 +10,8 @@ interface UseImportSessionOptions {
serverId?: string;
cwd?: string;
workspaceId?: string;
/** Each import gets a fresh workspace instead of joining the one open at its directory. */
newWorkspace?: boolean;
}
interface UseImportSessionResult {
@@ -49,6 +51,7 @@ export function useImportSession({
serverId,
cwd,
workspaceId,
newWorkspace,
}: UseImportSessionOptions = {}): UseImportSessionResult {
const { t } = useTranslation();
const chooseHost = useHostChooser();
@@ -84,6 +87,7 @@ export function useImportSession({
serverId={importServerId}
cwd={cwd}
workspaceId={workspaceId}
newWorkspace={newWorkspace}
onClose={close}
onImported={navigateToImportedAgent}
/>
+14 -10
View File
@@ -8,19 +8,23 @@ import { useHorizontalScrollOptional } from "@/contexts/horizontal-scroll-contex
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { usePanelStore } from "@/stores/panel-store";
import { canBeginMobilePanelGesture, isMobilePanelGestureCurrent } from "./model";
import { useMobilePanelsRuntime } from "./provider";
import { useMobilePanelGestureRefs, useMobilePanelsRuntime } from "./provider";
import { resolveMobilePanelGestureIntent } from "./gesture-intent";
/** A horizontal surface takes the current touch before either panel opens. */
/**
* A horizontal scroller keeps the touches that start on it: no mobile panel opens or closes under
* it, and once it scrolls a parent pan such as a sheet's cannot take the touch.
*/
export function usePanelAwareHorizontalScrollGesture() {
const { leftOpenGestureRef, rightOpenGestureRef } = useMobilePanelsRuntime();
return useMemo(
() =>
Gesture.Native()
.blocksExternalGesture(leftOpenGestureRef, rightOpenGestureRef)
.disallowInterruption(true),
[leftOpenGestureRef, rightOpenGestureRef],
);
const panelGestures = useMobilePanelGestureRefs();
const explorerCloseGesture = useFileExplorerCloseGestureRef();
return useMemo(() => {
const blocked = explorerCloseGesture ? [...panelGestures, explorerCloseGesture] : panelGestures;
return Gesture.Native()
.blocksExternalGesture(...blocked)
.disallowInterruption(true)
.shouldCancelWhenOutside(false);
}, [explorerCloseGesture, panelGestures]);
}
function isCurrentSelection(startedRevision: number): boolean {
@@ -301,6 +301,20 @@ export function useMobilePanelsRuntime(): MobilePanelsRuntime {
return context;
}
/**
* The panel pans a surface inside the panels can block. A sheet portaled above the panels has none.
*/
export function useMobilePanelGestureRefs(): readonly RefObject<GestureType | undefined>[] {
const context = useContext(MobilePanelsContext);
const leftOpen = context?.leftOpenGestureRef;
const leftClose = context?.leftCloseGestureRef;
const rightOpen = context?.rightOpenGestureRef;
return useMemo(
() => (leftOpen && leftClose && rightOpen ? [leftOpen, leftClose, rightOpen] : []),
[leftOpen, leftClose, rightOpen],
);
}
/** The resolved left sidebar width shared by the dock, the overlay, and their gestures. */
export function useLeftPanelWidth(): number {
return useMobilePanelsRuntime().leftPanelWidth;
+3 -1
View File
@@ -116,7 +116,6 @@ const FindField = forwardRef<
<TextInput
ref={ref}
autoFocus={autoFocus}
selectTextOnFocus
initialValue={initialValue}
onChangeText={onChangeText}
onKeyPress={onKeyPress}
@@ -161,6 +160,9 @@ export const PaneFind = forwardRef<PaneFindHandle, PaneFindProps>(function PaneF
input.current?.replaceText(text, { start: 0, end: text.length });
}, []);
useImperativeHandle(ref, () => ({ focus }), [focus]);
// Select here rather than with selectTextOnFocus: React Native Web defers that
// selection to a timer, which then swallows keys typed right after the shortcut.
useLayoutEffect(focus, [focus]);
const onKeyPress = useCallback(
(event: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
+4
View File
@@ -1192,6 +1192,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -1205,6 +1206,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -1217,6 +1219,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -1859,6 +1862,7 @@ function ActiveAgentComposer({
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={agentInputDraft.setAttachments}
cwd={cwd}
getDraftRevision={agentInputDraft.getRevision}
clearDraft={agentInputDraft.clear}
editingSession={editingSession}
autoFocus
@@ -1,3 +1,4 @@
import { Session } from "node:inspector/promises";
import { getPluginClientApi } from "./client-state/api";
import { filePanelTitle } from "@/file-panels/choice/presentation";
import { i18n } from "@/i18n/i18next";
@@ -236,3 +237,27 @@ test("locale snapshots preserve installation state and observations, then releas
expect(listeners.size).toBe(0);
await expect.poll(() => h.open.size).toBe(0);
});
test("reloading a plugin releases the previous installation", async () => {
const h = registry();
const options = { client: h.client, audio };
const entry = catalog("reloaded");
h.plugins.installCatalog("host", [entry], options);
// The published snapshot is a copy. Its lifetime belongs to the installation itself.
const previous = new WeakRef(h.plugins.getSnapshot()[0]!.lifetime);
h.plugins.installCatalog("host", [entry], { ...options, replacePluginId: entry.id });
expect(h.plugins.getSnapshot()[0]?.lifetime).not.toBe(previous.deref());
const inspector = new Session();
inspector.connect();
try {
await new Promise<void>((resolve) => setImmediate(resolve));
await inspector.post("HeapProfiler.collectGarbage");
expect(previous.deref() === undefined).toBe(true);
expect(h.plugins.getSnapshot()).toHaveLength(1);
} finally {
inspector.disconnect();
h.plugins.removeHost("host");
}
});
+107 -85
View File
@@ -89,91 +89,15 @@ export class PluginRegistry {
this.publish();
for (const plugin of removed) this.dispose(plugin);
}
const installed = catalog.flatMap((entry) => {
const key = `${serverId}/${entry.id}`;
let installation: InstalledPlugin | undefined;
try {
if (!entry.clientBundle) return [];
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
const existing = preserved.find(
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
);
if (existing) {
this.evaluationErrors.delete(key);
return [existing];
}
const client = options.client;
const lifetime = new AbortController();
installation = {
lifetime,
locale: this.dependencies.localeSource.getLocale(),
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
paseo: createPaseoApi(client),
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
subscribe: createPluginSubscribe({
client,
pluginId: entry.id,
lifetime: lifetime.signal,
}),
id: entry.id,
serverId,
clientBundle: entry.clientBundle,
requirements: entry.requirements,
queryClient: new QueryClient(),
cleanup: () => undefined,
surfaces: [],
settingsScreens: [],
sidebarViews: [],
sidebarItems: { header: [], footer: [] },
legacySidebarItems: [],
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
clientSlashCommands: [],
attachmentSources: [],
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
once: true,
});
const runtime = this.dependencies.createRuntime(installation, options.audio);
const evaluated = runPluginClientBundle(
{ serverId, pluginId: entry.id },
entry.clientBundle,
runtime,
() => this.publish(),
);
Object.assign(installation, evaluated);
const paseo = installation.paseo;
installation.cleanup = async () => {
const results = await Promise.allSettled([paseo.dispose(), evaluated.cleanup()]);
const failures = results.filter((result) => result.status === "rejected");
if (failures.length)
throw new AggregateError(
failures.map((result) => result.reason),
"Plugin cleanup failed",
);
};
this.evaluationErrors.delete(key);
return [installation];
} catch (error) {
installation?.lifetime.abort();
installation?.i18n.dispose();
void installation?.paseo
.dispose()
.catch((failure) => console.warn(`[Plugins] API cleanup failed for ${key}`, failure));
this.evaluationErrors.set(key, error instanceof Error ? error.message : String(error));
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
return [];
}
});
const installed = catalog.flatMap((entry) =>
this.installPlugin({
serverId,
entry,
preserved,
client: options.client,
audio: options.audio,
}),
);
const configuredIds = new Set(catalog.map((entry) => entry.id));
for (const key of this.evaluationErrors.keys()) {
if (key.startsWith(`${serverId}/`) && !configuredIds.has(key.slice(serverId.length + 1))) {
@@ -215,6 +139,104 @@ export class PluginRegistry {
this.publish();
}
// Keep the closures for one installation out of the scope that holds the previous catalog.
private installPlugin({
serverId,
entry,
preserved,
client,
audio,
}: {
serverId: string;
entry: CatalogPlugin;
preserved: InstalledPlugin[];
client: DaemonClient;
audio: Pick<AudioEngine, "play">;
}): InstalledPlugin[] {
const key = `${serverId}/${entry.id}`;
let installation: InstalledPlugin | undefined;
try {
if (!entry.clientBundle) return [];
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
const existing = preserved.find(
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
);
if (existing) {
this.evaluationErrors.delete(key);
return [existing];
}
const lifetime = new AbortController();
installation = {
lifetime,
locale: this.dependencies.localeSource.getLocale(),
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
paseo: createPaseoApi(client),
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
subscribe: createPluginSubscribe({
client,
pluginId: entry.id,
lifetime: lifetime.signal,
}),
id: entry.id,
serverId,
clientBundle: entry.clientBundle,
requirements: entry.requirements,
queryClient: new QueryClient(),
cleanup: () => undefined,
surfaces: [],
settingsScreens: [],
sidebarViews: [],
sidebarItems: { header: [], footer: [] },
legacySidebarItems: [],
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
clientSlashCommands: [],
attachmentSources: [],
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
once: true,
});
const runtime = this.dependencies.createRuntime(installation, audio);
const evaluated = runPluginClientBundle(
{ serverId, pluginId: entry.id },
entry.clientBundle,
runtime,
() => this.publish(),
);
Object.assign(installation, evaluated);
const paseo = installation.paseo;
installation.cleanup = async () => {
const results = await Promise.allSettled([paseo.dispose(), evaluated.cleanup()]);
const failures = results.filter((result) => result.status === "rejected");
if (failures.length)
throw new AggregateError(
failures.map((result) => result.reason),
"Plugin cleanup failed",
);
};
this.evaluationErrors.delete(key);
return [installation];
} catch (error) {
installation?.lifetime.abort();
installation?.i18n.dispose();
void installation?.paseo
.dispose()
.catch((failure) => console.warn(`[Plugins] API cleanup failed for ${key}`, failure));
this.evaluationErrors.set(key, error instanceof Error ? error.message : String(error));
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
return [];
}
}
private hostEvaluationErrors(serverId: string): string {
const prefix = `${serverId}/`;
return JSON.stringify(
@@ -200,6 +200,7 @@ interface NewWorkspaceScreenProps {
const NO_TERMINAL_ATTACHMENTS: UserComposerAttachment[] = [];
function noopChangeAttachments() {}
function noopClearDraft() {}
const getTerminalDraftRevision = () => 0;
// Stable reference so the keyboard-action handler doesn't re-register each render.
const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [
@@ -1658,7 +1659,7 @@ export function NewWorkspaceScreen({
},
});
const importSession = useImportSession({ serverId: selectedServerId });
const importSession = useImportSession({ serverId: selectedServerId, newWorkspace: true });
const isComposerFullscreen = composerEditing.isFullscreen(isTerminalLaunch);
const composer = isTerminalLaunch ? (
@@ -1685,6 +1686,7 @@ export function NewWorkspaceScreen({
attachments={NO_TERMINAL_ATTACHMENTS}
onChangeAttachments={noopChangeAttachments}
cwd={workingDirectory ?? ""}
getDraftRevision={getTerminalDraftRevision}
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
@@ -1716,6 +1718,7 @@ export function NewWorkspaceScreen({
onForgeChangeRequestDetected={handleForgeChangeRequestDetected}
onForgeChangeRequestAutoAttach={handleForgeChangeRequestAutoAttach}
cwd={workingDirectory ?? ""}
getDraftRevision={chatDraft.getRevision}
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
@@ -662,6 +662,13 @@ function useMiddleClickClose(onClose: () => void) {
const node = ref.current as unknown as HTMLElement | null;
if (!node) return;
function handleMouseUp(event: MouseEvent) {
// Chromium can paste the Linux primary selection after auxclick moves focus.
if (event.button === 1) {
event.preventDefault();
}
}
function handleAuxClick(event: MouseEvent) {
if (event.button === 1) {
event.preventDefault();
@@ -669,8 +676,12 @@ function useMiddleClickClose(onClose: () => void) {
}
}
node.addEventListener("mouseup", handleMouseUp);
node.addEventListener("auxclick", handleAuxClick);
return () => node.removeEventListener("auxclick", handleAuxClick);
return () => {
node.removeEventListener("mouseup", handleMouseUp);
node.removeEventListener("auxclick", handleAuxClick);
};
}, [onClose]);
return ref;
@@ -45,6 +45,7 @@ import { hasDraftContent } from "@/composer/draft/input-draft-core";
export type { DraftInput, DraftLifecycleState } from "./state";
interface DraftStoreActions {
getDraftRevision: (draftKey: string) => number;
getDraftInput: (draftKey: string) => DraftInput | undefined;
hydrateDraftInput: (input: { draftKey: string }) => Promise<DraftInput | undefined>;
saveDraftInput: (input: { draftKey: string; draft: DraftInput }) => void;
@@ -283,6 +284,11 @@ export const useDraftStore = create<DraftStore>()(
textReplacementRequestByDraftKey: {},
metadataByDraftKey: {},
getDraftRevision: (draftKey) => {
get().flushDraftText(draftKey);
return get().drafts[draftKey]?.version ?? 0;
},
getDraftInput: (draftKey) => {
const record = get().drafts[draftKey];
return toDraftInputIfReady(record);
@@ -28,6 +28,12 @@ describe("draft-store lifecycle", () => {
expect(editDraftRecordText(edited, "", 3).lifecycle).toBe("active");
expect(editDraftRecordText(undefined, "", 3).lifecycle).toBe("abandoned");
});
it("keeps the version when a cleared draft publishes empty text again", () => {
const cleared = editDraftRecordText(undefined, "", 1);
expect(editDraftRecordText(cleared, "", 2)).toBe(cleared);
expect(editDraftRecordText(cleared, "follow-up", 2).version).toBe(cleared.version + 1);
});
it("prunes finalized tombstones after TTL", () => {
const nowMs = 1_000_000;
const drafts = {
+5 -1
View File
@@ -38,7 +38,11 @@ export function editDraftRecordText(
text: string,
now: number,
): DraftRecord {
if (record?.lifecycle === "active" && record.input.text === text) return record;
if (
record?.input.text === text &&
(record.lifecycle === "active" || record.lifecycle === "abandoned")
)
return record;
const attachments = record?.lifecycle === "active" ? record.input.attachments : [];
return {
input: { text, attachments },
@@ -11,6 +11,7 @@ export const BottomSheetModalProvider = PassThrough;
export const BottomSheetBackdrop = Stub;
export const BottomSheetHandle = Stub;
export const BottomSheetScrollView = PassThrough;
export const BottomSheetFlatList = PassThrough;
export const BottomSheetView = PassThrough;
export const BottomSheetTextInput = Stub;
+4 -2
View File
@@ -12,7 +12,7 @@ import type {
UpdateScheduleNewAgentConfig,
} from "./types.js";
import { parseDuration } from "../../utils/duration.js";
import { resolveProviderAndModel } from "../../utils/provider-model.js";
import { parseModelOption, resolveProviderAndModel } from "../../utils/provider-model.js";
import { everyMsToFiveFieldCron } from "@getpaseo/protocol/schedule/cadence";
export interface ScheduleCommandOptions extends CommandOptions {
@@ -422,7 +422,7 @@ function buildNewAgentConfigPatch(
options: ScheduleUpdateOptionsInput,
): UpdateScheduleNewAgentConfig | undefined {
const patch: UpdateScheduleNewAgentConfig = {};
if (options.provider !== undefined || options.model !== undefined) {
if (options.provider !== undefined) {
const resolved = resolveProviderAndModel({
provider: options.provider,
model: options.model,
@@ -431,6 +431,8 @@ function buildNewAgentConfigPatch(
if (resolved.model !== undefined) {
patch.model = resolved.model;
}
} else if (options.model !== undefined) {
patch.model = parseModelOption(options.model);
}
if (options.mode !== undefined) {
const trimmed = options.mode.trim();
+1 -5
View File
@@ -17,11 +17,7 @@ export async function connectTerminalClient(target: DaemonTarget) {
try {
const daemonClient = await connectToDaemon({ target });
const terminals = createTerminalActions(daemonClient, async (workspaceId) => {
const result = await daemonClient.fetchWorkspaces({
filter: { idPrefix: workspaceId, includeBackground: true },
page: { limit: 10 },
});
const workspace = result.entries.find((entry) => entry.id === workspaceId);
const workspace = await daemonClient.findWorkspace(workspaceId);
if (!workspace?.workspaceDirectory) {
throw new Error(`Workspace ${workspaceId} is not active or has no available directory`);
}
+9 -8
View File
@@ -11,11 +11,18 @@ export interface ResolvedProviderModel {
model: string | undefined;
}
export function parseModelOption(value: string): string {
const model = value.trim();
if (!model) {
throw { code: "INVALID_MODEL", message: "--model cannot be empty" } satisfies CommandError;
}
return model;
}
export function resolveProviderAndModel(
options: ResolveProviderAndModelOptions,
): ResolvedProviderModel {
const providerInput = options.provider?.trim() || options.defaultProvider;
const modelInput = options.model?.trim();
if (!providerInput) {
const error: CommandError = {
@@ -27,13 +34,7 @@ export function resolveProviderAndModel(
throw error;
}
if (options.model !== undefined && !modelInput) {
const error: CommandError = {
code: "INVALID_MODEL",
message: "--model cannot be empty",
};
throw error;
}
const modelInput = options.model === undefined ? undefined : parseModelOption(options.model);
const slashIndex = providerInput.indexOf("/");
if (slashIndex === -1) {
@@ -90,14 +90,32 @@ async function startSupervisor() {
});
let output = "";
const startedWatchers = new Set<string>();
function captureOutput(chunk: Buffer) {
output = (output + chunk.toString()).slice(-32000);
const builtWatchers = new Set<string>();
let watchersBuiltBeforeWorker: string[] | undefined;
// Read whole lines in arrival order, so the worker line is checked against
// only the build lines that came before it.
function readLine(line: string) {
for (const watcher of ["protocol", "client"]) {
if (output.includes(`[${watcher}]`)) startedWatchers.add(watcher);
if (!line.includes(`[${watcher}]`)) continue;
startedWatchers.add(watcher);
if (line.includes("Watching for file changes")) builtWatchers.add(watcher);
}
if (!watchersBuiltBeforeWorker && line.includes("Starting daemon worker")) {
watchersBuiltBeforeWorker = [...builtWatchers].sort();
}
}
child.stdout.on("data", captureOutput);
child.stderr.on("data", captureOutput);
function captureOutput(stream: NodeJS.ReadableStream) {
let partial = "";
stream.on("data", (chunk: Buffer) => {
const text = chunk.toString();
output = (output + text).slice(-32000);
const lines = (partial + text).split("\n");
partial = lines.pop() ?? "";
lines.forEach(readLine);
});
}
captureOutput(child.stdout);
captureOutput(child.stderr);
try {
await Promise.race([
waitFor(
@@ -117,6 +135,12 @@ async function startSupervisor() {
await waitFor(async () => {
if (startedWatchers.size === 2) return true;
}, "dev runner did not start both dependency watchers");
// A worker that starts during a watcher's first build imports half-written dist files.
assert.deepEqual(
watchersBuiltBeforeWorker,
["client", "protocol"],
"daemon worker started before both watchers finished their first build",
);
}
} catch (error) {
await client.close();
@@ -169,9 +193,18 @@ try {
if (process.platform === "win32") {
await interruptForeground(daemon);
} else {
const idle = await daemon.client.createAgent({ provider: "antigravity", cwd });
const running = await daemon.client.createAgent({ provider: "antigravity", cwd });
const crashing = await daemon.client.createAgent({ provider: "antigravity", cwd });
const idle = await daemon.client.createAgent({
provider: "antigravity",
cwd,
});
const running = await daemon.client.createAgent({
provider: "antigravity",
cwd,
});
const crashing = await daemon.client.createAgent({
provider: "antigravity",
cwd,
});
const opened = (await readEvents()).filter((event) => event.type === "session");
const sessions = [idle, running, crashing].map((agent) => {
const handle = agent.persistence?.sessionId;
@@ -186,7 +219,9 @@ try {
const { agent } = (await daemon!.client.fetchAgent(crashing.id)) ?? {};
if (agent?.status === "error" && agent.attentionReason === "error") return agent;
}, "unexpected provider exit did not raise error attention");
const failure = await daemon.client.fetchAgentTimeline(crashing.id, { limit: 20 });
const failure = await daemon.client.fetchAgentTimeline(crashing.id, {
limit: 20,
});
assert.match(JSON.stringify(failure.entries), /\[System Error\].*ACP process exited/);
console.log("Unexpected ACP exit raised error attention and added a timeline entry.");
@@ -225,8 +260,16 @@ try {
assert.deepEqual(
(await readEvents()).filter((event) => event.type === "prompt"),
[
{ type: "prompt", sessionId: sessions[1].sessionId, text: "Hold the turn open." },
{ type: "prompt", sessionId: sessions[1].sessionId, text: resumePrompt },
{
type: "prompt",
sessionId: sessions[1].sessionId,
text: "Hold the turn open.",
},
{
type: "prompt",
sessionId: sessions[1].sessionId,
text: resumePrompt,
},
],
);
console.log(
+14
View File
@@ -97,6 +97,20 @@ try {
assert.strictEqual(inspectedJson.target.config.model, "gpt-5.4");
assert.strictEqual(inspectedJson.target.config.thinkingOptionId, "high");
const updated = await ctx.paseo([
"schedule",
"update",
createdJson.id,
"--model",
"gpt-5.4-mini",
"--json",
]);
assert.strictEqual(updated.exitCode, 0, updated.stderr);
assert.deepStrictEqual(JSON.parse(updated.stdout).target.config, {
...inspectedJson.target.config,
model: "gpt-5.4-mini",
});
const deleted = await ctx.paseo(["schedule", "delete", createdJson.id, "--json"]);
assert.strictEqual(deleted.exitCode, 0, deleted.stderr);
console.log("schedule provider/model syntax works\n");
@@ -73,6 +73,18 @@ try {
await cli(["terminal", "kill", feature.id]);
assert.deepEqual(await cli(["terminal", "ls", "--workspace", second.id]), []);
assert.deepEqual(await cli(["terminal", "ls", "--workspace", first.id]), [main]);
for (let i = 0; i < 9; i++) {
await sdk.workspaces.create({
source: { kind: "directory", path: ctx.workDir },
title: `extra-${i}`,
});
}
const workspaces = await cli(["workspace", "ls"]);
assert.equal(workspaces.length, 11);
const { workspaceId, cwd } = workspaces[10];
const created = await cli(["terminal", "create", "--workspace", workspaceId, "--name", "Older"]);
assert.deepEqual(created, { id: created.id, name: "Older", workspaceId, cwd });
await cli(["terminal", "kill", created.id]);
console.log("Terminal workspace CLI: ownership, lists, input, capture, kill, and errors passed");
} finally {
await sdk.close();
@@ -261,6 +261,8 @@ const PROJECT_GITHUB_CLONE_TIMEOUT_MS = 5 * 60 * 1000;
interface ImportAgentInputBase {
cwd?: string;
workspaceId?: string;
/** Import into a fresh workspace for `cwd` instead of the workspace already open there. */
newWorkspace?: boolean;
labels?: Record<string, string>;
}
@@ -4158,6 +4160,7 @@ export class DaemonClientCore {
: { provider: input.provider, sessionId: input.sessionId }),
...(input.cwd ? { cwd: input.cwd } : {}),
...(input.workspaceId ? { workspaceId: input.workspaceId } : {}),
...(input.newWorkspace ? { newWorkspace: true } : {}),
...(input.labels && Object.keys(input.labels).length > 0 ? { labels: input.labels } : {}),
});
@@ -0,0 +1,125 @@
import { expect } from "@playwright/test";
export async function runBrowserPermissionsRegression({
page,
call,
serverId,
targetUrl,
browserWorkspaceId,
}) {
await page.getByTestId(`sidebar-workspace-row-${serverId}:${browserWorkspaceId}`).click();
await page
.getByTestId(`workspace-deck-entry-${serverId}:${browserWorkspaceId}`)
.waitFor({ state: "visible" });
const created = await call("browser_new_tab", { url: targetUrl });
const browserId = created.browserId;
expect(typeof browserId, "browser_new_tab did not return a browserId").toBe("string");
try {
await call("browser_wait", { browserId, text: "Bridge target" });
const evaluated = await call("browser_evaluate", {
browserId,
function: `async () => {
const query = async (name) => {
try {
return (await navigator.permissions.query({ name })).state;
} catch (error) {
return "error:" + String(error);
}
};
const expectReject = async (fn) => {
try {
await fn();
return "resolved";
} catch (error) {
return "rejected:" + (error && error.name ? error.name : String(error));
}
};
const geoPosition = await new Promise((resolve) => {
navigator.geolocation.getCurrentPosition(
() => resolve("granted"),
(error) => resolve("denied:" + error.code),
{ timeout: 3000 },
);
});
return {
permissions: {
geolocation: await query("geolocation"),
microphone: await query("microphone"),
camera: await query("camera"),
notifications: await query("notifications"),
clipboardRead: await query("clipboard-read"),
clipboardWrite: await query("clipboard-write"),
},
geoPosition,
getUserMediaAudio: await expectReject(() =>
navigator.mediaDevices.getUserMedia({ audio: true }),
),
getUserMediaVideo: await expectReject(() =>
navigator.mediaDevices.getUserMedia({ video: true }),
),
getDisplayMedia: await expectReject(() =>
navigator.mediaDevices.getDisplayMedia({ video: true }),
),
notificationRequest: await Notification.requestPermission(),
midi: await expectReject(() => navigator.requestMIDIAccess()),
clipboardRead: await expectReject(() => navigator.clipboard.readText()),
};
}`,
});
const guestResult = JSON.parse(evaluated.resultJson);
expect(guestResult.permissions).toEqual({
geolocation: "denied",
microphone: "denied",
camera: "denied",
notifications: "denied",
clipboardRead: "denied",
clipboardWrite: "granted",
});
expect(guestResult.geoPosition).toBe("denied:1");
// Headless runners without capture hardware reject getUserMedia with NotFoundError
// before prompting; microphone/camera queries above verify permission denial directly.
expect(["rejected:NotAllowedError", "rejected:NotFoundError"]).toContain(
guestResult.getUserMediaAudio,
);
expect(["rejected:NotAllowedError", "rejected:NotFoundError"]).toContain(
guestResult.getUserMediaVideo,
);
expect(guestResult.getDisplayMedia).toBe("rejected:NotAllowedError");
expect(guestResult.notificationRequest).toBe("denied");
expect(guestResult.midi).toBe("rejected:NotAllowedError");
expect(guestResult.clipboardRead).toBe("rejected:NotAllowedError");
const appResult = await page.evaluate(async () => {
const query = async (name) => (await navigator.permissions.query({ name })).state;
return {
permissions: {
microphone: await query("microphone"),
notifications: await query("notifications"),
clipboardRead: await query("clipboard-read"),
clipboardWrite: await query("clipboard-write"),
camera: await query("camera"),
geolocation: await query("geolocation"),
},
notificationRequest: await Notification.requestPermission(),
};
});
expect(appResult.permissions).toEqual({
microphone: "granted",
notifications: "granted",
clipboardRead: "granted",
clipboardWrite: "granted",
camera: "denied",
geolocation: "denied",
});
expect(appResult.notificationRequest).toBe("granted");
return { guestResult, appResult };
} finally {
await call("browser_close_tab", { browserId });
}
}
+276 -12
View File
@@ -587,6 +587,236 @@ function describeProcess(pid) {
return { pid, serverId: serverId ?? null, command };
}
async function evaluateMainProcess(inspectorPort, expression) {
const [target] = await (await fetch(`http://127.0.0.1:${inspectorPort}/json/list`)).json();
const socket = new WebSocket(target.webSocketDebuggerUrl);
try {
return await new Promise((resolve, reject) => {
socket.once("error", reject);
socket.on("message", (data) => {
const response = JSON.parse(String(data));
if (response.id !== 1) return;
if (response.error || response.result?.exceptionDetails) reject(new Error(String(data)));
else resolve(response.result.result.value);
});
socket.once("open", () =>
socket.send(
JSON.stringify({
id: 1,
method: "Runtime.evaluate",
params: {
expression: `(async () => { const electron = process.mainModule.require('electron'); ${expression} })()`,
returnByValue: true,
awaitPromise: true,
},
}),
),
);
});
} finally {
socket.close();
}
}
/** Accepts the next native confirm dialog by clicking the button labeled `label`. */
async function acceptNextDialog(inspect, label) {
await inspect(`const { dialog } = electron; const show = dialog.showMessageBox;
dialog.showMessageBox = async (owner, options) => {
dialog.showMessageBox = show;
return { response: options.buttons.indexOf(${JSON.stringify(label)}), checkboxChecked: false };
}; return true;`);
}
async function openBrowserProfileSettings(page) {
await page.getByRole("button", { name: "Settings", exact: true }).click();
await page
.locator('[data-testid="settings-sidebar"]:visible')
.getByRole("button", { name: "Chat & panes", exact: true })
.click();
await expect(page.getByTestId("settings-browser-profile-row-default")).toBeVisible();
}
/**
* On a host-proxied tab, creates and switches profiles, and proves each profile on the
* host has its own storage while its requests still leave through the host daemon over
* the host's one tunnel. Then clears and removes the profile from Settings.
*/
async function verifyHostProxiedProfiles({
page,
inspect,
relayBridge,
targetServer,
targetUrl,
hostPartition,
routingPill,
userData,
}) {
const picker = () => page.locator('[data-testid="browser-profile-picker"]:visible');
const hostWorkPartition = `${hostPartition}-profile-work`;
const guestAt = (partition) => readGuestState(page, { exactPartition: partition });
const runInGuest = (partition, code) =>
page.evaluate(
async (input) => {
const wv = [...document.querySelectorAll("webview")].find(
(el) => el.getAttribute("partition") === input.partition,
);
return await wv.executeJavaScript(input.code);
},
{ partition, code },
);
const markGuest = (partition, marker) =>
runInGuest(
partition,
`localStorage.setItem("partition_marker", ${JSON.stringify(marker)}); document.cookie = "profile=${marker}; Path=/; Max-Age=86400";`,
);
const cookieAt = (partition) => runInGuest(partition, "document.cookie");
const choose = async (slug, name) => {
await picker().click();
await page.getByTestId(`browser-profile-option-${slug}`).click();
await expect(picker()).toHaveAttribute("aria-label", `Browser profile: ${name}`);
};
const tunnelStats = () => {
const stats = relayBridge.getStats("e2e-remote-host");
return {
clientConnections: stats.clientConnections,
tunnelBytes: stats.connections[1]?.serverToClientBytes ?? 0,
};
};
const loadedPage = {
found: true,
heading: "Proxied HTTP OK",
wsResult: "WS_OK:ack:hello-tunnel",
};
const poll = (fn) => expect.poll(fn, { timeout: 30_000, intervals: [250, 500, 1000] });
// 1. The profile picker is on the host-proxied tab; create Work there.
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Default");
const before = tunnelStats();
const wsCountBefore = targetServer.wsClientPorts.length;
await picker().click();
await page.getByTestId("browser-profile-create-trigger").click();
await page.getByTestId("browser-create-profile-input").fill("Work");
await page.getByTestId("browser-create-profile-submit").click();
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Work");
await poll(() => guestAt(hostWorkPartition)).toMatchObject({ ...loadedPage, marker: null });
// 2. Work still goes through the host: same SOCKS5 port, same tunnel, host daemon egress.
const status = await page.evaluate(
async () => await window.paseoDesktop.browser.getHostProxyStatus("e2e-remote-host"),
);
assert(
status?.status === "ready" &&
status.profilePartitions.default === hostPartition &&
status.profilePartitions.work === hostWorkPartition &&
typeof status.socksPort === "number",
`Expected Default and Work bound to the host proxy, got ${JSON.stringify(status)}`,
);
const resolvedProxy = await inspect(
`return await electron.session.fromPartition(${JSON.stringify(hostWorkPartition)}).resolveProxy("http://localhost:${targetServer.port}/");`,
);
assert(
resolvedProxy.includes(`SOCKS5 127.0.0.1:${status.socksPort}`),
`Expected Work to resolve to the host SOCKS5 port ${status.socksPort}, got ${resolvedProxy}`,
);
const after = tunnelStats();
assert(
after.clientConnections === before.clientConnections && after.tunnelBytes > before.tunnelBytes,
`Expected Work to reuse the host tunnel, before=${JSON.stringify(before)} after=${JSON.stringify(after)}`,
);
const workWsPort = targetServer.wsClientPorts.slice(wsCountBefore).at(-1);
assert(workWsPort, "Expected a guest WebSocket from the Work profile");
const egressPid =
process.platform === "linux"
? processOwningConnection({ localPort: workWsPort, peerPort: targetServer.port })
: null;
const egressProcess = egressPid ? describeProcess(egressPid) : "skipped: needs Linux";
assert(
process.platform !== "linux" || egressProcess.serverId === "e2e-remote-host",
`Expected the remote daemon to own Work's target connection, got ${JSON.stringify(egressProcess)}`,
);
// 3. Default and Work keep separate storage and cookies on the same host.
await markGuest(hostWorkPartition, "host-work");
await choose("default", "Default");
await poll(() => guestAt(hostPartition)).toMatchObject({
...loadedPage,
marker: "from-host-partition",
});
assert(
!(await cookieAt(hostPartition)).includes("profile=host-work"),
"Expected the host Default profile not to see Work's cookie",
);
await choose("work", "Work");
await poll(() => guestAt(hostWorkPartition)).toMatchObject({
...loadedPage,
marker: "host-work",
});
// 4. Work on the local route is a different partition from Work on the host route.
await routingPill.click();
await expect(routingPill).toHaveAttribute(
"aria-label",
"Switch browser routing from Local to Remote Proxy Host",
{ timeout: 15_000 },
);
await poll(() => guestAt("persist:paseo-profile-work")).toMatchObject({
...loadedPage,
marker: null,
});
await routingPill.click();
await expect(routingPill).toHaveAttribute(
"aria-label",
"Switch browser routing from Remote Proxy Host to Local",
{ timeout: 15_000 },
);
await poll(() => guestAt(hostWorkPartition)).toMatchObject({
...loadedPage,
marker: "host-work",
});
// 5. A second host tab on Default, to prove Clear and Remove leave Default alone.
await openNewBrowserTabAndNavigate(page, targetUrl);
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Default");
await poll(() => guestAt(hostPartition)).toMatchObject({
...loadedPage,
marker: "from-host-partition",
});
// 6. Clear Work in Settings clears it on the host route too; Default keeps its data.
const hostWorkDir = path.join(userData, "Partitions", hostWorkPartition.slice("persist:".length));
await poll(() => fs.existsSync(hostWorkDir)).toBe(true);
await openBrowserProfileSettings(page);
await acceptNextDialog(inspect, "Clear data");
await page.getByTestId("settings-browser-profile-menu-work").click();
await page.getByTestId("settings-browser-profile-clear-work").click();
await expect(page.getByText("Browser data cleared", { exact: true })).toBeVisible();
await poll(() => guestAt(hostWorkPartition)).toMatchObject({ ...loadedPage, marker: null });
assert(
!(await cookieAt(hostWorkPartition)).includes("profile=host-work"),
"Expected Clear data to remove Work's cookie on the host route",
);
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
// 7. Remove Work closes its host-proxied tab and deletes its host partition directory.
await acceptNextDialog(inspect, "Remove");
await page.getByTestId("settings-browser-profile-menu-work").click();
await page.getByTestId("settings-browser-profile-remove-work").click();
await expect(page.getByTestId("settings-browser-profile-row-work")).toHaveCount(0);
await poll(() => fs.existsSync(hostWorkDir)).toBe(false);
await page.getByTestId("settings-back-to-workspace").click();
await poll(async () => (await guestAt(hostWorkPartition)).found).toBe(false);
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
return {
hostWorkPartition,
socksPort: status.socksPort,
resolvedProxy,
tunnelConnections: after.clientConnections,
egressProcess,
clearAndRemove: "passed",
};
}
async function waitForAppPage(browser, expoPort) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
@@ -679,8 +909,10 @@ async function openNewBrowserTabAndNavigate(page, url) {
await expect(newTabBtn).toBeVisible({ timeout: 30_000 });
await newTabBtn.click();
// An empty pane lists launchers as buttons; a pane with tabs opens a menu instead.
const browserOption = page
.getByRole("button", { name: /^Browser/i })
.or(page.getByRole("menuitem", { name: /^Browser/i }))
.and(page.locator(":visible"))
.first();
await expect(browserOption).toBeVisible({ timeout: 15_000 });
@@ -750,7 +982,7 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
);
assert(
routedProxyStatus?.status === "ready" &&
routedProxyStatus.partition === routedPartition &&
routedProxyStatus.profilePartitions.default === routedPartition &&
typeof routedProxyStatus.socksPort === "number",
`Expected a ready routed host proxy, got ${JSON.stringify(routedProxyStatus)}`,
);
@@ -793,15 +1025,23 @@ async function main() {
const userData = path.join(runtimeDir, "electron-user-data");
const workspaceRoot = path.join(runtimeDir, "workspaces");
const [localDaemonPort, remoteDaemonPort, oldDaemonPort, routedDaemonPort, expoPort, cdpPort] =
await Promise.all([
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
]);
const [
localDaemonPort,
remoteDaemonPort,
oldDaemonPort,
routedDaemonPort,
expoPort,
cdpPort,
inspectorPort,
] = await Promise.all([
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
]);
// The local daemon requires a password the renderer never sees, so the routed
// tunnel can only authenticate to it with the desktop-managed local credential.
const localDaemonPassword = "browser-proxy-e2e-local-password";
@@ -811,6 +1051,7 @@ async function main() {
const children = [];
let legacyAdapter = null;
let browser = null;
let appPage = null;
try {
seedPaseoHome({
@@ -956,6 +1197,7 @@ async function main() {
const desktopArgs = [
process.execPath,
devRunner,
`--inspect=127.0.0.1:${inspectorPort}`,
...(process.platform === "linux" ? ["--no-sandbox"] : []),
];
const desktopCommand = process.platform === "linux" ? "xvfb-run" : desktopArgs.shift();
@@ -990,6 +1232,7 @@ async function main() {
browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`);
const page = await waitForAppPage(browser, expoPort);
appPage = page;
await hideDeveloperToasts(page);
await waitForDesktopStatus(page);
@@ -1169,7 +1412,22 @@ async function main() {
});
// -------------------------------------------------------------------------
// 3. Old daemon without features.networkTunnel fails closed + Browse locally
// 3. Browser profiles on the host-proxied tab
// -------------------------------------------------------------------------
const hostProfiles = await verifyHostProxiedProfiles({
page,
inspect: (expression) => evaluateMainProcess(inspectorPort, expression),
relayBridge,
targetServer,
targetUrl,
hostPartition: hostGuest.partition,
routingPill,
userData,
});
await page.screenshot({ path: path.join(artifactDir, "03-host-profiles.png") });
// -------------------------------------------------------------------------
// 4. Old daemon without features.networkTunnel fails closed + Browse locally
// -------------------------------------------------------------------------
const oldWsButton = page
.getByRole("button", {
@@ -1233,7 +1491,7 @@ async function main() {
await page.screenshot({ path: path.join(artifactDir, "04-old-daemon-browse-locally.png") });
// -------------------------------------------------------------------------
// 4. Routed host: desktop -> local daemon -> routed daemon -> target
// 5. Routed host: desktop -> local daemon -> routed daemon -> target
// -------------------------------------------------------------------------
const routedHost = await verifyRoutedHostBrowsing({
page,
@@ -1254,6 +1512,7 @@ async function main() {
binaryFrames: secondaryTunnelConn.binaryFrames,
},
togglePartitionIsolation: "passed",
hostProfiles,
oldDaemonFailClosedAndBrowseLocally: "passed",
routedHost,
artifactDir,
@@ -1262,6 +1521,11 @@ async function main() {
2,
),
);
} catch (error) {
await appPage
?.screenshot({ path: path.join(artifactDir, "failure.png") })
.catch(() => undefined);
throw error;
} finally {
await browser?.close().catch(() => undefined);
legacyAdapter?.close();
+26 -6
View File
@@ -24,6 +24,7 @@ import {
FOCUS_FIXTURE_PATH,
runBrowserFocusIsolationRegression,
} from "./browser-focus.electron.mjs";
import { runBrowserPermissionsRegression } from "./browser-permissions.electron.mjs";
import { runSettingsMemoryRegression } from "./settings-memory.electron.mjs";
import { seedPluginLinks, runPluginLinksRegression } from "./plugin-links.electron.mjs";
@@ -669,9 +670,10 @@ async function clickGuestElement(page, client, browserId, selector) {
}
async function selectDeviceSize(page, label) {
await page.locator('[aria-label="Device size"]').click();
const item = page.getByText(label, { exact: true });
await item.waitFor({ state: "visible", timeout: timeoutMs });
const trigger = page.getByLabel("Device size", { exact: true });
const item = page.getByRole("menuitem", { name: label, exact: true });
await trigger.click();
await item.click({ trial: true, timeout: timeoutMs });
const rect = await item.boundingBox();
assert(rect, `Device size menu item ${label} had no bounds`);
const clip = {
@@ -685,9 +687,9 @@ async function selectDeviceSize(page, label) {
await item.waitFor({ state: "hidden", timeout: timeoutMs });
const closedPixels = await page.screenshot({ clip });
await page.locator('[aria-label="Device size"]').click();
await item.waitFor({ state: "visible", timeout: timeoutMs });
await page.mouse.click(rect.x + rect.width / 2, rect.y + rect.height / 2);
await trigger.click();
// The reopened menu renders off-screen while measuring. Click its current position after layout.
await item.click({ timeout: timeoutMs });
await page.keyboard.press("Escape");
return !openPixels.equals(closedPixels);
}
@@ -1593,6 +1595,22 @@ async function main() {
resizeWindow: (size) => resizeDesktopWindow(inspectorPort, size),
evaluateMain: (expression) => evaluateDesktopWindow(inspectorPort, expression),
});
const checkPermissions = (browserClient) =>
runBrowserPermissionsRegression({
page,
call: (name, args) => callBrowserTool(browserClient, name, args),
serverId: status.serverId,
targetUrl: target.url,
browserWorkspaceId: workspaceIds[0],
});
if (process.env.PASEO_DESKTOP_BROWSER_PERMISSIONS_ONLY === "1") {
const callerAgentId = await createCallerAgent(daemonPort);
client = await connectBrowserToolClient(daemonPort, callerAgentId);
const permissions = await checkPermissions(client);
writeJson(path.join(artifactDir, "result.json"), { permissions });
console.log("Desktop browser permissions regression passed.");
return;
}
if (process.env.PASEO_DESKTOP_BROWSER_FOCUS_ONLY === "1") {
const callerAgentId = await createCallerAgent(daemonPort);
const typingAgent = {
@@ -1648,6 +1666,7 @@ async function main() {
artifactDir,
});
const focusIsolation = await checkFocusIsolation(client, callerAgentId, typingAgent);
const permissions = await checkPermissions(client);
const pluginLinks = await checkPluginLinks();
const routingClient = await connectBrowserToolClient(daemonPort, typingAgent.agentId);
try {
@@ -1665,6 +1684,7 @@ async function main() {
writeJson(path.join(artifactDir, "result.json"), {
...report,
focusIsolation,
permissions,
settingsMemory,
pluginLinks,
adaptiveTheme,
@@ -0,0 +1,74 @@
import { describe, expect, test } from "vitest";
import { getBrowserPartition, parseBrowserPartition } from "./browser-partition.js";
const LOCAL = { kind: "local" } as const;
const host = (serverId: string) => ({ kind: "host", serverId }) as const;
describe("browser partition naming", () => {
test("keeps the existing local and host default partition names", () => {
expect(getBrowserPartition(LOCAL, "default")).toBe("persist:paseo-browser");
expect(getBrowserPartition(LOCAL, "work")).toBe("persist:paseo-profile-work");
expect(getBrowserPartition(host("srv_alpha_123"), "default")).toMatch(
/^persist:paseo-browser-host-[0-9a-f]{16}$/,
);
});
test("composes a host route with a named profile into its own deterministic partition", () => {
const hostDefault = getBrowserPartition(host("srv_alpha_123"), "default");
const hostWork = getBrowserPartition(host("srv_alpha_123"), "work");
expect(hostWork).toBe(`${hostDefault}-profile-work`);
expect(getBrowserPartition(host("srv_alpha_123"), "work")).toBe(hostWork);
expect(getBrowserPartition(host("srv_beta_456"), "work")).not.toBe(hostWork);
expect(getBrowserPartition(host("srv_alpha_123"), "customer")).not.toBe(hostWork);
});
test("rejects invalid routes and profile slugs", () => {
expect(() => getBrowserPartition(host(" "), "default")).toThrow();
expect(() => getBrowserPartition(LOCAL, "Work")).toThrow();
expect(() => getBrowserPartition(host("srv"), "a--b")).toThrow();
});
test("parses every route and profile combination back", () => {
const hostDefault = getBrowserPartition(host("srv"), "default");
expect(parseBrowserPartition("persist:paseo-browser")).toEqual({
route: "local",
profileSlug: "default",
});
expect(parseBrowserPartition("persist:paseo-profile-work")).toEqual({
route: "local",
profileSlug: "work",
});
expect(parseBrowserPartition(hostDefault)).toEqual({ route: "host", profileSlug: "default" });
expect(parseBrowserPartition(`${hostDefault}-profile-work`)).toEqual({
route: "host",
profileSlug: "work",
});
// A slug may itself look like a host suffix; the local prefix still owns it.
expect(parseBrowserPartition("persist:paseo-profile-work-host-0123456789abcdef")).toEqual({
route: "local",
profileSlug: "work-host-0123456789abcdef",
});
});
test("rejects partitions outside the Paseo browser namespace", () => {
for (const partition of [
undefined,
42,
"persist:foreign",
"paseo-browser",
"persist:paseo-profile-default",
"persist:paseo-profile-Work",
"persist:paseo-browser-tab-a",
"persist:paseo-browser-host-0123456789abcde",
"persist:paseo-browser-host-0123456789ABCDEF",
"persist:paseo-browser-host-0123456789abcdef0",
"persist:paseo-browser-host-0123456789abcdef-profile-",
"persist:paseo-browser-host-0123456789abcdef-profile-default",
"persist:paseo-browser-host-0123456789abcdef-profile-Work",
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
]) {
expect(parseBrowserPartition(partition)).toBeNull();
}
});
});
@@ -0,0 +1,81 @@
import { createHash } from "node:crypto";
/**
* A browser tab's Electron session partition is the pair (route, profile).
* Electron binds `session.setProxy` per partition, so the route lives in the name,
* and the profile keeps cookies and storage apart on that route.
*
* local + default persist:paseo-browser
* local + <slug> persist:paseo-profile-<slug>
* host + default persist:paseo-browser-host-<16hex>
* host + <slug> persist:paseo-browser-host-<16hex>-profile-<slug>
*
* The first three names predate this module and must not change: they hold the user's
* existing cookies and storage on disk.
*/
export type BrowserRoute = { kind: "local" } | { kind: "host"; serverId: string };
export interface ParsedBrowserPartition {
route: BrowserRoute["kind"];
profileSlug: string;
}
export const DEFAULT_BROWSER_PROFILE_SLUG = "default";
export const PASEO_BROWSER_PROFILE_PARTITION = "persist:paseo-browser";
const PERSIST = "persist:";
const LOCAL_PROFILE_PREFIX = "paseo-profile-";
const HOST_PREFIX = "paseo-browser-host-";
const HOST_PROFILE_INFIX = "-profile-";
const NAMED_SLUG = /^(?=.{1,48}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
const HOST_PARTITION = /^paseo-browser-host-([0-9a-f]{16})(?:-profile-(.+))?$/;
export function isNamedBrowserProfileSlug(slug: string): boolean {
return NAMED_SLUG.test(slug) && slug !== DEFAULT_BROWSER_PROFILE_SLUG;
}
function hostKey(serverId: string): string {
const normalized = serverId.trim();
if (!normalized) {
throw new Error("Host serverId is required to derive a browser partition");
}
return createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 16);
}
export function getBrowserPartition(route: BrowserRoute, profileSlug: string): string {
const isDefault = profileSlug === DEFAULT_BROWSER_PROFILE_SLUG;
if (!isDefault && !isNamedBrowserProfileSlug(profileSlug)) {
throw new Error(`Invalid browser profile slug: ${profileSlug}`);
}
if (route.kind === "local") {
return isDefault
? PASEO_BROWSER_PROFILE_PARTITION
: `${PERSIST}${LOCAL_PROFILE_PREFIX}${profileSlug}`;
}
const hostPartition = `${PERSIST}${HOST_PREFIX}${hostKey(route.serverId)}`;
return isDefault ? hostPartition : `${hostPartition}${HOST_PROFILE_INFIX}${profileSlug}`;
}
/** Returns the (route, profile) of a Paseo browser partition, or null for any other partition. */
export function parseBrowserPartition(partition: unknown): ParsedBrowserPartition | null {
if (typeof partition !== "string" || !partition.startsWith(PERSIST)) {
return null;
}
if (partition === PASEO_BROWSER_PROFILE_PARTITION) {
return { route: "local", profileSlug: DEFAULT_BROWSER_PROFILE_SLUG };
}
const name = partition.slice(PERSIST.length);
if (name.startsWith(LOCAL_PROFILE_PREFIX)) {
const slug = name.slice(LOCAL_PROFILE_PREFIX.length);
return isNamedBrowserProfileSlug(slug) ? { route: "local", profileSlug: slug } : null;
}
const host = HOST_PARTITION.exec(name);
if (!host) {
return null;
}
const slug = host[2];
if (slug === undefined) {
return { route: "host", profileSlug: DEFAULT_BROWSER_PROFILE_SLUG };
}
return isNamedBrowserProfileSlug(slug) ? { route: "host", profileSlug: slug } : null;
}
@@ -2,11 +2,8 @@ import { randomUUID } from "node:crypto";
import { readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import {
BROWSER_PROFILE_COLORS,
isNamedBrowserProfileSlug,
type BrowserProfileColor,
} from "./browser-profile.js";
import { isNamedBrowserProfileSlug } from "./browser-partition.js";
import { BROWSER_PROFILE_COLORS, type BrowserProfileColor } from "./browser-profile.js";
const colorSchema = z.enum(BROWSER_PROFILE_COLORS);
const nameSchema = z.string().trim().min(1).max(80);
@@ -2,24 +2,27 @@ import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "./browser-partition.js";
import {
clearPaseoBrowserProfile,
deleteBrowserProfilePartitionDirectory,
getBrowserProfilePartition,
deleteBrowserProfilePartitionDirectories,
getLegacyPaseoBrowserProfileSession,
getPaseoBrowserProfileSession,
getPaseoBrowserProfileSessions,
isNamedBrowserProfileSlug,
isPaseoBrowserProfilePartition,
listBrowserPartitionDirectories,
listDiskHostBrowserProxyPartitions,
listPaseoBrowserProfileGuests,
PASEO_BROWSER_PROFILE_PARTITION,
pruneOrphanedBrowserProfilePartitions,
readHostBrowserProxyPartitions,
readLegacyPaseoBrowserIds,
} from "./browser-profile.js";
import { getHostBrowserProxyPartition } from "./browser-proxy/partition.js";
function getHostBrowserProxyPartition(serverId: string, profileSlug = "default"): string {
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
}
function directoryOf(partition: string): string {
return partition.slice("persist:".length);
}
function createFakeSession() {
return {
@@ -29,34 +32,37 @@ function createFakeSession() {
};
}
describe("browser profile partition naming", () => {
it("maps default and named slugs to persistent partitions", () => {
expect(getBrowserProfilePartition("default")).toBe(PASEO_BROWSER_PROFILE_PARTITION);
expect(getBrowserProfilePartition("work")).toBe("persist:paseo-profile-work");
expect(isNamedBrowserProfileSlug("work")).toBe(true);
expect(isNamedBrowserProfileSlug("default")).toBe(false);
expect(isNamedBrowserProfileSlug("Work")).toBe(false);
expect(isNamedBrowserProfileSlug("a--b")).toBe(false);
expect(isPaseoBrowserProfilePartition(PASEO_BROWSER_PROFILE_PARTITION)).toBe(true);
expect(isPaseoBrowserProfilePartition("persist:paseo-profile-work")).toBe(true);
expect(isPaseoBrowserProfilePartition("persist:paseo-profile-default")).toBe(false);
expect(isPaseoBrowserProfilePartition("persist:other")).toBe(false);
});
it("deletes a named profile partition directory and refuses default", async () => {
describe("browser profile partition directories", () => {
it("deletes a named profile's local and host-proxied directories and refuses default", async () => {
const userData = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-"));
try {
const workDir = path.join(userData, "Partitions", "paseo-profile-work");
const defaultDir = path.join(userData, "Partitions", "paseo-browser");
await mkdir(workDir, { recursive: true });
await mkdir(defaultDir, { recursive: true });
const partitions = (name: string) => path.join(userData, "Partitions", name);
const workDir = partitions("paseo-profile-work");
const hostWorkDir = partitions(directoryOf(getHostBrowserProxyPartition("remote-a", "work")));
const otherHostWorkDir = partitions(
directoryOf(getHostBrowserProxyPartition("remote-b", "work")),
);
const kept = [
partitions("paseo-browser"),
partitions(directoryOf(getHostBrowserProxyPartition("remote-a"))),
partitions(directoryOf(getHostBrowserProxyPartition("remote-a", "customer"))),
partitions("paseo-profile-customer"),
];
for (const dir of [workDir, hostWorkDir, otherHostWorkDir, ...kept]) {
await mkdir(dir, { recursive: true });
}
await writeFile(path.join(workDir, "Cookies"), "alice");
await writeFile(path.join(hostWorkDir, "Cookies"), "alice-on-host");
await deleteBrowserProfilePartitionDirectory(userData, "work");
await deleteBrowserProfilePartitionDirectories(userData, "work");
await expect(stat(workDir)).rejects.toThrow();
expect((await stat(defaultDir)).isDirectory()).toBe(true);
await expect(deleteBrowserProfilePartitionDirectory(userData, "default")).rejects.toThrow();
for (const dir of [workDir, hostWorkDir, otherHostWorkDir]) {
await expect(stat(dir)).rejects.toThrow();
}
for (const dir of kept) {
expect((await stat(dir)).isDirectory()).toBe(true);
}
await expect(deleteBrowserProfilePartitionDirectories(userData, "default")).rejects.toThrow();
} finally {
await rm(userData, { recursive: true, force: true });
}
@@ -109,9 +115,9 @@ describe("listPaseoBrowserProfileGuests", () => {
});
describe("getPaseoBrowserProfileSessions", () => {
it("scopes single-profile clearing to only that profile session", () => {
function createSessions() {
const byPartition = new Map<string, ReturnType<typeof createFakeSession>>();
const sessions = {
return {
fromPartition: vi.fn((partition: string) => {
let existing = byPartition.get(partition);
if (!existing) {
@@ -121,46 +127,82 @@ describe("getPaseoBrowserProfileSessions", () => {
return existing;
}),
};
}
const openedPartitions = (sessions: ReturnType<typeof createSessions>) =>
sessions.fromPartition.mock.calls.map(([partition]) => partition);
const directories = [
"paseo-profile-work",
"paseo-profile-customer",
"paseo-browser-11111111-1111-4111-8111-111111111111",
];
const hostDefault = getHostBrowserProxyPartition("remote-host-1");
const hostWork = getHostBrowserProxyPartition("remote-host-1", "work");
const otherHostWork = getHostBrowserProxyPartition("remote-host-2", "work");
const hostCustomer = getHostBrowserProxyPartition("remote-host-1", "customer");
const legacy = "paseo-browser-11111111-1111-4111-8111-111111111111";
const directories = [
"paseo-profile-work",
"paseo-profile-customer",
legacy,
directoryOf(hostDefault),
directoryOf(otherHostWork),
directoryOf(hostCustomer),
"unrelated",
];
const workOnly = getPaseoBrowserProfileSessions(sessions, directories, { slug: "work" });
expect(workOnly).toHaveLength(1);
expect(sessions.fromPartition).toHaveBeenCalledWith("persist:paseo-profile-work");
sessions.fromPartition.mockClear();
const hostPartition = getHostBrowserProxyPartition("remote-host-1");
const defaultWithHost = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "default",
hostPartitions: [hostPartition],
it("clears a named profile across the local route and every host route", () => {
const sessions = createSessions();
const work = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "work",
hostPartitions: [hostWork, hostDefault],
});
expect(defaultWithHost).toHaveLength(3);
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
hostPartition,
expect(work).toHaveLength(3);
expect(openedPartitions(sessions)).toEqual([
"persist:paseo-profile-work",
otherHostWork,
hostWork,
]);
});
sessions.fromPartition.mockClear();
it("clears Default across the local route, legacy tabs, and every host route", () => {
const sessions = createSessions();
const defaults = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "default",
hostPartitions: [hostWork, getHostBrowserProxyPartition("remote-host-3")],
});
expect(defaults).toHaveLength(4);
expect(openedPartitions(sessions)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
`persist:${legacy}`,
hostDefault,
getHostBrowserProxyPartition("remote-host-3"),
]);
});
it("clears every profile and route, including live sessions, without a slug", () => {
const sessions = createSessions();
const liveSession = createFakeSession();
const all = getPaseoBrowserProfileSessions(sessions, directories, {
hostPartitions: [hostPartition],
hostPartitions: [hostWork],
liveSessions: [liveSession],
});
expect(all).toContain(liveSession);
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
expect(openedPartitions(sessions)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
"persist:paseo-profile-work",
"persist:paseo-profile-customer",
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
hostPartition,
`persist:${legacy}`,
hostDefault,
otherHostWork,
hostCustomer,
hostWork,
]);
});
it("opens nothing for an invalid slug", () => {
const sessions = createSessions();
expect(getPaseoBrowserProfileSessions(sessions, directories, { slug: "Not Valid" })).toEqual(
[],
);
expect(sessions.fromPartition).not.toHaveBeenCalled();
});
it("reads host proxy and legacy browser IDs safely", () => {
expect(getPaseoBrowserProfileSession({ fromPartition: (p) => ({ p }) as never })).toEqual({
p: PASEO_BROWSER_PROFILE_PARTITION,
@@ -220,30 +262,30 @@ describe("clearPaseoBrowserProfile", () => {
});
describe("partition directory discovery", () => {
it("lists partition directories and host proxy partitions on disk", async () => {
it("lists partition directories and prunes orphaned profiles on every route", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-list-"));
try {
expect(await listBrowserPartitionDirectories(directory)).toEqual([]);
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([]);
const hostDir = getHostBrowserProxyPartition("remote-a").slice("persist:".length);
for (const name of ["paseo-profile-work", hostDir, "unrelated"]) {
const hostDefaultDir = directoryOf(getHostBrowserProxyPartition("remote-a"));
const hostWorkDir = directoryOf(getHostBrowserProxyPartition("remote-a", "work"));
const hostOrphanDir = directoryOf(getHostBrowserProxyPartition("remote-a", "orphaned"));
for (const name of [
"paseo-profile-work",
"paseo-profile-orphaned",
hostDefaultDir,
hostWorkDir,
hostOrphanDir,
"unrelated",
]) {
await mkdir(path.join(directory, "Partitions", name), { recursive: true });
}
await writeFile(path.join(directory, "Partitions", "paseo-profile-file"), "");
expect((await listBrowserPartitionDirectories(directory)).sort()).toEqual(
["paseo-profile-work", hostDir, "unrelated"].sort(),
);
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([`persist:${hostDir}`]);
await mkdir(path.join(directory, "Partitions", "paseo-profile-orphaned"), {
recursive: true,
});
const pruned = await pruneOrphanedBrowserProfilePartitions(directory, new Set(["work"]));
expect(pruned).toEqual(["orphaned"]);
expect((await listBrowserPartitionDirectories(directory)).sort()).toEqual(
["paseo-profile-work", hostDir, "unrelated"].sort(),
["paseo-profile-work", hostDefaultDir, hostWorkDir, "unrelated"].sort(),
);
} finally {
await rm(directory, { recursive: true, force: true });
+69 -102
View File
@@ -1,13 +1,12 @@
import { readdir, rm } from "node:fs/promises";
import { readdirSync } from "node:fs";
import path from "node:path";
import {
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
} from "./browser-proxy/partition.js";
export const PASEO_BROWSER_PROFILE_PARTITION = "persist:paseo-browser";
export const PASEO_BROWSER_NAMED_PROFILE_PREFIX = "paseo-profile-";
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserPartition,
isNamedBrowserProfileSlug,
PASEO_BROWSER_PROFILE_PARTITION,
parseBrowserPartition,
} from "./browser-partition.js";
export const BROWSER_PROFILE_COLORS = [
"violet",
@@ -24,42 +23,15 @@ export const BROWSER_PROFILE_COLORS = [
export type BrowserProfileColor = (typeof BROWSER_PROFILE_COLORS)[number];
const NAMED_SLUG = /^(?=.{1,48}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
const LEGACY_PREFIX = "paseo-browser-";
const LEGACY_BROWSER_ID_PATTERN =
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|\d{13,}-[0-9a-f]+)$/i;
const MAX_LEGACY_BROWSER_PROFILES = 1000;
const MAX_HOST_BROWSER_PROFILES = 500;
const DISK_HOST_PARTITION_DIR_PATTERN = /^paseo-browser-host-[0-9a-f]{16}$/;
export function isNamedBrowserProfileSlug(slug: string): boolean {
return NAMED_SLUG.test(slug) && slug !== "default";
}
export function getBrowserProfilePartition(slug: string): string {
if (slug === "default") {
return PASEO_BROWSER_PROFILE_PARTITION;
}
if (!isNamedBrowserProfileSlug(slug)) {
throw new Error(`Invalid browser profile slug: ${slug}`);
}
return `persist:${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`;
}
export function isNamedProfileDirectory(name: string): boolean {
return (
name.startsWith(PASEO_BROWSER_NAMED_PROFILE_PREFIX) &&
isNamedBrowserProfileSlug(name.slice(PASEO_BROWSER_NAMED_PROFILE_PREFIX.length))
);
}
export function isPaseoBrowserProfilePartition(partition: unknown): partition is string {
return (
partition === PASEO_BROWSER_PROFILE_PARTITION ||
(typeof partition === "string" &&
partition.startsWith("persist:") &&
isNamedProfileDirectory(partition.slice("persist:".length)))
);
/** The profile a partition directory under `<userData>/Partitions` belongs to, on any route. */
function readDirectoryProfileSlug(name: string): string | null {
return parseBrowserPartition(`persist:${name}`)?.profileSlug ?? null;
}
export async function listBrowserPartitionDirectories(userData: string): Promise<string[]> {
@@ -72,19 +44,20 @@ export async function listBrowserPartitionDirectories(userData: string): Promise
}
}
export async function deleteBrowserProfilePartitionDirectory(
/** Deletes a named profile's partition directories on the local route and every host route. */
export async function deleteBrowserProfilePartitionDirectories(
userData: string,
slug: string,
): Promise<void> {
if (!isNamedBrowserProfileSlug(slug)) {
throw new Error(`Cannot delete browser profile partition for slug: ${slug}`);
throw new Error(`Cannot delete browser profile partitions for slug: ${slug}`);
}
const partitionDir = path.join(
userData,
"Partitions",
`${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`,
const directories = await listBrowserPartitionDirectories(userData);
await Promise.all(
directories
.filter((name) => readDirectoryProfileSlug(name) === slug)
.map((name) => rm(path.join(userData, "Partitions", name), { recursive: true, force: true })),
);
await rm(partitionDir, { recursive: true, force: true });
}
export async function pruneOrphanedBrowserProfilePartitions(
@@ -92,15 +65,17 @@ export async function pruneOrphanedBrowserProfilePartitions(
activeSlugs: ReadonlySet<string>,
): Promise<string[]> {
const directories = await listBrowserPartitionDirectories(userData);
const removed: string[] = [];
const orphanedSlugs = new Set<string>();
for (const name of directories) {
if (!isNamedProfileDirectory(name)) continue;
const slug = name.slice(PASEO_BROWSER_NAMED_PROFILE_PREFIX.length);
if (activeSlugs.has(slug)) continue;
await deleteBrowserProfilePartitionDirectory(userData, slug);
removed.push(slug);
const slug = readDirectoryProfileSlug(name);
if (slug && isNamedBrowserProfileSlug(slug) && !activeSlugs.has(slug)) {
orphanedSlugs.add(slug);
}
}
return removed;
for (const slug of orphanedSlugs) {
await deleteBrowserProfilePartitionDirectories(userData, slug);
}
return [...orphanedSlugs];
}
const PASEO_BROWSER_STORAGE_TYPES = [
@@ -133,10 +108,10 @@ interface BrowserProfileWebContents extends BrowserProfileGuest {
getType(): string;
}
interface ListBrowserProfileGuestsInput {
interface ListBrowserProfileGuestsInput<W extends BrowserProfileWebContents> {
profileSession?: object;
profileSessions?: Iterable<object>;
webContents: BrowserProfileWebContents[];
webContents: W[];
}
interface ClearBrowserProfileInput {
@@ -180,6 +155,7 @@ export function readLegacyPaseoBrowserIds(input: unknown): string[] {
return [...browserIds];
}
/** Default-profile host partitions for renderer-supplied host server ids. */
export function readHostBrowserProxyPartitions(input: unknown): string[] {
if (!Array.isArray(input)) {
return [];
@@ -190,7 +166,9 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
const trimmed = value.trim();
if (!trimmed) continue;
partitions.add(
isHostBrowserProxyPartition(trimmed) ? trimmed : getHostBrowserProxyPartition(trimmed),
parseBrowserPartition(trimmed)?.route === "host"
? trimmed
: getBrowserPartition({ kind: "host", serverId: trimmed }, DEFAULT_BROWSER_PROFILE_SLUG),
);
if (partitions.size >= MAX_HOST_BROWSER_PROFILES) {
break;
@@ -199,22 +177,12 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
return [...partitions];
}
export function listDiskHostBrowserProxyPartitions(userDataDir: string): string[] {
try {
const partitionsDir = path.join(userDataDir, "Partitions");
const entries = readdirSync(partitionsDir, { withFileTypes: true });
const result: string[] = [];
for (const entry of entries) {
if (entry.isDirectory() && DISK_HOST_PARTITION_DIR_PATTERN.test(entry.name)) {
result.push(`persist:${entry.name}`);
}
}
return result.sort();
} catch {
return [];
}
}
/**
* Sessions that hold a profile's data on every route. With a slug, only that profile
* (Default also owns legacy per-tab partitions). Without a slug, every Paseo profile.
* Host partitions come from disk directories and from `hostPartitions`, the ones
* this process bound to a host proxy.
*/
export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
sessions: { fromPartition(partition: string): S },
directories: readonly string[],
@@ -224,43 +192,42 @@ export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
slug?: string;
} = {},
): S[] {
if (options.slug && options.slug !== "default") {
if (!isNamedBrowserProfileSlug(options.slug)) {
return [];
}
return [sessions.fromPartition(getBrowserProfilePartition(options.slug))];
}
const result = new Set<S>([sessions.fromPartition(PASEO_BROWSER_PROFILE_PARTITION)]);
if (options.slug === "default") {
// Clearing Default also sweeps legacy per-tab partitions and remote host-proxy partitions.
for (const name of directories) {
if (isLegacyDirectory(name)) {
result.add(sessions.fromPartition(`persist:${name}`));
}
}
for (const partition of options.hostPartitions ?? []) {
if (isHostBrowserProxyPartition(partition)) {
result.add(sessions.fromPartition(partition));
}
}
return [...result];
const { slug } = options;
if (
slug !== undefined &&
slug !== DEFAULT_BROWSER_PROFILE_SLUG &&
!isNamedBrowserProfileSlug(slug)
) {
return [];
}
const includes = (profileSlug: string) => slug === undefined || profileSlug === slug;
const partitions = new Set<string>([
getBrowserPartition({ kind: "local" }, slug ?? DEFAULT_BROWSER_PROFILE_SLUG),
]);
for (const name of directories) {
if (isNamedProfileDirectory(name) || isLegacyDirectory(name)) {
result.add(sessions.fromPartition(`persist:${name}`));
const profileSlug = readDirectoryProfileSlug(name);
if (
profileSlug !== null
? includes(profileSlug)
: isLegacyDirectory(name) && includes(DEFAULT_BROWSER_PROFILE_SLUG)
) {
partitions.add(`persist:${name}`);
}
}
for (const partition of options.hostPartitions ?? []) {
if (isHostBrowserProxyPartition(partition)) {
result.add(sessions.fromPartition(partition));
const parsed = parseBrowserPartition(partition);
if (parsed?.route === "host" && includes(parsed.profileSlug)) {
partitions.add(partition);
}
}
// A newly created profile's directory may not exist yet while its guest is live.
for (const live of options.liveSessions ?? []) {
result.add(live);
const result = new Set<S>([...partitions].map((partition) => sessions.fromPartition(partition)));
if (slug === undefined) {
// A newly created profile's directory may not exist yet while its guest is live.
for (const live of options.liveSessions ?? []) {
result.add(live);
}
}
return [...result];
}
@@ -276,9 +243,9 @@ export function getLegacyPaseoBrowserProfileSession(
: null;
}
export function listPaseoBrowserProfileGuests(
input: ListBrowserProfileGuestsInput,
): BrowserProfileGuest[] {
export function listPaseoBrowserProfileGuests<W extends BrowserProfileWebContents>(
input: ListBrowserProfileGuestsInput<W>,
): W[] {
const allowedSessions = new Set<object>(input.profileSessions ?? []);
if (input.profileSession) {
allowedSessions.add(input.profileSession);
@@ -1,11 +1,6 @@
import { randomUUID } from "node:crypto";
import { BrowserWindow, ipcMain, session as electronSession, type WebContents } from "electron";
import log from "electron-log/main";
import {
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
PASEO_BROWSER_HOST_PARTITION_PREFIX,
} from "./partition.js";
import {
createBrowserProxyManager,
type BrowserProxyManager,
@@ -20,10 +15,7 @@ import {
export {
createBrowserProxyManager,
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
parseBrowserProxyTarget,
PASEO_BROWSER_HOST_PARTITION_PREFIX,
type BrowserProxyManager,
type BrowserProxyStatus,
type BrowserProxyStatusSnapshot,
@@ -125,9 +117,13 @@ export function createElectronBrowserProxyController(deps: {
if (!target) {
throw new Error("Invalid browser proxy target");
}
if (rawInput.profileSlug !== undefined && typeof rawInput.profileSlug !== "string") {
throw new Error("Invalid browser proxy profile");
}
return await manager.ensureHostProxy({
serverId: rawInput.serverId,
target,
...(rawInput.profileSlug !== undefined ? { profileSlug: rawInput.profileSlug } : {}),
forceReconnect: rawInput.forceReconnect === true,
});
});
@@ -1,32 +0,0 @@
import { describe, expect, test } from "vitest";
import {
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
PASEO_BROWSER_HOST_PARTITION_PREFIX,
} from "./partition.js";
describe("host browser proxy partition naming", () => {
test("produces deterministic 16-hex-char persistent partitions per serverId", () => {
const first = getHostBrowserProxyPartition("srv_alpha_123");
const second = getHostBrowserProxyPartition("srv_alpha_123");
const other = getHostBrowserProxyPartition("srv_beta_456");
expect(first).toBe(second);
expect(first).not.toBe(other);
expect(first.startsWith(PASEO_BROWSER_HOST_PARTITION_PREFIX)).toBe(true);
expect(first).toMatch(/^persist:paseo-browser-host-[0-9a-f]{16}$/);
expect(isHostBrowserProxyPartition(first)).toBe(true);
expect(isHostBrowserProxyPartition(other)).toBe(true);
});
test("validates only exact host proxy partition format", () => {
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcdef")).toBe(true);
expect(isHostBrowserProxyPartition("persist:paseo-browser")).toBe(false);
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcde")).toBe(false);
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcdef0")).toBe(false);
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789ABCDEF")).toBe(false);
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-zzzzzzzzzzzzzzzz")).toBe(false);
expect(isHostBrowserProxyPartition("persist:foreign")).toBe(false);
expect(isHostBrowserProxyPartition(undefined)).toBe(false);
});
});
@@ -1,18 +0,0 @@
import { createHash } from "node:crypto";
export const PASEO_BROWSER_HOST_PARTITION_PREFIX = "persist:paseo-browser-host-";
const HOST_PARTITION_PATTERN = /^persist:paseo-browser-host-[0-9a-f]{16}$/;
export function getHostBrowserProxyPartition(serverId: string): string {
const normalized = serverId.trim();
if (!normalized) {
throw new Error("Host serverId is required to derive a browser proxy partition");
}
const digest = createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 16);
return `${PASEO_BROWSER_HOST_PARTITION_PREFIX}${digest}`;
}
export function isHostBrowserProxyPartition(partition: string | undefined): partition is string {
return typeof partition === "string" && HOST_PARTITION_PATTERN.test(partition);
}
@@ -6,7 +6,7 @@ import {
type DecodedNetworkTunnelFrame,
type NetworkTunnelFrame,
} from "@getpaseo/protocol/network-tunnel";
import { getHostBrowserProxyPartition } from "./partition.js";
import { getBrowserPartition } from "../../browser-partition.js";
import {
createBrowserProxyManager,
type BrowserProxyManager,
@@ -204,10 +204,13 @@ describe("BrowserProxyManager", () => {
const target = "tcp://10.0.0.5:6767";
const ready = await manager.ensureHostProxy({ serverId: "remote-1", target });
const expectedPartition = getHostBrowserProxyPartition("remote-1");
const expectedPartition = getBrowserPartition(
{ kind: "host", serverId: "remote-1" },
"default",
);
expect(ready.status).toBe("ready");
expect(ready.partition).toBe(expectedPartition);
expect(ready.profilePartitions).toEqual({ default: expectedPartition });
expect(ready.socksPort).toBeGreaterThan(0);
expect(manager.isAllowedHostPartition(expectedPartition)).toBe(true);
expect(manager.isProxiedSession(sessionsByPartition.get(expectedPartition)!)).toBe(true);
@@ -304,7 +307,12 @@ describe("BrowserProxyManager", () => {
expect(result.status).toBe("error");
expect(result.socksPort).toBeNull();
expect(result.error).toMatch(/resolveProxy|proxy/i);
expect(manager.isAllowedHostPartition(result.partition)).toBe(false);
expect(result.profilePartitions).toEqual({});
expect(
manager.isAllowedHostPartition(
getBrowserPartition({ kind: "host", serverId: "remote-broken-proxy" }, "default"),
),
).toBe(false);
});
test("keeps socksPort null on initial tunnel failure, and preserves socksPort across later reconnect errors", async () => {
@@ -335,7 +343,7 @@ describe("BrowserProxyManager", () => {
const initialFail = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
expect(initialFail.status).toBe("error");
expect(initialFail.socksPort).toBeNull();
expect(manager.isAllowedHostPartition(initialFail.partition)).toBe(false);
expect(initialFail.profilePartitions).toEqual({});
failTicket = false;
const ready = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
@@ -362,4 +370,85 @@ describe("BrowserProxyManager", () => {
expect(recovered.status).toBe("ready");
expect(recovered.socksPort).toBe(ready.socksPort);
});
test("binds every profile session on a host to the same SOCKS5 port and tunnel", async () => {
const sessionsByPartition = new Map<string, ReturnType<typeof createFakeSession>>();
const wires: Array<ReturnType<typeof createEchoTunnelWire>> = [];
const statuses: BrowserProxyStatusSnapshot[] = [];
const manager = createBrowserProxyManager({
verifySocketOwner: async () => true,
requestTicket: async () => "ticket",
openTunnelWire: async () => {
const created = createEchoTunnelWire();
wires.push(created);
return created.wire;
},
getSessionForPartition: (partition) => {
let session = sessionsByPartition.get(partition);
if (!session) {
session = createFakeSession();
sessionsByPartition.set(partition, session);
}
return session;
},
onStatusChange: (status) => statuses.push(status),
});
managers.push(manager);
const route = { kind: "host", serverId: "remote-profiles" } as const;
const defaultPartition = getBrowserPartition(route, "default");
const workPartition = getBrowserPartition(route, "work");
const target = "tcp://10.0.0.20:6767";
const [first, second] = await Promise.all([
manager.ensureHostProxy({ serverId: "remote-profiles", target }),
manager.ensureHostProxy({ serverId: "remote-profiles", target, profileSlug: "work" }),
]);
expect(first.socksPort).toBeGreaterThan(0);
expect(second.socksPort).toBe(first.socksPort);
expect(second.profilePartitions).toEqual({ default: defaultPartition, work: workPartition });
expect(manager.getHostProxyStatus("remote-profiles")?.profilePartitions).toEqual({
default: defaultPartition,
work: workPartition,
});
expect(statuses.at(-1)?.profilePartitions).toEqual({
default: defaultPartition,
work: workPartition,
});
for (const partition of [defaultPartition, workPartition]) {
const session = sessionsByPartition.get(partition)!;
expect(session.lastProxyConfig?.proxyRules).toBe(`socks5://127.0.0.1:${first.socksPort}`);
expect(manager.isAllowedHostPartition(partition)).toBe(true);
expect(manager.isProxiedSession(session)).toBe(true);
}
expect(manager.listKnownPartitions().sort()).toEqual([defaultPartition, workPartition].sort());
expect(wires).toHaveLength(1);
const reply = await socks5ConnectAndExchange(first.socksPort!, "localhost", 5173, "work");
expect(reply).toBe("ECHO:work");
expect(wires).toHaveLength(1);
await manager.releaseHostProxy("remote-profiles");
expect(manager.isAllowedHostPartition(defaultPartition)).toBe(false);
expect(manager.isAllowedHostPartition(workPartition)).toBe(false);
});
test("refuses to bind an invalid profile slug", async () => {
const manager = createBrowserProxyManager({
verifySocketOwner: async () => true,
requestTicket: async () => "ticket",
openTunnelWire: async () => createEchoTunnelWire().wire,
getSessionForPartition: () => createFakeSession(),
});
managers.push(manager);
await expect(
manager.ensureHostProxy({
serverId: "remote-invalid",
target: "tcp://10.0.0.21:6767",
profileSlug: "Not Valid",
}),
).rejects.toThrow(/profile/i);
});
});
@@ -1,5 +1,9 @@
import net, { type AddressInfo, type Server, type Socket } from "node:net";
import { getHostBrowserProxyPartition, isHostBrowserProxyPartition } from "./partition.js";
import {
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserPartition,
parseBrowserPartition,
} from "../../browser-partition.js";
import { createOsSocketOwnerVerifier, type SocketOwnerVerifier } from "./socket-owner.js";
import {
performSocks5Handshake,
@@ -17,7 +21,8 @@ export type BrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting
export interface BrowserProxyStatusSnapshot {
serverId: string;
partition: string;
/** Profile slug -> partition, for every profile session bound and verified on this host. */
profilePartitions: Record<string, string>;
status: BrowserProxyStatus;
error: string | null;
socksPort: number | null;
@@ -51,6 +56,8 @@ export interface BrowserProxyManagerDeps {
export interface EnsureHostProxyInput {
serverId: string;
target: HostTransportSpec;
/** The browser profile whose session to bind to the host proxy. Defaults to `default`. */
profileSlug?: string;
forceReconnect?: boolean;
}
@@ -65,19 +72,23 @@ export interface BrowserProxyManager {
disposeAll(): Promise<void>;
}
/**
* One host route: one loopback SOCKS5 server and one tunnel. Every profile session
* on the host points `setProxy` at the same SOCKS5 port.
*/
interface HostProxyEntry {
readonly serverId: string;
readonly partition: string;
target: HostTransportSpec;
status: BrowserProxyStatus;
error: string | null;
socksServer: Server | null;
socksPort: number | null;
session: BrowserProxySessionLike | null;
sessionConfigured: boolean;
/** Profile slug -> partition whose session is bound and verified. */
boundPartitions: Map<string, string>;
bindPromises: Map<string, Promise<void>>;
mux: TunnelMuxClient | null;
connectPromise: Promise<TunnelMuxClient> | null;
ensurePromise: Promise<BrowserProxyStatusSnapshot> | null;
routePromise: Promise<number> | null;
activeSockets: Set<Socket>;
disposed: boolean;
}
@@ -110,15 +121,19 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
function snapshotOf(entry: HostProxyEntry): BrowserProxyStatusSnapshot {
return {
serverId: entry.serverId,
partition: entry.partition,
profilePartitions: Object.fromEntries(entry.boundPartitions),
status: entry.status,
error: entry.error,
// Only expose socksPort once Chromium's session proxy has been configured and
// Only expose socksPort once a Chromium session proxy has been configured and
// verified via resolveProxy so renderers never mount an unverified partition.
socksPort: entry.sessionConfigured ? entry.socksPort : null,
socksPort: hasBoundSession(entry) ? entry.socksPort : null,
};
}
function hasBoundSession(entry: HostProxyEntry): boolean {
return entry.boundPartitions.size > 0;
}
function setEntryStatus(
entry: HostProxyEntry,
status: BrowserProxyStatus,
@@ -167,12 +182,44 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
return address.port;
}
async function ensureSessionConfigured(entry: HostProxyEntry, socksPort: number): Promise<void> {
if (entry.sessionConfigured && entry.session) {
async function bindSession(
entry: HostProxyEntry,
profileSlug: string,
partition: string,
socksPort: number,
): Promise<void> {
if (entry.boundPartitions.has(profileSlug)) {
return;
}
let bindTask = entry.bindPromises.get(profileSlug);
if (!bindTask) {
bindTask = (async () => {
const session = await configureSession(partition, socksPort);
if (entry.disposed) {
throw new Error("Host browser proxy was disposed");
}
entry.boundPartitions.set(profileSlug, partition);
allowedPartitions.add(partition);
proxiedSessions.add(session);
deps.onStatusChange?.(snapshotOf(entry));
})();
entry.bindPromises.set(profileSlug, bindTask);
const settled = () => {
if (entry.bindPromises.get(profileSlug) === bindTask) {
entry.bindPromises.delete(profileSlug);
}
};
bindTask.then(settled, settled);
}
await bindTask;
}
const hostSession = deps.getSessionForPartition(entry.partition);
async function configureSession(
partition: string,
socksPort: number,
): Promise<BrowserProxySessionLike> {
knownPartitions.add(partition);
const hostSession = deps.getSessionForPartition(partition);
await hostSession.setProxy({
mode: "fixed_servers",
proxyRules: `socks5://127.0.0.1:${socksPort}`,
@@ -194,12 +241,26 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
`Session resolveProxy verification failed (localhost="${resolvedLocalhost}", 127.0.0.1="${resolvedLoopbackIp}")`,
);
}
return hostSession;
}
entry.session = hostSession;
entry.sessionConfigured = true;
allowedPartitions.add(entry.partition);
knownPartitions.add(entry.partition);
proxiedSessions.add(hostSession);
/** The host route: its fixed SOCKS5 port and a connected tunnel, shared by every profile. */
async function ensureRoute(entry: HostProxyEntry): Promise<number> {
if (!entry.routePromise) {
const routeTask = (async () => {
const socksPort = await ensureSocksServer(entry);
await ensureTunnelConnected(entry);
return socksPort;
})();
entry.routePromise = routeTask;
const settled = () => {
if (entry.routePromise === routeTask) {
entry.routePromise = null;
}
};
routeTask.then(settled, settled);
}
return await entry.routePromise;
}
async function ensureTunnelConnected(entry: HostProxyEntry): Promise<TunnelMuxClient> {
@@ -214,7 +275,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
}
const nextStatus: BrowserProxyStatus =
entry.sessionConfigured || entry.status === "ready" || entry.status === "reconnecting"
hasBoundSession(entry) || entry.status === "ready" || entry.status === "reconnecting"
? "reconnecting"
: "connecting";
setEntryStatus(entry, nextStatus, null);
@@ -238,13 +299,13 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
mux.onClose(() => {
if (entry.mux === mux) {
entry.mux = null;
if (!entry.disposed && entry.sessionConfigured) {
if (!entry.disposed && hasBoundSession(entry)) {
setEntryStatus(entry, "reconnecting", null);
}
}
});
if (entry.sessionConfigured) {
if (hasBoundSession(entry)) {
setEntryStatus(entry, "ready", null);
}
return mux;
@@ -358,21 +419,18 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
return existing;
}
const partition = getHostBrowserProxyPartition(serverId);
knownPartitions.add(partition);
const entry: HostProxyEntry = {
serverId,
partition,
target,
status: "idle",
error: null,
socksServer: null,
socksPort: null,
session: null,
sessionConfigured: false,
boundPartitions: new Map(),
bindPromises: new Map(),
mux: null,
connectPromise: null,
ensurePromise: null,
routePromise: null,
activeSockets: new Set(),
disposed: false,
};
@@ -385,6 +443,8 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
if (!serverId) {
throw new Error("Host serverId is required");
}
const profileSlug = input.profileSlug ?? DEFAULT_BROWSER_PROFILE_SLUG;
const partition = getBrowserPartition({ kind: "host", serverId }, profileSlug);
const entry = getOrCreateEntry(serverId, input.target);
if (input.forceReconnect && entry.mux) {
@@ -392,37 +452,19 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
entry.mux = null;
}
if (entry.ensurePromise) {
return await entry.ensurePromise;
}
const ensureTask = (async (): Promise<BrowserProxyStatusSnapshot> => {
try {
if (entry.status !== "ready") {
setEntryStatus(entry, entry.sessionConfigured ? "reconnecting" : "connecting", null);
}
const socksPort = await ensureSocksServer(entry);
await ensureTunnelConnected(entry);
await ensureSessionConfigured(entry, socksPort);
setEntryStatus(entry, "ready", null);
return snapshotOf(entry);
} catch (error) {
const message = formatError(error);
if (!entry.disposed) {
setEntryStatus(entry, "error", message);
}
return snapshotOf(entry);
}
})();
entry.ensurePromise = ensureTask;
try {
return await ensureTask;
} finally {
if (entry.ensurePromise === ensureTask) {
entry.ensurePromise = null;
if (entry.status !== "ready") {
setEntryStatus(entry, hasBoundSession(entry) ? "reconnecting" : "connecting", null);
}
const socksPort = await ensureRoute(entry);
await bindSession(entry, profileSlug, partition, socksPort);
setEntryStatus(entry, "ready", null);
} catch (error) {
if (!entry.disposed) {
setEntryStatus(entry, "error", formatError(error));
}
}
return snapshotOf(entry);
}
function updateHostProxyTarget(input: { serverId: string; target: HostTransportSpec }): void {
@@ -432,7 +474,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
entry.target = input.target;
entry.mux?.close();
entry.mux = null;
if (entry.sessionConfigured) {
if (hasBoundSession(entry)) {
setEntryStatus(entry, "reconnecting", null);
}
}
@@ -444,7 +486,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
}
function isAllowedHostPartition(partition: string): boolean {
return isHostBrowserProxyPartition(partition) && allowedPartitions.has(partition);
return parseBrowserPartition(partition)?.route === "host" && allowedPartitions.has(partition);
}
function isProxiedSession(session: object): boolean {
@@ -459,7 +501,9 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
if (entry.disposed) return;
entry.disposed = true;
entriesByServerId.delete(entry.serverId);
allowedPartitions.delete(entry.partition);
for (const partition of entry.boundPartitions.values()) {
allowedPartitions.delete(partition);
}
entry.mux?.close();
entry.mux = null;
@@ -1,5 +0,0 @@
export {
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
PASEO_BROWSER_HOST_PARTITION_PREFIX,
} from "./internal/partition.js";
@@ -1,6 +1,5 @@
import { describe, expect, test } from "vitest";
import { PASEO_BROWSER_PROFILE_PARTITION } from "../browser-profile.js";
import { getHostBrowserProxyPartition } from "../browser-proxy/partition.js";
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "../browser-partition.js";
import {
getPaseoBrowserIdForWebContents,
getPaseoBrowserWorkspaceId,
@@ -11,6 +10,10 @@ import {
unregisterPaseoBrowserFromHost,
} from "./index.js";
function hostPartitionFor(serverId: string, profileSlug = "default"): string {
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
}
class FakeRenderer {
public constructor(public readonly id: number) {}
@@ -46,8 +49,8 @@ class FakeBrowserGuest {
describe("browser webview attachment", () => {
test("accepts only allowed URLs on the shared profile or registered host proxy partitions", () => {
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
const unregisteredHostPartition = getHostBrowserProxyPartition("remote-host-b");
const hostPartition = hostPartitionFor("remote-host-a");
const unregisteredHostPartition = hostPartitionFor("remote-host-b");
const isAllowedHostPartition = (partition: string) => partition === hostPartition;
expect(
@@ -88,7 +91,7 @@ describe("browser webview attachment", () => {
});
test("registers a guest attached to an allowed host proxy session", () => {
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
const hostPartition = hostPartitionFor("remote-host-a");
const proxiedSession = {};
const renderer = new FakeRenderer(9);
const guest = new FakeBrowserGuest(901, renderer, proxiedSession);
@@ -109,6 +112,53 @@ describe("browser webview attachment", () => {
unregisterPaseoBrowser("browser-proxied");
});
test("admits a host-proxied named profile only once its session is bound to the host proxy", () => {
const boundWork = hostPartitionFor("remote-host-a", "work");
const unboundWork = hostPartitionFor("remote-host-b", "work");
const isAllowedHostPartition = (partition: string) => partition === boundWork;
expect(
isPaseoBrowserWebviewAttach({
src: "http://localhost:3000",
partition: boundWork,
isAllowedHostPartition,
}),
).toBe(true);
expect(
isPaseoBrowserWebviewAttach({
src: "http://localhost:3000",
partition: unboundWork,
isAllowedHostPartition,
}),
).toBe(false);
expect(
isPaseoBrowserWebviewAttach({ src: "http://localhost:3000", partition: boundWork }),
).toBe(false);
});
test("registers a guest on a host-proxied named profile only when its session is proxied", () => {
const workPartition = hostPartitionFor("remote-host-a", "work");
const proxiedSession = {};
const renderer = new FakeRenderer(10);
const guest = new FakeBrowserGuest(1001, renderer, proxiedSession);
const register = (isAllowedHostSession: (session: object) => boolean) =>
registerAttachedPaseoBrowser({
browserId: "browser-proxied-work",
workspaceId: "workspace-remote",
webContentsId: guest.id,
sender: renderer,
partition: workPartition,
sessionFromPartition: (partition) => (partition === workPartition ? proxiedSession : {}),
isAllowedHostSession,
findWebContents: () => guest,
});
expect(register(() => false)).toBe(false);
expect(register((session) => session === proxiedSession)).toBe(true);
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-proxied-work");
unregisterPaseoBrowser("browser-proxied-work");
});
test("admits only complete lowercase named profile partitions on allowed URLs", () => {
const valid = "persist:paseo-profile-work";
for (const partition of [valid, `persist:paseo-profile-${"a".repeat(48)}`]) {
@@ -1,6 +1,5 @@
import { webContents as allWebContents, type WebContents } from "electron";
import { isPaseoBrowserProfilePartition } from "../browser-profile.js";
import { isHostBrowserProxyPartition } from "../browser-proxy/partition.js";
import { parseBrowserPartition } from "../browser-partition.js";
import {
BROWSER_NEW_TAB_REQUEST_EVENT,
buildBrowserPopupWebPreferences,
@@ -52,13 +51,12 @@ export function isPaseoBrowserWebviewAttach(input: {
if (!isAllowedBrowserWebviewUrl(input.src)) {
return false;
}
if (isPaseoBrowserProfilePartition(input.partition)) {
return true;
const parsed = parseBrowserPartition(input.partition);
if (!parsed || !input.partition) {
return false;
}
return (
isHostBrowserProxyPartition(input.partition) &&
(input.isAllowedHostPartition?.(input.partition) ?? false)
);
// A host-routed partition attaches only once main bound its session to the host proxy.
return parsed.route === "local" || (input.isAllowedHostPartition?.(input.partition) ?? false);
}
export function listRegisteredPaseoBrowserIds(): string[] {
@@ -83,14 +81,11 @@ export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput
if (!guest || guest.isDestroyed() || guest.hostWebContents !== input.sender) {
return false;
}
const sessionMatchesProfile =
isPaseoBrowserProfilePartition(input.partition) &&
guest.session === input.sessionFromPartition(input.partition);
const sessionMatchesHostProxy =
isHostBrowserProxyPartition(input.partition) &&
guest.session === input.sessionFromPartition(input.partition) &&
(input.isAllowedHostSession?.(guest.session) ?? false);
if (!sessionMatchesProfile && !sessionMatchesHostProxy) {
const parsed = parseBrowserPartition(input.partition);
if (!parsed || guest.session !== input.sessionFromPartition(input.partition)) {
return false;
}
if (parsed.route === "host" && !(input.isAllowedHostSession?.(guest.session) ?? false)) {
return false;
}
@@ -0,0 +1,437 @@
import { describe, expect, it, vi } from "vitest";
import {
installAppSessionPermissions,
installBrowserWebviewSessionPermissions,
resolveAppTrustedOrigin,
type PermissionSessionLike,
} from "./session-permissions.js";
function createFakeSession() {
let checkHandler: Parameters<PermissionSessionLike["setPermissionCheckHandler"]>[0] = null;
let requestHandler: Parameters<PermissionSessionLike["setPermissionRequestHandler"]>[0] = null;
let deviceHandler: Parameters<PermissionSessionLike["setDevicePermissionHandler"]>[0] = null;
let usbProtectedClassesHandler:
| Parameters<NonNullable<PermissionSessionLike["setUSBProtectedClassesHandler"]>>[0]
| null = null;
let bluetoothPairingHandler:
| Parameters<NonNullable<PermissionSessionLike["setBluetoothPairingHandler"]>>[0]
| null = null;
const session: PermissionSessionLike = {
setPermissionCheckHandler: vi.fn((handler) => {
checkHandler = handler;
}),
setPermissionRequestHandler: vi.fn((handler) => {
requestHandler = handler;
}),
setDevicePermissionHandler: vi.fn((handler) => {
deviceHandler = handler;
}),
setUSBProtectedClassesHandler: vi.fn((handler) => {
usbProtectedClassesHandler = handler;
}),
setBluetoothPairingHandler: vi.fn((handler) => {
bluetoothPairingHandler = handler;
}),
};
function check(
webContents: { getType: () => string } | null,
permission: string,
requestingOrigin: string,
details: {
isMainFrame: boolean;
requestingUrl?: string;
securityOrigin?: string;
embeddingOrigin?: string;
mediaType?: "video" | "audio" | "unknown";
} = { isMainFrame: true },
): boolean {
if (!checkHandler) {
throw new Error("Permission check handler was not installed");
}
return checkHandler(webContents as never, permission as never, requestingOrigin, details);
}
function request(
webContents: { getType: () => string },
permission: string,
details: {
isMainFrame: boolean;
requestingUrl: string;
securityOrigin?: string;
mediaTypes?: Array<"video" | "audio">;
} = { isMainFrame: true, requestingUrl: "https://example.com/" },
): boolean {
if (!requestHandler) {
throw new Error("Permission request handler was not installed");
}
let granted: boolean | undefined;
requestHandler(
webContents as never,
permission as never,
(value) => {
granted = value;
},
details as never,
);
if (granted === undefined) {
throw new Error("Permission request handler did not invoke callback synchronously");
}
return granted;
}
function checkDevice(details: {
deviceType: "hid" | "serial" | "usb";
origin: string;
device?: object;
}): boolean {
if (!deviceHandler) {
throw new Error("Device permission handler was not installed");
}
return deviceHandler({ device: {}, ...details } as never);
}
return {
session,
check,
request,
checkDevice,
getUsbProtectedClasses: (protectedClasses: string[]) => {
if (!usbProtectedClassesHandler) {
throw new Error("USB protected classes handler was not installed");
}
return usbProtectedClassesHandler({ protectedClasses: protectedClasses as never });
},
pairBluetooth: () => {
if (!bluetoothPairingHandler) {
throw new Error("Bluetooth pairing handler was not installed");
}
let response: { confirmed: boolean } | undefined;
bluetoothPairingHandler({ deviceId: "dev-1", pairingKind: "confirm", frame: null }, (res) => {
response = res;
});
return response;
},
};
}
describe("browser webview session permissions", () => {
const deniedPermissions = [
"media",
"display-capture",
"geolocation",
"geolocation-approximate",
"notifications",
"clipboard-read",
"deprecated-sync-clipboard-read",
"midi",
"midiSysex",
"usb",
"hid",
"serial",
"bluetooth",
"pointerLock",
"keyboardLock",
"openExternal",
"fileSystem",
"local-network",
"local-network-access",
"loopback-network",
"local-fonts",
"idle-detection",
"sensors",
"nfc",
"ar",
"vr",
"hand-tracking",
"screen-wake-lock",
"system-wake-lock",
"window-management",
"speaker-selection",
"storage-access",
"top-level-storage-access",
"mediaKeySystem",
"payment-handler",
"web-printing",
"web-app-installation",
"captured-surface-control",
"automatic-fullscreen",
"background-fetch",
"background-sync",
"periodic-background-sync",
"persistent-storage",
"smart-card",
"unknown",
];
const allowedHarmlessPermissions = ["fullscreen", "clipboard-sanitized-write"];
it("denies sensitive permissions by default for both checks and requests", () => {
const fake = createFakeSession();
const guest = { getType: () => "webview" };
installBrowserWebviewSessionPermissions(fake.session);
for (const permission of deniedPermissions) {
expect(fake.check(guest, permission, "https://example.com/")).toBe(false);
expect(
fake.request(guest, permission, {
isMainFrame: true,
requestingUrl: "https://example.com/",
mediaTypes: permission === "media" ? ["audio", "video"] : undefined,
}),
).toBe(false);
}
});
it("explicitly allows only harmless non-sensitive UX permissions", () => {
const fake = createFakeSession();
const guest = { getType: () => "webview" };
installBrowserWebviewSessionPermissions(fake.session);
for (const permission of allowedHarmlessPermissions) {
expect(fake.check(guest, permission, "https://example.com/")).toBe(true);
expect(
fake.request(guest, permission, {
isMainFrame: true,
requestingUrl: "https://example.com/",
}),
).toBe(true);
}
});
it("denies all device permissions, keeps USB classes protected, and cancels Bluetooth pairing", () => {
const fake = createFakeSession();
installBrowserWebviewSessionPermissions(fake.session);
expect(fake.checkDevice({ deviceType: "usb", origin: "https://example.com/" })).toBe(false);
expect(fake.checkDevice({ deviceType: "hid", origin: "https://example.com/" })).toBe(false);
expect(fake.checkDevice({ deviceType: "serial", origin: "https://example.com/" })).toBe(false);
expect(fake.getUsbProtectedClasses(["hid", "mass-storage", "video"])).toEqual([
"hid",
"mass-storage",
"video",
]);
expect(fake.pairBluetooth()).toEqual({ confirmed: false });
});
it("is idempotent when called multiple times on the same session", () => {
const fake = createFakeSession();
installBrowserWebviewSessionPermissions(fake.session);
installBrowserWebviewSessionPermissions(fake.session);
expect(fake.session.setPermissionCheckHandler).toHaveBeenCalledTimes(1);
expect(fake.session.setPermissionRequestHandler).toHaveBeenCalledTimes(1);
expect(fake.session.setDevicePermissionHandler).toHaveBeenCalledTimes(1);
expect(fake.session.setUSBProtectedClassesHandler).toHaveBeenCalledTimes(1);
expect(fake.session.setBluetoothPairingHandler).toHaveBeenCalledTimes(1);
});
});
describe("main app session permissions", () => {
it("resolves trusted app origin for packaged and dev URLs and fails closed on invalid input", () => {
expect(
resolveAppTrustedOrigin({
isPackaged: true,
appScheme: "paseo",
devServerUrl: "http://localhost:8081",
}),
).toBe("paseo://app");
expect(
resolveAppTrustedOrigin({
isPackaged: false,
appScheme: "paseo",
devServerUrl: "http://localhost:8081/chat",
}),
).toBe("http://localhost:8081");
expect(
resolveAppTrustedOrigin({
isPackaged: false,
appScheme: "paseo",
devServerUrl: "not-a-valid-url",
}),
).toBeNull();
});
it("preserves microphone audio, notifications, clipboard, and fullscreen on the trusted main frame", () => {
const fake = createFakeSession();
const appWindow = { getType: () => "window" };
installAppSessionPermissions(fake.session, { trustedOrigin: "paseo://app" });
// Electron passes requestingOrigin with a trailing slash (e.g. "paseo://app/").
expect(
fake.check(appWindow, "media", "paseo://app/", {
isMainFrame: true,
requestingUrl: "paseo://app/chat",
mediaType: "audio",
}),
).toBe(true);
expect(
fake.request(appWindow, "media", {
isMainFrame: true,
requestingUrl: "paseo://app/chat",
securityOrigin: "paseo://app/",
mediaTypes: ["audio"],
}),
).toBe(true);
for (const permission of [
"notifications",
"clipboard-read",
"clipboard-sanitized-write",
"fullscreen",
]) {
expect(
fake.check(appWindow, permission, "paseo://app/", {
isMainFrame: true,
requestingUrl: "paseo://app/chat",
}),
).toBe(true);
expect(
fake.request(appWindow, permission, {
isMainFrame: true,
requestingUrl: "paseo://app/chat",
securityOrigin: "paseo://app/",
}),
).toBe(true);
}
});
it("denies video camera, geolocation, devices, subframes, and untrusted origins in the app session", () => {
const fake = createFakeSession();
const appWindow = { getType: () => "window" };
const guest = { getType: () => "webview" };
installAppSessionPermissions(fake.session, { trustedOrigin: "http://localhost:8081" });
// Video camera is denied even for the trusted main frame
expect(
fake.check(appWindow, "media", "http://localhost:8081/", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
mediaType: "video",
}),
).toBe(false);
expect(
fake.request(appWindow, "media", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
securityOrigin: "http://localhost:8081/",
mediaTypes: ["video"],
}),
).toBe(false);
expect(
fake.request(appWindow, "media", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
securityOrigin: "http://localhost:8081/",
mediaTypes: ["audio", "video"],
}),
).toBe(false);
expect(
fake.request(appWindow, "media", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
securityOrigin: "http://localhost:8081/",
mediaTypes: [],
}),
).toBe(false);
// Other sensitive permissions are denied even on the trusted main frame
for (const permission of [
"geolocation",
"usb",
"hid",
"serial",
"midi",
"display-capture",
"pointerLock",
"openExternal",
]) {
expect(
fake.check(appWindow, permission, "http://localhost:8081/", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
}),
).toBe(false);
expect(
fake.request(appWindow, permission, {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
securityOrigin: "http://localhost:8081/",
}),
).toBe(false);
}
// Subframes (e.g. sandboxed HTML previews or Mermaid iframes) are denied
expect(
fake.check(appWindow, "media", "http://localhost:8081/", {
isMainFrame: false,
requestingUrl: "data:text/html,hi",
embeddingOrigin: "http://localhost:8081/",
mediaType: "audio",
}),
).toBe(false);
expect(
fake.check(appWindow, "notifications", "", {
isMainFrame: false,
requestingUrl: "data:text/html,hi",
embeddingOrigin: "http://localhost:8081/",
}),
).toBe(false);
expect(
fake.request(appWindow, "clipboard-read", {
isMainFrame: false,
requestingUrl: "http://localhost:8081/",
securityOrigin: "http://localhost:8081/",
}),
).toBe(false);
// Untrusted origins, null webContents, and webview webContents are denied
expect(
fake.check(appWindow, "media", "https://evil.example/", {
isMainFrame: true,
requestingUrl: "https://evil.example/",
mediaType: "audio",
}),
).toBe(false);
expect(
fake.check(null, "notifications", "http://localhost:8081/", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
}),
).toBe(false);
expect(
fake.check(guest, "media", "http://localhost:8081/", {
isMainFrame: true,
requestingUrl: "http://localhost:8081/",
mediaType: "audio",
}),
).toBe(false);
// Device permissions are denied
expect(fake.checkDevice({ deviceType: "usb", origin: "http://localhost:8081/" })).toBe(false);
expect(fake.checkDevice({ deviceType: "hid", origin: "http://localhost:8081/" })).toBe(false);
expect(fake.checkDevice({ deviceType: "serial", origin: "http://localhost:8081/" })).toBe(
false,
);
});
it("is idempotent when installed twice on the app session", () => {
const fake = createFakeSession();
installAppSessionPermissions(fake.session, { trustedOrigin: "paseo://app" });
installAppSessionPermissions(fake.session, { trustedOrigin: "paseo://app" });
expect(fake.session.setPermissionCheckHandler).toHaveBeenCalledTimes(1);
expect(fake.session.setPermissionRequestHandler).toHaveBeenCalledTimes(1);
expect(fake.session.setDevicePermissionHandler).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,171 @@
import type { Session } from "electron";
/**
* Subset of Electron's `Session` surface needed to enforce permission handlers.
*/
export type PermissionSessionLike = Pick<
Session,
"setPermissionCheckHandler" | "setPermissionRequestHandler" | "setDevicePermissionHandler"
> &
Partial<Pick<Session, "setUSBProtectedClassesHandler" | "setBluetoothPairingHandler">>;
type SessionPermissionPolicyKind = "app" | "browser-webview";
const BROWSER_WEBVIEW_ALLOWED_PERMISSIONS = new Set<string>([
"fullscreen",
"clipboard-sanitized-write",
]);
const APP_ALLOWED_PERMISSIONS = new Set<string>([
"notifications",
"clipboard-read",
"clipboard-sanitized-write",
"fullscreen",
]);
const configuredSessionPolicies = new WeakMap<object, SessionPermissionPolicyKind>();
/**
* Extracts `scheme://host[:port]` from a URL or origin string, including custom
* privileged schemes such as `paseo://app/` whose WHATWG `URL.origin` is `"null"`.
*/
function extractOrigin(raw: string | undefined): string | null {
if (!raw) {
return null;
}
try {
const parsed = new URL(raw);
if (parsed.origin && parsed.origin !== "null") {
return parsed.origin;
}
if (parsed.protocol && parsed.host) {
return `${parsed.protocol}//${parsed.host}`;
}
return null;
} catch {
return null;
}
}
function installSharedDeviceDenyHandlers(targetSession: PermissionSessionLike): void {
targetSession.setDevicePermissionHandler(() => false);
targetSession.setUSBProtectedClassesHandler?.((details) => details.protectedClasses);
targetSession.setBluetoothPairingHandler?.((_details, callback) => {
callback({ confirmed: false });
});
}
function isTrustedAppMainFrame(input: {
webContents: { getType: () => string } | null;
isMainFrame: boolean;
originCandidate: string | undefined;
trustedOrigin: string | null;
}): boolean {
if (input.trustedOrigin === null || !input.webContents || !input.isMainFrame) {
return false;
}
if (input.webContents.getType() === "webview") {
return false;
}
return extractOrigin(input.originCandidate) === input.trustedOrigin;
}
function isAudioOnlyMediaRequest(mediaTypes: unknown): boolean {
return (
Array.isArray(mediaTypes) &&
mediaTypes.length > 0 &&
mediaTypes.every((type) => type === "audio")
);
}
/**
* Resolves the expected origin of Paseo's own desktop UI window, returning `null`
* if the dev server URL cannot be parsed so callers fail closed.
*/
export function resolveAppTrustedOrigin(input: {
isPackaged: boolean;
appScheme: string;
devServerUrl: string;
}): string | null {
if (input.isPackaged) {
return extractOrigin(`${input.appScheme}://app/`);
}
return extractOrigin(input.devServerUrl);
}
/**
* Installs a deny-by-default permission policy on an embedded browser webview
* session, allowing only non-sensitive UX permissions (`fullscreen`,
* `clipboard-sanitized-write`). Safe to call repeatedly on the same session.
*/
export function installBrowserWebviewSessionPermissions(
targetSession: PermissionSessionLike,
): void {
if (configuredSessionPolicies.get(targetSession) === "browser-webview") {
return;
}
configuredSessionPolicies.set(targetSession, "browser-webview");
targetSession.setPermissionCheckHandler((_webContents, permission) => {
return BROWSER_WEBVIEW_ALLOWED_PERMISSIONS.has(permission);
});
targetSession.setPermissionRequestHandler((_webContents, permission, callback) => {
callback(BROWSER_WEBVIEW_ALLOWED_PERMISSIONS.has(permission));
});
installSharedDeviceDenyHandlers(targetSession);
}
/**
* Installs a fail-closed permission policy on the desktop app's own session so
* only the trusted top-level Paseo UI frame can use microphone audio,
* notifications, clipboard, and fullscreen while embedded subframes and device
* APIs stay denied. Safe to call repeatedly on the same session.
*/
export function installAppSessionPermissions(
targetSession: PermissionSessionLike,
options: { trustedOrigin: string | null },
): void {
if (configuredSessionPolicies.get(targetSession) === "app") {
return;
}
configuredSessionPolicies.set(targetSession, "app");
targetSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (
!isTrustedAppMainFrame({
webContents,
isMainFrame: details.isMainFrame,
originCandidate: requestingOrigin || details.requestingUrl,
trustedOrigin: options.trustedOrigin,
})
) {
return false;
}
if (permission === "media") {
return details.mediaType === "audio";
}
return APP_ALLOWED_PERMISSIONS.has(permission);
});
targetSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
const mediaDetails = details as { securityOrigin?: string; mediaTypes?: unknown };
if (
!isTrustedAppMainFrame({
webContents,
isMainFrame: details.isMainFrame,
originCandidate: mediaDetails.securityOrigin || details.requestingUrl,
trustedOrigin: options.trustedOrigin,
})
) {
callback(false);
return;
}
if (permission === "media") {
callback(isAudioOnlyMediaRequest(mediaDetails.mediaTypes));
return;
}
callback(APP_ALLOWED_PERMISSIONS.has(permission));
});
installSharedDeviceDenyHandlers(targetSession);
}
+35 -24
View File
@@ -79,25 +79,26 @@ import {
setWorkspaceActivePaseoBrowserId,
unregisterPaseoBrowserHost,
} from "./features/browser-webviews/index.js";
import { isNamedBrowserProfileSlug, parseBrowserPartition } from "./features/browser-partition.js";
import {
clearPaseoBrowserProfile,
deleteBrowserProfilePartitionDirectory,
getBrowserProfilePartition,
deleteBrowserProfilePartitionDirectories,
getLegacyPaseoBrowserProfileSession,
getPaseoBrowserProfileSessions,
isNamedBrowserProfileSlug,
isPaseoBrowserProfilePartition,
listBrowserPartitionDirectories,
listDiskHostBrowserProxyPartitions,
listPaseoBrowserProfileGuests,
pruneOrphanedBrowserProfilePartitions,
readHostBrowserProxyPartitions,
readLegacyPaseoBrowserIds,
} from "./features/browser-profile.js";
import {
installAppSessionPermissions,
installBrowserWebviewSessionPermissions,
resolveAppTrustedOrigin,
} from "./features/session-permissions.js";
import {
applyProxiedWebContentsPolicy,
createElectronBrowserProxyController,
isHostBrowserProxyPartition,
} from "./features/browser-proxy/index.js";
import { parseOpenProjectPathFromArgv } from "./open-project-routing.js";
import {
@@ -172,10 +173,7 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
}
const record = input as Record<string, unknown>;
const partition = record.partition;
if (
typeof partition !== "string" ||
(!isPaseoBrowserProfilePartition(partition) && !isHostBrowserProxyPartition(partition))
) {
if (typeof partition !== "string" || parseBrowserPartition(partition) === null) {
return null;
}
if (typeof record.browserId !== "string" || record.browserId.trim().length === 0) {
@@ -436,16 +434,17 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
if (!removed.ok) {
return removed;
}
const partition = getBrowserProfilePartition(slug);
const profileSession = session.fromPartition(partition);
const openGuests = webContents
.getAllWebContents()
.filter(
(contents) =>
!contents.isDestroyed() &&
(contents.getType() === "webview" || contents.getType() === "window") &&
contents.session === profileSession,
);
const userData = app.getPath("userData");
// The profile's sessions on the local route and on every host route.
const profileSessions = getPaseoBrowserProfileSessions(
session,
await listBrowserPartitionDirectories(userData),
{ slug, hostPartitions: browserProxy.manager.listKnownPartitions() },
);
const openGuests = listPaseoBrowserProfileGuests({
profileSessions,
webContents: webContents.getAllWebContents(),
});
for (const guest of openGuests) {
getPaseoBrowserWebviewRegistry().unregisterWebContents(guest.id);
try {
@@ -460,11 +459,13 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
}
try {
await clearPaseoBrowserProfile({
profileSessions: [profileSession],
profileSessions,
listGuests: () => [],
logReloadError: () => {},
});
profileSession.flushStorageData();
for (const profileSession of profileSessions) {
profileSession.flushStorageData();
}
} catch (error) {
log.warn("[browser-profile] failed to clear session before deleting partition", {
slug,
@@ -472,7 +473,7 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
});
}
try {
await deleteBrowserProfilePartitionDirectory(app.getPath("userData"), slug);
await deleteBrowserProfilePartitionDirectories(userData, slug);
} catch (error) {
log.warn("[browser-profile] failed to delete profile partition directory", {
slug,
@@ -619,10 +620,10 @@ ipcMain.handle("paseo:browser:clear-profile", async (_event, rawInput?: unknown)
(browserId) => `paseo-browser-${browserId}`,
);
const allDirectories = [...new Set([...directories, ...legacyDirectories])];
// Host partitions on disk arrive through `directories`.
const hostPartitions = [
...browserProxy.manager.listKnownPartitions(),
...readHostBrowserProxyPartitions(options?.hostServerIds),
...listDiskHostBrowserProxyPartitions(app.getPath("userData")),
];
const liveSessions = webContents
.getAllWebContents()
@@ -882,6 +883,9 @@ async function createWindow(
event.preventDefault();
return;
}
if (params.partition) {
installBrowserWebviewSessionPermissions(session.fromPartition(params.partition));
}
webPreferences.nodeIntegration = false;
// The sandboxed keyboard preload must run in every frame so focused iframes keep
// the same page-first shortcut boundary. Node integration remains disabled.
@@ -1066,6 +1070,13 @@ async function bootstrap(): Promise<void> {
}
await app.whenReady();
installAppSessionPermissions(session.defaultSession, {
trustedOrigin: resolveAppTrustedOrigin({
isPackaged: app.isPackaged,
appScheme: APP_SCHEME,
devServerUrl: DEV_SERVER_URL,
}),
});
try {
const profiles = await profileCatalog.list();
await pruneOrphanedBrowserProfilePartitions(
+1 -1
View File
@@ -3,7 +3,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { describe, expect, it } from "vitest";
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-profile.js";
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-partition.js";
// The preload runs inside Electron's sandbox and is tsc-compiled (not bundled), so at
// runtime it may only load Electron's sandbox allowlist. Any other module (local or
+1
View File
@@ -150,6 +150,7 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
ensureHostProxy: (input: {
serverId: string;
target: HostTransportSpec;
profileSlug?: string;
forceReconnect?: boolean;
}) =>
ipcRenderer.invoke(
+3
View File
@@ -2177,6 +2177,9 @@ export const ImportAgentRequestMessageSchema = z.object({
providerHandleId: z.string().optional(),
cwd: z.string().optional(),
workspaceId: z.string().optional(),
// Import into a fresh workspace for `cwd` instead of the workspace already open there.
// Daemons that predate this field ignore it and reuse that workspace.
newWorkspace: z.boolean().optional(),
labels: z.record(z.string(), z.string()).optional(),
requestId: z.string(),
});
+58 -20
View File
@@ -1,6 +1,7 @@
import { spawn } from "node:child_process";
import type { ChildProcess } from "node:child_process";
import { fileURLToPath } from "url";
import { concurrently } from "concurrently";
import { concurrently, type Command } from "concurrently";
import dotenv from "dotenv";
dotenv.config({
@@ -16,8 +17,16 @@ const args = process.argv.slice(2);
const watchers = args.includes("--watch-dependencies")
? concurrently(
[
{ command: "npm run watch:protocol", name: "protocol", prefixColor: "yellow" },
{ command: "npm run watch:client", name: "client", prefixColor: "blue" },
{
command: "npm run watch:protocol",
name: "protocol",
prefixColor: "yellow",
},
{
command: "npm run watch:client",
name: "client",
prefixColor: "blue",
},
],
{
cwd: fileURLToPath(new URL("../../../", import.meta.url)),
@@ -32,34 +41,50 @@ const supervisorArgs = [
...args.filter((arg) => arg !== "--watch-dependencies"),
];
const supervisor = spawn(process.execPath, supervisorArgs, {
stdio: "inherit",
env: {
...process.env,
PASEO_LOG_FORMAT: process.env.PASEO_LOG_FORMAT ?? "pretty",
},
});
// tsc --watch rewrites every dist file on its first build. A worker that starts
// during that build imports half-written modules, so wait for it to finish.
function firstBuild(watcher: Command): Promise<void> {
return new Promise((resolve) => {
let tail = "";
const subscription = watcher.stdout.subscribe((chunk) => {
tail = (tail + chunk.toString()).slice(-200);
if (!tail.includes("Watching for file changes")) return;
subscription.unsubscribe();
resolve();
});
});
}
const watchersBuilt = watchers ? Promise.all(watchers.commands.map(firstBuild)) : Promise.resolve();
function exitCodeForSignal(signal: NodeJS.Signals): number {
return signal === "SIGINT" ? 130 : 1;
}
let supervisor: ChildProcess | null = null;
let stopping = false;
let lostWatchers = false;
function supervisorRunning(): boolean {
return supervisor !== null && supervisor.exitCode === null && supervisor.signalCode === null;
}
function forwardSignal(signal: NodeJS.Signals): void {
if (supervisor.exitCode !== null || supervisor.signalCode !== null || supervisor.killed) {
if (!supervisor) {
void finish(exitCodeForSignal(signal));
return;
}
if (!supervisorRunning() || supervisor.killed) return;
stopping = true;
supervisor.kill(signal);
}
const watchersStopped = watchers?.result.catch(() => undefined);
function handleWatchersStopped(): void {
if (stopping || supervisor.exitCode !== null || supervisor.signalCode !== null) return;
if (stopping) return;
lostWatchers = true;
forwardSignal("SIGTERM");
if (supervisorRunning()) forwardSignal("SIGTERM");
else void finish(1);
}
void watchersStopped?.then(handleWatchersStopped);
@@ -76,11 +101,24 @@ async function finish(exitCode: number): Promise<void> {
process.on("SIGINT", () => forwardSignal("SIGINT"));
process.on("SIGTERM", () => forwardSignal("SIGTERM"));
supervisor.on("error", (error) => {
process.stderr.write(`Failed to start daemon supervisor: ${error.message}\n`);
void finish(1);
});
function startSupervisor(): void {
if (stopping) return;
supervisor = spawn(process.execPath, supervisorArgs, {
stdio: "inherit",
env: {
...process.env,
PASEO_LOG_FORMAT: process.env.PASEO_LOG_FORMAT ?? "pretty",
},
});
supervisor.on("exit", (code, signal) => {
void finish(code ?? (signal ? exitCodeForSignal(signal) : 1));
});
supervisor.on("error", (error) => {
process.stderr.write(`Failed to start daemon supervisor: ${error.message}\n`);
void finish(1);
});
supervisor.on("exit", (code, signal) => {
void finish(code ?? (signal ? exitCodeForSignal(signal) : 1));
});
}
void watchersBuilt.then(startSupervisor);
@@ -619,6 +619,39 @@ test("normalizeImportAgentRequest accepts new and legacy import handle shapes",
});
});
test("normalizeImportAgentRequest carries a request for a new workspace", () => {
expect(
normalizeImportAgentRequest({
type: "import_agent_request",
requestId: "new-workspace",
providerId: "codex",
providerHandleId: "thread-1",
cwd: "/tmp/repo",
newWorkspace: true,
}),
).toEqual({
requestId: "new-workspace",
provider: "codex",
providerHandleId: "thread-1",
cwd: "/tmp/repo",
newWorkspace: true,
});
});
test("normalizeImportAgentRequest rejects a request for both an existing and a new workspace", () => {
expect(
normalizeImportAgentRequest({
type: "import_agent_request",
requestId: "conflicting-placement",
providerId: "codex",
providerHandleId: "thread-1",
cwd: "/tmp/repo",
workspaceId: "wks_0000000000000001",
newWorkspace: true,
}),
).toEqual({ error: "Import targets either workspaceId or a new workspace, not both" });
});
function makeStoredProviderSession(input: {
id: string;
cwd: string;
@@ -47,6 +47,7 @@ export interface NormalizedImportAgentRequest {
providerHandleId: string;
cwd?: string;
workspaceId?: string;
newWorkspace?: boolean;
labels?: Record<string, string>;
requestId: string;
}
@@ -106,11 +107,15 @@ export function normalizeImportAgentRequest(
if (!provider || !providerHandleId) {
return { error: "Import requires providerId and providerHandleId" };
}
if (msg.workspaceId && msg.newWorkspace) {
return { error: "Import targets either workspaceId or a new workspace, not both" };
}
return {
provider: provider as AgentProvider,
providerHandleId,
cwd: msg.cwd,
workspaceId: msg.workspaceId,
newWorkspace: msg.newWorkspace,
labels: msg.labels,
requestId: msg.requestId,
};
@@ -192,7 +197,11 @@ export async function importProviderSession(
const key = await resolveProviderSessionImportMutationKey(input);
return serializeProviderSessionImport(input.agentManager, key, async () => {
const placement = await input.workspaceProvisioning.runInImportWorkspace(
{ cwd, requestedWorkspaceId: input.request.workspaceId },
{
cwd,
requestedWorkspaceId: input.request.workspaceId,
newWorkspace: input.request.newWorkspace,
},
(workspace) => importProviderSessionNow(input, cwd, workspace.workspaceId),
);
return { ...placement.value, createdWorkspace: placement.createdWorkspace };
@@ -4583,6 +4583,7 @@ describe("ClaudeAgentSession context window usage", () => {
[
notification("code-mode-opt-in", "Code Mode isn't available.", "medium"),
notification("urgent", "Something needs attention.", "immediate"),
notification("stop-hook-error", "stop hook problem · ctrl+o to see", "immediate"),
createSuccessResult(),
],
]),
@@ -4600,6 +4601,7 @@ describe("ClaudeAgentSession context window usage", () => {
).toEqual([
{ type: "notification", level: "info", message: "Code Mode isn't available." },
{ type: "notification", level: "warning", message: "Something needs attention." },
{ type: "notification", level: "warning", message: "stop hook problem" },
]);
expect(
logs
@@ -4608,6 +4610,7 @@ describe("ClaudeAgentSession context window usage", () => {
).toEqual([
{ level: 30, key: "code-mode-opt-in", text: "Code Mode isn't available." },
{ level: 40, key: "urgent", text: "Something needs attention." },
{ level: 40, key: "stop-hook-error", text: "stop hook problem · ctrl+o to see" },
]);
} finally {
await session.close();
@@ -5525,10 +5525,16 @@ class ClaudeAgentSession implements AgentSession {
const fields = { key: message.key, priority: message.priority, text: message.text };
if (urgent) this.logger.warn(fields, "claude.notification");
else this.logger.info(fields, "claude.notification");
// Claude Code's transcript shortcut only works in its terminal UI.
const transcriptHint = " · ctrl+o to see";
const text =
message.key === "stop-hook-error" && message.text.endsWith(transcriptHint)
? message.text.slice(0, -transcriptHint.length)
: message.text;
events.push({
type: "timeline",
provider: "claude",
item: { type: "notification", level: urgent ? "warning" : "info", message: message.text },
item: { type: "notification", level: urgent ? "warning" : "info", message: text },
});
}
@@ -9225,6 +9225,63 @@ test("Codex runtime safety queries live terminals and retains unsupported app se
}
});
test("lets idle cleanup release a Codex session after the app-server exits", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
createConfig(),
null,
createTestLogger(),
async () => appServer.child,
);
try {
await session.startTurn("hello");
await appServer.waitForTurnStart();
appServer.completeTurn();
await expect.poll(() => session.canStopRuntime()).toBe(true);
appServer.disconnect();
await expect(session.canStopRuntime()).resolves.toBe(true);
appServer.assertNoErrors();
} finally {
await session.close();
}
});
test("retains a disconnected Codex session while it reconnects", async () => {
const initialize = deferred<{ userAgent: string }>();
const first = createFakeCodexAppServer();
const replacement = createFakeCodexAppServer({ initialize: () => initialize.promise });
let child = first.child;
const session = new CodexAppServerAgentSession(
createConfig(),
null,
createTestLogger(),
async () => child,
);
let reconnect: Promise<void> | undefined;
try {
await session.startTurn("hello");
await first.waitForTurnStart();
first.completeTurn();
await expect.poll(() => session.canStopRuntime()).toBe(true);
first.disconnect();
child = replacement.child;
reconnect = session.connect();
await replacement.waitForRequest("initialize");
await expect(session.canStopRuntime()).resolves.toBe(false);
initialize.resolve({ userAgent: "codex/0.150.0" });
await reconnect;
await expect(session.canStopRuntime()).resolves.toBe(true);
first.assertNoErrors();
replacement.assertNoErrors();
} finally {
initialize.resolve({ userAgent: "codex/0.150.0" });
await reconnect?.catch(() => undefined);
await session.close();
}
});
test("publishes a materialized image before dispatching the following turn completion", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
@@ -5695,8 +5695,8 @@ export class CodexAppServerAgentSession implements AgentSession {
// A history session released its app-server once it read the thread, so nothing runs.
if (this.connectionState === "history-ready") return true;
if (
!this.client ||
this.client.hasPendingRequests() ||
this.connectionPromise ||
this.client?.hasPendingRequests() ||
!this.currentThreadId ||
this.activeForegroundTurnId ||
this.currentTurnId ||
@@ -5706,6 +5706,9 @@ export class CodexAppServerAgentSession implements AgentSession {
this.pendingSubAgentNotificationsByThreadId.size
)
return false;
// A disposed transport cannot answer inventory requests. The normal close path
// still owns process cleanup.
if (!this.client || this.client.isDisposed()) return true;
// Older app servers reject this request. A failed or malformed probe must retain
// the process: command completion alone does not mean its terminal has exited.
const loaded = z
@@ -1,3 +1,5 @@
import { spawn } from "node:child_process";
import { errorMonitor, once } from "node:events";
import { describe, expect, test, vi } from "vitest";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
@@ -8,6 +10,52 @@ import {
import { CodexAppServerClient, CodexAppServerExitError } from "./app-server-transport.js";
describe("Codex app-server transport", () => {
test.skipIf(process.platform === "win32")(
"keeps the provider exit diagnostic when initialization hits a closed stdin",
async () => {
const child = spawn(
process.execPath,
[
"-e",
[
'process.on("message", () => process.exit(86));',
'require("node:fs").closeSync(0);',
'process.stdout.write("ready");',
].join("\n"),
],
{ stdio: ["pipe", "pipe", "pipe", "ipc"] },
);
const client = new CodexAppServerClient(child, createTestLogger());
try {
await once(child.stdout, "data");
// errorMonitor observes EPIPE without handling it on the transport's behalf.
child.stdin.once(errorMonitor, () => child.send("exit"));
await expect(client.request("initialize", {}, 2_000)).rejects.toMatchObject({
name: "CodexAppServerExitError",
exitCode: 86,
});
} finally {
await client.dispose();
}
},
);
test("closes an active transport once when stdin fails before the child exits", async () => {
const child = createCodexAppServerChildProcess();
const client = new CodexAppServerClient(child, createTestLogger());
const terminated = vi.fn();
client.setUnexpectedTerminationHandler(terminated);
const failure = new Error("write EPIPE");
const first = expect(client.request("thread/read", {})).rejects.toBe(failure);
const second = expect(client.request("thread/loaded/list", {})).rejects.toBe(failure);
child.stdin.emit("error", failure);
child.stdin.emit("error", failure);
await Promise.all([first, second]);
expect(client.hasPendingRequests()).toBe(false);
expect(terminated).toHaveBeenCalledExactlyOnceWith(failure);
await expect(client.request("thread/read", {})).rejects.toThrow("client is closed");
});
test("classifies startup diagnostics delivered after the child exits", async () => {
const child = createCodexAppServerChildProcess();
const client = new CodexAppServerClient(child, createTestLogger());
@@ -268,6 +268,14 @@ export class CodexAppServerClient {
this.handleUnexpectedTermination(err);
});
const isInitializing = () =>
Array.from(this.pending.values()).some((request) => request.method === "initialize");
child.stdin.on("error", (error) => {
// During startup, close owns the final stderr and exit reason. The startup
// coordinator's deadline also covers a child that closes stdin and stays alive.
if (!isInitializing()) this.terminateAfterStreamFailure(error);
});
const reportExit = (code: number | null, signal: NodeJS.Signals | null) => {
this.handleUnexpectedTermination(
new CodexAppServerExitError({
@@ -280,10 +288,7 @@ export class CodexAppServerClient {
child.on("exit", (code, signal) => {
// Startup retries need complete diagnostics. Node drains the child's
// stdio before close, but exit can precede the final stderr data.
const initializing = Array.from(this.pending.values()).some(
(request) => request.method === "initialize",
);
if (!initializing) reportExit(code, signal);
if (!isInitializing()) reportExit(code, signal);
});
child.on("close", reportExit);
}
@@ -304,6 +309,10 @@ export class CodexAppServerClient {
return this.pending.size > 0 || this.activeProviderRequests > 0;
}
isDisposed(): boolean {
return this.disposed;
}
request(method: string, params?: unknown, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<unknown> {
if (this.disposed) {
return Promise.reject(new Error("Codex app-server client is closed"));
@@ -377,10 +386,14 @@ export class CodexAppServerClient {
}
// A lost notification or server request cannot be replayed. Fail the session,
// including live turns with no pending RPC, rather than dropping a stream unit.
this.stdoutLineReader.close();
this.terminateAfterStreamFailure(failure);
}
private terminateAfterStreamFailure(failure: Error): void {
if (this.disposed) return;
this.handleUnexpectedTermination(failure);
void this.dispose().catch((err) => {
this.logger.warn({ err }, "Failed to terminate oversized Codex stdout producer");
this.logger.warn({ err }, "Failed to terminate Codex app-server after stream failure");
});
}
@@ -552,6 +552,174 @@ describe("PiRpcAgentSession", () => {
});
await expect(session.close()).resolves.toBeUndefined();
});
test("answers a Pi select with selectedActionId when it names an offered label", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-1",
method: "select",
title: "Allow bash?",
options: ["Yes", "No"],
});
await session.respondToPermission("ui-1", { behavior: "allow", selectedActionId: "Yes" });
expect(fakeSession.extensionUiResponses).toEqual([{ id: "ui-1", response: { value: "Yes" } }]);
expect(session.getPendingPermissions()).toEqual([]);
});
test("answers a Pi confirm approved by selectedActionId as confirmed", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-1",
method: "confirm",
title: "Authorize",
message: "Run it?",
});
await session.respondToPermission("ui-1", { behavior: "allow", selectedActionId: "Yes" });
expect(fakeSession.extensionUiResponses).toEqual([
{ id: "ui-1", response: { confirmed: true } },
]);
});
test("rejects an undeliverable Pi allow and keeps the request pending for a corrected retry", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-1",
method: "select",
title: "Allow bash?",
options: ["Yes", "No"],
});
await expect(
session.respondToPermission("ui-1", { behavior: "allow", selectedActionId: "Sure" }),
).rejects.toThrow(/"Yes", "No"/);
await expect(session.respondToPermission("ui-1", { behavior: "allow" })).rejects.toThrow(
/must name the option/,
);
expect(fakeSession.extensionUiResponses).toEqual([]);
expect(session.getPendingPermissions()).toHaveLength(1);
await session.respondToPermission("ui-1", { behavior: "allow", selectedActionId: "Yes" });
expect(fakeSession.extensionUiResponses).toEqual([{ id: "ui-1", response: { value: "Yes" } }]);
});
test("never answers a free-text Pi input with a generic selectedActionId", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-1",
method: "input",
title: "Name?",
});
await expect(
session.respondToPermission("ui-1", { behavior: "allow", selectedActionId: "Yes" }),
).rejects.toThrow(/updatedInput\.answers/);
expect(fakeSession.extensionUiResponses).toEqual([]);
expect(session.getPendingPermissions()).toHaveLength(1);
});
test("prefers updatedInput.answers over selectedActionId and maps a confirm No", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-1",
method: "select",
title: "Pick",
options: ["A", "B"],
});
fakeSession.emit({
type: "extension_ui_request",
id: "ui-2",
method: "confirm",
title: "Authorize",
});
await session.respondToPermission("ui-1", {
behavior: "allow",
selectedActionId: "A",
updatedInput: { answers: { Response: "B" } },
});
await session.respondToPermission("ui-2", { behavior: "allow", selectedActionId: "No" });
expect(fakeSession.extensionUiResponses).toEqual([
{ id: "ui-1", response: { value: "B" } },
{ id: "ui-2", response: { confirmed: false } },
]);
});
test("quotes and caps what a rejected Pi allow echoes back", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
const options = Array.from({ length: 25 }, (_, index) => `Option ${index}`);
options[0] = "Yes', 'No\u001b[31m";
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-1",
method: "select",
title: "Pick",
options,
});
const error = await session
.respondToPermission("ui-1", { behavior: "allow", selectedActionId: "x".repeat(500) })
.catch((caught: unknown) => caught as Error);
expect(error).toBeInstanceOf(Error);
const message = (error as Error).message;
expect(message).toContain("\"Yes', 'No\\u001b[31m\"");
expect(message).not.toContain("\u001b");
expect(message).toContain("and 5 more");
expect(message).not.toContain("x".repeat(100));
expect(message).toContain(`--input '{"answers":{"Response":"<answer>"}}'`);
});
test("caps each echoed option label length in a rejected Pi allow error", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
await session.startTurn("ask");
fakeSession.emit({
type: "extension_ui_request",
id: "ui-long-label",
method: "select",
title: "Pick",
options: ["y".repeat(500), "Short"],
});
const error = await session
.respondToPermission("ui-long-label", { behavior: "allow" })
.catch((caught: unknown) => caught as Error);
expect(error).toBeInstanceOf(Error);
const message = (error as Error).message;
expect(message).toContain(`"${"y".repeat(80)}"...`);
expect(message).not.toContain("y".repeat(100));
expect(message).toContain('"Short"');
});
test("bridges Pi RPC select extension UI requests through question permissions", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
@@ -91,6 +91,12 @@ import {
piExtensionRuntimeBridge,
type PiExtensionEventOutput,
} from "./extensions/index.js";
import {
isRecord,
optionalString,
QUESTION_RESPONSE_HEADER,
resolveAllowedExtensionUiAnswer,
} from "./extension-ui-answer.js";
import { resolveResumeProcessCwd } from "../resume-process-cwd.js";
import { revertPiConversation } from "./rewind.js";
import {
@@ -135,7 +141,6 @@ const PASEO_PI_SUBMITTED_USER_ENTRY_MARKER = "PASEO_SUBMITTED_USER_ENTRY";
const PASEO_PI_COMMAND_RESULT_MARKER = "PASEO_COMMAND_RESULT";
const DEFAULT_PI_EXTENSION_RESULT_TIMEOUT_MS = 30_000;
const DEFAULT_PI_RPC_TIMEOUT_MS = 60_000;
const QUESTION_RESPONSE_HEADER = "Response";
export const PiProviderOptionsSchema = z
.object({
@@ -895,14 +900,6 @@ function isPiAbortedTerminalResponse(messages: PiAgentMessage[]): boolean {
return latestAssistant?.stopReason?.toLowerCase() === "aborted";
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function optionalString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function toNotificationLevel(value: unknown): "info" | "warning" | "error" {
if (value === "info" || value === "warning" || value === "error") {
return value;
@@ -1098,15 +1095,6 @@ function buildExtensionUiQuestionPermission(
};
}
function firstPermissionAnswer(input: AgentMetadata | undefined): string | null {
const answers = isRecord(input?.answers) ? input.answers : null;
if (!answers) {
return null;
}
const first = Object.values(answers).find((value) => typeof value === "string");
return typeof first === "string" ? first : null;
}
function buildExtensionUiResponse(
request: AgentPermissionRequest,
response: AgentPermissionResponse,
@@ -1116,10 +1104,7 @@ function buildExtensionUiResponse(
}
const method = optionalString(request.metadata?.extensionUiMethod);
const answer = firstPermissionAnswer(response.updatedInput);
if (answer === null) {
return { cancelled: true };
}
const answer = resolveAllowedExtensionUiAnswer(request, response);
if (method === "confirm") {
return { confirmed: /^yes$/i.test(answer.trim()) };
@@ -1563,12 +1548,13 @@ export class PiRpcAgentSession implements AgentSession {
if (!request) {
throw new Error(`No pending permission request with id '${requestId}'`);
}
this.pendingExtensionUiRequests.delete(requestId);
const mapped = this.extensionHost.respondToPermission(request, response);
for (const reply of mapped?.responses ?? [
const replies = mapped?.responses ?? [
{ id: requestId, response: buildExtensionUiResponse(request, response) },
]) {
];
this.pendingExtensionUiRequests.delete(requestId);
for (const reply of replies) {
this.runtimeSession.respondToExtensionUiRequest(reply.id, reply.response);
}
this.emit({
@@ -0,0 +1,113 @@
import type {
AgentMetadata,
AgentPermissionRequest,
AgentPermissionResponse,
} from "../../agent-sdk-types.js";
export const QUESTION_RESPONSE_HEADER = "Response";
// Caps on caller- and extension-supplied text echoed into a rejected-allow error.
export const MAX_ECHOED_LABELS = 20;
export const MAX_ECHOED_CHARS = 80;
const SAFE_CLI_HEADER_PATTERN = /^[A-Za-z0-9 _-]+$/;
export class PiPermissionResponseError extends Error {
constructor(message: string) {
super(message);
this.name = "PiPermissionResponseError";
}
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function optionalString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function firstPermissionAnswer(input: AgentMetadata | undefined): string | null {
const answers = isRecord(input?.answers) ? input.answers : null;
if (!answers) {
return null;
}
const first = Object.values(answers).find((value) => typeof value === "string");
return typeof first === "string" ? first : null;
}
export function offeredQuestionLabels(request: AgentPermissionRequest): string[] {
const questions = isRecord(request.input) ? request.input.questions : undefined;
if (!Array.isArray(questions)) {
return [];
}
const labels: string[] = [];
for (const question of questions) {
const options = isRecord(question) ? question.options : undefined;
if (!Array.isArray(options)) continue;
for (const option of options) {
if (isRecord(option) && typeof option.label === "string") {
labels.push(option.label);
}
}
}
return labels;
}
export interface ResolveAllowedExtensionUiAnswerOptions {
answer?: string | null;
labels?: readonly string[];
answerHeader?: string;
}
function formatEchoedText(text: string): string {
const truncated = text.length > MAX_ECHOED_CHARS;
const shown = JSON.stringify(truncated ? text.slice(0, MAX_ECHOED_CHARS) : text);
return truncated ? `${shown}...` : shown;
}
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", "'\\''")}'`;
}
function formatAnswersHint(header: string): string {
if (!SAFE_CLI_HEADER_PATTERN.test(header)) {
return "updatedInput.answers";
}
const payload = JSON.stringify({ answers: { [header]: "<answer>" } });
return `updatedInput.answers (CLI: --input ${shellSingleQuote(payload)})`;
}
// An allow must name the option it picks: `updatedInput.answers`, or `selectedActionId` equal to an
// offered label. Throwing (before the request is consumed) beats answering a human approval with a
// cancellation, which Pi extensions report to the agent as "the user denied this".
export function resolveAllowedExtensionUiAnswer(
request: AgentPermissionRequest,
response: Extract<AgentPermissionResponse, { behavior: "allow" }>,
options?: ResolveAllowedExtensionUiAnswerOptions,
): string {
const answer =
options?.answer !== undefined ? options.answer : firstPermissionAnswer(response.updatedInput);
if (answer !== null) {
return answer;
}
const labels = options?.labels ?? offeredQuestionLabels(request);
const selected = response.selectedActionId;
if (selected !== undefined && labels.includes(selected)) {
return selected;
}
const reason =
selected !== undefined
? `selectedActionId ${formatEchoedText(selected)} is not an offered option`
: "an allow response must name the option it picks";
const header =
options?.answerHeader ??
optionalString(request.metadata?.answerHeader) ??
QUESTION_RESPONSE_HEADER;
const viaAnswers = formatAnswersHint(header);
const shown = labels.slice(0, MAX_ECHOED_LABELS).map(formatEchoedText);
const more = labels.length > shown.length ? ` and ${labels.length - shown.length} more` : "";
const hint =
labels.length > 0
? `set selectedActionId to one of: ${shown.join(", ")}${more}, or pass ${viaAnswers}`
: `pass ${viaAnswers}`;
throw new PiPermissionResponseError(`Pi permission request '${request.id}': ${reason}; ${hint}`);
}

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