Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 48050814d3 fix(app): size mobile and web app icons to platform guidelines
build-app-icons.mjs applied macOS's 0.9 mark scale on top of the 527/700 brand mark box, shrinking the butterfly to 67.8% on iOS and 48.8dp on Android adaptive icons. iOS also shipped only a flat PNG instead of an Icon Composer bundle, Android lacked a monochrome adaptive layer for themed icons, and the Play Store and maskable PWA icons carried pre-cut transparent corners.

Size each mobile and web output for its platform while keeping desktop icons unchanged:
- iOS: add Paseo.icon (Icon Composer bundle for Liquid Glass, dark/tinted/clear, and pre-26 fallbacks) and resize icon.png / apple-touch-icon.png / splash-icon.png to 78% ink.
- Android: size adaptive foreground to 56dp (65dp circumscribed circle inside the 66dp safe zone), add android-icon-monochrome.png, and make the Play Store / F-Droid 512px icon a full-bleed opaque square.
- PWA: split rounded purpose:any icons from full-bleed opaque purpose:maskable icons sized inside the 80% safe circle.
2026-12-03 06:11:57 +01:00
155 changed files with 1119 additions and 4982 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://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>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></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://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>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></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://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>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></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://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>
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
</tr>
</table>
+6 -4
View File
@@ -76,14 +76,16 @@ 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 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`.
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.
To see what macOS draws from the document without packaging the app, export it with Icon Composer's command line tool on a Mac:
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:
```sh
"/Applications/Xcode.app/Contents/Applications/Icon Composer.app/Contents/Executables/ictool" \
packages/desktop/assets/icon.icon --export-image --output-file icon.png \
--platform macOS --rendition Default --width 1024 --height 1024 --scale 1
packages/app/assets/images/Paseo.icon --export-image --output-file icon.png \
--platform iOS --rendition Default --width 1024 --height 1024 --scale 1
```
`--rendition` also takes `Dark`, `TintedLight`, `TintedDark`, `ClearLight`, and `ClearDark`.
+62 -22
View File
@@ -38,13 +38,23 @@ const WINDOWS_LINUX_TILE_ON_CANVAS = 928 / CANVAS;
const TILE = 700;
const TILE_RADIUS = 185;
const MARK_INK = 527;
// 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;
// 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;
// Android shows the middle 72 of an adaptive icon's 108 units.
const ANDROID_ADAPTIVE_VISIBLE = 72 / 108;
// 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;
const NOTIFICATION_MARK_INK = 0.75;
// Apple's continuous corner. Each pair is a distance back along the incoming edge and a distance
@@ -251,13 +261,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 }) {
function tileIconSvg({ artwork, finish, tileOnCanvas, corners, markScale }) {
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(MARK_SCALE, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
const mark = scaledAboutCentre(markScale, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
return canvasSvg(
tileOnCanvas,
[
@@ -361,10 +371,10 @@ async function encodeIcns(icon) {
return Buffer.concat([header, body]);
}
// 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() {
// 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 }) {
const layer = "butterfly.svg";
const document = {
fill: { solid: "srgb:0.00000,0.00000,0.00000,1.00000" },
@@ -375,11 +385,11 @@ function iconComposerFiles() {
translucency: { enabled: false, value: 0.5 },
},
],
"supported-platforms": { squares: ["macOS"] },
"supported-platforms": { squares },
};
return [
["icon.json", `${JSON.stringify(document, null, 2)}\n`],
[`Assets/${layer}`, `${markOnlySvg(MARK_INK_ON_TILE)}\n`],
[`Assets/${layer}`, `${markOnlySvg(inkOnTile)}\n`],
];
}
@@ -390,7 +400,15 @@ function write(file, data) {
}
function desktopIcon(artwork, finish, tileOnCanvas) {
return rasterizer(tileIconSvg({ artwork, finish, tileOnCanvas, corners: "continuous" }));
return rasterizer(
tileIconSvg({
artwork,
finish,
tileOnCanvas,
corners: "continuous",
markScale: DESKTOP_MARK_SCALE,
}),
);
}
async function buildDesktopIcons() {
@@ -417,7 +435,10 @@ async function buildDesktopIcons() {
`${assets}/icon.icns`,
await encodeIcns(desktopIcon(PRODUCTION, "flat", MACOS_TILE_ON_CANVAS)),
);
for (const [file, content] of iconComposerFiles()) {
for (const [file, content] of iconComposerFiles({
inkOnTile: DESKTOP_MARK_INK_ON_TILE,
squares: ["macOS"],
})) {
write(`${assets}/icon.icon/${file}`, content);
}
write(
@@ -427,26 +448,45 @@ async function buildDesktopIcons() {
}
async function buildMobileIcons() {
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 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 square = flat("square");
// Shown as supplied, so the corners are part of the artwork.
// Shown unmasked (splash screen and PWA `purpose: "any"` icons), so continuous corners belong
// in the artwork.
const masked = flat("continuous");
const adaptiveForeground = rasterizer(markOnlySvg(ANDROID_ADAPTIVE_VISIBLE * MARK_INK_ON_TILE));
// 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 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("fastlane/metadata/android/en-US/images/icon.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));
}
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 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).
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
- **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.
+1 -8
View File
@@ -219,14 +219,7 @@ 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.** 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 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 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.
>
+3 -5
View File
@@ -216,11 +216,9 @@ 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.** 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.
- **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.
- **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
+1 -8
View File
@@ -104,14 +104,7 @@ 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 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.
- Gesture behavior comes from the four explicit hooks in `mobile-panels/gestures.ts`.
- 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.
+25 -36
View File
@@ -16,9 +16,8 @@ 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`.
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.
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.
### Ship
@@ -26,7 +25,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. 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.
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.
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
### Sync gates
@@ -121,7 +120,6 @@ 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.
@@ -129,8 +127,9 @@ 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), 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
`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
`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
@@ -175,35 +174,27 @@ For a promotion, every item defaults to defer.
## Reconcile main
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`:
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:
```bash
git fetch origin
git fetch origin --tags
git checkout -b reconcile/vX.Y.Z origin/main
npm run release:reconcile -- --ref origin/release/vX.Y.Z
npm run release:reconcile -- --tag 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 release branch's `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
- Copies the tagged `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 release branch for stable releases.
- Copies the generated F-Droid changelog files from the tag 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 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
Commit, open the PR into `main`, and merge once its checks pass. 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`.
@@ -259,16 +250,16 @@ npm run release:prep:patch
# or:
npm run release:prep:minor
# 2. Push the release branch, then open the reconcile/vX.Y.Z PR into main (do not merge it).
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
git push -u origin HEAD
# Wait for CI + Desktop Packages on this commit and complete the pre-release dependency checks.
# Complete the pre-release dependency checks on this commit.
# 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 merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
# Also open the reconcile/vX.Y.Z PR into main and create the release heartbeat.
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
```
@@ -303,13 +294,12 @@ 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)
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat.
```
## Beta flow
@@ -322,24 +312,23 @@ 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 open the reconcile/vX.Y.Z-beta.N PR into main (do not merge it):
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
git push -u origin HEAD
# Wait for CI + Desktop Packages to pass and complete the pre-release dependency checks.
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead: push the tag first, then run npm publish, merge the reconcile PR, and heartbeat in parallel:
# 3. After go-ahead: push the tag first, then run npm publish, reconcile, and heartbeat in parallel:
npm run release:push
npm run release:publish:beta
# (Or run `npm run release:ship:beta` in one shell while merging reconcile/vX.Y.Z-beta.N.)
# (Or run `npm run release:ship:beta` in one shell while opening 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
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat in parallel.
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat in parallel.
```
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
@@ -1015,9 +1004,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), with the unmerged reconcile PR opened right after the branch push
- [ ] `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)
- [ ] 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 merge of the green `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 `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
@@ -1039,9 +1028,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), with the unmerged reconcile PR opened right after the branch push
- [ ] `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)
- [ ] 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 merge of the green `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 `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: 19 KiB

After

Width:  |  Height:  |  Size: 15 KiB

+2
View File
@@ -111,6 +111,7 @@ 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.",
@@ -126,6 +127,7 @@ 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,3 +230,52 @@ 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

After

Width:  |  Height:  |  Size: 5.9 KiB

@@ -0,0 +1,26 @@
{
"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: 18 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 48 KiB

@@ -1,8 +1,5 @@
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";
@@ -58,45 +55,3 @@ 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,30 +1219,6 @@ 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,35 +606,6 @@ 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,7 +4,6 @@ import {
attachComposerTestImage,
cancelAgent,
composerLocator,
configureComposerQueueSend,
expectAttachmentPill,
expectComposerDraft,
expectComposerVisible,
@@ -103,27 +102,6 @@ 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,22 +294,6 @@ 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,8 +18,7 @@ function finish() {
process.exit(0);
}
// 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:".
process.stdout.write("\\x1b]11;?\\x07");
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
@@ -27,7 +26,6 @@ process.stdin.resume();
process.stdin.on("data", (chunk) => {
captured = Buffer.concat([captured, chunk]);
});
process.stdout.write("\\x1b]11;?\\x07");
setTimeout(finish, 700);
`;
@@ -1,10 +1,5 @@
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import {
clickNewTerminal,
gotoWorkspace,
openNewTabMenuWithShortcut,
} from "../support/helpers/launcher";
import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
@@ -35,44 +30,3 @@ 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, parseHostWorkspaceRouteFromPathname } from "@/utils/host-routes";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
import { gotoAppShell } from "./app";
import { openCommandCenter } from "./command-center";
import { openGlobalNewWorkspaceComposer } from "./new-workspace";
@@ -194,30 +194,6 @@ 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);
@@ -242,11 +218,6 @@ 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,9 +45,6 @@ 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");
@@ -201,13 +198,6 @@ 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> {
@@ -241,17 +231,14 @@ 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.
* A remount detaches the element mid-screenshot; that is not still yet, so the poll starts over.
*/
/** Resolves once `subject` renders the same pixels twice in a row: entering animations are done. */
async function expectStill(subject: Locator) {
let previous: Buffer | null = null;
await expect
.poll(
async () => {
const current = await screenshotAttached(subject);
const still = previous !== null && current !== null && current.equals(previous);
const current = await subject.screenshot();
const still = previous !== null && current.equals(previous);
previous = current;
return still;
},
@@ -260,17 +247,6 @@ 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) {
@@ -384,18 +360,15 @@ 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.0 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

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

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -55,47 +55,6 @@ 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,7 +4,6 @@ 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";
@@ -27,30 +26,27 @@ function isOutsideWorkspacePath(pathValue: string): boolean {
return isAbsolutePath(pathValue) || pathValue === "~" || pathValue.startsWith("~/");
}
/** Resolve folders from filesystem facts, including names that contain dots. */
/** Resolve workspace 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 || !input.workspaceRoot.trim() || !input.client) {
if (
input.lineStart !== undefined ||
isAbsolutePath(input.file) ||
!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(probe.cwd, probe.path);
await input.client.listDirectory(input.workspaceRoot, input.file);
} catch {
return { kind: "file" };
}
return {
kind: outside ? "outsideDirectory" : "directory",
directoryPath: input.file,
};
return { kind: "directory", directoryPath: input.file };
}
export type InlinePathDestination =
@@ -2,6 +2,7 @@ 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";
@@ -11,6 +12,7 @@ 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";
@@ -28,6 +30,7 @@ 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) {
@@ -92,7 +95,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
return (
<Modal transparent animationType="fade" statusBarTranslucent visible onRequestClose={onClose}>
<View style={styles.root}>
<ModalRoot 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>
@@ -126,7 +129,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
</View>
</WindowChromeRootRegion>
</WindowSafeArea>
</View>
</ModalRoot>
</Modal>
);
}
+3 -6
View File
@@ -10,11 +10,8 @@ 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";
// 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;
const ScrollView = isWeb ? RNScrollView : GHScrollView;
interface DiffViewerProps {
diffLines: DiffLine[];
@@ -185,14 +182,14 @@ export function DiffViewer({
if (!fillAvailableHeight) return horizontalScroll;
const content = (
<SectionScrollView
<ScrollView
style={outerScrollStyle}
contentContainerStyle={webVerticalContentStyle}
nestedScrollEnabled
showsVerticalScrollIndicator
>
{horizontalScroll}
</SectionScrollView>
</ScrollView>
);
return content;
@@ -371,12 +371,6 @@ 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,8 +215,6 @@ 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.
@@ -231,12 +229,7 @@ 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,8 +73,6 @@ 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;
@@ -509,7 +507,6 @@ export function ImportSessionSheet({
serverId,
cwd,
workspaceId,
newWorkspace = false,
onClose,
onImportedAgent,
onImported,
@@ -713,14 +710,12 @@ 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,6 +1,5 @@
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";
@@ -64,10 +63,8 @@ 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 (
<GestureHandlerRootView
<View
style={[
styles.container,
{
@@ -98,7 +95,7 @@ export function RootErrorFallback({ error, onReload }: RootErrorFallbackProps) {
{isCompact ? null : reload}
</View>
{isCompact ? <View style={styles.footer}>{reload}</View> : null}
</GestureHandlerRootView>
</View>
);
}
@@ -26,11 +26,8 @@ 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";
// 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;
const ScrollView = isWeb ? RNScrollView : GHScrollView;
// A capped detail scrolls as a whole. Only full-height sheets need section scrollers.
function DetailSectionBody({
@@ -43,13 +40,9 @@ function DetailSectionBody({
const bodyStyle = useMemo(() => [style, contentContainerStyle], [style, contentContainerStyle]);
if (fillAvailableHeight) {
return (
<SectionScrollView
{...scrollProps}
style={style}
contentContainerStyle={contentContainerStyle}
>
<ScrollView {...scrollProps} style={style} contentContainerStyle={contentContainerStyle}>
{children}
</SectionScrollView>
</ScrollView>
);
}
return <View style={bodyStyle}>{children}</View>;
@@ -583,13 +576,13 @@ export function ToolCallDetailsContent({
if (resolvedMaxHeight !== undefined) {
return (
<SectionScrollView
<ScrollView
style={inlineUnistylesStyle({ maxHeight: resolvedMaxHeight })}
contentContainerStyle={ds.fullBleedContainerStyle}
nestedScrollEnabled
>
{sections}
</SectionScrollView>
</ScrollView>
);
}
return <View style={ds.fullBleedContainerStyle}>{sections}</View>;
+3 -1
View File
@@ -32,6 +32,7 @@ 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,
@@ -1409,7 +1410,8 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
visible={props.isOpen}
onRequestClose={props.handleClose}
>
{overlay}
{/* Android Modal opens a separate window outside the app's gesture root. */}
<GestureHandlerRootView style={styles.desktopOverlay}>{overlay}</GestureHandlerRootView>
</Modal>
);
}
@@ -120,27 +120,6 @@ 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,12 +284,9 @@ 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. 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.
// before anyone saw the menu. Remounting on placement starts the native animation from the
// final position; web starts its own animation on placement.
const placed = position !== null;
const surfaceKey = isWeb || placed ? "placed" : "measuring";
useWebContentEntering({ placed, surfaceNativeID });
@@ -368,7 +365,7 @@ export function AnchoredSurface({
) : null}
<View pointerEvents="box-none" style={frame.holder}>
<FloatingSurface
key={surfaceKey}
key={placed ? "placed" : "measuring"}
collapsable={false}
tabIndex={-1}
nativeID={surfaceNativeID}
+2 -17
View File
@@ -3,12 +3,9 @@ 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"]> = [
@@ -25,26 +22,14 @@ type ModalProps = Omit<NativeModalProps, "onRequestClose"> & {
function noClose() {}
export function Modal({ children, ...props }: ModalProps) {
export function Modal(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}>
{isNative ? (
<GestureHandlerRootView style={styles.gestureRoot}>{children}</GestureHandlerRootView>
) : (
children
)}
</NativeModal>
);
return <NativeModal supportedOrientations={orientations} {...props} style={containerStyle} />;
}
// 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
@@ -1,229 +0,0 @@
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);
});
});
@@ -1,64 +0,0 @@
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;
+66 -2
View File
@@ -1,2 +1,66 @@
// Metro loads scroll-view.native.tsx or scroll-view.web.tsx; TypeScript checks callers against native.
export { ScrollView, FlatList } from "./scroll-view.native";
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;
@@ -467,7 +467,6 @@ export function WorkspaceSetupDialog() {
attachments={chatDraft.attachments}
onChangeAttachments={chatDraft.setAttachments}
cwd={sourceDirectory}
getDraftRevision={chatDraft.getRevision}
clearDraft={chatDraft.clear}
autoFocus
commandDraft={composerState?.commandDraft}
@@ -68,7 +68,6 @@ export interface AgentInputDraft {
textReplacement: TextReplacement;
attachments: UserComposerAttachment[];
setAttachments: (updater: AttachmentUpdater) => void;
getRevision: () => number;
clear: (lifecycle: "sent" | "abandoned") => void;
isHydrated: boolean;
attachmentFocusRequestId: number;
@@ -196,11 +195,6 @@ 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 });
@@ -387,7 +381,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -587,7 +587,6 @@ 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,7 +952,6 @@ 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;
@@ -1281,7 +1280,6 @@ function ComposerContentImpl({
onForgeChangeRequestDetected,
onForgeChangeRequestAutoAttach,
cwd,
getDraftRevision,
clearDraft,
autoFocus = false,
autoFocusKey,
@@ -1884,7 +1882,6 @@ function ComposerContentImpl({
await submitMessage(submitText, submitAttachments);
},
clearDraft,
getDraftRevision,
setUserInput: replaceUserInput,
setAttachments: (nextAttachments) => {
setSelectedAttachments(composerWorkspaceAttachment.userAttachmentsOnly(nextAttachments));
@@ -1907,7 +1904,6 @@ 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:steer"],
["queue", "a:interrupt"],
] 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 === "interrupt" ? "interrupt" : "steer",
input.sendBehavior === "steer" ? "steer" : "interrupt",
);
}
+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 interrupts only when it is `interrupt`; otherwise it steers. */
/** The user's send behavior setting. Send now steers or interrupts accordingly. */
sendBehavior: SendBehavior;
providerLabel: (provider: string) => string;
onRestore: (message: RestoredQueuedMessage) => void;
-53
View File
@@ -35,7 +35,6 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
@@ -60,53 +59,6 @@ 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" }];
@@ -128,7 +80,6 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
@@ -172,7 +123,6 @@ describe("submitAgentInput", () => {
submitMessage: async ({ message }) => {
sent.push(message);
},
getDraftRevision: () => 0,
clearDraft: (lifecycle) => {
composer.draft = lifecycle;
},
@@ -243,7 +193,6 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
@@ -283,7 +232,6 @@ describe("submitAgentInput", () => {
submitMessage: async () => {
throw error;
},
getDraftRevision: () => 0,
clearDraft: vi.fn(),
setUserInput,
setAttachments,
@@ -317,7 +265,6 @@ describe("submitAgentInput", () => {
canSubmit: true,
queueMessage,
submitMessage,
getDraftRevision: () => 0,
clearDraft,
setUserInput,
setAttachments,
+2 -6
View File
@@ -17,7 +17,6 @@ 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;
@@ -51,21 +50,18 @@ 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 });
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
input.clearDraft("sent");
}
input.clearDraft("sent");
input.setIsProcessing(false);
return shouldQueue ? "queued" : "submitted";
} catch (error) {
input.onSubmitError?.(error);
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
if (shouldClearOnSubmit) {
input.setUserInput(trimmedMessage);
input.setAttachments(attachments);
}
@@ -1,4 +1,8 @@
import { DEFAULT_BROWSER_PROFILE_SLUG, useBrowserProfileCatalog } from "../profiles";
import {
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserProfilePartition,
useBrowserProfileCatalog,
} from "../profiles";
import { ProfileSelector } from "./profile-selector.electron";
import {
useCallback,
@@ -827,12 +831,16 @@ 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,
profileSlug,
});
const activePartition = proxyState.kind === "ready" ? proxyState.partition : null;
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 browserViewport = browser?.viewport ?? RESPONSIVE_BROWSER_VIEWPORT;
const browserViewportRef = useRef(browserViewport);
browserViewportRef.current = browserViewport;
@@ -1805,13 +1813,15 @@ export function BrowserPane({
initialValue={draftUrl}
/>
</View>
<ProfileSelector
selectedSlug={profileSlug}
catalog={catalog.data ?? []}
triggerStyle={profileTriggerStyle}
onSelect={selectProfile}
refresh={refreshProfiles}
/>
{isLocalProfileMode ? (
<ProfileSelector
selectedSlug={profileSlug}
catalog={catalog.data ?? []}
triggerStyle={profileTriggerStyle}
onSelect={selectProfile}
refresh={refreshProfiles}
/>
) : null}
<View style={styles.chromeRight}>
<DeviceSizeMenu
selectedId={selectedDeviceSizeId}
@@ -1,5 +1,4 @@
import { getIsElectron } from "@/constants/platform";
import { DEFAULT_BROWSER_PROFILE_SLUG } from "@/desktop/browser/profiles";
import {
getDesktopHost,
type DesktopBrowserProxyStatusSnapshot,
@@ -36,18 +35,13 @@ 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 &&
hasSameProfilePartitions(existing.profilePartitions, snapshot.profilePartitions) &&
existing.partition === snapshot.partition &&
existing.socksPort === snapshot.socksPort
) {
return;
@@ -59,12 +53,9 @@ 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 profilePartitions === "object" &&
profilePartitions !== null &&
Object.values(profilePartitions).every((partition) => typeof partition === "string") &&
typeof record.partition === "string" &&
typeof record.status === "string"
);
}
@@ -277,7 +268,6 @@ export function subscribeBrowserProxyStatus(serverId: string, listener: () => vo
export async function ensureHostBrowserProxy(input: {
serverId: string;
target: SupportedTarget;
profileSlug?: string;
forceReconnect?: boolean;
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
installBrowserProxyRendererBridge();
@@ -355,15 +345,14 @@ export async function prepareHostBrowserPartition(
message: "Browser proxy bridge is unavailable in this desktop build.",
};
}
const partition = status.profilePartitions[DEFAULT_BROWSER_PROFILE_SLUG];
if (status.status !== "ready" || !partition) {
if (status.status !== "ready") {
return {
ok: false,
reason: "proxy_error",
message: status.error ?? "Unable to connect browser proxy.",
};
}
return { ok: true, partition, isRemoteHost: true };
return { ok: true, partition: status.partition, isRemoteHost: true };
} catch (error) {
return {
ok: false,
@@ -9,7 +9,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_connecting" },
effectiveRoutingMode: "host",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: null,
ensureError: null,
@@ -27,11 +27,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
partition: "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",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
partition: "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",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: preparedSnapshot,
ensureError: null,
@@ -68,7 +68,7 @@ describe("resolveBrowserProxyPaneState", () => {
}),
).toEqual({
kind: "ready",
partition: preparedSnapshot.profilePartitions.default,
partition: preparedSnapshot.partition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
@@ -79,7 +79,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_connecting" },
effectiveRoutingMode: "host",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: preparedSnapshot,
ensureError: null,
@@ -87,7 +87,7 @@ describe("resolveBrowserProxyPaneState", () => {
}),
).toEqual({
kind: "ready",
partition: preparedSnapshot.profilePartitions.default,
partition: preparedSnapshot.partition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
@@ -106,11 +106,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
partition: "persist:paseo-browser-host-0123456789abcdef",
status: "error",
error: "Host disconnected",
socksPort: 41234,
@@ -133,11 +133,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
partition: "persist:paseo-browser-host-0123456789abcdef",
status: "ready",
error: null,
socksPort: 41234,
@@ -159,11 +159,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
partition: "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,
profileSlug: "default",
localPartition: "persist:paseo-browser",
hostLabel: "dev",
ensureError: null,
onRetry: noop,
@@ -212,7 +212,7 @@ describe("resolveBrowserProxyPaneState", () => {
routing,
proxyStatusSnapshot: {
serverId: "srv-dev",
profilePartitions: { default: "persist:paseo-browser-host-dev" },
partition: "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",
profilePartitions: { default: "persist:paseo-browser-host-dev" },
partition: "persist:paseo-browser-host-dev",
status: "ready",
error: null,
socksPort: 41000,
@@ -259,102 +259,4 @@ 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,7 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { getIsElectron } from "@/constants/platform";
import type { DesktopBrowserProxyStatus } from "@/desktop/host";
import { getBrowserProfilePartition } from "@/desktop/browser/profiles";
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
import { useHosts } from "@/runtime/host-runtime";
import { normalizeHostLabel } from "@/types/host-connection";
@@ -52,35 +51,29 @@ export type BrowserProxyPaneState =
retry: () => void;
};
/** The profile's host partition, once main has bound its session to the host's SOCKS5 port. */
function readPreparedHostPartition(
function hasPreparedHostPartition(
snapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
profileSlug: string,
): string | null {
if (
!snapshot ||
snapshot.socksPort === null ||
!Object.hasOwn(snapshot.profilePartitions, profileSlug)
) {
return null;
}
return snapshot.profilePartitions[profileSlug] ?? null;
): snapshot is NonNullable<ReturnType<typeof getCachedBrowserProxyStatus>> & {
partition: string;
socksPort: number;
} {
return Boolean(snapshot?.partition && snapshot.socksPort !== null);
}
function resolveRemoteUnavailablePaneState(
support: Exclude<Extract<HostBrowserRouting, { kind: "remote" }>["support"], "supported">,
hostLabel: string,
preparedPartition: string | null,
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
): BrowserProxyPaneState {
// 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.
// 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.
const isTransientDisconnect = support === "host_connecting" || support === "host_offline";
if (isTransientDisconnect && preparedPartition) {
if (isTransientDisconnect && hasPreparedHostPartition(proxyStatusSnapshot)) {
return {
kind: "ready",
partition: preparedPartition,
partition: proxyStatusSnapshot.partition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel,
@@ -116,7 +109,7 @@ function resolvePreparedHostPaneStatus(
export function resolveBrowserProxyPaneState(input: {
routing: HostBrowserRouting;
effectiveRoutingMode: BrowserRoutingMode;
profileSlug: string;
localPartition: string;
hostLabel: string;
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>;
ensureError: string | null;
@@ -125,7 +118,7 @@ export function resolveBrowserProxyPaneState(input: {
const {
routing,
effectiveRoutingMode,
profileSlug,
localPartition,
hostLabel,
proxyStatusSnapshot,
ensureError,
@@ -135,7 +128,7 @@ export function resolveBrowserProxyPaneState(input: {
if (routing.kind === "local" || effectiveRoutingMode === "local") {
return {
kind: "ready",
partition: getBrowserProfilePartition(profileSlug),
partition: localPartition,
isRemoteHost: routing.kind === "remote",
effectiveRoutingMode: "local",
hostLabel,
@@ -143,18 +136,17 @@ export function resolveBrowserProxyPaneState(input: {
};
}
const preparedPartition = readPreparedHostPartition(proxyStatusSnapshot, profileSlug);
if (routing.support !== "supported") {
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, preparedPartition);
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, 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) {
// 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)) {
return {
kind: "ready",
partition: preparedPartition,
partition: proxyStatusSnapshot.partition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel,
@@ -187,9 +179,8 @@ export function resolveBrowserProxyPaneState(input: {
export function useHostBrowserProxy(input: {
serverId: string;
routingMode?: BrowserRoutingMode;
profileSlug: string;
}): BrowserProxyPaneState {
const { serverId, routingMode, profileSlug } = input;
const { serverId, routingMode } = input;
const hosts = useHosts();
const host = useMemo(
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
@@ -209,9 +200,6 @@ 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(
@@ -237,13 +225,10 @@ export function useHostBrowserProxy(input: {
installBrowserProxyRendererBridge();
setEnsureError(null);
const forceReconnect = retryCounter > reconnectedRetryRef.current;
reconnectedRetryRef.current = retryCounter;
void ensureHostBrowserProxy({
serverId,
target: supportedTarget,
profileSlug,
forceReconnect,
forceReconnect: retryCounter > 0,
})
.then((snapshot) => {
if (cancelled) return undefined;
@@ -264,12 +249,13 @@ export function useHostBrowserProxy(input: {
};
// targetKey serializes supportedTarget deterministically.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [effectiveRoutingMode, profileSlug, retryCounter, serverId, targetKey]);
}, [effectiveRoutingMode, retryCounter, serverId, targetKey]);
const localPartition = getDesktopHost()?.browser?.profilePartition ?? "persist:paseo-browser";
return resolveBrowserProxyPaneState({
routing,
effectiveRoutingMode,
profileSlug,
localPartition,
hostLabel,
proxyStatusSnapshot,
ensureError,
+1 -3
View File
@@ -177,8 +177,7 @@ export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "recon
export interface DesktopBrowserProxyStatusSnapshot {
serverId: string;
/** Profile slug -> partition, for every profile session bound to this host's proxy. */
profilePartitions: Record<string, string>;
partition: string;
status: DesktopBrowserProxyStatus;
error: string | null;
socksPort: number | null;
@@ -219,7 +218,6 @@ export interface DesktopBrowserBridge {
ensureHostProxy?: (input: {
serverId: string;
target: HostTransportSpec;
profileSlug?: string;
forceReconnect?: boolean;
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
@@ -10,8 +10,6 @@ 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 {
@@ -51,7 +49,6 @@ export function useImportSession({
serverId,
cwd,
workspaceId,
newWorkspace,
}: UseImportSessionOptions = {}): UseImportSessionResult {
const { t } = useTranslation();
const chooseHost = useHostChooser();
@@ -87,7 +84,6 @@ export function useImportSession({
serverId={importServerId}
cwd={cwd}
workspaceId={workspaceId}
newWorkspace={newWorkspace}
onClose={close}
onImported={navigateToImportedAgent}
/>
+10 -14
View File
@@ -8,23 +8,19 @@ 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 { useMobilePanelGestureRefs, useMobilePanelsRuntime } from "./provider";
import { useMobilePanelsRuntime } from "./provider";
import { resolveMobilePanelGestureIntent } from "./gesture-intent";
/**
* 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.
*/
/** A horizontal surface takes the current touch before either panel opens. */
export function usePanelAwareHorizontalScrollGesture() {
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]);
const { leftOpenGestureRef, rightOpenGestureRef } = useMobilePanelsRuntime();
return useMemo(
() =>
Gesture.Native()
.blocksExternalGesture(leftOpenGestureRef, rightOpenGestureRef)
.disallowInterruption(true),
[leftOpenGestureRef, rightOpenGestureRef],
);
}
function isCurrentSelection(startedRevision: number): boolean {
@@ -301,20 +301,6 @@ 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;
+1 -3
View File
@@ -116,6 +116,7 @@ const FindField = forwardRef<
<TextInput
ref={ref}
autoFocus={autoFocus}
selectTextOnFocus
initialValue={initialValue}
onChangeText={onChangeText}
onKeyPress={onKeyPress}
@@ -160,9 +161,6 @@ 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,7 +1192,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -1206,7 +1205,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -1219,7 +1217,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
textReplacement,
attachments,
setAttachments,
getRevision,
clear,
isHydrated,
attachmentFocusRequestId,
@@ -1862,7 +1859,6 @@ function ActiveAgentComposer({
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={agentInputDraft.setAttachments}
cwd={cwd}
getDraftRevision={agentInputDraft.getRevision}
clearDraft={agentInputDraft.clear}
editingSession={editingSession}
autoFocus
@@ -1,4 +1,3 @@
import { Session } from "node:inspector/promises";
import { getPluginClientApi } from "./client-state/api";
import { filePanelTitle } from "@/file-panels/choice/presentation";
import { i18n } from "@/i18n/i18next";
@@ -237,27 +236,3 @@ 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");
}
});
+85 -107
View File
@@ -89,15 +89,91 @@ export class PluginRegistry {
this.publish();
for (const plugin of removed) this.dispose(plugin);
}
const installed = catalog.flatMap((entry) =>
this.installPlugin({
serverId,
entry,
preserved,
client: options.client,
audio: options.audio,
}),
);
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 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))) {
@@ -139,104 +215,6 @@ 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,53 +271,6 @@ 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,7 +200,6 @@ 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[] = [
@@ -1659,7 +1658,7 @@ export function NewWorkspaceScreen({
},
});
const importSession = useImportSession({ serverId: selectedServerId, newWorkspace: true });
const importSession = useImportSession({ serverId: selectedServerId });
const isComposerFullscreen = composerEditing.isFullscreen(isTerminalLaunch);
const composer = isTerminalLaunch ? (
@@ -1686,7 +1685,6 @@ export function NewWorkspaceScreen({
attachments={NO_TERMINAL_ATTACHMENTS}
onChangeAttachments={noopChangeAttachments}
cwd={workingDirectory ?? ""}
getDraftRevision={getTerminalDraftRevision}
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
@@ -1718,7 +1716,6 @@ export function NewWorkspaceScreen({
onForgeChangeRequestDetected={handleForgeChangeRequestDetected}
onForgeChangeRequestAutoAttach={handleForgeChangeRequestAutoAttach}
cwd={workingDirectory ?? ""}
getDraftRevision={chatDraft.getRevision}
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
@@ -662,13 +662,6 @@ 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();
@@ -676,12 +669,8 @@ function useMiddleClickClose(onClose: () => void) {
}
}
node.addEventListener("mouseup", handleMouseUp);
node.addEventListener("auxclick", handleAuxClick);
return () => {
node.removeEventListener("mouseup", handleMouseUp);
node.removeEventListener("auxclick", handleAuxClick);
};
return () => node.removeEventListener("auxclick", handleAuxClick);
}, [onClose]);
return ref;
@@ -45,7 +45,6 @@ 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;
@@ -284,11 +283,6 @@ 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,12 +28,6 @@ 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 = {
+1 -5
View File
@@ -38,11 +38,7 @@ export function editDraftRecordText(
text: string,
now: number,
): DraftRecord {
if (
record?.input.text === text &&
(record.lifecycle === "active" || record.lifecycle === "abandoned")
)
return record;
if (record?.lifecycle === "active" && record.input.text === text) return record;
const attachments = record?.lifecycle === "active" ? record.input.attachments : [];
return {
input: { text, attachments },
@@ -75,49 +75,4 @@ 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,
});
});
});
+7 -38
View File
@@ -4,7 +4,7 @@ export interface ActiveTurnIdentity {
}
export type TurnLiveness =
| { phase: "idle"; cancellationRequestId: number | null; closedTurnId?: string }
| { phase: "idle"; cancellationRequestId: number | null }
| {
phase: "open";
turnId: string | null;
@@ -42,15 +42,8 @@ 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 &&
next.closedTurnId === undefined
) {
updated.delete(agentId);
} else {
updated.set(agentId, next);
}
if (next.phase === "idle" && next.cancellationRequestId === null) updated.delete(agentId);
else updated.set(agentId, next);
return updated;
}
@@ -116,14 +109,7 @@ function closeTurn(current: TurnLiveness, turnId: string | null): TurnLiveness {
turnId !== null &&
current.turnId !== null &&
turnId !== current.turnId;
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;
return targetsDifferentIdentifiedTurn ? current : TURN_LIVENESS_IDLE;
}
function openTurn(current: TurnLiveness, activeTurn: ActiveTurnIdentity): TurnLiveness {
@@ -161,24 +147,7 @@ export function reduceTurnLiveness(
return closeTurn(current, transition.turnId);
}
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);
const activeTurn = transition.type === "snapshot" ? transition.activeTurn : transition.turn;
if (!activeTurn) return TURN_LIVENESS_IDLE;
return openTurn(current, activeTurn);
}
@@ -11,7 +11,6 @@ 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;
+2 -4
View File
@@ -12,7 +12,7 @@ import type {
UpdateScheduleNewAgentConfig,
} from "./types.js";
import { parseDuration } from "../../utils/duration.js";
import { parseModelOption, resolveProviderAndModel } from "../../utils/provider-model.js";
import { 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) {
if (options.provider !== undefined || options.model !== undefined) {
const resolved = resolveProviderAndModel({
provider: options.provider,
model: options.model,
@@ -431,8 +431,6 @@ 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();
+5 -1
View File
@@ -17,7 +17,11 @@ export async function connectTerminalClient(target: DaemonTarget) {
try {
const daemonClient = await connectToDaemon({ target });
const terminals = createTerminalActions(daemonClient, async (workspaceId) => {
const workspace = await daemonClient.findWorkspace(workspaceId);
const result = await daemonClient.fetchWorkspaces({
filter: { idPrefix: workspaceId, includeBackground: true },
page: { limit: 10 },
});
const workspace = result.entries.find((entry) => entry.id === workspaceId);
if (!workspace?.workspaceDirectory) {
throw new Error(`Workspace ${workspaceId} is not active or has no available directory`);
}
+8 -9
View File
@@ -11,18 +11,11 @@ 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 = {
@@ -34,7 +27,13 @@ export function resolveProviderAndModel(
throw error;
}
const modelInput = options.model === undefined ? undefined : parseModelOption(options.model);
if (options.model !== undefined && !modelInput) {
const error: CommandError = {
code: "INVALID_MODEL",
message: "--model cannot be empty",
};
throw error;
}
const slashIndex = providerInput.indexOf("/");
if (slashIndex === -1) {
@@ -90,32 +90,14 @@ async function startSupervisor() {
});
let output = "";
const startedWatchers = new Set<string>();
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) {
function captureOutput(chunk: Buffer) {
output = (output + chunk.toString()).slice(-32000);
for (const watcher of ["protocol", "client"]) {
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();
if (output.includes(`[${watcher}]`)) startedWatchers.add(watcher);
}
}
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);
child.stdout.on("data", captureOutput);
child.stderr.on("data", captureOutput);
try {
await Promise.race([
waitFor(
@@ -135,12 +117,6 @@ 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();
@@ -193,18 +169,9 @@ 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;
@@ -219,9 +186,7 @@ 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.");
@@ -260,16 +225,8 @@ 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,20 +97,6 @@ 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,18 +73,6 @@ 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,8 +261,6 @@ 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>;
}
@@ -4160,7 +4158,6 @@ 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 } : {}),
});
@@ -1,125 +0,0 @@
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 });
}
}
+12 -276
View File
@@ -587,236 +587,6 @@ 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) {
@@ -909,10 +679,8 @@ 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 });
@@ -982,7 +750,7 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
);
assert(
routedProxyStatus?.status === "ready" &&
routedProxyStatus.profilePartitions.default === routedPartition &&
routedProxyStatus.partition === routedPartition &&
typeof routedProxyStatus.socksPort === "number",
`Expected a ready routed host proxy, got ${JSON.stringify(routedProxyStatus)}`,
);
@@ -1025,23 +793,15 @@ async function main() {
const userData = path.join(runtimeDir, "electron-user-data");
const workspaceRoot = path.join(runtimeDir, "workspaces");
const [
localDaemonPort,
remoteDaemonPort,
oldDaemonPort,
routedDaemonPort,
expoPort,
cdpPort,
inspectorPort,
] = await Promise.all([
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
]);
const [localDaemonPort, remoteDaemonPort, oldDaemonPort, routedDaemonPort, expoPort, cdpPort] =
await Promise.all([
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";
@@ -1051,7 +811,6 @@ async function main() {
const children = [];
let legacyAdapter = null;
let browser = null;
let appPage = null;
try {
seedPaseoHome({
@@ -1197,7 +956,6 @@ 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();
@@ -1232,7 +990,6 @@ 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);
@@ -1412,22 +1169,7 @@ async function main() {
});
// -------------------------------------------------------------------------
// 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
// 3. Old daemon without features.networkTunnel fails closed + Browse locally
// -------------------------------------------------------------------------
const oldWsButton = page
.getByRole("button", {
@@ -1491,7 +1233,7 @@ async function main() {
await page.screenshot({ path: path.join(artifactDir, "04-old-daemon-browse-locally.png") });
// -------------------------------------------------------------------------
// 5. Routed host: desktop -> local daemon -> routed daemon -> target
// 4. Routed host: desktop -> local daemon -> routed daemon -> target
// -------------------------------------------------------------------------
const routedHost = await verifyRoutedHostBrowsing({
page,
@@ -1512,7 +1254,6 @@ async function main() {
binaryFrames: secondaryTunnelConn.binaryFrames,
},
togglePartitionIsolation: "passed",
hostProfiles,
oldDaemonFailClosedAndBrowseLocally: "passed",
routedHost,
artifactDir,
@@ -1521,11 +1262,6 @@ 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();
+6 -26
View File
@@ -24,7 +24,6 @@ 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";
@@ -670,10 +669,9 @@ async function clickGuestElement(page, client, browserId, selector) {
}
async function selectDeviceSize(page, label) {
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 });
await page.locator('[aria-label="Device size"]').click();
const item = page.getByText(label, { exact: true });
await item.waitFor({ state: "visible", timeout: timeoutMs });
const rect = await item.boundingBox();
assert(rect, `Device size menu item ${label} had no bounds`);
const clip = {
@@ -687,9 +685,9 @@ async function selectDeviceSize(page, label) {
await item.waitFor({ state: "hidden", timeout: timeoutMs });
const closedPixels = await page.screenshot({ clip });
await trigger.click();
// The reopened menu renders off-screen while measuring. Click its current position after layout.
await item.click({ timeout: timeoutMs });
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 page.keyboard.press("Escape");
return !openPixels.equals(closedPixels);
}
@@ -1595,22 +1593,6 @@ 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 = {
@@ -1666,7 +1648,6 @@ 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 {
@@ -1684,7 +1665,6 @@ async function main() {
writeJson(path.join(artifactDir, "result.json"), {
...report,
focusIsolation,
permissions,
settingsMemory,
pluginLinks,
adaptiveTheme,
@@ -1,74 +0,0 @@
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();
}
});
});
@@ -1,81 +0,0 @@
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,8 +2,11 @@ import { randomUUID } from "node:crypto";
import { readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { isNamedBrowserProfileSlug } from "./browser-partition.js";
import { BROWSER_PROFILE_COLORS, type BrowserProfileColor } from "./browser-profile.js";
import {
BROWSER_PROFILE_COLORS,
isNamedBrowserProfileSlug,
type BrowserProfileColor,
} from "./browser-profile.js";
const colorSchema = z.enum(BROWSER_PROFILE_COLORS);
const nameSchema = z.string().trim().min(1).max(80);
@@ -2,27 +2,24 @@ 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,
deleteBrowserProfilePartitionDirectories,
deleteBrowserProfilePartitionDirectory,
getBrowserProfilePartition,
getLegacyPaseoBrowserProfileSession,
getPaseoBrowserProfileSession,
getPaseoBrowserProfileSessions,
isNamedBrowserProfileSlug,
isPaseoBrowserProfilePartition,
listBrowserPartitionDirectories,
listDiskHostBrowserProxyPartitions,
listPaseoBrowserProfileGuests,
PASEO_BROWSER_PROFILE_PARTITION,
pruneOrphanedBrowserProfilePartitions,
readHostBrowserProxyPartitions,
readLegacyPaseoBrowserIds,
} from "./browser-profile.js";
function getHostBrowserProxyPartition(serverId: string, profileSlug = "default"): string {
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
}
function directoryOf(partition: string): string {
return partition.slice("persist:".length);
}
import { getHostBrowserProxyPartition } from "./browser-proxy/partition.js";
function createFakeSession() {
return {
@@ -32,37 +29,34 @@ function createFakeSession() {
};
}
describe("browser profile partition directories", () => {
it("deletes a named profile's local and host-proxied directories and refuses default", async () => {
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 () => {
const userData = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-"));
try {
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 });
}
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 });
await writeFile(path.join(workDir, "Cookies"), "alice");
await writeFile(path.join(hostWorkDir, "Cookies"), "alice-on-host");
await deleteBrowserProfilePartitionDirectories(userData, "work");
await deleteBrowserProfilePartitionDirectory(userData, "work");
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();
await expect(stat(workDir)).rejects.toThrow();
expect((await stat(defaultDir)).isDirectory()).toBe(true);
await expect(deleteBrowserProfilePartitionDirectory(userData, "default")).rejects.toThrow();
} finally {
await rm(userData, { recursive: true, force: true });
}
@@ -115,9 +109,9 @@ describe("listPaseoBrowserProfileGuests", () => {
});
describe("getPaseoBrowserProfileSessions", () => {
function createSessions() {
it("scopes single-profile clearing to only that profile session", () => {
const byPartition = new Map<string, ReturnType<typeof createFakeSession>>();
return {
const sessions = {
fromPartition: vi.fn((partition: string) => {
let existing = byPartition.get(partition);
if (!existing) {
@@ -127,82 +121,46 @@ describe("getPaseoBrowserProfileSessions", () => {
return existing;
}),
};
}
const openedPartitions = (sessions: ReturnType<typeof createSessions>) =>
sessions.fromPartition.mock.calls.map(([partition]) => partition);
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 directories = [
"paseo-profile-work",
"paseo-profile-customer",
"paseo-browser-11111111-1111-4111-8111-111111111111",
];
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(work).toHaveLength(3);
expect(openedPartitions(sessions)).toEqual([
"persist:paseo-profile-work",
otherHostWork,
hostWork,
]);
});
const workOnly = getPaseoBrowserProfileSessions(sessions, directories, { slug: "work" });
expect(workOnly).toHaveLength(1);
expect(sessions.fromPartition).toHaveBeenCalledWith("persist:paseo-profile-work");
it("clears Default across the local route, legacy tabs, and every host route", () => {
const sessions = createSessions();
const defaults = getPaseoBrowserProfileSessions(sessions, directories, {
sessions.fromPartition.mockClear();
const hostPartition = getHostBrowserProxyPartition("remote-host-1");
const defaultWithHost = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "default",
hostPartitions: [hostWork, getHostBrowserProxyPartition("remote-host-3")],
hostPartitions: [hostPartition],
});
expect(defaults).toHaveLength(4);
expect(openedPartitions(sessions)).toEqual([
expect(defaultWithHost).toHaveLength(3);
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
`persist:${legacy}`,
hostDefault,
getHostBrowserProxyPartition("remote-host-3"),
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
hostPartition,
]);
});
it("clears every profile and route, including live sessions, without a slug", () => {
const sessions = createSessions();
sessions.fromPartition.mockClear();
const liveSession = createFakeSession();
const all = getPaseoBrowserProfileSessions(sessions, directories, {
hostPartitions: [hostWork],
hostPartitions: [hostPartition],
liveSessions: [liveSession],
});
expect(all).toContain(liveSession);
expect(openedPartitions(sessions)).toEqual([
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
"persist:paseo-profile-work",
"persist:paseo-profile-customer",
`persist:${legacy}`,
hostDefault,
otherHostWork,
hostCustomer,
hostWork,
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
hostPartition,
]);
});
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,
@@ -262,30 +220,30 @@ describe("clearPaseoBrowserProfile", () => {
});
describe("partition directory discovery", () => {
it("lists partition directories and prunes orphaned profiles on every route", async () => {
it("lists partition directories and host proxy partitions on disk", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-list-"));
try {
expect(await listBrowserPartitionDirectories(directory)).toEqual([]);
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([]);
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",
]) {
const hostDir = getHostBrowserProxyPartition("remote-a").slice("persist:".length);
for (const name of ["paseo-profile-work", hostDir, "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", hostDefaultDir, hostWorkDir, "unrelated"].sort(),
["paseo-profile-work", hostDir, "unrelated"].sort(),
);
} finally {
await rm(directory, { recursive: true, force: true });
+102 -69
View File
@@ -1,12 +1,13 @@
import { readdir, rm } from "node:fs/promises";
import { readdirSync } from "node:fs";
import path from "node:path";
import {
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserPartition,
isNamedBrowserProfileSlug,
PASEO_BROWSER_PROFILE_PARTITION,
parseBrowserPartition,
} from "./browser-partition.js";
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-";
export const BROWSER_PROFILE_COLORS = [
"violet",
@@ -23,15 +24,42 @@ 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}$/;
/** 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 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)))
);
}
export async function listBrowserPartitionDirectories(userData: string): Promise<string[]> {
@@ -44,20 +72,19 @@ export async function listBrowserPartitionDirectories(userData: string): Promise
}
}
/** Deletes a named profile's partition directories on the local route and every host route. */
export async function deleteBrowserProfilePartitionDirectories(
export async function deleteBrowserProfilePartitionDirectory(
userData: string,
slug: string,
): Promise<void> {
if (!isNamedBrowserProfileSlug(slug)) {
throw new Error(`Cannot delete browser profile partitions for slug: ${slug}`);
throw new Error(`Cannot delete browser profile partition for slug: ${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 })),
const partitionDir = path.join(
userData,
"Partitions",
`${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`,
);
await rm(partitionDir, { recursive: true, force: true });
}
export async function pruneOrphanedBrowserProfilePartitions(
@@ -65,17 +92,15 @@ export async function pruneOrphanedBrowserProfilePartitions(
activeSlugs: ReadonlySet<string>,
): Promise<string[]> {
const directories = await listBrowserPartitionDirectories(userData);
const orphanedSlugs = new Set<string>();
const removed: string[] = [];
for (const name of directories) {
const slug = readDirectoryProfileSlug(name);
if (slug && isNamedBrowserProfileSlug(slug) && !activeSlugs.has(slug)) {
orphanedSlugs.add(slug);
}
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);
}
for (const slug of orphanedSlugs) {
await deleteBrowserProfilePartitionDirectories(userData, slug);
}
return [...orphanedSlugs];
return removed;
}
const PASEO_BROWSER_STORAGE_TYPES = [
@@ -108,10 +133,10 @@ interface BrowserProfileWebContents extends BrowserProfileGuest {
getType(): string;
}
interface ListBrowserProfileGuestsInput<W extends BrowserProfileWebContents> {
interface ListBrowserProfileGuestsInput {
profileSession?: object;
profileSessions?: Iterable<object>;
webContents: W[];
webContents: BrowserProfileWebContents[];
}
interface ClearBrowserProfileInput {
@@ -155,7 +180,6 @@ 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 [];
@@ -166,9 +190,7 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
const trimmed = value.trim();
if (!trimmed) continue;
partitions.add(
parseBrowserPartition(trimmed)?.route === "host"
? trimmed
: getBrowserPartition({ kind: "host", serverId: trimmed }, DEFAULT_BROWSER_PROFILE_SLUG),
isHostBrowserProxyPartition(trimmed) ? trimmed : getHostBrowserProxyPartition(trimmed),
);
if (partitions.size >= MAX_HOST_BROWSER_PROFILES) {
break;
@@ -177,12 +199,22 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
return [...partitions];
}
/**
* 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 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 [];
}
}
export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
sessions: { fromPartition(partition: string): S },
directories: readonly string[],
@@ -192,42 +224,43 @@ export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
slug?: string;
} = {},
): S[] {
const { slug } = options;
if (
slug !== undefined &&
slug !== DEFAULT_BROWSER_PROFILE_SLUG &&
!isNamedBrowserProfileSlug(slug)
) {
return [];
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 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) {
const profileSlug = readDirectoryProfileSlug(name);
if (
profileSlug !== null
? includes(profileSlug)
: isLegacyDirectory(name) && includes(DEFAULT_BROWSER_PROFILE_SLUG)
) {
partitions.add(`persist:${name}`);
if (isNamedProfileDirectory(name) || isLegacyDirectory(name)) {
result.add(sessions.fromPartition(`persist:${name}`));
}
}
for (const partition of options.hostPartitions ?? []) {
const parsed = parseBrowserPartition(partition);
if (parsed?.route === "host" && includes(parsed.profileSlug)) {
partitions.add(partition);
if (isHostBrowserProxyPartition(partition)) {
result.add(sessions.fromPartition(partition));
}
}
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);
}
// 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];
}
@@ -243,9 +276,9 @@ export function getLegacyPaseoBrowserProfileSession(
: null;
}
export function listPaseoBrowserProfileGuests<W extends BrowserProfileWebContents>(
input: ListBrowserProfileGuestsInput<W>,
): W[] {
export function listPaseoBrowserProfileGuests(
input: ListBrowserProfileGuestsInput,
): BrowserProfileGuest[] {
const allowedSessions = new Set<object>(input.profileSessions ?? []);
if (input.profileSession) {
allowedSessions.add(input.profileSession);
@@ -1,6 +1,11 @@
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,
@@ -15,7 +20,10 @@ import {
export {
createBrowserProxyManager,
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
parseBrowserProxyTarget,
PASEO_BROWSER_HOST_PARTITION_PREFIX,
type BrowserProxyManager,
type BrowserProxyStatus,
type BrowserProxyStatusSnapshot,
@@ -117,13 +125,9 @@ 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,
});
});
@@ -0,0 +1,32 @@
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);
});
});
@@ -0,0 +1,18 @@
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 { getBrowserPartition } from "../../browser-partition.js";
import { getHostBrowserProxyPartition } from "./partition.js";
import {
createBrowserProxyManager,
type BrowserProxyManager,
@@ -204,13 +204,10 @@ describe("BrowserProxyManager", () => {
const target = "tcp://10.0.0.5:6767";
const ready = await manager.ensureHostProxy({ serverId: "remote-1", target });
const expectedPartition = getBrowserPartition(
{ kind: "host", serverId: "remote-1" },
"default",
);
const expectedPartition = getHostBrowserProxyPartition("remote-1");
expect(ready.status).toBe("ready");
expect(ready.profilePartitions).toEqual({ default: expectedPartition });
expect(ready.partition).toBe(expectedPartition);
expect(ready.socksPort).toBeGreaterThan(0);
expect(manager.isAllowedHostPartition(expectedPartition)).toBe(true);
expect(manager.isProxiedSession(sessionsByPartition.get(expectedPartition)!)).toBe(true);
@@ -307,12 +304,7 @@ describe("BrowserProxyManager", () => {
expect(result.status).toBe("error");
expect(result.socksPort).toBeNull();
expect(result.error).toMatch(/resolveProxy|proxy/i);
expect(result.profilePartitions).toEqual({});
expect(
manager.isAllowedHostPartition(
getBrowserPartition({ kind: "host", serverId: "remote-broken-proxy" }, "default"),
),
).toBe(false);
expect(manager.isAllowedHostPartition(result.partition)).toBe(false);
});
test("keeps socksPort null on initial tunnel failure, and preserves socksPort across later reconnect errors", async () => {
@@ -343,7 +335,7 @@ describe("BrowserProxyManager", () => {
const initialFail = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
expect(initialFail.status).toBe("error");
expect(initialFail.socksPort).toBeNull();
expect(initialFail.profilePartitions).toEqual({});
expect(manager.isAllowedHostPartition(initialFail.partition)).toBe(false);
failTicket = false;
const ready = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
@@ -370,85 +362,4 @@ 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