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 |
+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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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