mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-02 21:26:57 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c37a407bc8 | ||
|
|
ef8de256ce | ||
|
|
68a1cd9a33 | ||
|
|
d4d8441f06 | ||
|
|
515392cd7b | ||
|
|
230037c03b | ||
|
|
0d9e960d10 | ||
|
|
8d7676a5af | ||
|
|
56a88882d8 | ||
|
|
2929e99147 | ||
|
|
f9529add94 |
@@ -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.
|
||||
>
|
||||
|
||||
+5
-3
@@ -216,9 +216,11 @@ its own.
|
||||
grew once its data arrived left the menu clipped, or hanging over its anchor, until it moved
|
||||
again. `AnchoredSurface` plays the same keyframes through the Web Animations API on web, which
|
||||
leaves no inline style; native keeps the Reanimated `Keyframe`.
|
||||
- **Animate only once placed.** `AnchoredSurface` remounts the surface when its position resolves,
|
||||
so the entering animation runs at the final position rather than ending unseen at the
|
||||
off-screen measuring position.
|
||||
- **Animate only once placed.** The entering animation must run at the final position, not end
|
||||
unseen at the off-screen measuring position. Native remounts the surface when its position
|
||||
resolves, because Reanimated's `entering` runs only on mount. Web keeps the surface mounted and
|
||||
starts its Web Animations entering animation on placement, so a popover's content mounts once
|
||||
per open.
|
||||
- **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is
|
||||
rarely the height of the page before it. A fill page is the one exception.
|
||||
- **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds
|
||||
|
||||
+36
-25
@@ -16,8 +16,9 @@ Preparation is reversible and runs on the release branch before the user authori
|
||||
4. Run the [pre-release sanity check](#pre-release-sanity-check) for stable releases, and report any findings to the user.
|
||||
5. Commit the approved changelog and any requested ACP update, then run `npm run format`, `npm run lint`, and `npm run typecheck`.
|
||||
6. Run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag.
|
||||
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` and wait for `CI` and `Desktop Packages` on that branch to pass (never wait on `main` CI).
|
||||
8. Run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
|
||||
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`.
|
||||
8. Right after the push, open the unmerged [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`, so its CI runs in parallel with the release branch's `CI` and `Desktop Packages`. Do not merge it during Preparation.
|
||||
9. Wait for `CI` and `Desktop Packages` on the release branch to pass (never wait on `main` CI), and run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
|
||||
|
||||
### Ship
|
||||
|
||||
@@ -25,7 +26,7 @@ Ship starts after the user says "go ahead". All tag-triggered GitHub Actions wor
|
||||
|
||||
1. Run `npm run release:push` first to verify the clean release branch and push `vX.Y.Z` or `vX.Y.Z-beta.N`. Pushing the tag takes a few seconds and starts `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and (for stable tags) `Deploy App` on GitHub Actions, plus `Release Mobile` (stable) or `Release iOS Beta` (beta) on EAS. (`Deploy Website` runs later on the `release: published` event when `Desktop Release` publishes the stable GitHub Release.)
|
||||
2. Run `npm run release:publish` (stable) or `npm run release:publish:beta` (beta) in parallel with the remote builds. `scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency waves and polls npm visibility between packages to avoid `E409` or `E404` propagation races.
|
||||
3. Open the [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N` right after `npm run release:push` finishes, so its CI run overlaps with npm publication and the release builds.
|
||||
3. Check the green [reconcile `main`](#reconcile-main) PR against the pushed tag, then merge it right after `npm run release:push` finishes, in parallel with npm publication and the release builds. Wait for its checks only if the tag check produced changes.
|
||||
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
|
||||
|
||||
### Sync gates
|
||||
@@ -120,6 +121,7 @@ An explicit user instruction can select another base.
|
||||
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
|
||||
each other and a newer merge replaces the pending one.
|
||||
Open the [reconcile `main`](#reconcile-main) PR now so its CI runs in parallel with these two.
|
||||
Wait for both runs on the release branch commit to pass before shipping.
|
||||
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
|
||||
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
|
||||
@@ -127,9 +129,8 @@ An explicit user instruction can select another base.
|
||||
Because the release branch is already pushed at `HEAD`, no second branch CI run starts, and only
|
||||
the tag release workflows run.
|
||||
7. Immediately in parallel after `npm run release:push` finishes: publish npm packages with
|
||||
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), start
|
||||
[Reconcile `main`](#reconcile-main) so its PR checks overlap with desktop and EAS builds, and
|
||||
create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
|
||||
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), merge the
|
||||
already-green [reconcile `main`](#reconcile-main) PR, and create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
|
||||
`release:push` before `release:publish`, so tag builds never wait behind npm.)
|
||||
|
||||
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
|
||||
@@ -174,27 +175,35 @@ For a promotion, every item defaults to defer.
|
||||
|
||||
## Reconcile main
|
||||
|
||||
Right after `npm run release:push` pushes the tag (in parallel with npm publication and all desktop, APK, Docker, and EAS builds), open a PR into `main` from a fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`. Reconcile reads only the tagged git commit, so it does not wait for npm or any release build:
|
||||
Open the reconcile PR during Preparation, right after pushing `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`. Its CI takes about 30 minutes and npm publication takes about 5, so opening it at Ship would leave Ship waiting on CI. An unmerged PR changes nothing on `main`. Reconcile reads only the release branch commit, so it does not wait for the release branch's `CI` or `Desktop Packages`:
|
||||
|
||||
```bash
|
||||
git fetch origin --tags
|
||||
git fetch origin
|
||||
git checkout -b reconcile/vX.Y.Z origin/main
|
||||
npm run release:reconcile -- --tag vX.Y.Z
|
||||
npm run release:reconcile -- --ref origin/release/vX.Y.Z
|
||||
```
|
||||
|
||||
Use `release/vX.Y.Z-beta.N` and `reconcile/vX.Y.Z-beta.N` for a beta. `--tag vX.Y.Z` reads a published tag instead, for a release that is already tagged.
|
||||
|
||||
`scripts/reconcile-release.mjs` updates the working tree without cherry-picking stale lockfile
|
||||
hunks from the release base:
|
||||
|
||||
- Copies the tagged `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
|
||||
- Copies the release branch's `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
|
||||
entry replaces the series beta entry on `main`. A stable hotfix on an older line is placed below
|
||||
any newer entries.
|
||||
- Copies the generated F-Droid changelog files from the tag for stable releases.
|
||||
- Copies the generated F-Droid changelog files from the release branch for stable releases.
|
||||
- Updates every `package.json` version and regenerates `package-lock.json` on top of current `main`
|
||||
only when the shipped version is newer than `main`'s version.
|
||||
- Leaves unshipped work on `main` untouched and makes no claims about unshipped work in the
|
||||
changelog entry.
|
||||
|
||||
Commit, open the PR into `main`, and merge once its checks pass. Delete the remote release branch
|
||||
Commit and open the PR into `main`, but do not merge it during Preparation:
|
||||
|
||||
- If the release is cancelled, close the PR. `main` is untouched.
|
||||
- If the release branch changes during Preparation, re-run `npm run release:reconcile -- --ref origin/release/vX.Y.Z` on the same branch and push to the same PR.
|
||||
- At Ship, right after `npm run release:push` pushes the tag, run `npm run release:reconcile -- --tag vX.Y.Z` on the reconcile branch. A clean `git status` means the PR already matches the tag, so merge it in parallel with `npm run release:publish` and the tag builds. If it shows changes, push them and wait for the PR checks before merging.
|
||||
|
||||
Delete the remote release branch
|
||||
(`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`) only after the reconcile PR
|
||||
merges and every [sync gate](#sync-gates) passes. The tag is the record of shipped source, and
|
||||
Paseo maintains no release track besides `main`.
|
||||
@@ -250,16 +259,16 @@ npm run release:prep:patch
|
||||
# or:
|
||||
npm run release:prep:minor
|
||||
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
|
||||
# 2. Push the release branch, then open the reconcile/vX.Y.Z PR into main (do not merge it).
|
||||
git push -u origin HEAD
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
# Wait for CI + Desktop Packages on this commit and complete the pre-release dependency checks.
|
||||
|
||||
# 3. After go-ahead and green release-branch checks: push the tag first to start builds.
|
||||
npm run release:push
|
||||
|
||||
# 4. Run these in parallel immediately after step 3:
|
||||
npm run release:publish
|
||||
# Also open the reconcile/vX.Y.Z PR into main and create the release heartbeat.
|
||||
# Also merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
|
||||
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
|
||||
```
|
||||
|
||||
@@ -294,12 +303,13 @@ npm run release:check # Typecheck, build, dry-run pack
|
||||
npm run version:all:patch
|
||||
npm run version:all:minor
|
||||
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
|
||||
# Open the reconcile/vX.Y.Z PR into main now (do not merge it).
|
||||
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
npm run release:push # Create tag vX.Y.Z on HEAD and push (starts release builds)
|
||||
# In parallel right after release:push:
|
||||
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
|
||||
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat.
|
||||
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
|
||||
```
|
||||
|
||||
## Beta flow
|
||||
@@ -312,23 +322,24 @@ npm run release:prep:beta:minor # Start the next minor beta line
|
||||
# or for follow-up betas:
|
||||
npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
|
||||
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
|
||||
# 2. Push the release branch and open the reconcile/vX.Y.Z-beta.N PR into main (do not merge it):
|
||||
git push -u origin HEAD
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
# Wait for CI + Desktop Packages to pass and complete the pre-release dependency checks.
|
||||
|
||||
# 3. After go-ahead: push the tag first, then run npm publish, reconcile, and heartbeat in parallel:
|
||||
# 3. After go-ahead: push the tag first, then run npm publish, merge the reconcile PR, and heartbeat in parallel:
|
||||
npm run release:push
|
||||
npm run release:publish:beta
|
||||
# (Or run `npm run release:ship:beta` in one shell while opening reconcile/vX.Y.Z-beta.N.)
|
||||
# (Or run `npm run release:ship:beta` in one shell while merging reconcile/vX.Y.Z-beta.N.)
|
||||
|
||||
# Later, after soak, promote on release/vX.Y.Z:
|
||||
npm run release:prep:promote
|
||||
git push -u origin HEAD
|
||||
# Open the reconcile/vX.Y.Z PR into main (do not merge it).
|
||||
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
npm run release:push
|
||||
npm run release:publish
|
||||
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat in parallel.
|
||||
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat in parallel.
|
||||
```
|
||||
|
||||
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
|
||||
@@ -1004,9 +1015,9 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
|
||||
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
|
||||
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
||||
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI), with the unmerged reconcile PR opened right after the branch push
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the merge of the green `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
|
||||
- [ ] All seven `@getpaseo/*` npm packages show the version under the `beta` dist-tag, not `latest`
|
||||
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
|
||||
@@ -1028,9 +1039,9 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes, not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
|
||||
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
|
||||
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
|
||||
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI), with the unmerged reconcile PR opened right after the branch push
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the merge of the green `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
|
||||
- [ ] All seven `@getpaseo/*` npm packages show `latest` at the new stable, and `beta` at the new stable too unless an active newer beta holds `beta`
|
||||
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { gateNextAgentMessage } from "../support/helpers/agent-message-gate";
|
||||
import { expectComposerDraft, submitMessage } from "../support/helpers/composer";
|
||||
import { expectAgentIdle } from "../support/helpers/agent-stream";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import { openChangesPanel, openChangesTreePanel } from "../support/helpers/workspace-tabs";
|
||||
@@ -55,3 +58,45 @@ for (const width of [1400, 390]) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function addChangedFileToChat(page: Page) {
|
||||
await openChangesPanel(page);
|
||||
await page.getByTestId("diff-file-0-toggle").click({ button: "right" });
|
||||
await page.getByTestId("diff-file-0-add-to-chat").click();
|
||||
}
|
||||
|
||||
async function expectFollowUpAttachment(page: Page) {
|
||||
await expect(page.getByTestId("composer-workspace-file-attachment-pill")).toContainText(
|
||||
"follow-up.ts",
|
||||
);
|
||||
}
|
||||
|
||||
test("keeps a file added from Changes when an earlier send fails", async ({ page }) => {
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "attachment-during-send-",
|
||||
title: "Target chat",
|
||||
featureValues: { mockPromptRejections: 1 },
|
||||
});
|
||||
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "follow-up.ts"), "export const followUp = true;\n");
|
||||
await workspace.client.checkoutRefresh(workspace.cwd);
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectAgentIdle(page);
|
||||
await submitMessage(page, "Send this first.");
|
||||
await gate.waitForRequest();
|
||||
|
||||
await addChangedFileToChat(page);
|
||||
await expectFollowUpAttachment(page);
|
||||
|
||||
gate.accept();
|
||||
await expect(
|
||||
page.getByRole("alert").filter({ hasText: "Requested mock prompt rejection" }),
|
||||
).toBeVisible();
|
||||
await expectFollowUpAttachment(page);
|
||||
await expectComposerDraft(page, "");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1219,6 +1219,30 @@ test.describe("Agent message submission", () => {
|
||||
await retryRestoredSubmission(page, prompt);
|
||||
});
|
||||
|
||||
test("keeps a follow-up draft after the earlier send is rejected", async ({ page }, testInfo) => {
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: `pending-rejection-${testInfo.workerIndex}-`,
|
||||
title: "Pending rejection",
|
||||
model: "ten-second-stream",
|
||||
featureValues: { mockPromptRejections: 1 },
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectAgentIdle(page);
|
||||
await submitMessage(page, "Send this first.");
|
||||
await gate.waitForRequest();
|
||||
await fillComposerDraft(page, "Keep this follow-up.");
|
||||
gate.accept();
|
||||
await expect(
|
||||
page.getByRole("alert").filter({ hasText: "Requested mock prompt rejection" }),
|
||||
).toBeVisible();
|
||||
await expectComposerDraft(page, "Keep this follow-up.");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("restores an ambiguous Steer failure without retrying or interrupting", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -18,7 +18,8 @@ function finish() {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
process.stdout.write("\\x1b]11;?\\x07");
|
||||
// Raw mode before the query: a reply that arrives while the tty still echoes
|
||||
// would be printed on the capture line as a second "]11;rgb:".
|
||||
if (process.stdin.isTTY) {
|
||||
process.stdin.setRawMode(true);
|
||||
}
|
||||
@@ -26,6 +27,7 @@ process.stdin.resume();
|
||||
process.stdin.on("data", (chunk) => {
|
||||
captured = Buffer.concat([captured, chunk]);
|
||||
});
|
||||
process.stdout.write("\\x1b]11;?\\x07");
|
||||
setTimeout(finish, 700);
|
||||
`;
|
||||
|
||||
|
||||
@@ -45,6 +45,9 @@ function Details({ workspaceId, theme, layout, close }) {
|
||||
owner.subscribe({ snapshot(value) { setOwnerId(value.subscriptionId); }, update() { setUpdates((n) => n + 1); } });
|
||||
return () => { void owner.release(); };
|
||||
}, [paseo]);
|
||||
React.useEffect(() => {
|
||||
globalThis.__buttonContentMounts = (globalThis.__buttonContentMounts ?? 0) + 1;
|
||||
}, []);
|
||||
const rpc = useRpc(summary);
|
||||
const query = useQuery({ queryKey: ["summary"], queryFn: () => rpc({}) });
|
||||
if (failed) throw new Error("Button content failed");
|
||||
@@ -198,6 +201,13 @@ async function expectDetails(page: Page) {
|
||||
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
|
||||
}
|
||||
|
||||
/** How many times button content has mounted on the page, counted by the content itself. */
|
||||
async function contentMounts(page: Page): Promise<number> {
|
||||
return page.evaluate(
|
||||
() => (globalThis as { __buttonContentMounts?: number }).__buttonContentMounts ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
// The details render before the daemon answers their event subscription, and reopened
|
||||
// details show the cached summary at once, so wait for the subscription id to arrive.
|
||||
async function readContentObservation(page: Page): Promise<string> {
|
||||
@@ -231,14 +241,17 @@ async function expectCompactDetails(page: Page) {
|
||||
await expect(menu.getByText("Presentation: compact", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
/** Resolves once `subject` renders the same pixels twice in a row: entering animations are done. */
|
||||
/**
|
||||
* Resolves once `subject` renders the same pixels twice in a row: entering animations are done.
|
||||
* A remount detaches the element mid-screenshot; that is not still yet, so the poll starts over.
|
||||
*/
|
||||
async function expectStill(subject: Locator) {
|
||||
let previous: Buffer | null = null;
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const current = await subject.screenshot();
|
||||
const still = previous !== null && current.equals(previous);
|
||||
const current = await screenshotAttached(subject);
|
||||
const still = previous !== null && current !== null && current.equals(previous);
|
||||
previous = current;
|
||||
return still;
|
||||
},
|
||||
@@ -247,6 +260,17 @@ async function expectStill(subject: Locator) {
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function screenshotAttached(subject: Locator): Promise<Buffer | null> {
|
||||
try {
|
||||
return await subject.screenshot();
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Element is not attached to the DOM")) {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Attaches the screen once per colour scheme, for review alongside the run. */
|
||||
async function captureSchemes(page: Page, info: TestInfo, name: string, subject: Locator) {
|
||||
for (const colorScheme of ["light", "dark"] as const) {
|
||||
@@ -360,15 +384,18 @@ export async function withButtonShowcase(
|
||||
await run({
|
||||
verifyObservationLifetime: () =>
|
||||
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
|
||||
const mountsBefore = await contentMounts(page);
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const first = await readContentObservation(page);
|
||||
expect(await contentMounts(page)).toBe(mountsBefore + 1);
|
||||
await press(page, "Close deployment details");
|
||||
await expect.poll(() => released.has(first)).toBe(true);
|
||||
await press(page, "Composer status");
|
||||
await expectDetails(page);
|
||||
const second = await readContentObservation(page);
|
||||
expect(second).not.toBe(first);
|
||||
expect(await contentMounts(page)).toBe(mountsBefore + 2);
|
||||
await workspace.client.renameProject(workspace.projectId, "Observer control");
|
||||
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
|
||||
await press(page, "Fail button content");
|
||||
|
||||
@@ -55,6 +55,47 @@ it("keeps unavailable probes and external paths on the existing file-open path",
|
||||
}
|
||||
});
|
||||
|
||||
it("opens an existing absolute folder outside the workspace without a trailing slash", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "outside-folder-link-"));
|
||||
roots.push(root);
|
||||
const workspaceRoot = path.join(root, "workspace");
|
||||
const folder = path.join(root, "reports").split(path.sep).join("/");
|
||||
const file = path.join(root, "notes.txt").split(path.sep).join("/");
|
||||
await mkdir(workspaceRoot);
|
||||
await mkdir(folder);
|
||||
await writeFile(file, "notes");
|
||||
|
||||
const { classifyForResolution } = await import("./resolver");
|
||||
const { resolveInlinePathDestination } = await import("./path-open");
|
||||
const client = {
|
||||
listDirectory: (cwd: string, requestedPath: string) => {
|
||||
const absolute = path.resolve(cwd, requestedPath);
|
||||
if (path.relative(cwd, absolute).split(path.sep)[0] === "..") {
|
||||
throw new Error("Access outside of workspace is not allowed");
|
||||
}
|
||||
return readdir(absolute);
|
||||
},
|
||||
getDirectorySuggestions: async () => ({ entries: [], error: null }),
|
||||
};
|
||||
const destination = async (href: string) => {
|
||||
const resolution = classifyForResolution({ href, text: "Open path" }, { workspaceRoot });
|
||||
if (resolution.kind !== "resolved" || resolution.value.kind !== "file") {
|
||||
throw new Error("Expected an explicit path link");
|
||||
}
|
||||
return resolveInlinePathDestination({ target: resolution.value.target, workspaceRoot, client });
|
||||
};
|
||||
|
||||
await expect(destination(file)).resolves.toMatchObject({
|
||||
kind: "file",
|
||||
location: { path: file },
|
||||
});
|
||||
await expect(destination(folder + "/")).resolves.toEqual({
|
||||
kind: "outsideDirectory",
|
||||
path: folder,
|
||||
});
|
||||
await expect(destination(folder)).resolves.toEqual({ kind: "outsideDirectory", path: folder });
|
||||
});
|
||||
|
||||
it("ignores an older probe after a newer file link opens", async () => {
|
||||
const { createInlinePathOpener } = await import("./path-open");
|
||||
let rejectProbe!: (error: Error) => void;
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type WorkspaceFileLocation,
|
||||
type OpenFileDisposition,
|
||||
} from "@/workspace/file-open";
|
||||
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||
import { isAbsolutePath } from "@/utils/path";
|
||||
import { resolveMissingNestedRelativeFile, type GetDirectorySuggestions } from "./resolver";
|
||||
|
||||
@@ -26,27 +27,30 @@ function isOutsideWorkspacePath(pathValue: string): boolean {
|
||||
return isAbsolutePath(pathValue) || pathValue === "~" || pathValue.startsWith("~/");
|
||||
}
|
||||
|
||||
/** Resolve workspace folders from filesystem facts, including names that contain dots. */
|
||||
/** Resolve folders from filesystem facts, including names that contain dots. */
|
||||
export async function resolveInlinePathOpen(input: PathOpenInput): Promise<PathOpenTarget> {
|
||||
if (!input.file) {
|
||||
return isOutsideWorkspacePath(input.directory)
|
||||
? { kind: "outsideDirectory", directoryPath: input.directory }
|
||||
: { kind: "directory", directoryPath: input.directory };
|
||||
}
|
||||
if (
|
||||
input.lineStart !== undefined ||
|
||||
isAbsolutePath(input.file) ||
|
||||
!input.workspaceRoot.trim() ||
|
||||
!input.client
|
||||
) {
|
||||
if (input.lineStart !== undefined || !input.workspaceRoot.trim() || !input.client) {
|
||||
return { kind: "file" };
|
||||
}
|
||||
const outside = isOutsideWorkspacePath(input.file);
|
||||
const probe = outside
|
||||
? resolveFilePreviewReadTarget({ path: input.file, workspaceRoot: input.workspaceRoot })
|
||||
: { cwd: input.workspaceRoot, path: input.file };
|
||||
if (!probe) return { kind: "file" };
|
||||
try {
|
||||
await input.client.listDirectory(input.workspaceRoot, input.file);
|
||||
await input.client.listDirectory(probe.cwd, probe.path);
|
||||
} catch {
|
||||
return { kind: "file" };
|
||||
}
|
||||
return { kind: "directory", directoryPath: input.file };
|
||||
return {
|
||||
kind: outside ? "outsideDirectory" : "directory",
|
||||
directoryPath: input.file,
|
||||
};
|
||||
}
|
||||
|
||||
export type InlinePathDestination =
|
||||
|
||||
@@ -120,6 +120,27 @@ describe("anchored menu surface on web", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("mounts its content once per open", async () => {
|
||||
const lifecycle: string[] = [];
|
||||
function RecordsMounts() {
|
||||
useEffect(() => {
|
||||
lifecycle.push("mount");
|
||||
return () => {
|
||||
lifecycle.push("unmount");
|
||||
};
|
||||
}, []);
|
||||
return <View testID="body" style={SHORT} />;
|
||||
}
|
||||
mountMenuAbovePill(<RecordsMounts />);
|
||||
|
||||
await wait(SETTLE_MS);
|
||||
|
||||
expect(element("panel").getBoundingClientRect().bottom).toBeLessThanOrEqual(
|
||||
element("pill").getBoundingClientRect().top,
|
||||
);
|
||||
expect(lifecycle).toEqual(["mount"]);
|
||||
});
|
||||
|
||||
it("widens when its content widens after the entering animation", async () => {
|
||||
mountMenuAbovePill(<GrowsAfterOpen afterMs={GROWS_BEFORE_CLEANUP_MS} from={SHORT} to={WIDE} />);
|
||||
|
||||
|
||||
@@ -284,9 +284,12 @@ export function AnchoredSurface({
|
||||
|
||||
// The surface is placed once both measurements land. Until then it sits off-screen so it can
|
||||
// be measured, and it must not animate: an entering animation that ran there would be over
|
||||
// before anyone saw the menu. Remounting on placement starts the native animation from the
|
||||
// final position; web starts its own animation on placement.
|
||||
// before anyone saw the menu. Native remounts the surface on placement so Reanimated's
|
||||
// `entering` starts from the final position. Web keeps it mounted and starts its own animation
|
||||
// on placement: a remount would mount the content twice per open, running its effects and
|
||||
// requests again and dropping its first state.
|
||||
const placed = position !== null;
|
||||
const surfaceKey = isWeb || placed ? "placed" : "measuring";
|
||||
|
||||
useWebContentEntering({ placed, surfaceNativeID });
|
||||
|
||||
@@ -365,7 +368,7 @@ export function AnchoredSurface({
|
||||
) : null}
|
||||
<View pointerEvents="box-none" style={frame.holder}>
|
||||
<FloatingSurface
|
||||
key={placed ? "placed" : "measuring"}
|
||||
key={surfaceKey}
|
||||
collapsable={false}
|
||||
tabIndex={-1}
|
||||
nativeID={surfaceNativeID}
|
||||
|
||||
@@ -467,6 +467,7 @@ export function WorkspaceSetupDialog() {
|
||||
attachments={chatDraft.attachments}
|
||||
onChangeAttachments={chatDraft.setAttachments}
|
||||
cwd={sourceDirectory}
|
||||
getDraftRevision={chatDraft.getRevision}
|
||||
clearDraft={chatDraft.clear}
|
||||
autoFocus
|
||||
commandDraft={composerState?.commandDraft}
|
||||
|
||||
@@ -68,6 +68,7 @@ export interface AgentInputDraft {
|
||||
textReplacement: TextReplacement;
|
||||
attachments: UserComposerAttachment[];
|
||||
setAttachments: (updater: AttachmentUpdater) => void;
|
||||
getRevision: () => number;
|
||||
clear: (lifecycle: "sent" | "abandoned") => void;
|
||||
isHydrated: boolean;
|
||||
attachmentFocusRequestId: number;
|
||||
@@ -195,6 +196,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
const getRevision = useCallback(
|
||||
() => useDraftStore.getState().getDraftRevision(draftKey),
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
const clear = useCallback(
|
||||
(lifecycle: "sent" | "abandoned") => {
|
||||
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
|
||||
@@ -381,6 +387,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
|
||||
@@ -587,6 +587,7 @@ export function WorkspaceDraftComposer({
|
||||
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
|
||||
onChangeAttachments={draftInput.setAttachments}
|
||||
cwd={composerState.workingDir}
|
||||
getDraftRevision={draftInput.getRevision}
|
||||
clearDraft={draftInput.clear}
|
||||
editingSession={editingSession}
|
||||
autoFocus={shouldAutoFocusWorkspaceDraftComposer({ isPaneFocused, isSubmitting })}
|
||||
|
||||
@@ -952,6 +952,7 @@ interface ComposerProps {
|
||||
onForgeChangeRequestDetected?: () => void;
|
||||
onForgeChangeRequestAutoAttach?: (item: ForgeSearchItem) => void;
|
||||
cwd: string;
|
||||
getDraftRevision: () => number;
|
||||
clearDraft: (lifecycle: "sent" | "abandoned") => void;
|
||||
/** When true, auto-focuses the text input on web. */
|
||||
autoFocus?: boolean;
|
||||
@@ -1280,6 +1281,7 @@ function ComposerContentImpl({
|
||||
onForgeChangeRequestDetected,
|
||||
onForgeChangeRequestAutoAttach,
|
||||
cwd,
|
||||
getDraftRevision,
|
||||
clearDraft,
|
||||
autoFocus = false,
|
||||
autoFocusKey,
|
||||
@@ -1882,6 +1884,7 @@ function ComposerContentImpl({
|
||||
await submitMessage(submitText, submitAttachments);
|
||||
},
|
||||
clearDraft,
|
||||
getDraftRevision,
|
||||
setUserInput: replaceUserInput,
|
||||
setAttachments: (nextAttachments) => {
|
||||
setSelectedAttachments(composerWorkspaceAttachment.userAttachmentsOnly(nextAttachments));
|
||||
@@ -1904,6 +1907,7 @@ function ComposerContentImpl({
|
||||
clearDraft,
|
||||
completeSubmit,
|
||||
enqueueMessage,
|
||||
getDraftRevision,
|
||||
hasExternalContent,
|
||||
isAgentRunning,
|
||||
supportsQueue,
|
||||
|
||||
@@ -35,6 +35,7 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -59,6 +60,53 @@ describe("submitAgentInput", () => {
|
||||
expect(clearDraft).toHaveBeenCalledWith("sent");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ delivery: "send", outcome: "failed" },
|
||||
{ delivery: "send", outcome: "submitted" },
|
||||
{ delivery: "queue", outcome: "failed" },
|
||||
{ delivery: "queue", outcome: "queued" },
|
||||
] as const)(
|
||||
"preserves edits made while a $delivery is pending ($outcome)",
|
||||
async ({ delivery, outcome }) => {
|
||||
let revision = 0;
|
||||
let text = "first message";
|
||||
let attachments = ["first.txt"];
|
||||
const setUserInput = (next: string) => {
|
||||
text = next;
|
||||
revision++;
|
||||
};
|
||||
const setAttachments = (next: string[]) => {
|
||||
attachments = next;
|
||||
revision++;
|
||||
};
|
||||
const deferred = createDeferredPromise<void>();
|
||||
const result = submitAgentInput({
|
||||
message: text,
|
||||
attachments,
|
||||
isAgentRunning: delivery === "queue",
|
||||
canSubmit: true,
|
||||
queueMessage: () => deferred.promise,
|
||||
submitMessage: () => deferred.promise,
|
||||
clearDraft: () => {
|
||||
setUserInput("");
|
||||
setAttachments([]);
|
||||
},
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
getDraftRevision: () => revision,
|
||||
setSendError: vi.fn(),
|
||||
setIsProcessing: vi.fn(),
|
||||
});
|
||||
setUserInput("follow-up");
|
||||
setAttachments(["second.txt"]);
|
||||
if (outcome === "failed") deferred.reject(new Error("offline"));
|
||||
else deferred.resolve();
|
||||
expect(await result).toBe(outcome);
|
||||
expect(text).toBe("follow-up");
|
||||
expect(attachments).toEqual(["second.txt"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the composer before an in-flight submit resolves when requested", async () => {
|
||||
const deferred = createDeferredPromise<void>();
|
||||
const attachments = [{ id: "img-1" }];
|
||||
@@ -80,6 +128,7 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -123,6 +172,7 @@ describe("submitAgentInput", () => {
|
||||
submitMessage: async ({ message }) => {
|
||||
sent.push(message);
|
||||
},
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft: (lifecycle) => {
|
||||
composer.draft = lifecycle;
|
||||
},
|
||||
@@ -193,6 +243,7 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -232,6 +283,7 @@ describe("submitAgentInput", () => {
|
||||
submitMessage: async () => {
|
||||
throw error;
|
||||
},
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft: vi.fn(),
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -265,6 +317,7 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface AgentInputSubmitActionInput<TAttachment> {
|
||||
clearDraft: (lifecycle: "sent" | "abandoned") => void;
|
||||
setUserInput: (text: string) => void;
|
||||
setAttachments: (attachments: TAttachment[]) => void;
|
||||
getDraftRevision: () => number;
|
||||
setSendError: (message: string | null) => void;
|
||||
setIsProcessing: (isProcessing: boolean) => void;
|
||||
onSubmitError?: (error: unknown) => void;
|
||||
@@ -50,18 +51,21 @@ export async function submitAgentInput<TAttachment>(
|
||||
input.setUserInput("");
|
||||
input.setAttachments([]);
|
||||
}
|
||||
const submittedRevision = shouldClearOnSubmit ? input.getDraftRevision() : null;
|
||||
input.setSendError(null);
|
||||
input.setIsProcessing(true);
|
||||
|
||||
try {
|
||||
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
|
||||
await deliver({ message: trimmedMessage, attachments });
|
||||
input.clearDraft("sent");
|
||||
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
|
||||
input.clearDraft("sent");
|
||||
}
|
||||
input.setIsProcessing(false);
|
||||
return shouldQueue ? "queued" : "submitted";
|
||||
} catch (error) {
|
||||
input.onSubmitError?.(error);
|
||||
if (shouldClearOnSubmit) {
|
||||
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
|
||||
input.setUserInput(trimmedMessage);
|
||||
input.setAttachments(attachments);
|
||||
}
|
||||
|
||||
@@ -1,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,
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -1192,6 +1192,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
@@ -1205,6 +1206,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
@@ -1217,6 +1219,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
@@ -1859,6 +1862,7 @@ function ActiveAgentComposer({
|
||||
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
|
||||
onChangeAttachments={agentInputDraft.setAttachments}
|
||||
cwd={cwd}
|
||||
getDraftRevision={agentInputDraft.getRevision}
|
||||
clearDraft={agentInputDraft.clear}
|
||||
editingSession={editingSession}
|
||||
autoFocus
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Session } from "node:inspector/promises";
|
||||
import { getPluginClientApi } from "./client-state/api";
|
||||
import { filePanelTitle } from "@/file-panels/choice/presentation";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
@@ -236,3 +237,27 @@ test("locale snapshots preserve installation state and observations, then releas
|
||||
expect(listeners.size).toBe(0);
|
||||
await expect.poll(() => h.open.size).toBe(0);
|
||||
});
|
||||
|
||||
test("reloading a plugin releases the previous installation", async () => {
|
||||
const h = registry();
|
||||
const options = { client: h.client, audio };
|
||||
const entry = catalog("reloaded");
|
||||
h.plugins.installCatalog("host", [entry], options);
|
||||
// The published snapshot is a copy. Its lifetime belongs to the installation itself.
|
||||
const previous = new WeakRef(h.plugins.getSnapshot()[0]!.lifetime);
|
||||
|
||||
h.plugins.installCatalog("host", [entry], { ...options, replacePluginId: entry.id });
|
||||
expect(h.plugins.getSnapshot()[0]?.lifetime).not.toBe(previous.deref());
|
||||
|
||||
const inspector = new Session();
|
||||
inspector.connect();
|
||||
try {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await inspector.post("HeapProfiler.collectGarbage");
|
||||
expect(previous.deref() === undefined).toBe(true);
|
||||
expect(h.plugins.getSnapshot()).toHaveLength(1);
|
||||
} finally {
|
||||
inspector.disconnect();
|
||||
h.plugins.removeHost("host");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -89,91 +89,15 @@ export class PluginRegistry {
|
||||
this.publish();
|
||||
for (const plugin of removed) this.dispose(plugin);
|
||||
}
|
||||
const installed = catalog.flatMap((entry) => {
|
||||
const key = `${serverId}/${entry.id}`;
|
||||
let installation: InstalledPlugin | undefined;
|
||||
try {
|
||||
if (!entry.clientBundle) return [];
|
||||
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
|
||||
const existing = preserved.find(
|
||||
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
|
||||
);
|
||||
if (existing) {
|
||||
this.evaluationErrors.delete(key);
|
||||
return [existing];
|
||||
}
|
||||
const client = options.client;
|
||||
const lifetime = new AbortController();
|
||||
installation = {
|
||||
lifetime,
|
||||
locale: this.dependencies.localeSource.getLocale(),
|
||||
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
|
||||
paseo: createPaseoApi(client),
|
||||
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
|
||||
subscribe: createPluginSubscribe({
|
||||
client,
|
||||
pluginId: entry.id,
|
||||
lifetime: lifetime.signal,
|
||||
}),
|
||||
id: entry.id,
|
||||
serverId,
|
||||
clientBundle: entry.clientBundle,
|
||||
requirements: entry.requirements,
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
surfaces: [],
|
||||
settingsScreens: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
|
||||
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
|
||||
once: true,
|
||||
});
|
||||
const runtime = this.dependencies.createRuntime(installation, options.audio);
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId, pluginId: entry.id },
|
||||
entry.clientBundle,
|
||||
runtime,
|
||||
() => this.publish(),
|
||||
);
|
||||
Object.assign(installation, evaluated);
|
||||
const paseo = installation.paseo;
|
||||
installation.cleanup = async () => {
|
||||
const results = await Promise.allSettled([paseo.dispose(), evaluated.cleanup()]);
|
||||
const failures = results.filter((result) => result.status === "rejected");
|
||||
if (failures.length)
|
||||
throw new AggregateError(
|
||||
failures.map((result) => result.reason),
|
||||
"Plugin cleanup failed",
|
||||
);
|
||||
};
|
||||
this.evaluationErrors.delete(key);
|
||||
return [installation];
|
||||
} catch (error) {
|
||||
installation?.lifetime.abort();
|
||||
installation?.i18n.dispose();
|
||||
void installation?.paseo
|
||||
.dispose()
|
||||
.catch((failure) => console.warn(`[Plugins] API cleanup failed for ${key}`, failure));
|
||||
this.evaluationErrors.set(key, error instanceof Error ? error.message : String(error));
|
||||
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
|
||||
return [];
|
||||
}
|
||||
});
|
||||
const installed = catalog.flatMap((entry) =>
|
||||
this.installPlugin({
|
||||
serverId,
|
||||
entry,
|
||||
preserved,
|
||||
client: options.client,
|
||||
audio: options.audio,
|
||||
}),
|
||||
);
|
||||
const configuredIds = new Set(catalog.map((entry) => entry.id));
|
||||
for (const key of this.evaluationErrors.keys()) {
|
||||
if (key.startsWith(`${serverId}/`) && !configuredIds.has(key.slice(serverId.length + 1))) {
|
||||
@@ -215,6 +139,104 @@ export class PluginRegistry {
|
||||
this.publish();
|
||||
}
|
||||
|
||||
// Keep the closures for one installation out of the scope that holds the previous catalog.
|
||||
private installPlugin({
|
||||
serverId,
|
||||
entry,
|
||||
preserved,
|
||||
client,
|
||||
audio,
|
||||
}: {
|
||||
serverId: string;
|
||||
entry: CatalogPlugin;
|
||||
preserved: InstalledPlugin[];
|
||||
client: DaemonClient;
|
||||
audio: Pick<AudioEngine, "play">;
|
||||
}): InstalledPlugin[] {
|
||||
const key = `${serverId}/${entry.id}`;
|
||||
let installation: InstalledPlugin | undefined;
|
||||
try {
|
||||
if (!entry.clientBundle) return [];
|
||||
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
|
||||
const existing = preserved.find(
|
||||
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
|
||||
);
|
||||
if (existing) {
|
||||
this.evaluationErrors.delete(key);
|
||||
return [existing];
|
||||
}
|
||||
const lifetime = new AbortController();
|
||||
installation = {
|
||||
lifetime,
|
||||
locale: this.dependencies.localeSource.getLocale(),
|
||||
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
|
||||
paseo: createPaseoApi(client),
|
||||
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
|
||||
subscribe: createPluginSubscribe({
|
||||
client,
|
||||
pluginId: entry.id,
|
||||
lifetime: lifetime.signal,
|
||||
}),
|
||||
id: entry.id,
|
||||
serverId,
|
||||
clientBundle: entry.clientBundle,
|
||||
requirements: entry.requirements,
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
surfaces: [],
|
||||
settingsScreens: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
|
||||
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
|
||||
once: true,
|
||||
});
|
||||
const runtime = this.dependencies.createRuntime(installation, audio);
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId, pluginId: entry.id },
|
||||
entry.clientBundle,
|
||||
runtime,
|
||||
() => this.publish(),
|
||||
);
|
||||
Object.assign(installation, evaluated);
|
||||
const paseo = installation.paseo;
|
||||
installation.cleanup = async () => {
|
||||
const results = await Promise.allSettled([paseo.dispose(), evaluated.cleanup()]);
|
||||
const failures = results.filter((result) => result.status === "rejected");
|
||||
if (failures.length)
|
||||
throw new AggregateError(
|
||||
failures.map((result) => result.reason),
|
||||
"Plugin cleanup failed",
|
||||
);
|
||||
};
|
||||
this.evaluationErrors.delete(key);
|
||||
return [installation];
|
||||
} catch (error) {
|
||||
installation?.lifetime.abort();
|
||||
installation?.i18n.dispose();
|
||||
void installation?.paseo
|
||||
.dispose()
|
||||
.catch((failure) => console.warn(`[Plugins] API cleanup failed for ${key}`, failure));
|
||||
this.evaluationErrors.set(key, error instanceof Error ? error.message : String(error));
|
||||
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private hostEvaluationErrors(serverId: string): string {
|
||||
const prefix = `${serverId}/`;
|
||||
return JSON.stringify(
|
||||
|
||||
@@ -271,6 +271,53 @@ describe("AgentDirectoryReplica", () => {
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("ignores a lagging running snapshot for a turn already closed by stream_close", () => {
|
||||
const serverId = "agent-replica-stale-running-snapshot";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
replica.commitSnapshot(
|
||||
[
|
||||
entry({
|
||||
...payload("running"),
|
||||
status: "running",
|
||||
activeTurn: { turnId: "turn-1", startedAt: "2026-07-17T00:01:00.000Z" },
|
||||
}),
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
replica.applyTurnLiveness("agent", { type: "stream_close", turnId: "turn-1" });
|
||||
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
|
||||
|
||||
// An empty directory catch-up re-projects the unchanged idle agent as activeTurn: null;
|
||||
// it must preserve the closed turn marker so a lagging running delta still cannot re-open it.
|
||||
replica.commitChanges([], [], []);
|
||||
|
||||
replica.applyDelta({
|
||||
kind: "upsert",
|
||||
agent: {
|
||||
...payload("stale usage update"),
|
||||
status: "running",
|
||||
activeTurn: { turnId: "turn-1", startedAt: "2026-07-17T00:01:00.000Z" },
|
||||
},
|
||||
project: entry(payload("project")).project,
|
||||
});
|
||||
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
|
||||
|
||||
replica.applyDelta({
|
||||
kind: "upsert",
|
||||
agent: { ...payload("idle"), status: "idle", activeTurn: null },
|
||||
project: entry(payload("project")).project,
|
||||
});
|
||||
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
|
||||
expect(store.getSession(serverId)?.agents.get("agent")?.turn).toMatchObject({
|
||||
phase: "idle",
|
||||
cancellationRequestId: null,
|
||||
});
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("preserves an unchanged running agent's turn identity during catch-up", () => {
|
||||
const serverId = "agent-replica-catch-up";
|
||||
const store = useSessionStore.getState();
|
||||
|
||||
@@ -200,6 +200,7 @@ interface NewWorkspaceScreenProps {
|
||||
const NO_TERMINAL_ATTACHMENTS: UserComposerAttachment[] = [];
|
||||
function noopChangeAttachments() {}
|
||||
function noopClearDraft() {}
|
||||
const getTerminalDraftRevision = () => 0;
|
||||
|
||||
// Stable reference so the keyboard-action handler doesn't re-register each render.
|
||||
const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [
|
||||
@@ -1685,6 +1686,7 @@ export function NewWorkspaceScreen({
|
||||
attachments={NO_TERMINAL_ATTACHMENTS}
|
||||
onChangeAttachments={noopChangeAttachments}
|
||||
cwd={workingDirectory ?? ""}
|
||||
getDraftRevision={getTerminalDraftRevision}
|
||||
clearDraft={noopClearDraft}
|
||||
autoFocus={terminalTakesPrompt}
|
||||
autoFocusKey={launchFocusKey}
|
||||
@@ -1716,6 +1718,7 @@ export function NewWorkspaceScreen({
|
||||
onForgeChangeRequestDetected={handleForgeChangeRequestDetected}
|
||||
onForgeChangeRequestAutoAttach={handleForgeChangeRequestAutoAttach}
|
||||
cwd={workingDirectory ?? ""}
|
||||
getDraftRevision={chatDraft.getRevision}
|
||||
clearDraft={handleClearDraft}
|
||||
autoFocus
|
||||
autoFocusKey={launchFocusKey}
|
||||
|
||||
@@ -45,6 +45,7 @@ import { hasDraftContent } from "@/composer/draft/input-draft-core";
|
||||
export type { DraftInput, DraftLifecycleState } from "./state";
|
||||
|
||||
interface DraftStoreActions {
|
||||
getDraftRevision: (draftKey: string) => number;
|
||||
getDraftInput: (draftKey: string) => DraftInput | undefined;
|
||||
hydrateDraftInput: (input: { draftKey: string }) => Promise<DraftInput | undefined>;
|
||||
saveDraftInput: (input: { draftKey: string; draft: DraftInput }) => void;
|
||||
@@ -283,6 +284,11 @@ export const useDraftStore = create<DraftStore>()(
|
||||
textReplacementRequestByDraftKey: {},
|
||||
metadataByDraftKey: {},
|
||||
|
||||
getDraftRevision: (draftKey) => {
|
||||
get().flushDraftText(draftKey);
|
||||
return get().drafts[draftKey]?.version ?? 0;
|
||||
},
|
||||
|
||||
getDraftInput: (draftKey) => {
|
||||
const record = get().drafts[draftKey];
|
||||
return toDraftInputIfReady(record);
|
||||
|
||||
@@ -28,6 +28,12 @@ describe("draft-store lifecycle", () => {
|
||||
expect(editDraftRecordText(edited, "", 3).lifecycle).toBe("active");
|
||||
expect(editDraftRecordText(undefined, "", 3).lifecycle).toBe("abandoned");
|
||||
});
|
||||
it("keeps the version when a cleared draft publishes empty text again", () => {
|
||||
const cleared = editDraftRecordText(undefined, "", 1);
|
||||
expect(editDraftRecordText(cleared, "", 2)).toBe(cleared);
|
||||
expect(editDraftRecordText(cleared, "follow-up", 2).version).toBe(cleared.version + 1);
|
||||
});
|
||||
|
||||
it("prunes finalized tombstones after TTL", () => {
|
||||
const nowMs = 1_000_000;
|
||||
const drafts = {
|
||||
|
||||
@@ -38,7 +38,11 @@ export function editDraftRecordText(
|
||||
text: string,
|
||||
now: number,
|
||||
): DraftRecord {
|
||||
if (record?.lifecycle === "active" && record.input.text === text) return record;
|
||||
if (
|
||||
record?.input.text === text &&
|
||||
(record.lifecycle === "active" || record.lifecycle === "abandoned")
|
||||
)
|
||||
return record;
|
||||
const attachments = record?.lifecycle === "active" ? record.input.attachments : [];
|
||||
return {
|
||||
input: { text, attachments },
|
||||
|
||||
@@ -75,4 +75,49 @@ describe("turn activity", () => {
|
||||
turnId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not re-open a turn from a lagging snapshot after stream_close ended it", () => {
|
||||
const open = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "stream_open",
|
||||
turn: { turnId: "turn-1", startedAt },
|
||||
});
|
||||
const closed = reduceTurnLiveness(open, { type: "stream_close", turnId: "turn-1" });
|
||||
expect(closed.phase).toBe("idle");
|
||||
|
||||
// A stale running snapshot for the just-closed turn must not flash it back to open.
|
||||
const afterStaleSnapshot = reduceTurnLiveness(closed, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "turn-1", startedAt },
|
||||
});
|
||||
expect(afterStaleSnapshot).toBe(closed);
|
||||
expect(resolveTurnPresentation(afterStaleSnapshot, false).isActive).toBe(false);
|
||||
|
||||
// An idle snapshot (including an empty directory catch-up) preserves the closed turn marker
|
||||
// so a delayed running snapshot for the same turn still cannot re-open it.
|
||||
const afterIdleSnapshot = reduceTurnLiveness(afterStaleSnapshot, {
|
||||
type: "snapshot",
|
||||
activeTurn: null,
|
||||
});
|
||||
expect(afterIdleSnapshot).toBe(closed);
|
||||
expect(
|
||||
reduceTurnLiveness(afterIdleSnapshot, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "turn-1", startedAt },
|
||||
}),
|
||||
).toBe(closed);
|
||||
|
||||
// A snapshot for a different turn still opens immediately.
|
||||
const nextStartedAt = new Date("2026-07-31T10:01:00.000Z");
|
||||
expect(
|
||||
reduceTurnLiveness(closed, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "turn-2", startedAt: nextStartedAt },
|
||||
}),
|
||||
).toEqual({
|
||||
phase: "open",
|
||||
turnId: "turn-2",
|
||||
startedAt: nextStartedAt,
|
||||
cancellationRequestId: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ export interface ActiveTurnIdentity {
|
||||
}
|
||||
|
||||
export type TurnLiveness =
|
||||
| { phase: "idle"; cancellationRequestId: number | null }
|
||||
| { phase: "idle"; cancellationRequestId: number | null; closedTurnId?: string }
|
||||
| {
|
||||
phase: "open";
|
||||
turnId: string | null;
|
||||
@@ -42,8 +42,15 @@ export function applyTurnLivenessTransition(
|
||||
const next = transitions.reduce(reduceTurnLiveness, current);
|
||||
if (next === current) return turns as Map<string, TurnLiveness>;
|
||||
const updated = new Map(turns);
|
||||
if (next.phase === "idle" && next.cancellationRequestId === null) updated.delete(agentId);
|
||||
else updated.set(agentId, next);
|
||||
if (
|
||||
next.phase === "idle" &&
|
||||
next.cancellationRequestId === null &&
|
||||
next.closedTurnId === undefined
|
||||
) {
|
||||
updated.delete(agentId);
|
||||
} else {
|
||||
updated.set(agentId, next);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -109,7 +116,14 @@ function closeTurn(current: TurnLiveness, turnId: string | null): TurnLiveness {
|
||||
turnId !== null &&
|
||||
current.turnId !== null &&
|
||||
turnId !== current.turnId;
|
||||
return targetsDifferentIdentifiedTurn ? current : TURN_LIVENESS_IDLE;
|
||||
if (targetsDifferentIdentifiedTurn) return current;
|
||||
// Remember the closed turn id until a newer turn opens or destructive_close resets liveness,
|
||||
// so a lagging running snapshot (even after an empty directory catch-up) cannot re-open a turn
|
||||
// the stream already ended.
|
||||
const closedTurnId = turnId ?? (current.phase === "open" ? current.turnId : current.closedTurnId);
|
||||
return closedTurnId
|
||||
? { phase: "idle", cancellationRequestId: null, closedTurnId }
|
||||
: TURN_LIVENESS_IDLE;
|
||||
}
|
||||
|
||||
function openTurn(current: TurnLiveness, activeTurn: ActiveTurnIdentity): TurnLiveness {
|
||||
@@ -147,7 +161,24 @@ export function reduceTurnLiveness(
|
||||
return closeTurn(current, transition.turnId);
|
||||
}
|
||||
|
||||
const activeTurn = transition.type === "snapshot" ? transition.activeTurn : transition.turn;
|
||||
if (!activeTurn) return TURN_LIVENESS_IDLE;
|
||||
return openTurn(current, activeTurn);
|
||||
if (transition.type === "snapshot") {
|
||||
if (!transition.activeTurn) {
|
||||
if (current.phase === "idle") {
|
||||
return current.cancellationRequestId === null
|
||||
? current
|
||||
: { ...current, cancellationRequestId: null };
|
||||
}
|
||||
return TURN_LIVENESS_IDLE;
|
||||
}
|
||||
if (
|
||||
current.phase === "idle" &&
|
||||
current.closedTurnId !== undefined &&
|
||||
transition.activeTurn.turnId === current.closedTurnId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
return openTurn(current, transition.activeTurn);
|
||||
}
|
||||
|
||||
return openTurn(current, transition.turn);
|
||||
}
|
||||
|
||||
@@ -17,11 +17,7 @@ export async function connectTerminalClient(target: DaemonTarget) {
|
||||
try {
|
||||
const daemonClient = await connectToDaemon({ target });
|
||||
const terminals = createTerminalActions(daemonClient, async (workspaceId) => {
|
||||
const result = await daemonClient.fetchWorkspaces({
|
||||
filter: { idPrefix: workspaceId, includeBackground: true },
|
||||
page: { limit: 10 },
|
||||
});
|
||||
const workspace = result.entries.find((entry) => entry.id === workspaceId);
|
||||
const workspace = await daemonClient.findWorkspace(workspaceId);
|
||||
if (!workspace?.workspaceDirectory) {
|
||||
throw new Error(`Workspace ${workspaceId} is not active or has no available directory`);
|
||||
}
|
||||
|
||||
@@ -73,6 +73,18 @@ try {
|
||||
await cli(["terminal", "kill", feature.id]);
|
||||
assert.deepEqual(await cli(["terminal", "ls", "--workspace", second.id]), []);
|
||||
assert.deepEqual(await cli(["terminal", "ls", "--workspace", first.id]), [main]);
|
||||
for (let i = 0; i < 9; i++) {
|
||||
await sdk.workspaces.create({
|
||||
source: { kind: "directory", path: ctx.workDir },
|
||||
title: `extra-${i}`,
|
||||
});
|
||||
}
|
||||
const workspaces = await cli(["workspace", "ls"]);
|
||||
assert.equal(workspaces.length, 11);
|
||||
const { workspaceId, cwd } = workspaces[10];
|
||||
const created = await cli(["terminal", "create", "--workspace", workspaceId, "--name", "Older"]);
|
||||
assert.deepEqual(created, { id: created.id, name: "Older", workspaceId, cwd });
|
||||
await cli(["terminal", "kill", created.id]);
|
||||
console.log("Terminal workspace CLI: ownership, lists, input, capture, kill, and errors passed");
|
||||
} finally {
|
||||
await sdk.close();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -669,9 +669,10 @@ async function clickGuestElement(page, client, browserId, selector) {
|
||||
}
|
||||
|
||||
async function selectDeviceSize(page, label) {
|
||||
await page.locator('[aria-label="Device size"]').click();
|
||||
const item = page.getByText(label, { exact: true });
|
||||
await item.waitFor({ state: "visible", timeout: timeoutMs });
|
||||
const trigger = page.getByLabel("Device size", { exact: true });
|
||||
const item = page.getByRole("menuitem", { name: label, exact: true });
|
||||
await trigger.click();
|
||||
await item.click({ trial: true, timeout: timeoutMs });
|
||||
const rect = await item.boundingBox();
|
||||
assert(rect, `Device size menu item ${label} had no bounds`);
|
||||
const clip = {
|
||||
@@ -685,9 +686,9 @@ async function selectDeviceSize(page, label) {
|
||||
await item.waitFor({ state: "hidden", timeout: timeoutMs });
|
||||
const closedPixels = await page.screenshot({ clip });
|
||||
|
||||
await page.locator('[aria-label="Device size"]').click();
|
||||
await item.waitFor({ state: "visible", timeout: timeoutMs });
|
||||
await page.mouse.click(rect.x + rect.width / 2, rect.y + rect.height / 2);
|
||||
await trigger.click();
|
||||
// The reopened menu renders off-screen while measuring. Click its current position after layout.
|
||||
await item.click({ timeout: timeoutMs });
|
||||
await page.keyboard.press("Escape");
|
||||
return !openPixels.equals(closedPixels);
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import net, { type AddressInfo, type Server, type Socket } from "node:net";
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_SLUG,
|
||||
getBrowserPartition,
|
||||
parseBrowserPartition,
|
||||
} from "../../browser-partition.js";
|
||||
import { getHostBrowserProxyPartition, isHostBrowserProxyPartition } from "./partition.js";
|
||||
import { createOsSocketOwnerVerifier, type SocketOwnerVerifier } from "./socket-owner.js";
|
||||
import {
|
||||
performSocks5Handshake,
|
||||
@@ -21,8 +17,7 @@ export type BrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting
|
||||
|
||||
export interface BrowserProxyStatusSnapshot {
|
||||
serverId: string;
|
||||
/** Profile slug -> partition, for every profile session bound and verified on this host. */
|
||||
profilePartitions: Record<string, string>;
|
||||
partition: string;
|
||||
status: BrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksPort: number | null;
|
||||
@@ -56,8 +51,6 @@ export interface BrowserProxyManagerDeps {
|
||||
export interface EnsureHostProxyInput {
|
||||
serverId: string;
|
||||
target: HostTransportSpec;
|
||||
/** The browser profile whose session to bind to the host proxy. Defaults to `default`. */
|
||||
profileSlug?: string;
|
||||
forceReconnect?: boolean;
|
||||
}
|
||||
|
||||
@@ -72,23 +65,19 @@ export interface BrowserProxyManager {
|
||||
disposeAll(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One host route: one loopback SOCKS5 server and one tunnel. Every profile session
|
||||
* on the host points `setProxy` at the same SOCKS5 port.
|
||||
*/
|
||||
interface HostProxyEntry {
|
||||
readonly serverId: string;
|
||||
readonly partition: string;
|
||||
target: HostTransportSpec;
|
||||
status: BrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksServer: Server | null;
|
||||
socksPort: number | null;
|
||||
/** Profile slug -> partition whose session is bound and verified. */
|
||||
boundPartitions: Map<string, string>;
|
||||
bindPromises: Map<string, Promise<void>>;
|
||||
session: BrowserProxySessionLike | null;
|
||||
sessionConfigured: boolean;
|
||||
mux: TunnelMuxClient | null;
|
||||
connectPromise: Promise<TunnelMuxClient> | null;
|
||||
routePromise: Promise<number> | null;
|
||||
ensurePromise: Promise<BrowserProxyStatusSnapshot> | null;
|
||||
activeSockets: Set<Socket>;
|
||||
disposed: boolean;
|
||||
}
|
||||
@@ -121,19 +110,15 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
function snapshotOf(entry: HostProxyEntry): BrowserProxyStatusSnapshot {
|
||||
return {
|
||||
serverId: entry.serverId,
|
||||
profilePartitions: Object.fromEntries(entry.boundPartitions),
|
||||
partition: entry.partition,
|
||||
status: entry.status,
|
||||
error: entry.error,
|
||||
// Only expose socksPort once a Chromium session proxy has been configured and
|
||||
// Only expose socksPort once Chromium's session proxy has been configured and
|
||||
// verified via resolveProxy so renderers never mount an unverified partition.
|
||||
socksPort: hasBoundSession(entry) ? entry.socksPort : null,
|
||||
socksPort: entry.sessionConfigured ? entry.socksPort : null,
|
||||
};
|
||||
}
|
||||
|
||||
function hasBoundSession(entry: HostProxyEntry): boolean {
|
||||
return entry.boundPartitions.size > 0;
|
||||
}
|
||||
|
||||
function setEntryStatus(
|
||||
entry: HostProxyEntry,
|
||||
status: BrowserProxyStatus,
|
||||
@@ -182,44 +167,12 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function bindSession(
|
||||
entry: HostProxyEntry,
|
||||
profileSlug: string,
|
||||
partition: string,
|
||||
socksPort: number,
|
||||
): Promise<void> {
|
||||
if (entry.boundPartitions.has(profileSlug)) {
|
||||
async function ensureSessionConfigured(entry: HostProxyEntry, socksPort: number): Promise<void> {
|
||||
if (entry.sessionConfigured && entry.session) {
|
||||
return;
|
||||
}
|
||||
let bindTask = entry.bindPromises.get(profileSlug);
|
||||
if (!bindTask) {
|
||||
bindTask = (async () => {
|
||||
const session = await configureSession(partition, socksPort);
|
||||
if (entry.disposed) {
|
||||
throw new Error("Host browser proxy was disposed");
|
||||
}
|
||||
entry.boundPartitions.set(profileSlug, partition);
|
||||
allowedPartitions.add(partition);
|
||||
proxiedSessions.add(session);
|
||||
deps.onStatusChange?.(snapshotOf(entry));
|
||||
})();
|
||||
entry.bindPromises.set(profileSlug, bindTask);
|
||||
const settled = () => {
|
||||
if (entry.bindPromises.get(profileSlug) === bindTask) {
|
||||
entry.bindPromises.delete(profileSlug);
|
||||
}
|
||||
};
|
||||
bindTask.then(settled, settled);
|
||||
}
|
||||
await bindTask;
|
||||
}
|
||||
|
||||
async function configureSession(
|
||||
partition: string,
|
||||
socksPort: number,
|
||||
): Promise<BrowserProxySessionLike> {
|
||||
knownPartitions.add(partition);
|
||||
const hostSession = deps.getSessionForPartition(partition);
|
||||
const hostSession = deps.getSessionForPartition(entry.partition);
|
||||
await hostSession.setProxy({
|
||||
mode: "fixed_servers",
|
||||
proxyRules: `socks5://127.0.0.1:${socksPort}`,
|
||||
@@ -241,26 +194,12 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
`Session resolveProxy verification failed (localhost="${resolvedLocalhost}", 127.0.0.1="${resolvedLoopbackIp}")`,
|
||||
);
|
||||
}
|
||||
return hostSession;
|
||||
}
|
||||
|
||||
/** The host route: its fixed SOCKS5 port and a connected tunnel, shared by every profile. */
|
||||
async function ensureRoute(entry: HostProxyEntry): Promise<number> {
|
||||
if (!entry.routePromise) {
|
||||
const routeTask = (async () => {
|
||||
const socksPort = await ensureSocksServer(entry);
|
||||
await ensureTunnelConnected(entry);
|
||||
return socksPort;
|
||||
})();
|
||||
entry.routePromise = routeTask;
|
||||
const settled = () => {
|
||||
if (entry.routePromise === routeTask) {
|
||||
entry.routePromise = null;
|
||||
}
|
||||
};
|
||||
routeTask.then(settled, settled);
|
||||
}
|
||||
return await entry.routePromise;
|
||||
entry.session = hostSession;
|
||||
entry.sessionConfigured = true;
|
||||
allowedPartitions.add(entry.partition);
|
||||
knownPartitions.add(entry.partition);
|
||||
proxiedSessions.add(hostSession);
|
||||
}
|
||||
|
||||
async function ensureTunnelConnected(entry: HostProxyEntry): Promise<TunnelMuxClient> {
|
||||
@@ -275,7 +214,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
}
|
||||
|
||||
const nextStatus: BrowserProxyStatus =
|
||||
hasBoundSession(entry) || entry.status === "ready" || entry.status === "reconnecting"
|
||||
entry.sessionConfigured || entry.status === "ready" || entry.status === "reconnecting"
|
||||
? "reconnecting"
|
||||
: "connecting";
|
||||
setEntryStatus(entry, nextStatus, null);
|
||||
@@ -299,13 +238,13 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
mux.onClose(() => {
|
||||
if (entry.mux === mux) {
|
||||
entry.mux = null;
|
||||
if (!entry.disposed && hasBoundSession(entry)) {
|
||||
if (!entry.disposed && entry.sessionConfigured) {
|
||||
setEntryStatus(entry, "reconnecting", null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (hasBoundSession(entry)) {
|
||||
if (entry.sessionConfigured) {
|
||||
setEntryStatus(entry, "ready", null);
|
||||
}
|
||||
return mux;
|
||||
@@ -419,18 +358,21 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
return existing;
|
||||
}
|
||||
|
||||
const partition = getHostBrowserProxyPartition(serverId);
|
||||
knownPartitions.add(partition);
|
||||
const entry: HostProxyEntry = {
|
||||
serverId,
|
||||
partition,
|
||||
target,
|
||||
status: "idle",
|
||||
error: null,
|
||||
socksServer: null,
|
||||
socksPort: null,
|
||||
boundPartitions: new Map(),
|
||||
bindPromises: new Map(),
|
||||
session: null,
|
||||
sessionConfigured: false,
|
||||
mux: null,
|
||||
connectPromise: null,
|
||||
routePromise: null,
|
||||
ensurePromise: null,
|
||||
activeSockets: new Set(),
|
||||
disposed: false,
|
||||
};
|
||||
@@ -443,8 +385,6 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
if (!serverId) {
|
||||
throw new Error("Host serverId is required");
|
||||
}
|
||||
const profileSlug = input.profileSlug ?? DEFAULT_BROWSER_PROFILE_SLUG;
|
||||
const partition = getBrowserPartition({ kind: "host", serverId }, profileSlug);
|
||||
|
||||
const entry = getOrCreateEntry(serverId, input.target);
|
||||
if (input.forceReconnect && entry.mux) {
|
||||
@@ -452,19 +392,37 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
entry.mux = null;
|
||||
}
|
||||
|
||||
try {
|
||||
if (entry.status !== "ready") {
|
||||
setEntryStatus(entry, hasBoundSession(entry) ? "reconnecting" : "connecting", null);
|
||||
if (entry.ensurePromise) {
|
||||
return await entry.ensurePromise;
|
||||
}
|
||||
|
||||
const ensureTask = (async (): Promise<BrowserProxyStatusSnapshot> => {
|
||||
try {
|
||||
if (entry.status !== "ready") {
|
||||
setEntryStatus(entry, entry.sessionConfigured ? "reconnecting" : "connecting", null);
|
||||
}
|
||||
const socksPort = await ensureSocksServer(entry);
|
||||
await ensureTunnelConnected(entry);
|
||||
await ensureSessionConfigured(entry, socksPort);
|
||||
setEntryStatus(entry, "ready", null);
|
||||
return snapshotOf(entry);
|
||||
} catch (error) {
|
||||
const message = formatError(error);
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", message);
|
||||
}
|
||||
return snapshotOf(entry);
|
||||
}
|
||||
const socksPort = await ensureRoute(entry);
|
||||
await bindSession(entry, profileSlug, partition, socksPort);
|
||||
setEntryStatus(entry, "ready", null);
|
||||
} catch (error) {
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", formatError(error));
|
||||
})();
|
||||
|
||||
entry.ensurePromise = ensureTask;
|
||||
try {
|
||||
return await ensureTask;
|
||||
} finally {
|
||||
if (entry.ensurePromise === ensureTask) {
|
||||
entry.ensurePromise = null;
|
||||
}
|
||||
}
|
||||
return snapshotOf(entry);
|
||||
}
|
||||
|
||||
function updateHostProxyTarget(input: { serverId: string; target: HostTransportSpec }): void {
|
||||
@@ -474,7 +432,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
entry.target = input.target;
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
if (hasBoundSession(entry)) {
|
||||
if (entry.sessionConfigured) {
|
||||
setEntryStatus(entry, "reconnecting", null);
|
||||
}
|
||||
}
|
||||
@@ -486,7 +444,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
}
|
||||
|
||||
function isAllowedHostPartition(partition: string): boolean {
|
||||
return parseBrowserPartition(partition)?.route === "host" && allowedPartitions.has(partition);
|
||||
return isHostBrowserProxyPartition(partition) && allowedPartitions.has(partition);
|
||||
}
|
||||
|
||||
function isProxiedSession(session: object): boolean {
|
||||
@@ -501,9 +459,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
if (entry.disposed) return;
|
||||
entry.disposed = true;
|
||||
entriesByServerId.delete(entry.serverId);
|
||||
for (const partition of entry.boundPartitions.values()) {
|
||||
allowedPartitions.delete(partition);
|
||||
}
|
||||
allowedPartitions.delete(entry.partition);
|
||||
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./internal/partition.js";
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "../browser-partition.js";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "../browser-profile.js";
|
||||
import { getHostBrowserProxyPartition } from "../browser-proxy/partition.js";
|
||||
import {
|
||||
getPaseoBrowserIdForWebContents,
|
||||
getPaseoBrowserWorkspaceId,
|
||||
@@ -10,10 +11,6 @@ import {
|
||||
unregisterPaseoBrowserFromHost,
|
||||
} from "./index.js";
|
||||
|
||||
function hostPartitionFor(serverId: string, profileSlug = "default"): string {
|
||||
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
|
||||
}
|
||||
|
||||
class FakeRenderer {
|
||||
public constructor(public readonly id: number) {}
|
||||
|
||||
@@ -49,8 +46,8 @@ class FakeBrowserGuest {
|
||||
|
||||
describe("browser webview attachment", () => {
|
||||
test("accepts only allowed URLs on the shared profile or registered host proxy partitions", () => {
|
||||
const hostPartition = hostPartitionFor("remote-host-a");
|
||||
const unregisteredHostPartition = hostPartitionFor("remote-host-b");
|
||||
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
|
||||
const unregisteredHostPartition = getHostBrowserProxyPartition("remote-host-b");
|
||||
const isAllowedHostPartition = (partition: string) => partition === hostPartition;
|
||||
|
||||
expect(
|
||||
@@ -91,7 +88,7 @@ describe("browser webview attachment", () => {
|
||||
});
|
||||
|
||||
test("registers a guest attached to an allowed host proxy session", () => {
|
||||
const hostPartition = hostPartitionFor("remote-host-a");
|
||||
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
|
||||
const proxiedSession = {};
|
||||
const renderer = new FakeRenderer(9);
|
||||
const guest = new FakeBrowserGuest(901, renderer, proxiedSession);
|
||||
@@ -112,53 +109,6 @@ describe("browser webview attachment", () => {
|
||||
unregisterPaseoBrowser("browser-proxied");
|
||||
});
|
||||
|
||||
test("admits a host-proxied named profile only once its session is bound to the host proxy", () => {
|
||||
const boundWork = hostPartitionFor("remote-host-a", "work");
|
||||
const unboundWork = hostPartitionFor("remote-host-b", "work");
|
||||
const isAllowedHostPartition = (partition: string) => partition === boundWork;
|
||||
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "http://localhost:3000",
|
||||
partition: boundWork,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "http://localhost:3000",
|
||||
partition: unboundWork,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({ src: "http://localhost:3000", partition: boundWork }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("registers a guest on a host-proxied named profile only when its session is proxied", () => {
|
||||
const workPartition = hostPartitionFor("remote-host-a", "work");
|
||||
const proxiedSession = {};
|
||||
const renderer = new FakeRenderer(10);
|
||||
const guest = new FakeBrowserGuest(1001, renderer, proxiedSession);
|
||||
const register = (isAllowedHostSession: (session: object) => boolean) =>
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-proxied-work",
|
||||
workspaceId: "workspace-remote",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
partition: workPartition,
|
||||
sessionFromPartition: (partition) => (partition === workPartition ? proxiedSession : {}),
|
||||
isAllowedHostSession,
|
||||
findWebContents: () => guest,
|
||||
});
|
||||
|
||||
expect(register(() => false)).toBe(false);
|
||||
expect(register((session) => session === proxiedSession)).toBe(true);
|
||||
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-proxied-work");
|
||||
unregisterPaseoBrowser("browser-proxied-work");
|
||||
});
|
||||
|
||||
test("admits only complete lowercase named profile partitions on allowed URLs", () => {
|
||||
const valid = "persist:paseo-profile-work";
|
||||
for (const partition of [valid, `persist:paseo-profile-${"a".repeat(48)}`]) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { webContents as allWebContents, type WebContents } from "electron";
|
||||
import { parseBrowserPartition } from "../browser-partition.js";
|
||||
import { isPaseoBrowserProfilePartition } from "../browser-profile.js";
|
||||
import { isHostBrowserProxyPartition } from "../browser-proxy/partition.js";
|
||||
import {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
buildBrowserPopupWebPreferences,
|
||||
@@ -51,12 +52,13 @@ export function isPaseoBrowserWebviewAttach(input: {
|
||||
if (!isAllowedBrowserWebviewUrl(input.src)) {
|
||||
return false;
|
||||
}
|
||||
const parsed = parseBrowserPartition(input.partition);
|
||||
if (!parsed || !input.partition) {
|
||||
return false;
|
||||
if (isPaseoBrowserProfilePartition(input.partition)) {
|
||||
return true;
|
||||
}
|
||||
// A host-routed partition attaches only once main bound its session to the host proxy.
|
||||
return parsed.route === "local" || (input.isAllowedHostPartition?.(input.partition) ?? false);
|
||||
return (
|
||||
isHostBrowserProxyPartition(input.partition) &&
|
||||
(input.isAllowedHostPartition?.(input.partition) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
export function listRegisteredPaseoBrowserIds(): string[] {
|
||||
@@ -81,11 +83,14 @@ export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput
|
||||
if (!guest || guest.isDestroyed() || guest.hostWebContents !== input.sender) {
|
||||
return false;
|
||||
}
|
||||
const parsed = parseBrowserPartition(input.partition);
|
||||
if (!parsed || guest.session !== input.sessionFromPartition(input.partition)) {
|
||||
return false;
|
||||
}
|
||||
if (parsed.route === "host" && !(input.isAllowedHostSession?.(guest.session) ?? false)) {
|
||||
const sessionMatchesProfile =
|
||||
isPaseoBrowserProfilePartition(input.partition) &&
|
||||
guest.session === input.sessionFromPartition(input.partition);
|
||||
const sessionMatchesHostProxy =
|
||||
isHostBrowserProxyPartition(input.partition) &&
|
||||
guest.session === input.sessionFromPartition(input.partition) &&
|
||||
(input.isAllowedHostSession?.(guest.session) ?? false);
|
||||
if (!sessionMatchesProfile && !sessionMatchesHostProxy) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -79,13 +79,16 @@ import {
|
||||
setWorkspaceActivePaseoBrowserId,
|
||||
unregisterPaseoBrowserHost,
|
||||
} from "./features/browser-webviews/index.js";
|
||||
import { isNamedBrowserProfileSlug, parseBrowserPartition } from "./features/browser-partition.js";
|
||||
import {
|
||||
clearPaseoBrowserProfile,
|
||||
deleteBrowserProfilePartitionDirectories,
|
||||
deleteBrowserProfilePartitionDirectory,
|
||||
getBrowserProfilePartition,
|
||||
getLegacyPaseoBrowserProfileSession,
|
||||
getPaseoBrowserProfileSessions,
|
||||
isNamedBrowserProfileSlug,
|
||||
isPaseoBrowserProfilePartition,
|
||||
listBrowserPartitionDirectories,
|
||||
listDiskHostBrowserProxyPartitions,
|
||||
listPaseoBrowserProfileGuests,
|
||||
pruneOrphanedBrowserProfilePartitions,
|
||||
readHostBrowserProxyPartitions,
|
||||
@@ -94,6 +97,7 @@ import {
|
||||
import {
|
||||
applyProxiedWebContentsPolicy,
|
||||
createElectronBrowserProxyController,
|
||||
isHostBrowserProxyPartition,
|
||||
} from "./features/browser-proxy/index.js";
|
||||
import { parseOpenProjectPathFromArgv } from "./open-project-routing.js";
|
||||
import {
|
||||
@@ -168,7 +172,10 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
|
||||
}
|
||||
const record = input as Record<string, unknown>;
|
||||
const partition = record.partition;
|
||||
if (typeof partition !== "string" || parseBrowserPartition(partition) === null) {
|
||||
if (
|
||||
typeof partition !== "string" ||
|
||||
(!isPaseoBrowserProfilePartition(partition) && !isHostBrowserProxyPartition(partition))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (typeof record.browserId !== "string" || record.browserId.trim().length === 0) {
|
||||
@@ -429,17 +436,16 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
if (!removed.ok) {
|
||||
return removed;
|
||||
}
|
||||
const userData = app.getPath("userData");
|
||||
// The profile's sessions on the local route and on every host route.
|
||||
const profileSessions = getPaseoBrowserProfileSessions(
|
||||
session,
|
||||
await listBrowserPartitionDirectories(userData),
|
||||
{ slug, hostPartitions: browserProxy.manager.listKnownPartitions() },
|
||||
);
|
||||
const openGuests = listPaseoBrowserProfileGuests({
|
||||
profileSessions,
|
||||
webContents: webContents.getAllWebContents(),
|
||||
});
|
||||
const partition = getBrowserProfilePartition(slug);
|
||||
const profileSession = session.fromPartition(partition);
|
||||
const openGuests = webContents
|
||||
.getAllWebContents()
|
||||
.filter(
|
||||
(contents) =>
|
||||
!contents.isDestroyed() &&
|
||||
(contents.getType() === "webview" || contents.getType() === "window") &&
|
||||
contents.session === profileSession,
|
||||
);
|
||||
for (const guest of openGuests) {
|
||||
getPaseoBrowserWebviewRegistry().unregisterWebContents(guest.id);
|
||||
try {
|
||||
@@ -454,13 +460,11 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
}
|
||||
try {
|
||||
await clearPaseoBrowserProfile({
|
||||
profileSessions,
|
||||
profileSessions: [profileSession],
|
||||
listGuests: () => [],
|
||||
logReloadError: () => {},
|
||||
});
|
||||
for (const profileSession of profileSessions) {
|
||||
profileSession.flushStorageData();
|
||||
}
|
||||
profileSession.flushStorageData();
|
||||
} catch (error) {
|
||||
log.warn("[browser-profile] failed to clear session before deleting partition", {
|
||||
slug,
|
||||
@@ -468,7 +472,7 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
});
|
||||
}
|
||||
try {
|
||||
await deleteBrowserProfilePartitionDirectories(userData, slug);
|
||||
await deleteBrowserProfilePartitionDirectory(app.getPath("userData"), slug);
|
||||
} catch (error) {
|
||||
log.warn("[browser-profile] failed to delete profile partition directory", {
|
||||
slug,
|
||||
@@ -615,10 +619,10 @@ ipcMain.handle("paseo:browser:clear-profile", async (_event, rawInput?: unknown)
|
||||
(browserId) => `paseo-browser-${browserId}`,
|
||||
);
|
||||
const allDirectories = [...new Set([...directories, ...legacyDirectories])];
|
||||
// Host partitions on disk arrive through `directories`.
|
||||
const hostPartitions = [
|
||||
...browserProxy.manager.listKnownPartitions(),
|
||||
...readHostBrowserProxyPartitions(options?.hostServerIds),
|
||||
...listDiskHostBrowserProxyPartitions(app.getPath("userData")),
|
||||
];
|
||||
const liveSessions = webContents
|
||||
.getAllWebContents()
|
||||
|
||||
@@ -3,7 +3,7 @@ import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import ts from "typescript";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-partition.js";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-profile.js";
|
||||
|
||||
// The preload runs inside Electron's sandbox and is tsc-compiled (not bundled), so at
|
||||
// runtime it may only load Electron's sandbox allowlist. Any other module (local or
|
||||
|
||||
@@ -150,7 +150,6 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
|
||||
ensureHostProxy: (input: {
|
||||
serverId: string;
|
||||
target: HostTransportSpec;
|
||||
profileSlug?: string;
|
||||
forceReconnect?: boolean;
|
||||
}) =>
|
||||
ipcRenderer.invoke(
|
||||
|
||||
@@ -4583,6 +4583,7 @@ describe("ClaudeAgentSession context window usage", () => {
|
||||
[
|
||||
notification("code-mode-opt-in", "Code Mode isn't available.", "medium"),
|
||||
notification("urgent", "Something needs attention.", "immediate"),
|
||||
notification("stop-hook-error", "stop hook problem · ctrl+o to see", "immediate"),
|
||||
createSuccessResult(),
|
||||
],
|
||||
]),
|
||||
@@ -4600,6 +4601,7 @@ describe("ClaudeAgentSession context window usage", () => {
|
||||
).toEqual([
|
||||
{ type: "notification", level: "info", message: "Code Mode isn't available." },
|
||||
{ type: "notification", level: "warning", message: "Something needs attention." },
|
||||
{ type: "notification", level: "warning", message: "stop hook problem" },
|
||||
]);
|
||||
expect(
|
||||
logs
|
||||
@@ -4608,6 +4610,7 @@ describe("ClaudeAgentSession context window usage", () => {
|
||||
).toEqual([
|
||||
{ level: 30, key: "code-mode-opt-in", text: "Code Mode isn't available." },
|
||||
{ level: 40, key: "urgent", text: "Something needs attention." },
|
||||
{ level: 40, key: "stop-hook-error", text: "stop hook problem · ctrl+o to see" },
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
|
||||
@@ -5525,10 +5525,16 @@ class ClaudeAgentSession implements AgentSession {
|
||||
const fields = { key: message.key, priority: message.priority, text: message.text };
|
||||
if (urgent) this.logger.warn(fields, "claude.notification");
|
||||
else this.logger.info(fields, "claude.notification");
|
||||
// Claude Code's transcript shortcut only works in its terminal UI.
|
||||
const transcriptHint = " · ctrl+o to see";
|
||||
const text =
|
||||
message.key === "stop-hook-error" && message.text.endsWith(transcriptHint)
|
||||
? message.text.slice(0, -transcriptHint.length)
|
||||
: message.text;
|
||||
events.push({
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: { type: "notification", level: urgent ? "warning" : "info", message: message.text },
|
||||
item: { type: "notification", level: urgent ? "warning" : "info", message: text },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -422,3 +422,49 @@ function isFixtureProcessRunning(pid: number): boolean {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function observeWorkspaceScriptNames(
|
||||
daemonClient: DaemonClient,
|
||||
): Promise<Map<string, string[]>> {
|
||||
const scriptNames = new Map<string, string[]>();
|
||||
daemonClient.subscribe((event) => {
|
||||
if (event.type !== "workspace_update" || event.payload.kind !== "upsert") return;
|
||||
const names = event.payload.workspace.scripts.map((script) => script.scriptName);
|
||||
scriptNames.set(event.workspaceId, names);
|
||||
});
|
||||
await daemonClient.fetchWorkspaces({ subscribe: {} });
|
||||
return scriptNames;
|
||||
}
|
||||
|
||||
test("editing paseo.json refreshes every subscribed client for each workspace sharing a directory", async () => {
|
||||
const first = await createWorkspace("First workspace");
|
||||
const second = await createWorkspace("Second workspace");
|
||||
const registry = path.join(daemon.paseoHome, "projects", "workspaces.json");
|
||||
const originalRegistry = await readFile(registry, "utf8");
|
||||
const observer = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
await observer.connect();
|
||||
try {
|
||||
const seen = await Promise.all([client, observer].map(observeWorkspaceScriptNames));
|
||||
const expectScripts = (names: string[]) =>
|
||||
expect
|
||||
.poll(() => seen.map((scriptNames) => [scriptNames.get(first), scriptNames.get(second)]), {
|
||||
timeout: 10_000,
|
||||
})
|
||||
.toEqual([
|
||||
[names, names],
|
||||
[names, names],
|
||||
]);
|
||||
|
||||
await writeFile(
|
||||
path.join(cwd, "paseo.json"),
|
||||
JSON.stringify({ scripts: { build: { command: "npm run build" } } }),
|
||||
);
|
||||
await expectScripts(["build"]);
|
||||
await rm(path.join(cwd, "paseo.json"));
|
||||
await expectScripts([]);
|
||||
expect(await readFile(registry, "utf8")).toBe(originalRegistry);
|
||||
expect((await client.listTerminals()).terminals).toEqual([]);
|
||||
} finally {
|
||||
await observer.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -35,8 +35,16 @@ class ObservationControls implements FileObserverDependencies {
|
||||
this.interval = null;
|
||||
}
|
||||
|
||||
async fileChanged(filename: string): Promise<void> {
|
||||
signalFileChange(filename: string): void {
|
||||
this.change?.(filename);
|
||||
}
|
||||
|
||||
async fileChanged(filename: string): Promise<void> {
|
||||
this.signalFileChange(filename);
|
||||
await this.flushPendingChange();
|
||||
}
|
||||
|
||||
async flushPendingChange(): Promise<void> {
|
||||
const timeout = this.timeout;
|
||||
this.timeout = null;
|
||||
await timeout?.();
|
||||
@@ -82,6 +90,30 @@ describe("FileObserver", () => {
|
||||
expect(controls.closes).toBe(1);
|
||||
});
|
||||
|
||||
test("reports a pending edit to existing listeners when another listener joins", async () => {
|
||||
const root = await workspace();
|
||||
const controls = new ObservationControls();
|
||||
const observer = new FileObserver(controls);
|
||||
const input = { cwd: root, path: "file.txt" };
|
||||
const updates: string[] = [];
|
||||
const first = await observer.subscribe(input, (version) => updates.push(version.status));
|
||||
|
||||
await unlink(path.join(root, input.path));
|
||||
controls.signalFileChange(input.path);
|
||||
const newListenerUpdates: string[] = [];
|
||||
const second = await observer.subscribe(input, (version) =>
|
||||
newListenerUpdates.push(version.status),
|
||||
);
|
||||
expect(second.initial.status).toBe("missing");
|
||||
|
||||
await controls.flushPendingChange();
|
||||
expect(updates).toEqual(["missing"]);
|
||||
expect(newListenerUpdates).toEqual([]);
|
||||
|
||||
first.unsubscribe();
|
||||
second.unsubscribe();
|
||||
});
|
||||
|
||||
test("coalesces concurrent subscriptions onto one watcher", async () => {
|
||||
const root = await workspace();
|
||||
const controls = new ObservationControls();
|
||||
|
||||
@@ -26,8 +26,10 @@ interface ObservedFile {
|
||||
cwd: string;
|
||||
path: string;
|
||||
basename: string;
|
||||
listeners: Map<(version: FileVersion) => void, { cwd: string; path: string }>;
|
||||
fingerprint: string;
|
||||
listeners: Map<
|
||||
(version: FileVersion) => void,
|
||||
{ cwd: string; path: string; fingerprint: string }
|
||||
>;
|
||||
watcher: FileWatch | null;
|
||||
debounce: ReturnType<typeof setTimeout> | null;
|
||||
fallback: ReturnType<typeof setInterval> | null;
|
||||
@@ -62,29 +64,27 @@ export class FileObserver {
|
||||
const target = await resolveExplorerFilePath({ root: input.cwd, relativePath: input.path });
|
||||
let observed = this.observed.get(target);
|
||||
if (!observed) {
|
||||
const initial = await getExplorerFileVersion({ root: input.cwd, relativePath: input.path });
|
||||
observed = this.observed.get(target);
|
||||
if (!observed) {
|
||||
observed = {
|
||||
cwd: input.cwd,
|
||||
path: input.path,
|
||||
basename: path.basename(target),
|
||||
listeners: new Map(),
|
||||
fingerprint: fingerprint(initial),
|
||||
watcher: null,
|
||||
debounce: null,
|
||||
fallback: null,
|
||||
};
|
||||
this.observed.set(target, observed);
|
||||
this.startWatching(target, path.dirname(target), observed);
|
||||
}
|
||||
observed = {
|
||||
cwd: input.cwd,
|
||||
path: input.path,
|
||||
basename: path.basename(target),
|
||||
listeners: new Map(),
|
||||
watcher: null,
|
||||
debounce: null,
|
||||
fallback: null,
|
||||
};
|
||||
this.observed.set(target, observed);
|
||||
this.startWatching(target, path.dirname(target), observed);
|
||||
}
|
||||
const initial = await getExplorerFileVersion({
|
||||
root: input.cwd,
|
||||
relativePath: input.path,
|
||||
});
|
||||
observed.listeners.set(listener, { cwd: initial.cwd, path: initial.path });
|
||||
observed.fingerprint = fingerprint(initial);
|
||||
observed.listeners.set(listener, {
|
||||
cwd: initial.cwd,
|
||||
path: initial.path,
|
||||
fingerprint: fingerprint(initial),
|
||||
});
|
||||
|
||||
let active = true;
|
||||
return {
|
||||
@@ -148,10 +148,10 @@ export class FileObserver {
|
||||
relativePath: observed.path,
|
||||
});
|
||||
const nextFingerprint = fingerprint(version);
|
||||
if (nextFingerprint === observed.fingerprint) return;
|
||||
observed.fingerprint = nextFingerprint;
|
||||
for (const [listener, identity] of observed.listeners) {
|
||||
listener({ ...version, ...identity });
|
||||
for (const [listener, subscription] of observed.listeners) {
|
||||
if (nextFingerprint === subscription.fingerprint) continue;
|
||||
subscription.fingerprint = nextFingerprint;
|
||||
listener({ ...version, cwd: subscription.cwd, path: subscription.path });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7577,3 +7577,172 @@ describe("agent.queue RPCs and live updates in Session", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("session agent_update and agent_stream ordering", () => {
|
||||
test("delivers queued agent_update snapshots ahead of agent_stream turn_completed and keeps subsequent stream events ordered", async () => {
|
||||
const messages: SessionOutboundMessage[] = [];
|
||||
let listener: ((event: AgentManagerEvent) => void) | null = null;
|
||||
const record = createStoredAgentRecord({
|
||||
id: "agent-order",
|
||||
cwd: "/tmp/order-repo",
|
||||
workspaceId: "ws-order",
|
||||
provider: "antigravity",
|
||||
title: "Order Test",
|
||||
});
|
||||
const workspace = createPersistedWorkspaceRecord({
|
||||
workspaceId: "ws-order",
|
||||
projectId: "proj-order",
|
||||
cwd: record.cwd,
|
||||
kind: "directory",
|
||||
displayName: "Order Workspace",
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
});
|
||||
const project = createPersistedProjectRecord({
|
||||
projectId: workspace.projectId,
|
||||
rootPath: workspace.cwd,
|
||||
kind: "non_git",
|
||||
displayName: "order-repo",
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
});
|
||||
const storageReads: Array<{ resolve: (value: StoredAgentRecord | null) => void }> = [];
|
||||
const providers = createProviderSnapshotManagerStub();
|
||||
providers.listRegisteredProviderIds.mockReturnValue(["antigravity"]);
|
||||
|
||||
const makeManaged = (
|
||||
lifecycle: "running" | "idle",
|
||||
activeTurnId: string | null,
|
||||
usage?: { inputTokens: number; outputTokens: number },
|
||||
): ManagedAgent =>
|
||||
({
|
||||
id: record.id,
|
||||
provider: record.provider,
|
||||
cwd: record.cwd,
|
||||
workspaceId: record.workspaceId,
|
||||
lifecycle,
|
||||
activeTurnId,
|
||||
activeForegroundTurnId: activeTurnId,
|
||||
activeTurnStartedAt: activeTurnId ? new Date("2026-12-02T12:00:00.000Z") : null,
|
||||
createdAt: new Date(record.createdAt),
|
||||
updatedAt: new Date("2026-12-02T12:00:05.000Z"),
|
||||
lastUserMessageAt: new Date("2026-12-02T12:00:00.000Z"),
|
||||
config: { provider: record.provider, cwd: record.cwd },
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: true,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: true,
|
||||
supportsToolInvocations: true,
|
||||
},
|
||||
currentModeId: null,
|
||||
availableModes: [],
|
||||
pendingPermissions: new Map(),
|
||||
persistence: null,
|
||||
lastUsage: usage,
|
||||
labels: {},
|
||||
attention: { requiresAttention: false },
|
||||
internal: false,
|
||||
background: false,
|
||||
}) as unknown as ManagedAgent;
|
||||
|
||||
const session = createSessionForTest({
|
||||
messages,
|
||||
providerSnapshotManager: providers.manager,
|
||||
permissions: ["workspace.read"],
|
||||
agentManager: {
|
||||
getAgent: () => undefined,
|
||||
getAgentBackgroundWorkSummary: () => undefined,
|
||||
subscribe: (callback: (event: AgentManagerEvent) => void) => {
|
||||
listener = callback;
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
agentStorage: {
|
||||
get: () =>
|
||||
new Promise<StoredAgentRecord | null>((resolve) => {
|
||||
storageReads.push({ resolve });
|
||||
}),
|
||||
listAll: async () => [],
|
||||
},
|
||||
workspaceRegistry: { get: vi.fn(async () => workspace) },
|
||||
projectRegistry: { get: async () => project },
|
||||
});
|
||||
|
||||
try {
|
||||
session.updateClientCapabilities({ all_providers: true });
|
||||
await session.handleMessage({
|
||||
type: "fetch_agents_request",
|
||||
requestId: "sub-agents",
|
||||
subscribe: { subscriptionId: "agents-sub" },
|
||||
});
|
||||
messages.length = 0;
|
||||
|
||||
if (!listener) throw new Error("Agent event listener was not installed");
|
||||
|
||||
// Mirror Antigravity turn end with interleaved stream events:
|
||||
// U1 (running, usage_updated) -> S1 (timeline) -> U2 (idle) -> S2 (turn_completed) -> S3 (turn_started).
|
||||
listener({
|
||||
type: "agent_state",
|
||||
agent: makeManaged("running", "turn-1", { inputTokens: 100, outputTokens: 20 }),
|
||||
});
|
||||
listener({
|
||||
type: "agent_stream",
|
||||
agentId: record.id,
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "antigravity",
|
||||
item: { type: "assistant_message", text: "ok" },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
timestamp: "2026-12-02T12:00:04.999Z",
|
||||
});
|
||||
listener({
|
||||
type: "agent_state",
|
||||
agent: makeManaged("idle", null, { inputTokens: 100, outputTokens: 20 }),
|
||||
});
|
||||
listener({
|
||||
type: "agent_stream",
|
||||
agentId: record.id,
|
||||
event: { type: "turn_completed", provider: "antigravity", turnId: "turn-1" },
|
||||
timestamp: "2026-12-02T12:00:05.000Z",
|
||||
});
|
||||
listener({
|
||||
type: "agent_stream",
|
||||
agentId: record.id,
|
||||
event: { type: "turn_started", provider: "antigravity", turnId: "turn-2" },
|
||||
timestamp: "2026-12-02T12:00:05.001Z",
|
||||
});
|
||||
|
||||
// While the first storage read is still pending, no stream event may cut ahead.
|
||||
await expect.poll(() => storageReads.length).toBe(1);
|
||||
expect(messages.filter((m) => m.type === "agent_stream")).toEqual([]);
|
||||
|
||||
// Complete both agent_update storage reads in order.
|
||||
storageReads.shift()!.resolve(record);
|
||||
await expect.poll(() => storageReads.length).toBe(1);
|
||||
storageReads.shift()!.resolve(record);
|
||||
|
||||
const relevantMessages = () =>
|
||||
messages.filter((m) => m.type === "agent_update" || m.type === "agent_stream");
|
||||
await expect.poll(() => relevantMessages().length).toBe(5);
|
||||
|
||||
const sequence = relevantMessages().map((m) =>
|
||||
m.type === "agent_update"
|
||||
? `agent_update:${m.payload.kind === "upsert" ? `${m.payload.agent.status}:${m.payload.agent.activeTurn?.turnId ?? "null"}` : "remove"}`
|
||||
: `agent_stream:${m.payload.event.type}:${"turnId" in m.payload.event ? (m.payload.event.turnId ?? "null") : "none"}`,
|
||||
);
|
||||
|
||||
expect(sequence).toEqual([
|
||||
"agent_update:running:turn-1",
|
||||
"agent_stream:timeline:turn-1",
|
||||
"agent_update:idle:null",
|
||||
"agent_stream:turn_completed:turn-1",
|
||||
"agent_stream:turn_started:turn-2",
|
||||
]);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2468,30 +2468,35 @@ export class Session {
|
||||
"agent.session.forward_stream",
|
||||
);
|
||||
|
||||
this.forwardAgentStream(event, serializedEvent);
|
||||
|
||||
// An internal agent streams only to clients subscribed to it by id;
|
||||
// session-wide prompts would surface it everywhere.
|
||||
const internal = this.agentManager.getAgent(event.agentId)?.internal === true;
|
||||
if (event.event.type === "permission_requested" && !internal) {
|
||||
this.emit({
|
||||
type: "agent_permission_request",
|
||||
payload: {
|
||||
agentId: event.agentId,
|
||||
request: event.event.request,
|
||||
},
|
||||
});
|
||||
} else if (event.event.type === "permission_resolved") {
|
||||
// A provider event is not the outcome of whichever request is currently running.
|
||||
this.emitSubscribedEvent({
|
||||
type: "agent_permission_resolved",
|
||||
payload: {
|
||||
agentId: event.agentId,
|
||||
requestId: event.event.requestId,
|
||||
resolution: event.event.resolution,
|
||||
},
|
||||
});
|
||||
}
|
||||
const streamEventWithTimestamp =
|
||||
event.timestamp !== undefined ? event : { ...event, timestamp: new Date().toISOString() };
|
||||
this.agentUpdates.runAfterUpdates(event.agentId, () => {
|
||||
if (this.isCleanedUp) return;
|
||||
this.forwardAgentStream(streamEventWithTimestamp, serializedEvent);
|
||||
|
||||
if (event.event.type === "permission_requested" && !internal) {
|
||||
this.emit({
|
||||
type: "agent_permission_request",
|
||||
payload: {
|
||||
agentId: event.agentId,
|
||||
request: event.event.request,
|
||||
},
|
||||
});
|
||||
} else if (event.event.type === "permission_resolved") {
|
||||
// A provider event is not the outcome of whichever request is currently running.
|
||||
this.emitSubscribedEvent({
|
||||
type: "agent_permission_resolved",
|
||||
payload: {
|
||||
agentId: event.agentId,
|
||||
requestId: event.event.requestId,
|
||||
resolution: event.event.resolution,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Title updates may be applied asynchronously after agent creation.
|
||||
},
|
||||
|
||||
@@ -96,6 +96,7 @@ function makeProject(overrides?: Partial<ProjectPlacementPayload>): ProjectPlace
|
||||
function buildHarness() {
|
||||
const emitted: SessionOutboundMessage[] = [];
|
||||
const workspaceUpdates: string[] = [];
|
||||
const queuedWorkspaceUpdates: Promise<void>[] = [];
|
||||
const loggedErrors: unknown[][] = [];
|
||||
const payloadById = new Map<string, AgentSnapshotPayload>();
|
||||
const queuedPayloadBuilds: Promise<AgentSnapshotPayload>[] = [];
|
||||
@@ -136,6 +137,10 @@ function buildHarness() {
|
||||
projectByWorkspaceId.get(workspaceId) ?? null,
|
||||
emitWorkspaceUpdateForWorkspaceId: async (workspaceId) => {
|
||||
workspaceUpdates.push(workspaceId);
|
||||
const pending = queuedWorkspaceUpdates.shift();
|
||||
if (pending) {
|
||||
await pending;
|
||||
}
|
||||
},
|
||||
sequenceAgentUpdate: (payload, agent, project, agentId, includeSequence) =>
|
||||
directorySync.sequenceAgentUpdate(
|
||||
@@ -176,6 +181,9 @@ function buildHarness() {
|
||||
queuePayloadBuilds(...payloads: Promise<AgentSnapshotPayload>[]) {
|
||||
queuedPayloadBuilds.push(...payloads);
|
||||
},
|
||||
queueWorkspaceUpdates(...updates: Promise<void>[]) {
|
||||
queuedWorkspaceUpdates.push(...updates);
|
||||
},
|
||||
agentUpdates(): AgentUpdatePayload[] {
|
||||
return emitted
|
||||
.filter((message) => message.type === "agent_update")
|
||||
@@ -795,3 +803,36 @@ test("non-sync paginated subscriptions (snapshotAgentIds: null) still emit remov
|
||||
|
||||
expect(h.agentUpdates()).toEqual([{ kind: "remove", agentId: "page-2-agent" }]);
|
||||
});
|
||||
|
||||
test("does not block a subsequent agent_update behind a slow workspace update", async () => {
|
||||
const h = buildHarness();
|
||||
h.service.beginSubscription({ subscriptionId: "sub", filter: {} });
|
||||
h.service.flushBootstrapped("sub");
|
||||
|
||||
const running = makeAgentPayload({ id: "a", workspaceId: "ws-1", status: "running" });
|
||||
const idle = makeAgentPayload({ id: "a", workspaceId: "ws-1", status: "idle" });
|
||||
h.register(running);
|
||||
h.queuePayloadBuilds(Promise.resolve(running), Promise.resolve(idle));
|
||||
const slowWorkspaceUpdate = deferred<void>();
|
||||
h.queueWorkspaceUpdates(slowWorkspaceUpdate.promise);
|
||||
|
||||
const runningForward = h.service.forwardLiveAgent(h.managed("a"));
|
||||
const idleForward = h.service.forwardLiveAgent(h.managed("a"));
|
||||
|
||||
// Both agent_update emissions complete while the first workspace broadcast is still in flight.
|
||||
await expect
|
||||
.poll(() => h.agentUpdates().map((update) => update.kind === "upsert" && update.agent.status))
|
||||
.toEqual(["running", "idle"]);
|
||||
|
||||
let flushed = false;
|
||||
const flushPromise = (async () => {
|
||||
await h.service.flushPendingUpdates();
|
||||
flushed = true;
|
||||
})();
|
||||
await Promise.resolve();
|
||||
expect(flushed).toBe(false);
|
||||
|
||||
slowWorkspaceUpdate.resolve();
|
||||
await Promise.all([runningForward, idleForward, flushPromise]);
|
||||
expect(flushed).toBe(true);
|
||||
});
|
||||
|
||||
@@ -62,6 +62,12 @@ export interface AgentUpdatesService {
|
||||
removeAgent(agentId: string): Promise<void>;
|
||||
/** Await all currently queued agent update emissions so callers can order follow-up broadcasts after them. */
|
||||
flushPendingUpdates(): Promise<void>;
|
||||
/**
|
||||
* Runs a per-agent outbound step (such as forwarding an `agent_stream` event) in strict FIFO
|
||||
* order with queued `agent_update` frames for that agent. Runs synchronously when nothing is
|
||||
* queued for the agent, and never waits on workspace broadcasts.
|
||||
*/
|
||||
runAfterUpdates(agentId: string, action: () => void): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
@@ -182,6 +188,7 @@ function agentUpdateTargetId(update: AgentUpdatePayload): string {
|
||||
export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentUpdatesService {
|
||||
const subscriptions = new Map<string, AgentUpdatesSubscriptionState>();
|
||||
const liveAgentUpdateTails = new Map<string, Promise<void>>();
|
||||
const pendingWorkspaceUpdates = new Set<Promise<void>>();
|
||||
const sequence = <T extends AgentUpdatePayload>(
|
||||
sub: AgentUpdatesSubscriptionState,
|
||||
payload: T,
|
||||
@@ -344,13 +351,22 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function emitAgentUpdate(
|
||||
workspaceId: string | undefined,
|
||||
projectPayload?: () => AgentSnapshotPayload | Promise<AgentSnapshotPayload>,
|
||||
function triggerWorkspaceUpdate(workspaceId: string): Promise<void> {
|
||||
const update = deps.emitWorkspaceUpdateForWorkspaceId(workspaceId).catch((error) => {
|
||||
deps.logger.error({ err: error }, "Failed to emit agent update");
|
||||
});
|
||||
pendingWorkspaceUpdates.add(update);
|
||||
void update.finally(() => {
|
||||
pendingWorkspaceUpdates.delete(update);
|
||||
});
|
||||
return update;
|
||||
}
|
||||
|
||||
async function emitAgentPayload(
|
||||
projectPayload: () => AgentSnapshotPayload | Promise<AgentSnapshotPayload>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (projectPayload && hasSubscription()) await publishPayload(await projectPayload());
|
||||
if (workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId);
|
||||
if (hasSubscription()) await publishPayload(await projectPayload());
|
||||
} catch (error) {
|
||||
deps.logger.error({ err: error }, "Failed to emit agent update");
|
||||
}
|
||||
@@ -371,23 +387,40 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
return next;
|
||||
}
|
||||
|
||||
function forwardWithWorkspaceUpdate(
|
||||
agentId: string,
|
||||
workspaceId: string | undefined,
|
||||
projectPayload: () => AgentSnapshotPayload | Promise<AgentSnapshotPayload>,
|
||||
): Promise<void> {
|
||||
if (!hasSubscription()) {
|
||||
return workspaceId ? triggerWorkspaceUpdate(workspaceId) : Promise.resolve();
|
||||
}
|
||||
// Keep workspace broadcasts off the per-agent queue so a slow workspace rebuild cannot
|
||||
// stall a subsequent agent_update (for example, running -> idle) or agent_stream frame.
|
||||
let workspaceUpdate: Promise<void> | null = null;
|
||||
const agentUpdate = enqueueAgentUpdate(agentId, async () => {
|
||||
await emitAgentPayload(projectPayload);
|
||||
if (workspaceId) {
|
||||
workspaceUpdate = triggerWorkspaceUpdate(workspaceId);
|
||||
}
|
||||
});
|
||||
return agentUpdate.then(() => workspaceUpdate ?? undefined);
|
||||
}
|
||||
|
||||
function forwardLiveAgent(agent: ManagedAgent): Promise<void> {
|
||||
if (!hasSubscription()) {
|
||||
const workspaceId = agent.workspaceId;
|
||||
return workspaceId
|
||||
? enqueueAgentUpdate(agent.id, () => emitAgentUpdate(workspaceId))
|
||||
: Promise.resolve();
|
||||
return agent.workspaceId ? triggerWorkspaceUpdate(agent.workspaceId) : Promise.resolve();
|
||||
}
|
||||
const payload = toAgentPayload(agent);
|
||||
return enqueueAgentUpdate(payload.id, () =>
|
||||
emitAgentUpdate(payload.workspaceId, () => deps.enrichAgentPayload(payload)),
|
||||
return forwardWithWorkspaceUpdate(payload.id, payload.workspaceId, () =>
|
||||
deps.enrichAgentPayload(payload),
|
||||
);
|
||||
}
|
||||
|
||||
function forwardStoredAgent(record: StoredAgentRecord): Promise<void> {
|
||||
if (!hasSubscription() && !record.workspaceId) return Promise.resolve();
|
||||
return enqueueAgentUpdate(record.id, () =>
|
||||
emitAgentUpdate(record.workspaceId, () => deps.buildStoredAgentPayload(record)),
|
||||
return forwardWithWorkspaceUpdate(record.id, record.workspaceId, () =>
|
||||
deps.buildStoredAgentPayload(record),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -400,10 +433,23 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
}
|
||||
|
||||
async function flushPendingUpdates(): Promise<void> {
|
||||
if (liveAgentUpdateTails.size === 0) return;
|
||||
// Await a single snapshot of currently queued tails so pre-barrier updates settle
|
||||
// ahead of workspace broadcasts without starving on unrelated active streams.
|
||||
await Promise.allSettled(liveAgentUpdateTails.values());
|
||||
if (liveAgentUpdateTails.size === 0 && pendingWorkspaceUpdates.size === 0) return;
|
||||
// Await currently queued agent updates first (which may trigger workspace broadcasts),
|
||||
// then settle any pending workspace updates.
|
||||
if (liveAgentUpdateTails.size > 0) {
|
||||
await Promise.allSettled(liveAgentUpdateTails.values());
|
||||
}
|
||||
if (pendingWorkspaceUpdates.size > 0) {
|
||||
await Promise.allSettled(pendingWorkspaceUpdates);
|
||||
}
|
||||
}
|
||||
|
||||
function runAfterUpdates(agentId: string, action: () => void): void {
|
||||
if (!liveAgentUpdateTails.has(agentId)) {
|
||||
action();
|
||||
return;
|
||||
}
|
||||
void enqueueAgentUpdate(agentId, action);
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
@@ -421,6 +467,7 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
emitStoredRecord,
|
||||
removeAgent,
|
||||
flushPendingUpdates,
|
||||
runAfterUpdates,
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
|
||||
+130
-1
@@ -1,6 +1,7 @@
|
||||
import { resolve } from "node:path";
|
||||
import type pino from "pino";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { FileObserver } from "../../file-explorer/observer.js";
|
||||
import type { WorkspaceDescriptorPayload } from "../../messages.js";
|
||||
import type {
|
||||
WorkspaceGitListener,
|
||||
@@ -49,7 +50,9 @@ function flushMicrotasks(): Promise<void> {
|
||||
return new Promise((done) => setImmediate(done));
|
||||
}
|
||||
|
||||
function buildHarness(opts: { emitCwdRejects?: boolean } = {}) {
|
||||
function buildHarness(
|
||||
opts: { emitCwdRejects?: boolean; configWatchRejects?: boolean; configExists?: boolean } = {},
|
||||
) {
|
||||
const listeners = new Map<string, WorkspaceGitListener>();
|
||||
const registerCalls: string[] = [];
|
||||
const unsubscribeCalls: string[] = [];
|
||||
@@ -57,6 +60,30 @@ function buildHarness(opts: { emitCwdRejects?: boolean } = {}) {
|
||||
const statusCalls: Array<{ cwd: string; branch: string | null }> = [];
|
||||
const branchChanges: Array<[string, string | null, string | null]> = [];
|
||||
const warnCalls: unknown[][] = [];
|
||||
const configWatchCalls: Array<{ cwd: string; path: string }> = [];
|
||||
const configUnwatchCalls: string[] = [];
|
||||
const configListeners = new Map<string, () => void>();
|
||||
const pendingConfigWatches: Array<() => void> = [];
|
||||
|
||||
// paseo.json watches stay pending until a test calls resolveConfigWatches(), so a test
|
||||
// controls when each watch starts.
|
||||
const configObserver: Pick<FileObserver, "subscribe"> = {
|
||||
async subscribe(input, listener) {
|
||||
configWatchCalls.push(input);
|
||||
if (opts.configWatchRejects) throw new Error("watch boom");
|
||||
await new Promise<void>((done) => pendingConfigWatches.push(done));
|
||||
configListeners.set(input.cwd, () => listener({ status: "missing", ...input }));
|
||||
return {
|
||||
initial: opts.configExists
|
||||
? { status: "ready", ...input, size: 2, modifiedAt: "2026-01-01T00:00:00.000Z" }
|
||||
: { status: "missing", ...input },
|
||||
unsubscribe() {
|
||||
configUnwatchCalls.push(input.cwd);
|
||||
configListeners.delete(input.cwd);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const workspaceGitService: Pick<WorkspaceGitService, "registerWorkspace"> = {
|
||||
registerWorkspace({ cwd }, listener) {
|
||||
@@ -85,6 +112,7 @@ function buildHarness(opts: { emitCwdRejects?: boolean } = {}) {
|
||||
onBranchChanged: (workspaceId, oldBranch, newBranch) => {
|
||||
branchChanges.push([workspaceId, oldBranch, newBranch]);
|
||||
},
|
||||
configObserver,
|
||||
logger: { warn: (...args: unknown[]) => warnCalls.push(args) } as unknown as pino.Logger,
|
||||
});
|
||||
|
||||
@@ -96,9 +124,25 @@ function buildHarness(opts: { emitCwdRejects?: boolean } = {}) {
|
||||
listener(makeSnapshot(cwd, branch));
|
||||
}
|
||||
|
||||
function changeConfig(cwd: string): void {
|
||||
const listener = configListeners.get(cwd);
|
||||
if (!listener) {
|
||||
throw new Error(`no paseo.json listener registered for ${cwd}`);
|
||||
}
|
||||
listener();
|
||||
}
|
||||
|
||||
function resolveConfigWatches(): void {
|
||||
for (const done of pendingConfigWatches.splice(0)) done();
|
||||
}
|
||||
|
||||
return {
|
||||
service,
|
||||
emitSnapshot,
|
||||
changeConfig,
|
||||
resolveConfigWatches,
|
||||
configWatchCalls,
|
||||
configUnwatchCalls,
|
||||
registerCalls,
|
||||
unsubscribeCalls,
|
||||
emitCwdCalls,
|
||||
@@ -342,3 +386,88 @@ describe("teardown", () => {
|
||||
expect(h.branchChanges).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("paseo.json observation", () => {
|
||||
const directory = (id: string, workspaceDirectory: string) =>
|
||||
makeDescriptor({
|
||||
id,
|
||||
workspaceDirectory,
|
||||
projectKind: "directory",
|
||||
workspaceKind: "directory",
|
||||
});
|
||||
|
||||
test("watches paseo.json for Git and directory workspaces and refreshes on start and change", async () => {
|
||||
const h = buildHarness({ configExists: true });
|
||||
h.service.syncObservers([
|
||||
directory("ws1", WS1),
|
||||
makeDescriptor({ id: "ws2", workspaceDirectory: WS2 }),
|
||||
]);
|
||||
expect(h.configWatchCalls).toEqual([
|
||||
{ cwd: WS1, path: "paseo.json" },
|
||||
{ cwd: WS2, path: "paseo.json" },
|
||||
]);
|
||||
|
||||
h.resolveConfigWatches();
|
||||
await flushMicrotasks();
|
||||
expect(h.emitCwdCalls).toEqual([WS1, WS2]);
|
||||
|
||||
h.changeConfig(WS1);
|
||||
await flushMicrotasks();
|
||||
expect(h.emitCwdCalls).toEqual([WS1, WS2, WS1]);
|
||||
});
|
||||
|
||||
test("shares one watch per directory until its last workspace is removed", async () => {
|
||||
const h = buildHarness();
|
||||
h.service.syncObservers([directory("ws1", WS1), directory("ws2", WS1)]);
|
||||
h.service.syncObservers([directory("ws1", WS1)]);
|
||||
h.resolveConfigWatches();
|
||||
await flushMicrotasks();
|
||||
expect(h.configWatchCalls).toHaveLength(1);
|
||||
expect(h.emitCwdCalls).toEqual([]);
|
||||
|
||||
h.service.removeForWorkspaceId("ws1");
|
||||
expect(h.configUnwatchCalls).toEqual([]);
|
||||
h.service.removeForWorkspaceId("ws2");
|
||||
expect(h.configUnwatchCalls).toEqual([WS1]);
|
||||
});
|
||||
|
||||
test("moves the watch when a workspace changes directory", async () => {
|
||||
const h = buildHarness();
|
||||
h.service.syncObservers([directory("ws1", WS1)]);
|
||||
h.resolveConfigWatches();
|
||||
await flushMicrotasks();
|
||||
h.service.syncObservers([directory("ws1", WS2)]);
|
||||
expect(h.configUnwatchCalls).toEqual([WS1]);
|
||||
expect(h.configWatchCalls.map((call) => call.cwd)).toEqual([WS1, WS2]);
|
||||
});
|
||||
|
||||
test("releases a watch removed before its subscription resolves", async () => {
|
||||
const h = buildHarness();
|
||||
h.service.syncObservers([directory("ws1", WS1)]);
|
||||
h.service.removeForWorkspaceId("ws1");
|
||||
expect(h.configUnwatchCalls).toEqual([]);
|
||||
|
||||
h.resolveConfigWatches();
|
||||
await flushMicrotasks();
|
||||
expect(h.configUnwatchCalls).toEqual([WS1]);
|
||||
});
|
||||
|
||||
test("reconcile and dispose release watches", async () => {
|
||||
const h = buildHarness();
|
||||
h.service.syncObservers([directory("ws1", WS1), directory("ws2", WS2)]);
|
||||
h.resolveConfigWatches();
|
||||
await flushMicrotasks();
|
||||
|
||||
h.service.reconcileObservers([directory("ws2", WS2)]);
|
||||
expect(h.configUnwatchCalls).toEqual([WS1]);
|
||||
h.service.dispose();
|
||||
expect(h.configUnwatchCalls).toEqual([WS1, WS2]);
|
||||
});
|
||||
|
||||
test("logs a failed watch without failing the sync", async () => {
|
||||
const h = buildHarness({ configWatchRejects: true });
|
||||
expect(() => h.service.syncObservers([directory("ws1", WS1)])).not.toThrow();
|
||||
await flushMicrotasks();
|
||||
expect(h.warnCalls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
+82
-5
@@ -1,5 +1,7 @@
|
||||
import { resolve } from "node:path";
|
||||
import type pino from "pino";
|
||||
import { PASEO_CONFIG_FILE_NAME } from "../../../utils/paseo-config-file.js";
|
||||
import { workspaceFileObserver, type FileObserver } from "../../file-explorer/observer.js";
|
||||
import type { WorkspaceDescriptorPayload } from "../../messages.js";
|
||||
import type {
|
||||
WorkspaceGitRuntimeSnapshot,
|
||||
@@ -32,6 +34,9 @@ export interface WorkspaceGitObserverMetrics {
|
||||
* Branch changes reach `onBranchChanged` from two paths that share `lastBranchName`: the
|
||||
* on-disk snapshot listener (handleBranchSnapshot) and the workspace-emit loop's Git runtime
|
||||
* projection (recordDescriptorState). Both stay inside this module so the shared state is coherent.
|
||||
*
|
||||
* Every workspace, Git or not, also watches its paseo.json and refreshes its workspace cards on
|
||||
* change, so the Scripts menu follows edits made outside Paseo.
|
||||
*/
|
||||
export interface WorkspaceGitObserverService {
|
||||
syncObservers(workspaces: Iterable<WorkspaceDescriptorPayload>): void;
|
||||
@@ -56,6 +61,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
oldBranch: string | null,
|
||||
newBranch: string | null,
|
||||
) => void;
|
||||
configObserver?: Pick<FileObserver, "subscribe">;
|
||||
logger: pino.Logger;
|
||||
}): WorkspaceGitObserverService {
|
||||
const {
|
||||
@@ -63,12 +69,72 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
emitWorkspaceUpdateForCwd,
|
||||
emitStatusUpdate,
|
||||
onBranchChanged,
|
||||
configObserver = workspaceFileObserver,
|
||||
logger,
|
||||
} = deps;
|
||||
|
||||
const watchTargets = new Map<string, WorkspaceGitWatchTarget>();
|
||||
const workspaceStates = new Map<string, WorkspaceGitWatchState>();
|
||||
const subscriptions = new Map<string, () => void>();
|
||||
const configWatches = new Map<string, { workspaceIds: Set<string>; release: () => void }>();
|
||||
const configCwds = new Map<string, string>();
|
||||
|
||||
function observeConfig(cwd: string, workspaceId: string): void {
|
||||
const currentCwd = configCwds.get(workspaceId);
|
||||
if (currentCwd === cwd) return;
|
||||
if (currentCwd !== undefined) unobserveConfig(workspaceId);
|
||||
configCwds.set(workspaceId, cwd);
|
||||
const existing = configWatches.get(cwd);
|
||||
if (existing) {
|
||||
existing.workspaceIds.add(workspaceId);
|
||||
return;
|
||||
}
|
||||
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
let released = false;
|
||||
configWatches.set(cwd, {
|
||||
workspaceIds: new Set([workspaceId]),
|
||||
release: () => {
|
||||
released = true;
|
||||
unsubscribe?.();
|
||||
},
|
||||
});
|
||||
const refresh = () => {
|
||||
void emitWorkspaceUpdateForCwd(cwd).catch((error) => {
|
||||
logger.warn({ err: error, cwd }, "Failed to emit workspace update after paseo.json change");
|
||||
});
|
||||
};
|
||||
void (async () => {
|
||||
try {
|
||||
const subscription = await configObserver.subscribe(
|
||||
{ cwd, path: PASEO_CONFIG_FILE_NAME },
|
||||
refresh,
|
||||
);
|
||||
if (released) {
|
||||
subscription.unsubscribe();
|
||||
return;
|
||||
}
|
||||
unsubscribe = subscription.unsubscribe;
|
||||
// Catch an edit made between the client's snapshot and the watch starting.
|
||||
// shortcut: a removal in that window stays stale until the next edit; drop the check if that matters.
|
||||
if (subscription.initial.status !== "missing") refresh();
|
||||
} catch (error) {
|
||||
logger.warn({ err: error, cwd }, "Failed to observe paseo.json");
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
function unobserveConfig(workspaceId: string): void {
|
||||
const cwd = configCwds.get(workspaceId);
|
||||
if (cwd === undefined) return;
|
||||
configCwds.delete(workspaceId);
|
||||
const watch = configWatches.get(cwd);
|
||||
watch?.workspaceIds.delete(workspaceId);
|
||||
if (watch?.workspaceIds.size === 0) {
|
||||
configWatches.delete(cwd);
|
||||
watch.release();
|
||||
}
|
||||
}
|
||||
|
||||
function rememberDescriptorState(
|
||||
workspaceId: string,
|
||||
@@ -95,7 +161,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
subscriptions.delete(normalizedCwd);
|
||||
}
|
||||
|
||||
function removeForWorkspaceId(workspaceId: string): void {
|
||||
function removeGitObservation(workspaceId: string): void {
|
||||
const state = workspaceStates.get(workspaceId);
|
||||
if (!state) {
|
||||
return;
|
||||
@@ -108,6 +174,11 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
}
|
||||
}
|
||||
|
||||
function removeForWorkspaceId(workspaceId: string): void {
|
||||
unobserveConfig(workspaceId);
|
||||
removeGitObservation(workspaceId);
|
||||
}
|
||||
|
||||
function handleBranchSnapshot(cwd: string, branchName: string | null): void {
|
||||
const target = watchTargets.get(resolve(cwd));
|
||||
if (!target) {
|
||||
@@ -130,12 +201,13 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
|
||||
function syncObserver(cwd: string, options: { isGit: boolean; workspaceId: string }): void {
|
||||
const normalizedCwd = resolve(cwd);
|
||||
observeConfig(normalizedCwd, options.workspaceId);
|
||||
const currentState = workspaceStates.get(options.workspaceId);
|
||||
if (currentState && currentState.cwd !== normalizedCwd) {
|
||||
removeForWorkspaceId(options.workspaceId);
|
||||
removeGitObservation(options.workspaceId);
|
||||
}
|
||||
if (!options.isGit) {
|
||||
removeForWorkspaceId(options.workspaceId);
|
||||
removeGitObservation(options.workspaceId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -168,7 +240,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
emitStatusUpdate(normalizedCwd, snapshot);
|
||||
});
|
||||
} catch (error) {
|
||||
removeForWorkspaceId(options.workspaceId);
|
||||
removeGitObservation(options.workspaceId);
|
||||
throw error;
|
||||
}
|
||||
subscriptions.set(normalizedCwd, subscription.unsubscribe);
|
||||
@@ -187,7 +259,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
return {
|
||||
reconcileObservers(workspaces) {
|
||||
const retained = new Map([...workspaces].map((workspace) => [workspace.id, workspace]));
|
||||
for (const workspaceId of workspaceStates.keys()) {
|
||||
for (const workspaceId of new Set([...workspaceStates.keys(), ...configCwds.keys()])) {
|
||||
if (!retained.has(workspaceId)) removeForWorkspaceId(workspaceId);
|
||||
}
|
||||
for (const workspace of retained.values()) {
|
||||
@@ -228,6 +300,11 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
subscriptions.clear();
|
||||
watchTargets.clear();
|
||||
workspaceStates.clear();
|
||||
for (const watch of configWatches.values()) {
|
||||
watch.release();
|
||||
}
|
||||
configWatches.clear();
|
||||
configCwds.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -16,12 +16,15 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(__dirname, "..");
|
||||
|
||||
function usageAndExit(code = 1) {
|
||||
process.stderr.write("Usage: node scripts/reconcile-release.mjs --tag <vX.Y.Z[-beta.N]>\n");
|
||||
process.stderr.write(
|
||||
"Usage: node scripts/reconcile-release.mjs (--ref <git-ref> | --tag <vX.Y.Z[-beta.N]>)\n",
|
||||
);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
let tag = "";
|
||||
let ref = "";
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--tag") {
|
||||
@@ -29,15 +32,20 @@ function parseArgs(argv) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--ref") {
|
||||
ref = argv[index + 1] ?? "";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
usageAndExit(0);
|
||||
}
|
||||
usageAndExit(1);
|
||||
}
|
||||
if (!tag) {
|
||||
if (Boolean(tag) === Boolean(ref)) {
|
||||
usageAndExit(1);
|
||||
}
|
||||
return { tag };
|
||||
return ref ? { ref } : { tag };
|
||||
}
|
||||
|
||||
function splitRawEntries(content) {
|
||||
@@ -60,12 +68,12 @@ function safeParseVersion(version) {
|
||||
}
|
||||
}
|
||||
|
||||
export function mergeChangelogEntry(mainContent, tagContent, targetVersion) {
|
||||
export function mergeChangelogEntry(mainContent, releaseContent, targetVersion) {
|
||||
const target = parseReleaseVersion(targetVersion);
|
||||
const tagParsed = splitRawEntries(tagContent);
|
||||
const taggedBlock = tagParsed.blocks.find((block) => block.version === target.version);
|
||||
if (!taggedBlock) {
|
||||
throw new Error(`No changelog entry found for ${target.version} in tagged changelog.`);
|
||||
const releaseParsed = splitRawEntries(releaseContent);
|
||||
const releaseBlock = releaseParsed.blocks.find((block) => block.version === target.version);
|
||||
if (!releaseBlock) {
|
||||
throw new Error(`No changelog entry found for ${target.version} in release changelog.`);
|
||||
}
|
||||
|
||||
const mainParsed = splitRawEntries(mainContent);
|
||||
@@ -114,7 +122,7 @@ export function mergeChangelogEntry(mainContent, tagContent, targetVersion) {
|
||||
insertIndex = kept.length;
|
||||
}
|
||||
|
||||
kept.splice(insertIndex, 0, taggedBlock);
|
||||
kept.splice(insertIndex, 0, releaseBlock);
|
||||
|
||||
const parts = [];
|
||||
if (mainParsed.preamble.length > 0) {
|
||||
@@ -126,15 +134,15 @@ export function mergeChangelogEntry(mainContent, tagContent, targetVersion) {
|
||||
return `${parts.join("\n\n")}\n`;
|
||||
}
|
||||
|
||||
function defaultVerifyTag(tag, cwd) {
|
||||
execFileSync("git", ["rev-parse", "--verify", `refs/tags/${tag}^{commit}`], {
|
||||
function defaultVerifyRef(ref, cwd) {
|
||||
execFileSync("git", ["rev-parse", "--verify", `${ref}^{commit}`], {
|
||||
cwd,
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
function defaultReadTagFile(tag, filePath, cwd) {
|
||||
return execFileSync("git", ["show", `${tag}:${filePath}`], {
|
||||
function defaultReadRefFile(ref, filePath, cwd) {
|
||||
return execFileSync("git", ["show", `${ref}:${filePath}`], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
});
|
||||
@@ -169,23 +177,29 @@ function lockfileMatchesVersion(cwd, rootPackage, version) {
|
||||
|
||||
export function reconcileRelease(options, deps = {}) {
|
||||
const cwd = options.cwd ?? rootDir;
|
||||
const tag = normalizeReleaseTag(options.tag);
|
||||
const version = tag.slice(1);
|
||||
const parsed = parseReleaseVersion(version);
|
||||
if (Boolean(options.ref) === Boolean(options.tag)) {
|
||||
throw new Error("Pass exactly one of --ref or --tag.");
|
||||
}
|
||||
// A release tag and a release branch are both git refs; everything below reads from `ref`.
|
||||
const tag = options.tag ? normalizeReleaseTag(options.tag) : null;
|
||||
const ref = tag ? `refs/tags/${tag}` : options.ref;
|
||||
|
||||
const verifyTag = deps.verifyTag ?? ((targetTag) => defaultVerifyTag(targetTag, cwd));
|
||||
const readTagFile =
|
||||
deps.readTagFile ?? ((targetTag, filePath) => defaultReadTagFile(targetTag, filePath, cwd));
|
||||
const verifyRef = deps.verifyRef ?? ((target) => defaultVerifyRef(target, cwd));
|
||||
const readRefFile =
|
||||
deps.readRefFile ?? ((target, filePath) => defaultReadRefFile(target, filePath, cwd));
|
||||
const runNpm = deps.runNpm ?? ((args) => defaultRunNpm(args, cwd));
|
||||
const getFdroidVersionCodes = deps.getFdroidVersionCodes ?? defaultGetFdroidVersionCodes;
|
||||
|
||||
verifyTag(tag);
|
||||
verifyRef(ref);
|
||||
|
||||
const version = tag ? tag.slice(1) : JSON.parse(readRefFile(ref, "package.json")).version;
|
||||
const parsed = parseReleaseVersion(version);
|
||||
|
||||
for (const changelogFile of ["CHANGELOG.md", "CHANGELOG.zh-CN.md"]) {
|
||||
const targetPath = path.join(cwd, changelogFile);
|
||||
const mainContent = readFileSync(targetPath, "utf8");
|
||||
const tagContent = readTagFile(tag, changelogFile);
|
||||
const merged = mergeChangelogEntry(mainContent, tagContent, version);
|
||||
const refContent = readRefFile(ref, changelogFile);
|
||||
const merged = mergeChangelogEntry(mainContent, refContent, version);
|
||||
writeFileSync(targetPath, merged);
|
||||
}
|
||||
|
||||
@@ -200,7 +214,7 @@ export function reconcileRelease(options, deps = {}) {
|
||||
"changelogs",
|
||||
`${versionCode}.txt`,
|
||||
);
|
||||
const content = readTagFile(tag, relativePath.replaceAll("\\", "/"));
|
||||
const content = readRefFile(ref, relativePath.replaceAll("\\", "/"));
|
||||
const destination = path.join(cwd, relativePath);
|
||||
mkdirSync(path.dirname(destination), { recursive: true });
|
||||
writeFileSync(destination, content);
|
||||
@@ -232,7 +246,7 @@ export function reconcileRelease(options, deps = {}) {
|
||||
console.log(`Kept main version at ${currentMainVersion} (newer than or equal to ${version}).`);
|
||||
}
|
||||
|
||||
return { tag, version, versionUpdated, fdroidFiles };
|
||||
return { ref, version, versionUpdated, fdroidFiles };
|
||||
}
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
|
||||
@@ -144,13 +144,13 @@ test("reconcileRelease updates changelogs, F-Droid files, and versions only when
|
||||
{ abi: "armeabi-v7a", versionCode: 160031 },
|
||||
{ abi: "arm64-v8a", versionCode: 160032 },
|
||||
],
|
||||
readTagFile(_tag, filePath) {
|
||||
readRefFile(_ref, filePath) {
|
||||
if (!tagFiles.has(filePath)) {
|
||||
throw new Error(`Missing ${filePath}`);
|
||||
}
|
||||
return tagFiles.get(filePath);
|
||||
},
|
||||
verifyTag: () => {},
|
||||
verifyRef: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
@@ -189,10 +189,10 @@ test("reconcileRelease updates changelogs, F-Droid files, and versions only when
|
||||
{ tag: "v0.17.0", cwd: dir },
|
||||
{
|
||||
getFdroidVersionCodes: () => [{ abi: "armeabi-v7a", versionCode: 170001 }],
|
||||
readTagFile(_tag, filePath) {
|
||||
readRefFile(_ref, filePath) {
|
||||
return tagFiles.get(filePath);
|
||||
},
|
||||
verifyTag: () => {},
|
||||
verifyRef: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
@@ -249,8 +249,8 @@ test("reconcileRelease retries version sync and lockfile install when a prior ru
|
||||
const result = reconcileRelease(
|
||||
{ tag: "v0.17.0-beta.2", cwd: dir },
|
||||
{
|
||||
readTagFile: (_tag, filePath) => tagFiles.get(filePath),
|
||||
verifyTag: () => {},
|
||||
readRefFile: (_ref, filePath) => tagFiles.get(filePath),
|
||||
verifyRef: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
if (args[1] === "release:prepare") {
|
||||
@@ -274,8 +274,8 @@ test("reconcileRelease retries version sync and lockfile install when a prior ru
|
||||
const idempotent = reconcileRelease(
|
||||
{ tag: "v0.17.0-beta.2", cwd: dir },
|
||||
{
|
||||
readTagFile: (_tag, filePath) => tagFiles.get(filePath),
|
||||
verifyTag: () => {},
|
||||
readRefFile: (_ref, filePath) => tagFiles.get(filePath),
|
||||
verifyRef: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
@@ -287,3 +287,109 @@ test("reconcileRelease retries version sync and lockfile install when a prior ru
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeRefDeps(dir, refFiles, calls = {}) {
|
||||
return {
|
||||
getFdroidVersionCodes: () => [{ abi: "arm64-v8a", versionCode: 170002 }],
|
||||
verifyRef(ref) {
|
||||
calls.verified = ref;
|
||||
},
|
||||
readRefFile(ref, filePath) {
|
||||
calls.reads = [...(calls.reads ?? []), `${ref}:${filePath}`];
|
||||
if (!refFiles.has(filePath)) {
|
||||
throw new Error(`Missing ${filePath}`);
|
||||
}
|
||||
return refFiles.get(filePath);
|
||||
},
|
||||
runNpm(args) {
|
||||
calls.npm = [...(calls.npm ?? []), args];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function writeMainCheckout(dir) {
|
||||
writeFileSync(path.join(dir, "CHANGELOG.md"), MAIN_CHANGELOG_WITH_BETA);
|
||||
writeFileSync(
|
||||
path.join(dir, "CHANGELOG.zh-CN.md"),
|
||||
"# Changelog\n\n## 0.17.0-beta.1 - 2026-11-19\n\n- 旧内容\n",
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(dir, "package.json"),
|
||||
`${JSON.stringify({ name: "paseo", version: "0.17.0-beta.1" }, null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
test("reconcileRelease reads a beta release branch ref without any tag", () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "reconcile-ref-beta-"));
|
||||
try {
|
||||
writeMainCheckout(dir);
|
||||
const refFiles = new Map([
|
||||
["package.json", `${JSON.stringify({ name: "paseo", version: "0.17.0-beta.2" })}\n`],
|
||||
["CHANGELOG.md", "# Changelog\n\n## 0.17.0-beta.2 - 2026-11-21\n\n- Beta 2\n"],
|
||||
["CHANGELOG.zh-CN.md", "# Changelog\n\n## 0.17.0-beta.2 - 2026-11-21\n\n- 测试版 2\n"],
|
||||
]);
|
||||
const calls = {};
|
||||
|
||||
const result = reconcileRelease(
|
||||
{ ref: "origin/release/v0.17.0-beta.2", cwd: dir },
|
||||
makeRefDeps(dir, refFiles, calls),
|
||||
);
|
||||
|
||||
assert.equal(calls.verified, "origin/release/v0.17.0-beta.2");
|
||||
assert.equal(result.version, "0.17.0-beta.2");
|
||||
assert.equal(result.versionUpdated, true);
|
||||
assert.deepEqual(result.fdroidFiles, []);
|
||||
assert.deepEqual(calls.npm, [
|
||||
["run", "version:sync-internal"],
|
||||
["run", "release:prepare"],
|
||||
]);
|
||||
assert.match(
|
||||
readFileSync(path.join(dir, "CHANGELOG.md"), "utf8"),
|
||||
/^# Changelog\n\n## 0\.17\.0-beta\.2 - 2026-11-21\n/,
|
||||
);
|
||||
assert.doesNotMatch(readFileSync(path.join(dir, "CHANGELOG.md"), "utf8"), /beta\.1/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reconcileRelease reads a stable release branch ref including F-Droid changelogs", () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "reconcile-ref-stable-"));
|
||||
try {
|
||||
writeMainCheckout(dir);
|
||||
const refFiles = new Map([
|
||||
["package.json", `${JSON.stringify({ name: "paseo", version: "0.17.0" })}\n`],
|
||||
["CHANGELOG.md", "# Changelog\n\n## 0.17.0 - 2026-11-22\n\n- Stable\n"],
|
||||
["CHANGELOG.zh-CN.md", "# Changelog\n\n## 0.17.0 - 2026-11-22\n\n- 稳定版\n"],
|
||||
["fastlane/metadata/android/en-US/changelogs/170002.txt", "Stable notes\n"],
|
||||
]);
|
||||
const calls = {};
|
||||
|
||||
const result = reconcileRelease(
|
||||
{ ref: "release/v0.17.0", cwd: dir },
|
||||
makeRefDeps(dir, refFiles, calls),
|
||||
);
|
||||
|
||||
assert.equal(calls.verified, "release/v0.17.0");
|
||||
assert.equal(result.version, "0.17.0");
|
||||
assert.equal(result.versionUpdated, true);
|
||||
assert.deepEqual(result.fdroidFiles, [
|
||||
path.join("fastlane", "metadata", "android", "en-US", "changelogs", "170002.txt"),
|
||||
]);
|
||||
assert.equal(
|
||||
readFileSync(path.join(dir, "fastlane/metadata/android/en-US/changelogs/170002.txt"), "utf8"),
|
||||
"Stable notes\n",
|
||||
);
|
||||
assert.ok(calls.reads.every((read) => read.startsWith("release/v0.17.0:")));
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reconcileRelease requires exactly one of ref or tag", () => {
|
||||
assert.throws(() => reconcileRelease({}), /exactly one of --ref or --tag/);
|
||||
assert.throws(
|
||||
() => reconcileRelease({ ref: "release/v0.17.0", tag: "v0.17.0" }),
|
||||
/exactly one of --ref or --tag/,
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user