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
paseo-bot[bot]andClaude Opus 5.5 8d7676a5af Fix flaky OSC 11 query test that echoed the reply onto the capture line (#11773)
The capture script wrote the OSC 11 query before it put stdin in raw
mode. When the daemon's reply arrived first, the tty was still in
cooked mode with echo on, so it printed the reply as `^[]11;rgb:...`
on the same line as the capture. The test then counted two replies.
Put stdin in raw mode before the query, as a real program does.

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-02 15:48:03 +00:00
Mohamed Boudra 56a88882d8 Stop completed agent turns from flashing back to running (#11764)
* fix(server,app): stop completed turns from flashing back to running

Session forwarded agent_state asynchronously through AgentUpdatesService while sending agent_stream synchronously. When a provider emitted usage_updated right before turn_completed (as ACP providers do on every prompt response carrying usage), agent_stream turn_completed overtook the queued running agent_update on the wire, and a slow workspace_update stretched the gap before the idle agent_update landed. On the client, TurnLiveness forgot the closed turnId on stream_close, so the lagging running snapshot re-opened the turn for a few frames.

Keep workspace broadcasts off the per-agent agent_update queue, serialize an agent's outbound agent_stream events behind any in-flight agent_update for that agent (staying synchronous when none is queued), and remember closed turn IDs in TurnLiveness so lagging snapshots from older daemons or concurrent fetches cannot re-open a finished turn.

* refactor(server): sequence agent_update and agent_stream on one per-agent queue

Replace the separate Session.agentStreamTails queue and pendingAgentUpdate() bridge with AgentUpdatesService.runAfterUpdates() so interleaved agent_update and agent_stream frames share a single per-agent FIFO queue while staying synchronous when nothing is queued.

* fix(app): preserve closedTurnId across idle snapshots and directory catch-up

An empty AgentDirectoryReplica.commitChanges() re-projects unchanged idle agents as activeTurn: null, which previously cleared closedTurnId and let a later lagging running snapshot re-open the finished turn. Keep closedTurnId on idle TurnLiveness until a newer turn opens or destructive_close resets liveness.
2026-12-02 22:29:27 +07:00
paseo-bot[bot]andodoo-mvds 2929e99147 Refresh the Scripts menu after external paseo.json edits (#11768)
* fix(server): refresh workspace scripts when paseo.json changes

Directory workspaces had no observer at all, and Git workspaces only
picked up a new paseo.json when the edit also changed their Git
snapshot. A connected app therefore kept a stale Scripts menu after
paseo.json was edited outside Paseo.

The workspace observer now watches paseo.json for every observed
workspace, Git or not, through the existing single-file observer, and
refreshes the workspace cards for that directory on change. Workspaces
sharing a directory share one watch.

Co-authored-by: odoo-mvds <odoo@applix.be>

* Keep pending file changes visible to existing subscribers

---------

Co-authored-by: odoo-mvds <odoo@applix.be>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 15:12:56 +00:00
Mohamed Boudra f9529add94 Open the reconcile PR during release preparation (#11758)
* Open the reconcile PR during release preparation

reconcile-release gains --ref so it can read the release branch before any
tag exists. The release docs open the unmerged reconcile PR right after the
release branch push, so its CI overlaps with the branch checks, and merge it
at Ship alongside npm publication.

* Check the reconcile PR against the tag before merging at Ship
2026-12-02 22:00:11 +07:00
155 changed files with 4985 additions and 1122 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>
+4 -6
View File
@@ -76,16 +76,14 @@ node assets/brand/build-app-icons.mjs
The icons that ship are flat. Each platform masks and lights its own icons, so lit artwork ends up lit twice. `app-icons/` keeps a lit version of the two desktop icons, a baked approximation of macOS Liquid Glass. Nothing uses them.
The packaged Mac app (`packages/desktop/assets/icon.icon`) and the iOS app (`packages/app/assets/images/Paseo.icon`) take their icons from Icon Composer documents the script writes. Xcode's `actool` (26 or later) compiles them into live Liquid Glass layers plus dark, tinted, clear, and pre-26 fallback assets. The Nix desktop build has no Xcode and uses `icon.icns`, and `packages/app/assets/images/icon.png` remains as the opaque square Expo fallback.
The packaged Mac app takes its icon from `packages/desktop/assets/icon.icon`, an Icon Composer document the script also writes. macOS draws Liquid Glass on it and derives the dark, tinted, and clear variants. electron-builder compiles the document with `actool`, so packaging the Mac app needs Xcode 26 or later. The Nix build has no Xcode and uses `icon.icns`.
Android uses separate `android-icon-foreground.png` and `android-icon-monochrome.png` layers sized to keep the butterfly inside the `66 dp` circular safe zone on a `108 dp` adaptive canvas, plus a full-bleed opaque `512 × 512` store icon at `fastlane/metadata/android/en-US/images/icon.png` for Google Play and F-Droid. The web manifest splits rounded `purpose: "any"` icons from full-bleed opaque `purpose: "maskable"` icons sized inside the central `80%` safe circle.
To see what Apple renders from either Icon Composer document without packaging the app, export it with Icon Composer's command line tool on a Mac:
To see what macOS draws from the document without packaging the app, export it with Icon Composer's command line tool on a Mac:
```sh
"/Applications/Xcode.app/Contents/Applications/Icon Composer.app/Contents/Executables/ictool" \
packages/app/assets/images/Paseo.icon --export-image --output-file icon.png \
--platform iOS --rendition Default --width 1024 --height 1024 --scale 1
packages/desktop/assets/icon.icon --export-image --output-file icon.png \
--platform macOS --rendition Default --width 1024 --height 1024 --scale 1
```
`--rendition` also takes `Dark`, `TintedLight`, `TintedDark`, `ClearLight`, and `ClearDark`.
+22 -62
View File
@@ -38,23 +38,13 @@ const WINDOWS_LINUX_TILE_ON_CANVAS = 928 / CANVAS;
const TILE = 700;
const TILE_RADIUS = 185;
const MARK_INK = 527;
// Desktop keeps extra breathing room on the macOS Dock tile (824/1024 canvas).
const DESKTOP_MARK_SCALE = 0.9;
const DESKTOP_MARK_INK_ON_TILE = (MARK_INK * DESKTOP_MARK_SCALE) / TILE;
// Scaled down, the mark keeps clear of the tile's corners and covers as much of the tile as the
// glyphs in Apple's icons do.
const MARK_SCALE = 0.9;
const MARK_INK_ON_TILE = (MARK_INK * MARK_SCALE) / TILE;
// iOS and full-bleed square tiles size the open single-stroke butterfly close to Apple's ~80%
// safe-area keyline (~11% edge margin, matching neighboring icons on the Home Screen).
const MOBILE_MARK_INK_ON_TILE = 0.78;
const MOBILE_MARK_SCALE = (MOBILE_MARK_INK_ON_TILE * TILE) / MARK_INK;
// Android adaptive icons use a 108dp canvas with a 72dp visible viewport and a 66dp circular safe
// zone. Because the butterfly's diagonal span is ~1.16x its bounding box, 56dp height fills 77.8%
// of the 72dp visible area while keeping its 65dp circumscribed circle inside the 66dp safe zone.
const ANDROID_ADAPTIVE_MARK_INK = 56 / 108;
// W3C maskable PWA icons guarantee an inner safe circle of 80% diameter. At 68% bounding-box ink,
// the butterfly's circumscribed circle is 79% of the canvas.
const PWA_MASKABLE_MARK_INK_ON_TILE = 0.68;
const PWA_MASKABLE_MARK_SCALE = (PWA_MASKABLE_MARK_INK_ON_TILE * TILE) / MARK_INK;
// Android shows the middle 72 of an adaptive icon's 108 units.
const ANDROID_ADAPTIVE_VISIBLE = 72 / 108;
const NOTIFICATION_MARK_INK = 0.75;
// Apple's continuous corner. Each pair is a distance back along the incoming edge and a distance
@@ -261,13 +251,13 @@ function canvasSvg(boxOnCanvas, content) {
// The tile with the mark on it. A masked tile has the continuous corners cut into the artwork. A
// square tile is for platforms that apply their own mask.
function tileIconSvg({ artwork, finish, tileOnCanvas, corners, markScale }) {
function tileIconSvg({ artwork, finish, tileOnCanvas, corners }) {
const look = artwork[finish];
const isLit = finish === "lit";
const filtered = (id, content) => (isLit ? `<g filter="url(#${id})">${content}</g>` : content);
const tile =
corners === "continuous" ? `<g clip-path="url(#tile)">${look.surface}</g>` : look.surface;
const mark = scaledAboutCentre(markScale, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
const mark = scaledAboutCentre(MARK_SCALE, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
return canvasSvg(
tileOnCanvas,
[
@@ -371,10 +361,10 @@ async function encodeIcns(icon) {
return Buffer.concat([header, body]);
}
// An Icon Composer document compiled by Xcode's actool (26 and later). The canvas is the whole
// tile: the OS adds the mask, margin, Liquid Glass lighting, and dark/tinted/clear variants. The
// mark stays opaque so it reads as solid white on the black tile.
function iconComposerFiles({ inkOnTile, squares }) {
// The Icon Composer document macOS 26 and later build the app icon from. The canvas is the whole
// tile: macOS adds the mask, the margin, and the lighting. The mark stays opaque so it reads as
// solid white on the black tile.
function iconComposerFiles() {
const layer = "butterfly.svg";
const document = {
fill: { solid: "srgb:0.00000,0.00000,0.00000,1.00000" },
@@ -385,11 +375,11 @@ function iconComposerFiles({ inkOnTile, squares }) {
translucency: { enabled: false, value: 0.5 },
},
],
"supported-platforms": { squares },
"supported-platforms": { squares: ["macOS"] },
};
return [
["icon.json", `${JSON.stringify(document, null, 2)}\n`],
[`Assets/${layer}`, `${markOnlySvg(inkOnTile)}\n`],
[`Assets/${layer}`, `${markOnlySvg(MARK_INK_ON_TILE)}\n`],
];
}
@@ -400,15 +390,7 @@ function write(file, data) {
}
function desktopIcon(artwork, finish, tileOnCanvas) {
return rasterizer(
tileIconSvg({
artwork,
finish,
tileOnCanvas,
corners: "continuous",
markScale: DESKTOP_MARK_SCALE,
}),
);
return rasterizer(tileIconSvg({ artwork, finish, tileOnCanvas, corners: "continuous" }));
}
async function buildDesktopIcons() {
@@ -435,10 +417,7 @@ async function buildDesktopIcons() {
`${assets}/icon.icns`,
await encodeIcns(desktopIcon(PRODUCTION, "flat", MACOS_TILE_ON_CANVAS)),
);
for (const [file, content] of iconComposerFiles({
inkOnTile: DESKTOP_MARK_INK_ON_TILE,
squares: ["macOS"],
})) {
for (const [file, content] of iconComposerFiles()) {
write(`${assets}/icon.icon/${file}`, content);
}
write(
@@ -448,45 +427,26 @@ async function buildDesktopIcons() {
}
async function buildMobileIcons() {
const flat = (corners, markScale = MOBILE_MARK_SCALE) =>
rasterizer(
tileIconSvg({ artwork: PRODUCTION, finish: "flat", tileOnCanvas: 1, corners, markScale }),
);
// Full-bleed opaque square for platforms and stores that apply their own mask (iOS fallback,
// Apple touch icon, Google Play / F-Droid store listing).
const flat = (corners) =>
rasterizer(tileIconSvg({ artwork: PRODUCTION, finish: "flat", tileOnCanvas: 1, corners }));
// iOS masks these itself, and Expo flattens any transparency in the app icon onto white.
const square = flat("square");
// Shown unmasked (splash screen and PWA `purpose: "any"` icons), so continuous corners belong
// in the artwork.
// Shown as supplied, so the corners are part of the artwork.
const masked = flat("continuous");
// PWA `purpose: "maskable"` icons must be full-bleed opaque squares with artwork inside the
// central 80% safe circle.
const pwaMaskable = flat("square", PWA_MASKABLE_MARK_SCALE);
const adaptiveForeground = rasterizer(markOnlySvg(ANDROID_ADAPTIVE_MARK_INK));
const adaptiveForeground = rasterizer(markOnlySvg(ANDROID_ADAPTIVE_VISIBLE * MARK_INK_ON_TILE));
const notification = rasterizer(markOnlySvg(NOTIFICATION_MARK_INK));
for (const [file, content] of iconComposerFiles({
inkOnTile: MOBILE_MARK_INK_ON_TILE,
squares: "shared",
})) {
write(`packages/app/assets/images/Paseo.icon/${file}`, content);
}
write("packages/app/assets/images/icon.png", await square.opaquePng(1024));
write("packages/app/public/apple-touch-icon.png", await square.opaquePng(180));
write(
"packages/app/assets/images/android-icon-foreground.png",
await adaptiveForeground.png(1024),
);
write(
"packages/app/assets/images/android-icon-monochrome.png",
await adaptiveForeground.png(1024),
);
write("packages/app/assets/images/notification-icon.png", await notification.png(96));
write("packages/app/assets/images/splash-icon.png", await masked.png(1024));
write("packages/app/public/pwa-icon-192.png", await masked.png(192));
write("packages/app/public/pwa-icon-512.png", await masked.png(512));
write("packages/app/public/pwa-icon-maskable-192.png", await pwaMaskable.opaquePng(192));
write("packages/app/public/pwa-icon-maskable-512.png", await pwaMaskable.opaquePng(512));
write("fastlane/metadata/android/en-US/images/icon.png", await square.opaquePng(512));
write("fastlane/metadata/android/en-US/images/icon.png", await masked.png(512));
}
async function buildLitIcons() {
+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.
+36 -25
View File
@@ -16,8 +16,9 @@ Preparation is reversible and runs on the release branch before the user authori
4. Run the [pre-release sanity check](#pre-release-sanity-check) for stable releases, and report any findings to the user.
5. Commit the approved changelog and any requested ACP update, then run `npm run format`, `npm run lint`, and `npm run typecheck`.
6. Run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag.
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` and wait for `CI` and `Desktop Packages` on that branch to pass (never wait on `main` CI).
8. Run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`.
8. Right after the push, open the unmerged [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`, so its CI runs in parallel with the release branch's `CI` and `Desktop Packages`. Do not merge it during Preparation.
9. Wait for `CI` and `Desktop Packages` on the release branch to pass (never wait on `main` CI), and run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
### Ship
@@ -25,7 +26,7 @@ Ship starts after the user says "go ahead". All tag-triggered GitHub Actions wor
1. Run `npm run release:push` first to verify the clean release branch and push `vX.Y.Z` or `vX.Y.Z-beta.N`. Pushing the tag takes a few seconds and starts `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and (for stable tags) `Deploy App` on GitHub Actions, plus `Release Mobile` (stable) or `Release iOS Beta` (beta) on EAS. (`Deploy Website` runs later on the `release: published` event when `Desktop Release` publishes the stable GitHub Release.)
2. Run `npm run release:publish` (stable) or `npm run release:publish:beta` (beta) in parallel with the remote builds. `scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency waves and polls npm visibility between packages to avoid `E409` or `E404` propagation races.
3. Open the [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N` right after `npm run release:push` finishes, so its CI run overlaps with npm publication and the release builds.
3. Check the green [reconcile `main`](#reconcile-main) PR against the pushed tag, then merge it right after `npm run release:push` finishes, in parallel with npm publication and the release builds. Wait for its checks only if the tag check produced changes.
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
### Sync gates
@@ -120,6 +121,7 @@ An explicit user instruction can select another base.
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
each other and a newer merge replaces the pending one.
Open the [reconcile `main`](#reconcile-main) PR now so its CI runs in parallel with these two.
Wait for both runs on the release branch commit to pass before shipping.
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
@@ -127,9 +129,8 @@ An explicit user instruction can select another base.
Because the release branch is already pushed at `HEAD`, no second branch CI run starts, and only
the tag release workflows run.
7. Immediately in parallel after `npm run release:push` finishes: publish npm packages with
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), start
[Reconcile `main`](#reconcile-main) so its PR checks overlap with desktop and EAS builds, and
create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), merge the
already-green [reconcile `main`](#reconcile-main) PR, and create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
`release:push` before `release:publish`, so tag builds never wait behind npm.)
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
@@ -174,27 +175,35 @@ For a promotion, every item defaults to defer.
## Reconcile main
Right after `npm run release:push` pushes the tag (in parallel with npm publication and all desktop, APK, Docker, and EAS builds), open a PR into `main` from a fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`. Reconcile reads only the tagged git commit, so it does not wait for npm or any release build:
Open the reconcile PR during Preparation, right after pushing `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`. Its CI takes about 30 minutes and npm publication takes about 5, so opening it at Ship would leave Ship waiting on CI. An unmerged PR changes nothing on `main`. Reconcile reads only the release branch commit, so it does not wait for the release branch's `CI` or `Desktop Packages`:
```bash
git fetch origin --tags
git fetch origin
git checkout -b reconcile/vX.Y.Z origin/main
npm run release:reconcile -- --tag vX.Y.Z
npm run release:reconcile -- --ref origin/release/vX.Y.Z
```
Use `release/vX.Y.Z-beta.N` and `reconcile/vX.Y.Z-beta.N` for a beta. `--tag vX.Y.Z` reads a published tag instead, for a release that is already tagged.
`scripts/reconcile-release.mjs` updates the working tree without cherry-picking stale lockfile
hunks from the release base:
- Copies the tagged `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
- Copies the release branch's `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
entry replaces the series beta entry on `main`. A stable hotfix on an older line is placed below
any newer entries.
- Copies the generated F-Droid changelog files from the tag for stable releases.
- Copies the generated F-Droid changelog files from the release branch for stable releases.
- Updates every `package.json` version and regenerates `package-lock.json` on top of current `main`
only when the shipped version is newer than `main`'s version.
- Leaves unshipped work on `main` untouched and makes no claims about unshipped work in the
changelog entry.
Commit, open the PR into `main`, and merge once its checks pass. Delete the remote release branch
Commit and open the PR into `main`, but do not merge it during Preparation:
- If the release is cancelled, close the PR. `main` is untouched.
- If the release branch changes during Preparation, re-run `npm run release:reconcile -- --ref origin/release/vX.Y.Z` on the same branch and push to the same PR.
- At Ship, right after `npm run release:push` pushes the tag, run `npm run release:reconcile -- --tag vX.Y.Z` on the reconcile branch. A clean `git status` means the PR already matches the tag, so merge it in parallel with `npm run release:publish` and the tag builds. If it shows changes, push them and wait for the PR checks before merging.
Delete the remote release branch
(`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`) only after the reconcile PR
merges and every [sync gate](#sync-gates) passes. The tag is the record of shipped source, and
Paseo maintains no release track besides `main`.
@@ -250,16 +259,16 @@ npm run release:prep:patch
# or:
npm run release:prep:minor
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
# 2. Push the release branch, then open the reconcile/vX.Y.Z PR into main (do not merge it).
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# Wait for CI + Desktop Packages on this commit and complete the pre-release dependency checks.
# 3. After go-ahead and green release-branch checks: push the tag first to start builds.
npm run release:push
# 4. Run these in parallel immediately after step 3:
npm run release:publish
# Also open the reconcile/vX.Y.Z PR into main and create the release heartbeat.
# Also merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
```
@@ -294,12 +303,13 @@ npm run release:check # Typecheck, build, dry-run pack
npm run version:all:patch
npm run version:all:minor
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
# Open the reconcile/vX.Y.Z PR into main now (do not merge it).
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:push # Create tag vX.Y.Z on HEAD and push (starts release builds)
# In parallel right after release:push:
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat.
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
```
## Beta flow
@@ -312,23 +322,24 @@ npm run release:prep:beta:minor # Start the next minor beta line
# or for follow-up betas:
npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
# 2. Push the release branch and open the reconcile/vX.Y.Z-beta.N PR into main (do not merge it):
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# Wait for CI + Desktop Packages to pass and complete the pre-release dependency checks.
# 3. After go-ahead: push the tag first, then run npm publish, reconcile, and heartbeat in parallel:
# 3. After go-ahead: push the tag first, then run npm publish, merge the reconcile PR, and heartbeat in parallel:
npm run release:push
npm run release:publish:beta
# (Or run `npm run release:ship:beta` in one shell while opening reconcile/vX.Y.Z-beta.N.)
# (Or run `npm run release:ship:beta` in one shell while merging reconcile/vX.Y.Z-beta.N.)
# Later, after soak, promote on release/vX.Y.Z:
npm run release:prep:promote
git push -u origin HEAD
# Open the reconcile/vX.Y.Z PR into main (do not merge it).
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:push
npm run release:publish
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat in parallel.
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat in parallel.
```
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
@@ -1004,9 +1015,9 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI), with the unmerged reconcile PR opened right after the branch push
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the merge of the green `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
- [ ] All seven `@getpaseo/*` npm packages show the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
@@ -1028,9 +1039,9 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes, not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI), with the unmerged reconcile PR opened right after the branch push
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the merge of the green `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
- [ ] All seven `@getpaseo/*` npm packages show `latest` at the new stable, and `beta` at the new stable too unless an active newer beta holds `beta`
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 19 KiB

-2
View File
@@ -111,7 +111,6 @@ export default {
userInterfaceStyle: "automatic",
newArchEnabled: true,
ios: {
icon: "./assets/images/Paseo.icon",
supportsTablet: true,
infoPlist: {
NSMicrophoneUsageDescription: "This app needs access to the microphone for voice commands.",
@@ -127,7 +126,6 @@ export default {
adaptiveIcon: {
backgroundColor: "#000000",
foregroundImage: "./assets/images/android-icon-foreground.png",
monochromeImage: "./assets/images/android-icon-monochrome.png",
},
edgeToEdgeEnabled: true,
predictiveBackGestureEnabled: false,
-49
View File
@@ -230,52 +230,3 @@ describe("Android Bold text opt-out", () => {
expect(exp.plugins).toContain("withAndroidIgnoreBoldText");
}, 30_000);
});
describe("app icons", () => {
it("configures an iOS Icon Composer bundle alongside the opaque fallback icon", async () => {
const { existsSync, readFileSync } = await import("node:fs");
const { resolve } = await import("node:path");
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["ios"] });
expect(exp.ios?.icon).toBe("./assets/images/Paseo.icon");
expect(exp.icon).toBe("./assets/images/icon.png");
const bundleDir = resolve(__dirname, exp.ios?.icon as string);
const iconJson = JSON.parse(readFileSync(resolve(bundleDir, "icon.json"), "utf8"));
const layer = iconJson.groups?.[0]?.layers?.[0]?.["image-name"];
expect(layer).toBe("butterfly.svg");
expect(existsSync(resolve(bundleDir, "Assets", layer))).toBe(true);
expect(existsSync(resolve(__dirname, exp.icon as string))).toBe(true);
}, 30_000);
it("configures Android adaptive foreground and monochrome layers", async () => {
const { existsSync } = await import("node:fs");
const { resolve } = await import("node:path");
const { getAdaptiveIcon, createAdaptiveIconXmlString } = requireFromExpoCli(
"@expo/prebuild-config/build/plugins/icons/withAndroidIcons.js",
);
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
const adaptive = getAdaptiveIcon(exp);
expect(adaptive.backgroundColor).toBe("#000000");
expect(adaptive.foregroundImage).toBe("./assets/images/android-icon-foreground.png");
expect(adaptive.monochromeImage).toBe("./assets/images/android-icon-monochrome.png");
expect(existsSync(resolve(__dirname, adaptive.foregroundImage))).toBe(true);
expect(existsSync(resolve(__dirname, adaptive.monochromeImage))).toBe(true);
const xml = createAdaptiveIconXmlString(adaptive.backgroundImage, adaptive.monochromeImage);
expect(xml).toContain('<foreground android:drawable="@mipmap/ic_launcher_foreground"/>');
expect(xml).toContain('<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>');
}, 30_000);
it("declares separate any and maskable PWA icons that exist on disk", async () => {
const { existsSync, readFileSync } = await import("node:fs");
const { resolve } = await import("node:path");
const manifest = JSON.parse(readFileSync(resolve(__dirname, "public/manifest.json"), "utf8"));
const purposes = manifest.icons.map((icon: { purpose: string }) => icon.purpose);
expect(purposes).toContain("any");
expect(purposes).toContain("maskable");
expect(purposes).not.toContain("any maskable");
for (const icon of manifest.icons) {
expect(existsSync(resolve(__dirname, "public", icon.src.replace(/^\//, "")))).toBe(true);
}
});
});
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.9 KiB

@@ -1,26 +0,0 @@
{
"fill": {
"solid": "srgb:0.00000,0.00000,0.00000,1.00000"
},
"groups": [
{
"layers": [
{
"image-name": "butterfly.svg",
"name": "butterfly"
}
],
"shadow": {
"kind": "neutral",
"opacity": 0.5
},
"translucency": {
"enabled": false,
"value": 0.5
}
}
],
"supported-platforms": {
"squares": "shared"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 43 KiB

@@ -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 });
@@ -18,7 +18,8 @@ function finish() {
process.exit(0);
}
process.stdout.write("\\x1b]11;?\\x07");
// Raw mode before the query: a reply that arrives while the tty still echoes
// would be printed on the capture line as a second "]11;rgb:".
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
@@ -26,6 +27,7 @@ process.stdin.resume();
process.stdin.on("data", (chunk) => {
captured = Buffer.concat([captured, chunk]);
});
process.stdout.write("\\x1b]11;?\\x07");
setTimeout(finish, 700);
`;
@@ -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");
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

+2 -14
View File
@@ -15,25 +15,13 @@
"src": "/pwa-icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
"purpose": "any maskable"
},
{
"src": "/pwa-icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/pwa-icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/pwa-icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
"purpose": "any maskable"
}
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

@@ -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(
@@ -271,6 +271,53 @@ describe("AgentDirectoryReplica", () => {
store.clearSession(serverId);
});
it("ignores a lagging running snapshot for a turn already closed by stream_close", () => {
const serverId = "agent-replica-stale-running-snapshot";
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
replica.commitSnapshot(
[
entry({
...payload("running"),
status: "running",
activeTurn: { turnId: "turn-1", startedAt: "2026-07-17T00:01:00.000Z" },
}),
],
[],
);
replica.applyTurnLiveness("agent", { type: "stream_close", turnId: "turn-1" });
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
// An empty directory catch-up re-projects the unchanged idle agent as activeTurn: null;
// it must preserve the closed turn marker so a lagging running delta still cannot re-open it.
replica.commitChanges([], [], []);
replica.applyDelta({
kind: "upsert",
agent: {
...payload("stale usage update"),
status: "running",
activeTurn: { turnId: "turn-1", startedAt: "2026-07-17T00:01:00.000Z" },
},
project: entry(payload("project")).project,
});
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
replica.applyDelta({
kind: "upsert",
agent: { ...payload("idle"), status: "idle", activeTurn: null },
project: entry(payload("project")).project,
});
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
expect(store.getSession(serverId)?.agents.get("agent")?.turn).toMatchObject({
phase: "idle",
cancellationRequestId: null,
});
store.clearSession(serverId);
});
it("preserves an unchanged running agent's turn identity during catch-up", () => {
const serverId = "agent-replica-catch-up";
const store = useSessionStore.getState();
@@ -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 },
@@ -75,4 +75,49 @@ describe("turn activity", () => {
turnId: null,
});
});
it("does not re-open a turn from a lagging snapshot after stream_close ended it", () => {
const open = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
type: "stream_open",
turn: { turnId: "turn-1", startedAt },
});
const closed = reduceTurnLiveness(open, { type: "stream_close", turnId: "turn-1" });
expect(closed.phase).toBe("idle");
// A stale running snapshot for the just-closed turn must not flash it back to open.
const afterStaleSnapshot = reduceTurnLiveness(closed, {
type: "snapshot",
activeTurn: { turnId: "turn-1", startedAt },
});
expect(afterStaleSnapshot).toBe(closed);
expect(resolveTurnPresentation(afterStaleSnapshot, false).isActive).toBe(false);
// An idle snapshot (including an empty directory catch-up) preserves the closed turn marker
// so a delayed running snapshot for the same turn still cannot re-open it.
const afterIdleSnapshot = reduceTurnLiveness(afterStaleSnapshot, {
type: "snapshot",
activeTurn: null,
});
expect(afterIdleSnapshot).toBe(closed);
expect(
reduceTurnLiveness(afterIdleSnapshot, {
type: "snapshot",
activeTurn: { turnId: "turn-1", startedAt },
}),
).toBe(closed);
// A snapshot for a different turn still opens immediately.
const nextStartedAt = new Date("2026-07-31T10:01:00.000Z");
expect(
reduceTurnLiveness(closed, {
type: "snapshot",
activeTurn: { turnId: "turn-2", startedAt: nextStartedAt },
}),
).toEqual({
phase: "open",
turnId: "turn-2",
startedAt: nextStartedAt,
cancellationRequestId: null,
});
});
});
+38 -7
View File
@@ -4,7 +4,7 @@ export interface ActiveTurnIdentity {
}
export type TurnLiveness =
| { phase: "idle"; cancellationRequestId: number | null }
| { phase: "idle"; cancellationRequestId: number | null; closedTurnId?: string }
| {
phase: "open";
turnId: string | null;
@@ -42,8 +42,15 @@ export function applyTurnLivenessTransition(
const next = transitions.reduce(reduceTurnLiveness, current);
if (next === current) return turns as Map<string, TurnLiveness>;
const updated = new Map(turns);
if (next.phase === "idle" && next.cancellationRequestId === null) updated.delete(agentId);
else updated.set(agentId, next);
if (
next.phase === "idle" &&
next.cancellationRequestId === null &&
next.closedTurnId === undefined
) {
updated.delete(agentId);
} else {
updated.set(agentId, next);
}
return updated;
}
@@ -109,7 +116,14 @@ function closeTurn(current: TurnLiveness, turnId: string | null): TurnLiveness {
turnId !== null &&
current.turnId !== null &&
turnId !== current.turnId;
return targetsDifferentIdentifiedTurn ? current : TURN_LIVENESS_IDLE;
if (targetsDifferentIdentifiedTurn) return current;
// Remember the closed turn id until a newer turn opens or destructive_close resets liveness,
// so a lagging running snapshot (even after an empty directory catch-up) cannot re-open a turn
// the stream already ended.
const closedTurnId = turnId ?? (current.phase === "open" ? current.turnId : current.closedTurnId);
return closedTurnId
? { phase: "idle", cancellationRequestId: null, closedTurnId }
: TURN_LIVENESS_IDLE;
}
function openTurn(current: TurnLiveness, activeTurn: ActiveTurnIdentity): TurnLiveness {
@@ -147,7 +161,24 @@ export function reduceTurnLiveness(
return closeTurn(current, transition.turnId);
}
const activeTurn = transition.type === "snapshot" ? transition.activeTurn : transition.turn;
if (!activeTurn) return TURN_LIVENESS_IDLE;
return openTurn(current, activeTurn);
if (transition.type === "snapshot") {
if (!transition.activeTurn) {
if (current.phase === "idle") {
return current.cancellationRequestId === null
? current
: { ...current, cancellationRequestId: null };
}
return TURN_LIVENESS_IDLE;
}
if (
current.phase === "idle" &&
current.closedTurnId !== undefined &&
transition.activeTurn.turnId === current.closedTurnId
) {
return current;
}
return openTurn(current, transition.activeTurn);
}
return openTurn(current, transition.turn);
}
@@ -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);
});
});

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