mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-02 21:26:57 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0697e17877 | ||
|
|
1645ca5f78 | ||
|
|
c478bcfe8a |
+3
-5
@@ -216,11 +216,9 @@ its own.
|
||||
grew once its data arrived left the menu clipped, or hanging over its anchor, until it moved
|
||||
again. `AnchoredSurface` plays the same keyframes through the Web Animations API on web, which
|
||||
leaves no inline style; native keeps the Reanimated `Keyframe`.
|
||||
- **Animate only once placed.** The entering animation must run at the final position, not end
|
||||
unseen at the off-screen measuring position. Native remounts the surface when its position
|
||||
resolves, because Reanimated's `entering` runs only on mount. Web keeps the surface mounted and
|
||||
starts its Web Animations entering animation on placement, so a popover's content mounts once
|
||||
per open.
|
||||
- **Animate only once placed.** `AnchoredSurface` remounts the surface when its position resolves,
|
||||
so the entering animation runs at the final position rather than ending unseen at the
|
||||
off-screen measuring position.
|
||||
- **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is
|
||||
rarely the height of the page before it. A fill page is the one exception.
|
||||
- **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds
|
||||
|
||||
+3
-7
@@ -257,13 +257,9 @@ Do not put any other code modules in the plugin root.
|
||||
|
||||
Shared files import contract helpers and types from `@getpaseo/plugin`. Server handler files import
|
||||
`PluginHandlerContext` from `@getpaseo/plugin/server`. Client files import Paseo UI from
|
||||
`@getpaseo/plugin/client/ui`. The module provides host-rendered `Icon` and `ProviderIcon`
|
||||
components. `Icon` draws a Lucide name from the client's installed icon set, or any `PluginIcon`
|
||||
through its `icon` prop; an unknown name or unsafe SVG renders nothing so it cannot break the
|
||||
plugin surface. `ProviderIcon` resolves a built-in, catalog, or host-scoped plugin provider icon,
|
||||
defaulting to the installation's host when `hostId` is omitted; unknown providers render the
|
||||
standard provider fallback. `PluginCatalogSync` hydrates the host's provider snapshot before
|
||||
installing client contributions so `ProviderIcon` resolves plugin SVGs on initial render.
|
||||
`@getpaseo/plugin/client/ui`. Its `Icon` draws a Lucide name from the client's installed
|
||||
icon set, or any `PluginIcon` through its `icon` prop; an unknown name or unsafe SVG renders nothing
|
||||
so it cannot break the plugin surface.
|
||||
Its controlled modal keeps presentation metadata on `<Modal title="…" icon={…}>` and body UI in
|
||||
`<Modal.Content>`. Body layout, sheet-aware scrolling, and clipboard actions follow the
|
||||
[host UI contract](../public-docs/plugins/reference.md#host-ui).
|
||||
|
||||
+25
-36
@@ -16,9 +16,8 @@ Preparation is reversible and runs on the release branch before the user authori
|
||||
4. Run the [pre-release sanity check](#pre-release-sanity-check) for stable releases, and report any findings to the user.
|
||||
5. Commit the approved changelog and any requested ACP update, then run `npm run format`, `npm run lint`, and `npm run typecheck`.
|
||||
6. Run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag.
|
||||
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`.
|
||||
8. Right after the push, open the unmerged [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`, so its CI runs in parallel with the release branch's `CI` and `Desktop Packages`. Do not merge it during Preparation.
|
||||
9. Wait for `CI` and `Desktop Packages` on the release branch to pass (never wait on `main` CI), and run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
|
||||
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` and wait for `CI` and `Desktop Packages` on that branch to pass (never wait on `main` CI).
|
||||
8. Run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
|
||||
|
||||
### Ship
|
||||
|
||||
@@ -26,7 +25,7 @@ Ship starts after the user says "go ahead". All tag-triggered GitHub Actions wor
|
||||
|
||||
1. Run `npm run release:push` first to verify the clean release branch and push `vX.Y.Z` or `vX.Y.Z-beta.N`. Pushing the tag takes a few seconds and starts `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and (for stable tags) `Deploy App` on GitHub Actions, plus `Release Mobile` (stable) or `Release iOS Beta` (beta) on EAS. (`Deploy Website` runs later on the `release: published` event when `Desktop Release` publishes the stable GitHub Release.)
|
||||
2. Run `npm run release:publish` (stable) or `npm run release:publish:beta` (beta) in parallel with the remote builds. `scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency waves and polls npm visibility between packages to avoid `E409` or `E404` propagation races.
|
||||
3. Check the green [reconcile `main`](#reconcile-main) PR against the pushed tag, then merge it right after `npm run release:push` finishes, in parallel with npm publication and the release builds. Wait for its checks only if the tag check produced changes.
|
||||
3. Open the [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N` right after `npm run release:push` finishes, so its CI run overlaps with npm publication and the release builds.
|
||||
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
|
||||
|
||||
### Sync gates
|
||||
@@ -121,7 +120,6 @@ An explicit user instruction can select another base.
|
||||
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
|
||||
each other and a newer merge replaces the pending one.
|
||||
Open the [reconcile `main`](#reconcile-main) PR now so its CI runs in parallel with these two.
|
||||
Wait for both runs on the release branch commit to pass before shipping.
|
||||
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
|
||||
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
|
||||
@@ -129,8 +127,9 @@ An explicit user instruction can select another base.
|
||||
Because the release branch is already pushed at `HEAD`, no second branch CI run starts, and only
|
||||
the tag release workflows run.
|
||||
7. Immediately in parallel after `npm run release:push` finishes: publish npm packages with
|
||||
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), merge the
|
||||
already-green [reconcile `main`](#reconcile-main) PR, and create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
|
||||
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), start
|
||||
[Reconcile `main`](#reconcile-main) so its PR checks overlap with desktop and EAS builds, and
|
||||
create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
|
||||
`release:push` before `release:publish`, so tag builds never wait behind npm.)
|
||||
|
||||
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
|
||||
@@ -175,35 +174,27 @@ For a promotion, every item defaults to defer.
|
||||
|
||||
## Reconcile main
|
||||
|
||||
Open the reconcile PR during Preparation, right after pushing `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`. Its CI takes about 30 minutes and npm publication takes about 5, so opening it at Ship would leave Ship waiting on CI. An unmerged PR changes nothing on `main`. Reconcile reads only the release branch commit, so it does not wait for the release branch's `CI` or `Desktop Packages`:
|
||||
Right after `npm run release:push` pushes the tag (in parallel with npm publication and all desktop, APK, Docker, and EAS builds), open a PR into `main` from a fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`. Reconcile reads only the tagged git commit, so it does not wait for npm or any release build:
|
||||
|
||||
```bash
|
||||
git fetch origin
|
||||
git fetch origin --tags
|
||||
git checkout -b reconcile/vX.Y.Z origin/main
|
||||
npm run release:reconcile -- --ref origin/release/vX.Y.Z
|
||||
npm run release:reconcile -- --tag vX.Y.Z
|
||||
```
|
||||
|
||||
Use `release/vX.Y.Z-beta.N` and `reconcile/vX.Y.Z-beta.N` for a beta. `--tag vX.Y.Z` reads a published tag instead, for a release that is already tagged.
|
||||
|
||||
`scripts/reconcile-release.mjs` updates the working tree without cherry-picking stale lockfile
|
||||
hunks from the release base:
|
||||
|
||||
- Copies the release branch's `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
|
||||
- Copies the tagged `CHANGELOG.md` and `CHANGELOG.zh-CN.md` entries verbatim. A beta or promotion
|
||||
entry replaces the series beta entry on `main`. A stable hotfix on an older line is placed below
|
||||
any newer entries.
|
||||
- Copies the generated F-Droid changelog files from the release branch for stable releases.
|
||||
- Copies the generated F-Droid changelog files from the tag for stable releases.
|
||||
- Updates every `package.json` version and regenerates `package-lock.json` on top of current `main`
|
||||
only when the shipped version is newer than `main`'s version.
|
||||
- Leaves unshipped work on `main` untouched and makes no claims about unshipped work in the
|
||||
changelog entry.
|
||||
|
||||
Commit and open the PR into `main`, but do not merge it during Preparation:
|
||||
|
||||
- If the release is cancelled, close the PR. `main` is untouched.
|
||||
- If the release branch changes during Preparation, re-run `npm run release:reconcile -- --ref origin/release/vX.Y.Z` on the same branch and push to the same PR.
|
||||
- At Ship, right after `npm run release:push` pushes the tag, run `npm run release:reconcile -- --tag vX.Y.Z` on the reconcile branch. A clean `git status` means the PR already matches the tag, so merge it in parallel with `npm run release:publish` and the tag builds. If it shows changes, push them and wait for the PR checks before merging.
|
||||
|
||||
Delete the remote release branch
|
||||
Commit, open the PR into `main`, and merge once its checks pass. Delete the remote release branch
|
||||
(`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`) only after the reconcile PR
|
||||
merges and every [sync gate](#sync-gates) passes. The tag is the record of shipped source, and
|
||||
Paseo maintains no release track besides `main`.
|
||||
@@ -259,16 +250,16 @@ npm run release:prep:patch
|
||||
# or:
|
||||
npm run release:prep:minor
|
||||
|
||||
# 2. Push the release branch, then open the reconcile/vX.Y.Z PR into main (do not merge it).
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
|
||||
git push -u origin HEAD
|
||||
# Wait for CI + Desktop Packages on this commit and complete the pre-release dependency checks.
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
|
||||
# 3. After go-ahead and green release-branch checks: push the tag first to start builds.
|
||||
npm run release:push
|
||||
|
||||
# 4. Run these in parallel immediately after step 3:
|
||||
npm run release:publish
|
||||
# Also merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
|
||||
# Also open the reconcile/vX.Y.Z PR into main and create the release heartbeat.
|
||||
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
|
||||
```
|
||||
|
||||
@@ -303,13 +294,12 @@ npm run release:check # Typecheck, build, dry-run pack
|
||||
npm run version:all:patch
|
||||
npm run version:all:minor
|
||||
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
|
||||
# Open the reconcile/vX.Y.Z PR into main now (do not merge it).
|
||||
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
npm run release:push # Create tag vX.Y.Z on HEAD and push (starts release builds)
|
||||
# In parallel right after release:push:
|
||||
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
|
||||
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
|
||||
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat.
|
||||
```
|
||||
|
||||
## Beta flow
|
||||
@@ -322,24 +312,23 @@ npm run release:prep:beta:minor # Start the next minor beta line
|
||||
# or for follow-up betas:
|
||||
npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
|
||||
|
||||
# 2. Push the release branch and open the reconcile/vX.Y.Z-beta.N PR into main (do not merge it):
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
|
||||
git push -u origin HEAD
|
||||
# Wait for CI + Desktop Packages to pass and complete the pre-release dependency checks.
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
|
||||
# 3. After go-ahead: push the tag first, then run npm publish, merge the reconcile PR, and heartbeat in parallel:
|
||||
# 3. After go-ahead: push the tag first, then run npm publish, reconcile, and heartbeat in parallel:
|
||||
npm run release:push
|
||||
npm run release:publish:beta
|
||||
# (Or run `npm run release:ship:beta` in one shell while merging reconcile/vX.Y.Z-beta.N.)
|
||||
# (Or run `npm run release:ship:beta` in one shell while opening reconcile/vX.Y.Z-beta.N.)
|
||||
|
||||
# Later, after soak, promote on release/vX.Y.Z:
|
||||
npm run release:prep:promote
|
||||
git push -u origin HEAD
|
||||
# Open the reconcile/vX.Y.Z PR into main (do not merge it).
|
||||
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
npm run release:push
|
||||
npm run release:publish
|
||||
# Merge the green reconcile/vX.Y.Z PR and create the release heartbeat in parallel.
|
||||
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat in parallel.
|
||||
```
|
||||
|
||||
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
|
||||
@@ -1015,9 +1004,9 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
|
||||
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
|
||||
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
||||
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI), with the unmerged reconcile PR opened right after the branch push
|
||||
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the merge of the green `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
|
||||
- [ ] All seven `@getpaseo/*` npm packages show the version under the `beta` dist-tag, not `latest`
|
||||
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
|
||||
@@ -1039,9 +1028,9 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes, not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
|
||||
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
|
||||
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
|
||||
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI), with the unmerged reconcile PR opened right after the branch push
|
||||
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the merge of the green `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
|
||||
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
|
||||
- [ ] All seven `@getpaseo/*` npm packages show `latest` at the new stable, and `beta` at the new stable too unless an active newer beta holds `beta`
|
||||
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-oBd6CQ8+BhzMHhrpRIwzojuFPUwqXpgc3ZAPqKPs5QQ=
|
||||
sha256-x6E6SY98/8pUNLomlPzSNedZ+ZKJPzsQeS9L455i+n0=
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { gateNextAgentMessage } from "../support/helpers/agent-message-gate";
|
||||
import { expectComposerDraft, submitMessage } from "../support/helpers/composer";
|
||||
import { expectAgentIdle } from "../support/helpers/agent-stream";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import { openChangesPanel, openChangesTreePanel } from "../support/helpers/workspace-tabs";
|
||||
@@ -58,45 +55,3 @@ for (const width of [1400, 390]) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function addChangedFileToChat(page: Page) {
|
||||
await openChangesPanel(page);
|
||||
await page.getByTestId("diff-file-0-toggle").click({ button: "right" });
|
||||
await page.getByTestId("diff-file-0-add-to-chat").click();
|
||||
}
|
||||
|
||||
async function expectFollowUpAttachment(page: Page) {
|
||||
await expect(page.getByTestId("composer-workspace-file-attachment-pill")).toContainText(
|
||||
"follow-up.ts",
|
||||
);
|
||||
}
|
||||
|
||||
test("keeps a file added from Changes when an earlier send fails", async ({ page }) => {
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "attachment-during-send-",
|
||||
title: "Target chat",
|
||||
featureValues: { mockPromptRejections: 1 },
|
||||
});
|
||||
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "follow-up.ts"), "export const followUp = true;\n");
|
||||
await workspace.client.checkoutRefresh(workspace.cwd);
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectAgentIdle(page);
|
||||
await submitMessage(page, "Send this first.");
|
||||
await gate.waitForRequest();
|
||||
|
||||
await addChangedFileToChat(page);
|
||||
await expectFollowUpAttachment(page);
|
||||
|
||||
gate.accept();
|
||||
await expect(
|
||||
page.getByRole("alert").filter({ hasText: "Requested mock prompt rejection" }),
|
||||
).toBeVisible();
|
||||
await expectFollowUpAttachment(page);
|
||||
await expectComposerDraft(page, "");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1219,30 +1219,6 @@ test.describe("Agent message submission", () => {
|
||||
await retryRestoredSubmission(page, prompt);
|
||||
});
|
||||
|
||||
test("keeps a follow-up draft after the earlier send is rejected", async ({ page }, testInfo) => {
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: `pending-rejection-${testInfo.workerIndex}-`,
|
||||
title: "Pending rejection",
|
||||
model: "ten-second-stream",
|
||||
featureValues: { mockPromptRejections: 1 },
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectAgentIdle(page);
|
||||
await submitMessage(page, "Send this first.");
|
||||
await gate.waitForRequest();
|
||||
await fillComposerDraft(page, "Keep this follow-up.");
|
||||
gate.accept();
|
||||
await expect(
|
||||
page.getByRole("alert").filter({ hasText: "Requested mock prompt rejection" }),
|
||||
).toBeVisible();
|
||||
await expectComposerDraft(page, "Keep this follow-up.");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("restores an ambiguous Steer failure without retrying or interrupting", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -9,8 +9,7 @@ import {
|
||||
expectRemovedPlugin,
|
||||
} from "../support/helpers/plugin-reconnect";
|
||||
import { verifyPluginTranslations } from "../support/helpers/plugin-translations";
|
||||
import { copyPluginExample, pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { expectProviderIcon, readIconPaths } from "../support/helpers/plugin-provider-icons";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -27,7 +26,7 @@ const TINY_PNG = Buffer.from(
|
||||
);
|
||||
|
||||
const PLUGIN_SOURCE = `import { usePaseo } from "@getpaseo/plugin/client";
|
||||
import { Icon, Modal, ProviderIcon, useToast, Markdown } from "@getpaseo/plugin/client/ui";
|
||||
import { Icon, Modal, useToast, Markdown } from "@getpaseo/plugin/client/ui";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import React, { useState } from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
@@ -54,7 +53,7 @@ function ModalBody({ onSaved }) {
|
||||
</View>;
|
||||
}
|
||||
|
||||
function Surface({ host, theme, playAudio }) {
|
||||
function Surface({ playAudio }) {
|
||||
const [audioStatus, setAudioStatus] = useState("Audio ready");
|
||||
async function play(base64) {
|
||||
setAudioStatus("Playing audio");
|
||||
@@ -63,18 +62,6 @@ function Surface({ host, theme, playAudio }) {
|
||||
}
|
||||
const [open, setOpen] = useState(false);
|
||||
return <View>
|
||||
<View testID="plugin-provider-icon-builtin">
|
||||
<ProviderIcon provider="codex" size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<View testID="plugin-provider-icon-plugin">
|
||||
<ProviderIcon provider="direct-example" hostId={host.id} size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<View testID="plugin-provider-icon-fallback">
|
||||
<ProviderIcon provider="unknown-provider-e2e" size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<View testID="plugin-provider-icon-bot-ref">
|
||||
<Icon name="Bot" size={18} color={theme.colors.foreground} />
|
||||
</View>
|
||||
<Text>{audioStatus}</Text>
|
||||
<Markdown>{"\\n\\n"}</Markdown>
|
||||
<Pressable accessibilityRole="button" onPress={() => play(AUDIO_BASE64)}><Text>Play plugin audio</Text></Pressable>
|
||||
@@ -99,7 +86,7 @@ function Surface({ host, theme, playAudio }) {
|
||||
}
|
||||
|
||||
export default function contribute(plugin) {
|
||||
plugin.addSurface("main", (props) => <Surface {...props} playAudio={plugin.playAudio} />);
|
||||
plugin.addSurface("main", () => <Surface playAudio={plugin.playAudio} />);
|
||||
plugin.addSidebarItem({
|
||||
id: "main",
|
||||
title: "Host UI",
|
||||
@@ -179,9 +166,8 @@ async function savePluginIssue(page: Page): Promise<void> {
|
||||
await expect(page.getByText("Plugin modal contexts ready", { exact: true })).not.toBeVisible();
|
||||
}
|
||||
|
||||
test("plugin host UI renders provider icons and preserves modal contexts", async ({ page }) => {
|
||||
test("plugin modal adapts its presentation and preserves host contexts", async ({ page }) => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-host-ui-e2e-"));
|
||||
const providerPlugin = await copyPluginExample("provider-direct");
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previousConfig = await client.getDaemonConfig();
|
||||
await writeFile(
|
||||
@@ -201,29 +187,10 @@ test("plugin host UI renders provider icons and preserves modal contexts", async
|
||||
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(providerPlugin.directory);
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await useNonCompactLayout(page);
|
||||
await openHostUiPlugin(page);
|
||||
|
||||
await test.step("ProviderIcon renders built-in, daemon plugin SVG, and fallback icons", async () => {
|
||||
const providerIconPaths = await readIconPaths(page, providerPlugin.directory);
|
||||
await expectProviderIcon(page.getByTestId("plugin-provider-icon-plugin"), providerIconPaths);
|
||||
|
||||
const builtinSvg = page.getByTestId("plugin-provider-icon-builtin").locator("svg");
|
||||
const fallbackSvg = page.getByTestId("plugin-provider-icon-fallback").locator("svg");
|
||||
const botRefSvg = page.getByTestId("plugin-provider-icon-bot-ref").locator("svg");
|
||||
await expect(builtinSvg).toBeVisible();
|
||||
await expect(fallbackSvg).toBeVisible();
|
||||
await expect(botRefSvg).toBeVisible();
|
||||
|
||||
const fallbackMarkup = await fallbackSvg.innerHTML();
|
||||
const botRefMarkup = await botRefSvg.innerHTML();
|
||||
const builtinMarkup = await builtinSvg.innerHTML();
|
||||
expect(fallbackMarkup).toBe(botRefMarkup);
|
||||
expect(builtinMarkup).not.toBe(botRefMarkup);
|
||||
});
|
||||
|
||||
await test.step("plugin screen Markdown renders local absolute and file:// PNG images inline", async () => {
|
||||
await expectLoadedMarkdownImage(page, "Before");
|
||||
await expectLoadedMarkdownImage(page, "After");
|
||||
@@ -250,13 +217,11 @@ test("plugin host UI renders provider icons and preserves modal contexts", async
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client.removePlugin("provider-direct-example").catch(() => undefined);
|
||||
await client
|
||||
.patchDaemonConfig({ pluginsEnabled: previousConfig.config.pluginsEnabled ?? false })
|
||||
.catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
await providerPlugin.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -18,8 +18,7 @@ function finish() {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Raw mode before the query: a reply that arrives while the tty still echoes
|
||||
// would be printed on the capture line as a second "]11;rgb:".
|
||||
process.stdout.write("\\x1b]11;?\\x07");
|
||||
if (process.stdin.isTTY) {
|
||||
process.stdin.setRawMode(true);
|
||||
}
|
||||
@@ -27,7 +26,6 @@ process.stdin.resume();
|
||||
process.stdin.on("data", (chunk) => {
|
||||
captured = Buffer.concat([captured, chunk]);
|
||||
});
|
||||
process.stdout.write("\\x1b]11;?\\x07");
|
||||
setTimeout(finish, 700);
|
||||
`;
|
||||
|
||||
|
||||
@@ -45,9 +45,6 @@ function Details({ workspaceId, theme, layout, close }) {
|
||||
owner.subscribe({ snapshot(value) { setOwnerId(value.subscriptionId); }, update() { setUpdates((n) => n + 1); } });
|
||||
return () => { void owner.release(); };
|
||||
}, [paseo]);
|
||||
React.useEffect(() => {
|
||||
globalThis.__buttonContentMounts = (globalThis.__buttonContentMounts ?? 0) + 1;
|
||||
}, []);
|
||||
const rpc = useRpc(summary);
|
||||
const query = useQuery({ queryKey: ["summary"], queryFn: () => rpc({}) });
|
||||
if (failed) throw new Error("Button content failed");
|
||||
@@ -201,13 +198,6 @@ async function expectDetails(page: Page) {
|
||||
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
|
||||
}
|
||||
|
||||
/** How many times button content has mounted on the page, counted by the content itself. */
|
||||
async function contentMounts(page: Page): Promise<number> {
|
||||
return page.evaluate(
|
||||
() => (globalThis as { __buttonContentMounts?: number }).__buttonContentMounts ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
// The details render before the daemon answers their event subscription, and reopened
|
||||
// details show the cached summary at once, so wait for the subscription id to arrive.
|
||||
async function readContentObservation(page: Page): Promise<string> {
|
||||
@@ -241,17 +231,14 @@ async function expectCompactDetails(page: Page) {
|
||||
await expect(menu.getByText("Presentation: compact", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once `subject` renders the same pixels twice in a row: entering animations are done.
|
||||
* A remount detaches the element mid-screenshot; that is not still yet, so the poll starts over.
|
||||
*/
|
||||
/** Resolves once `subject` renders the same pixels twice in a row: entering animations are done. */
|
||||
async function expectStill(subject: Locator) {
|
||||
let previous: Buffer | null = null;
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const current = await screenshotAttached(subject);
|
||||
const still = previous !== null && current !== null && current.equals(previous);
|
||||
const current = await subject.screenshot();
|
||||
const still = previous !== null && current.equals(previous);
|
||||
previous = current;
|
||||
return still;
|
||||
},
|
||||
@@ -260,17 +247,6 @@ async function expectStill(subject: Locator) {
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function screenshotAttached(subject: Locator): Promise<Buffer | null> {
|
||||
try {
|
||||
return await subject.screenshot();
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Element is not attached to the DOM")) {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Attaches the screen once per colour scheme, for review alongside the run. */
|
||||
async function captureSchemes(page: Page, info: TestInfo, name: string, subject: Locator) {
|
||||
for (const colorScheme of ["light", "dark"] as const) {
|
||||
@@ -384,18 +360,15 @@ export async function withButtonShowcase(
|
||||
await run({
|
||||
verifyObservationLifetime: () =>
|
||||
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
|
||||
const mountsBefore = await contentMounts(page);
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const first = await readContentObservation(page);
|
||||
expect(await contentMounts(page)).toBe(mountsBefore + 1);
|
||||
await press(page, "Close deployment details");
|
||||
await expect.poll(() => released.has(first)).toBe(true);
|
||||
await press(page, "Composer status");
|
||||
await expectDetails(page);
|
||||
const second = await readContentObservation(page);
|
||||
expect(second).not.toBe(first);
|
||||
expect(await contentMounts(page)).toBe(mountsBefore + 2);
|
||||
await workspace.client.renameProject(workspace.projectId, "Observer control");
|
||||
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
|
||||
await press(page, "Fail button content");
|
||||
|
||||
@@ -15,7 +15,7 @@ const MODEL_LABEL = "Select model (Example 1)";
|
||||
const WIDE = { width: 1400, height: 950 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
|
||||
export async function readIconPaths(page: Page, pluginDirectory: string): Promise<string[]> {
|
||||
async function readIconPaths(page: Page, pluginDirectory: string): Promise<string[]> {
|
||||
const svg = await readFile(path.join(pluginDirectory, "icon.svg"), "utf8");
|
||||
return page.evaluate(
|
||||
(source) =>
|
||||
@@ -33,7 +33,7 @@ function readIconDrawings(icons: SVGElement[]): string[][] {
|
||||
);
|
||||
}
|
||||
|
||||
export async function expectProviderIcon(surface: Locator, paths: string[]): Promise<void> {
|
||||
async function expectProviderIcon(surface: Locator, paths: string[]): Promise<void> {
|
||||
await expect(surface).toBeVisible();
|
||||
// Provider icons are decorative SVGs without accessible names. Compare the
|
||||
// plugin asset's drawing, allowing surface-specific size and theme colours.
|
||||
|
||||
@@ -242,28 +242,6 @@ const longEditDetail = {
|
||||
newString: "new line\n".repeat(80),
|
||||
};
|
||||
|
||||
describe("tool detail empty state", () => {
|
||||
it("insets the empty-state text from the disclosure edge", () => {
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToolCallDetailsContent maxHeight={200} />
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
const text = view().getByText("No additional details available");
|
||||
const style = getComputedStyle(text);
|
||||
expect(style.paddingTop).toBe("12px");
|
||||
expect(style.paddingRight).toBe("12px");
|
||||
expect(style.paddingBottom).toBe("12px");
|
||||
expect(style.paddingLeft).toBe("12px");
|
||||
const textBox = text.getBoundingClientRect();
|
||||
const containerBox = container.getBoundingClientRect();
|
||||
expect(textBox.left).toBeGreaterThanOrEqual(containerBox.left);
|
||||
expect(textBox.right).toBeLessThanOrEqual(containerBox.right);
|
||||
});
|
||||
});
|
||||
|
||||
describe("capped tool scrolling", () => {
|
||||
it.each([longShellDetail, longEditDetail])(
|
||||
"gives a capped $type detail one vertical scroll owner",
|
||||
|
||||
@@ -55,47 +55,6 @@ it("keeps unavailable probes and external paths on the existing file-open path",
|
||||
}
|
||||
});
|
||||
|
||||
it("opens an existing absolute folder outside the workspace without a trailing slash", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "outside-folder-link-"));
|
||||
roots.push(root);
|
||||
const workspaceRoot = path.join(root, "workspace");
|
||||
const folder = path.join(root, "reports").split(path.sep).join("/");
|
||||
const file = path.join(root, "notes.txt").split(path.sep).join("/");
|
||||
await mkdir(workspaceRoot);
|
||||
await mkdir(folder);
|
||||
await writeFile(file, "notes");
|
||||
|
||||
const { classifyForResolution } = await import("./resolver");
|
||||
const { resolveInlinePathDestination } = await import("./path-open");
|
||||
const client = {
|
||||
listDirectory: (cwd: string, requestedPath: string) => {
|
||||
const absolute = path.resolve(cwd, requestedPath);
|
||||
if (path.relative(cwd, absolute).split(path.sep)[0] === "..") {
|
||||
throw new Error("Access outside of workspace is not allowed");
|
||||
}
|
||||
return readdir(absolute);
|
||||
},
|
||||
getDirectorySuggestions: async () => ({ entries: [], error: null }),
|
||||
};
|
||||
const destination = async (href: string) => {
|
||||
const resolution = classifyForResolution({ href, text: "Open path" }, { workspaceRoot });
|
||||
if (resolution.kind !== "resolved" || resolution.value.kind !== "file") {
|
||||
throw new Error("Expected an explicit path link");
|
||||
}
|
||||
return resolveInlinePathDestination({ target: resolution.value.target, workspaceRoot, client });
|
||||
};
|
||||
|
||||
await expect(destination(file)).resolves.toMatchObject({
|
||||
kind: "file",
|
||||
location: { path: file },
|
||||
});
|
||||
await expect(destination(folder + "/")).resolves.toEqual({
|
||||
kind: "outsideDirectory",
|
||||
path: folder,
|
||||
});
|
||||
await expect(destination(folder)).resolves.toEqual({ kind: "outsideDirectory", path: folder });
|
||||
});
|
||||
|
||||
it("ignores an older probe after a newer file link opens", async () => {
|
||||
const { createInlinePathOpener } = await import("./path-open");
|
||||
let rejectProbe!: (error: Error) => void;
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
type WorkspaceFileLocation,
|
||||
type OpenFileDisposition,
|
||||
} from "@/workspace/file-open";
|
||||
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||
import { isAbsolutePath } from "@/utils/path";
|
||||
import { resolveMissingNestedRelativeFile, type GetDirectorySuggestions } from "./resolver";
|
||||
|
||||
@@ -27,30 +26,27 @@ function isOutsideWorkspacePath(pathValue: string): boolean {
|
||||
return isAbsolutePath(pathValue) || pathValue === "~" || pathValue.startsWith("~/");
|
||||
}
|
||||
|
||||
/** Resolve folders from filesystem facts, including names that contain dots. */
|
||||
/** Resolve workspace folders from filesystem facts, including names that contain dots. */
|
||||
export async function resolveInlinePathOpen(input: PathOpenInput): Promise<PathOpenTarget> {
|
||||
if (!input.file) {
|
||||
return isOutsideWorkspacePath(input.directory)
|
||||
? { kind: "outsideDirectory", directoryPath: input.directory }
|
||||
: { kind: "directory", directoryPath: input.directory };
|
||||
}
|
||||
if (input.lineStart !== undefined || !input.workspaceRoot.trim() || !input.client) {
|
||||
if (
|
||||
input.lineStart !== undefined ||
|
||||
isAbsolutePath(input.file) ||
|
||||
!input.workspaceRoot.trim() ||
|
||||
!input.client
|
||||
) {
|
||||
return { kind: "file" };
|
||||
}
|
||||
const outside = isOutsideWorkspacePath(input.file);
|
||||
const probe = outside
|
||||
? resolveFilePreviewReadTarget({ path: input.file, workspaceRoot: input.workspaceRoot })
|
||||
: { cwd: input.workspaceRoot, path: input.file };
|
||||
if (!probe) return { kind: "file" };
|
||||
try {
|
||||
await input.client.listDirectory(probe.cwd, probe.path);
|
||||
await input.client.listDirectory(input.workspaceRoot, input.file);
|
||||
} catch {
|
||||
return { kind: "file" };
|
||||
}
|
||||
return {
|
||||
kind: outside ? "outsideDirectory" : "directory",
|
||||
directoryPath: input.file,
|
||||
};
|
||||
return { kind: "directory", directoryPath: input.file };
|
||||
}
|
||||
|
||||
export type InlinePathDestination =
|
||||
|
||||
@@ -747,7 +747,6 @@ const styles = StyleSheet.create((theme) => {
|
||||
color: theme.colors.destructive,
|
||||
},
|
||||
emptyStateText: {
|
||||
padding: insets.padding,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontStyle: "italic",
|
||||
|
||||
@@ -120,27 +120,6 @@ describe("anchored menu surface on web", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("mounts its content once per open", async () => {
|
||||
const lifecycle: string[] = [];
|
||||
function RecordsMounts() {
|
||||
useEffect(() => {
|
||||
lifecycle.push("mount");
|
||||
return () => {
|
||||
lifecycle.push("unmount");
|
||||
};
|
||||
}, []);
|
||||
return <View testID="body" style={SHORT} />;
|
||||
}
|
||||
mountMenuAbovePill(<RecordsMounts />);
|
||||
|
||||
await wait(SETTLE_MS);
|
||||
|
||||
expect(element("panel").getBoundingClientRect().bottom).toBeLessThanOrEqual(
|
||||
element("pill").getBoundingClientRect().top,
|
||||
);
|
||||
expect(lifecycle).toEqual(["mount"]);
|
||||
});
|
||||
|
||||
it("widens when its content widens after the entering animation", async () => {
|
||||
mountMenuAbovePill(<GrowsAfterOpen afterMs={GROWS_BEFORE_CLEANUP_MS} from={SHORT} to={WIDE} />);
|
||||
|
||||
|
||||
@@ -284,12 +284,9 @@ export function AnchoredSurface({
|
||||
|
||||
// The surface is placed once both measurements land. Until then it sits off-screen so it can
|
||||
// be measured, and it must not animate: an entering animation that ran there would be over
|
||||
// before anyone saw the menu. Native remounts the surface on placement so Reanimated's
|
||||
// `entering` starts from the final position. Web keeps it mounted and starts its own animation
|
||||
// on placement: a remount would mount the content twice per open, running its effects and
|
||||
// requests again and dropping its first state.
|
||||
// before anyone saw the menu. Remounting on placement starts the native animation from the
|
||||
// final position; web starts its own animation on placement.
|
||||
const placed = position !== null;
|
||||
const surfaceKey = isWeb || placed ? "placed" : "measuring";
|
||||
|
||||
useWebContentEntering({ placed, surfaceNativeID });
|
||||
|
||||
@@ -368,7 +365,7 @@ export function AnchoredSurface({
|
||||
) : null}
|
||||
<View pointerEvents="box-none" style={frame.holder}>
|
||||
<FloatingSurface
|
||||
key={surfaceKey}
|
||||
key={placed ? "placed" : "measuring"}
|
||||
collapsable={false}
|
||||
tabIndex={-1}
|
||||
nativeID={surfaceNativeID}
|
||||
|
||||
@@ -467,7 +467,6 @@ export function WorkspaceSetupDialog() {
|
||||
attachments={chatDraft.attachments}
|
||||
onChangeAttachments={chatDraft.setAttachments}
|
||||
cwd={sourceDirectory}
|
||||
getDraftRevision={chatDraft.getRevision}
|
||||
clearDraft={chatDraft.clear}
|
||||
autoFocus
|
||||
commandDraft={composerState?.commandDraft}
|
||||
|
||||
@@ -68,7 +68,6 @@ export interface AgentInputDraft {
|
||||
textReplacement: TextReplacement;
|
||||
attachments: UserComposerAttachment[];
|
||||
setAttachments: (updater: AttachmentUpdater) => void;
|
||||
getRevision: () => number;
|
||||
clear: (lifecycle: "sent" | "abandoned") => void;
|
||||
isHydrated: boolean;
|
||||
attachmentFocusRequestId: number;
|
||||
@@ -196,11 +195,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
const getRevision = useCallback(
|
||||
() => useDraftStore.getState().getDraftRevision(draftKey),
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
const clear = useCallback(
|
||||
(lifecycle: "sent" | "abandoned") => {
|
||||
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
|
||||
@@ -387,7 +381,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
|
||||
@@ -587,7 +587,6 @@ export function WorkspaceDraftComposer({
|
||||
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
|
||||
onChangeAttachments={draftInput.setAttachments}
|
||||
cwd={composerState.workingDir}
|
||||
getDraftRevision={draftInput.getRevision}
|
||||
clearDraft={draftInput.clear}
|
||||
editingSession={editingSession}
|
||||
autoFocus={shouldAutoFocusWorkspaceDraftComposer({ isPaneFocused, isSubmitting })}
|
||||
|
||||
@@ -952,7 +952,6 @@ interface ComposerProps {
|
||||
onForgeChangeRequestDetected?: () => void;
|
||||
onForgeChangeRequestAutoAttach?: (item: ForgeSearchItem) => void;
|
||||
cwd: string;
|
||||
getDraftRevision: () => number;
|
||||
clearDraft: (lifecycle: "sent" | "abandoned") => void;
|
||||
/** When true, auto-focuses the text input on web. */
|
||||
autoFocus?: boolean;
|
||||
@@ -1281,7 +1280,6 @@ function ComposerContentImpl({
|
||||
onForgeChangeRequestDetected,
|
||||
onForgeChangeRequestAutoAttach,
|
||||
cwd,
|
||||
getDraftRevision,
|
||||
clearDraft,
|
||||
autoFocus = false,
|
||||
autoFocusKey,
|
||||
@@ -1884,7 +1882,6 @@ function ComposerContentImpl({
|
||||
await submitMessage(submitText, submitAttachments);
|
||||
},
|
||||
clearDraft,
|
||||
getDraftRevision,
|
||||
setUserInput: replaceUserInput,
|
||||
setAttachments: (nextAttachments) => {
|
||||
setSelectedAttachments(composerWorkspaceAttachment.userAttachmentsOnly(nextAttachments));
|
||||
@@ -1907,7 +1904,6 @@ function ComposerContentImpl({
|
||||
clearDraft,
|
||||
completeSubmit,
|
||||
enqueueMessage,
|
||||
getDraftRevision,
|
||||
hasExternalContent,
|
||||
isAgentRunning,
|
||||
supportsQueue,
|
||||
|
||||
@@ -35,7 +35,6 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -60,53 +59,6 @@ describe("submitAgentInput", () => {
|
||||
expect(clearDraft).toHaveBeenCalledWith("sent");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ delivery: "send", outcome: "failed" },
|
||||
{ delivery: "send", outcome: "submitted" },
|
||||
{ delivery: "queue", outcome: "failed" },
|
||||
{ delivery: "queue", outcome: "queued" },
|
||||
] as const)(
|
||||
"preserves edits made while a $delivery is pending ($outcome)",
|
||||
async ({ delivery, outcome }) => {
|
||||
let revision = 0;
|
||||
let text = "first message";
|
||||
let attachments = ["first.txt"];
|
||||
const setUserInput = (next: string) => {
|
||||
text = next;
|
||||
revision++;
|
||||
};
|
||||
const setAttachments = (next: string[]) => {
|
||||
attachments = next;
|
||||
revision++;
|
||||
};
|
||||
const deferred = createDeferredPromise<void>();
|
||||
const result = submitAgentInput({
|
||||
message: text,
|
||||
attachments,
|
||||
isAgentRunning: delivery === "queue",
|
||||
canSubmit: true,
|
||||
queueMessage: () => deferred.promise,
|
||||
submitMessage: () => deferred.promise,
|
||||
clearDraft: () => {
|
||||
setUserInput("");
|
||||
setAttachments([]);
|
||||
},
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
getDraftRevision: () => revision,
|
||||
setSendError: vi.fn(),
|
||||
setIsProcessing: vi.fn(),
|
||||
});
|
||||
setUserInput("follow-up");
|
||||
setAttachments(["second.txt"]);
|
||||
if (outcome === "failed") deferred.reject(new Error("offline"));
|
||||
else deferred.resolve();
|
||||
expect(await result).toBe(outcome);
|
||||
expect(text).toBe("follow-up");
|
||||
expect(attachments).toEqual(["second.txt"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the composer before an in-flight submit resolves when requested", async () => {
|
||||
const deferred = createDeferredPromise<void>();
|
||||
const attachments = [{ id: "img-1" }];
|
||||
@@ -128,7 +80,6 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -172,7 +123,6 @@ describe("submitAgentInput", () => {
|
||||
submitMessage: async ({ message }) => {
|
||||
sent.push(message);
|
||||
},
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft: (lifecycle) => {
|
||||
composer.draft = lifecycle;
|
||||
},
|
||||
@@ -243,7 +193,6 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -283,7 +232,6 @@ describe("submitAgentInput", () => {
|
||||
submitMessage: async () => {
|
||||
throw error;
|
||||
},
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft: vi.fn(),
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
@@ -317,7 +265,6 @@ describe("submitAgentInput", () => {
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage,
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
|
||||
@@ -17,7 +17,6 @@ export interface AgentInputSubmitActionInput<TAttachment> {
|
||||
clearDraft: (lifecycle: "sent" | "abandoned") => void;
|
||||
setUserInput: (text: string) => void;
|
||||
setAttachments: (attachments: TAttachment[]) => void;
|
||||
getDraftRevision: () => number;
|
||||
setSendError: (message: string | null) => void;
|
||||
setIsProcessing: (isProcessing: boolean) => void;
|
||||
onSubmitError?: (error: unknown) => void;
|
||||
@@ -51,21 +50,18 @@ export async function submitAgentInput<TAttachment>(
|
||||
input.setUserInput("");
|
||||
input.setAttachments([]);
|
||||
}
|
||||
const submittedRevision = shouldClearOnSubmit ? input.getDraftRevision() : null;
|
||||
input.setSendError(null);
|
||||
input.setIsProcessing(true);
|
||||
|
||||
try {
|
||||
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
|
||||
await deliver({ message: trimmedMessage, attachments });
|
||||
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
|
||||
input.clearDraft("sent");
|
||||
}
|
||||
input.clearDraft("sent");
|
||||
input.setIsProcessing(false);
|
||||
return shouldQueue ? "queued" : "submitted";
|
||||
} catch (error) {
|
||||
input.onSubmitError?.(error);
|
||||
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
|
||||
if (shouldClearOnSubmit) {
|
||||
input.setUserInput(trimmedMessage);
|
||||
input.setAttachments(attachments);
|
||||
}
|
||||
|
||||
@@ -1192,7 +1192,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
@@ -1206,7 +1205,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
@@ -1219,7 +1217,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
getRevision,
|
||||
clear,
|
||||
isHydrated,
|
||||
attachmentFocusRequestId,
|
||||
@@ -1862,7 +1859,6 @@ function ActiveAgentComposer({
|
||||
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
|
||||
onChangeAttachments={agentInputDraft.setAttachments}
|
||||
cwd={cwd}
|
||||
getDraftRevision={agentInputDraft.getRevision}
|
||||
clearDraft={agentInputDraft.clear}
|
||||
editingSession={editingSession}
|
||||
autoFocus
|
||||
|
||||
@@ -3,13 +3,8 @@ import appPackage from "../../package.json";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { QueryObserver } from "@tanstack/react-query";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
GetProvidersSnapshotResponseMessage,
|
||||
SessionOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { compactProviderSnapshot } from "@getpaseo/protocol/provider-snapshot-codec";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { settingsRpc } from "@getpaseo/plugin";
|
||||
import { providerSnapshotIcons, replaceProviderSnapshotIcons } from "@/data/provider-icons";
|
||||
import { syncPluginCatalog } from "./catalog-sync-model";
|
||||
import { createPluginHosts } from "./hosts";
|
||||
import { openPluginNotification } from "./notification-open";
|
||||
@@ -574,90 +569,3 @@ it("keeps catalog loading before server_info arrives so cold-launch plugin taps
|
||||
expect(h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(openedRoutes).toEqual(["/h/host/plugin/ci-alerts/surface/alert?param.buildId=77"]);
|
||||
});
|
||||
|
||||
function providerSnapshotPayload(
|
||||
provider: string,
|
||||
iconSvg: string,
|
||||
snapshotHash: string,
|
||||
): GetProvidersSnapshotResponseMessage["payload"] {
|
||||
const entries = [
|
||||
{
|
||||
provider,
|
||||
label: provider,
|
||||
iconSvg,
|
||||
enabled: true,
|
||||
available: true,
|
||||
status: "ready" as const,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
const compactSnapshot = compactProviderSnapshot(entries);
|
||||
return {
|
||||
requestId: "snapshot-req",
|
||||
snapshotHash,
|
||||
generatedAt: "2026-01-01T00:00:00.000Z",
|
||||
entries,
|
||||
compactSnapshot,
|
||||
};
|
||||
}
|
||||
|
||||
it("hydrates provider snapshot icons before installing plugins and refreshes them on catalog changes", async () => {
|
||||
replaceProviderSnapshotIcons("host", []);
|
||||
const events: string[] = [];
|
||||
const firstSvg = '<svg viewBox="0 0 24 24"><path d="M2 2h20v20H2z" /></svg>';
|
||||
const secondSvg = '<svg viewBox="0 0 24 24"><path d="M6 6h12v12H6z" /></svg>';
|
||||
let current = { svg: firstSvg, hash: "hash-1" };
|
||||
|
||||
class SnapshotCatalogClient extends CatalogClient {
|
||||
override async getProvidersSnapshot() {
|
||||
events.push(`snapshot:${current.hash}`);
|
||||
return providerSnapshotPayload("direct-example", current.svg, current.hash);
|
||||
}
|
||||
|
||||
override async getPluginCatalog() {
|
||||
events.push(
|
||||
`catalog:${providerSnapshotIcons.getState().get("host")?.get("direct-example") ?? "missing"}`,
|
||||
);
|
||||
return super.getPluginCatalog();
|
||||
}
|
||||
}
|
||||
|
||||
const h = harness();
|
||||
const client = new SnapshotCatalogClient();
|
||||
h.sync({ client, supportsProviderSnapshots: true });
|
||||
|
||||
await expect.poll(() => h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(events).toEqual(["snapshot:hash-1", `catalog:${firstSvg}`]);
|
||||
expect(providerSnapshotIcons.getState().get("host")?.get("direct-example")).toBe(firstSvg);
|
||||
|
||||
current = { svg: secondSvg, hash: "hash-2" };
|
||||
client.update({
|
||||
type: "status",
|
||||
payload: { status: "plugin_catalog_changed", pluginId: "direct-example" },
|
||||
});
|
||||
|
||||
await expect
|
||||
.poll(() => providerSnapshotIcons.getState().get("host")?.get("direct-example"))
|
||||
.toBe(secondSvg);
|
||||
expect(events).toEqual([
|
||||
"snapshot:hash-1",
|
||||
`catalog:${firstSvg}`,
|
||||
"snapshot:hash-2",
|
||||
`catalog:${secondSvg}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("still installs the plugin catalog when provider icon hydration fails", async () => {
|
||||
replaceProviderSnapshotIcons("host", []);
|
||||
class FailingSnapshotClient extends CatalogClient {
|
||||
override async getProvidersSnapshot(): Promise<GetProvidersSnapshotResponseMessage["payload"]> {
|
||||
throw new Error("Snapshot unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
const h = harness();
|
||||
h.sync({ client: new FailingSnapshotClient(), supportsProviderSnapshots: true });
|
||||
|
||||
await expect.poll(() => h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(h.installed().id).toBe("reports");
|
||||
});
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { CancelledError } from "@tanstack/react-query";
|
||||
import type { AudioEngine } from "@/audio";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { fetchProvidersSnapshot } from "@/data/providers-snapshot";
|
||||
import type { PluginRegistry } from "./registry";
|
||||
import { pluginSettingsKey, pluginSettingsPrefix } from "./settings/query";
|
||||
|
||||
@@ -12,7 +10,6 @@ interface CatalogSyncInput {
|
||||
connected: boolean;
|
||||
/** `null` while `server_info` has not yet arrived for this host. */
|
||||
supported: boolean | null;
|
||||
supportsProviderSnapshots?: boolean;
|
||||
registry: Pick<
|
||||
PluginRegistry,
|
||||
"installCatalog" | "getSnapshot" | "removeHost" | "setCatalogStatus"
|
||||
@@ -26,7 +23,6 @@ export function syncPluginCatalog({
|
||||
audio,
|
||||
connected,
|
||||
supported,
|
||||
supportsProviderSnapshots = false,
|
||||
registry,
|
||||
onCatalogChanged,
|
||||
}: CatalogSyncInput): () => void {
|
||||
@@ -45,42 +41,27 @@ export function syncPluginCatalog({
|
||||
registry.setCatalogStatus(serverId, "loading");
|
||||
const installationOptions = { client, audio };
|
||||
let cancelled = false;
|
||||
const abortController = new AbortController();
|
||||
let refreshQueue = Promise.resolve();
|
||||
async function prepareProviderIcons() {
|
||||
if (!supportsProviderSnapshots) return;
|
||||
try {
|
||||
await fetchProvidersSnapshot({
|
||||
client,
|
||||
serverId,
|
||||
cwd: null,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!cancelled && !(error instanceof CancelledError)) {
|
||||
console.warn(`[Plugins] Failed to load provider icons for ${serverId}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
function refresh(replacePluginId?: string) {
|
||||
refreshQueue = refreshQueue.then(async () => {
|
||||
refreshQueue = refreshQueue.then(() => {
|
||||
if (cancelled) return undefined;
|
||||
registry.setCatalogStatus(serverId, "loading");
|
||||
await prepareProviderIcons();
|
||||
if (cancelled) return undefined;
|
||||
try {
|
||||
const catalog = await client.getPluginCatalog();
|
||||
if (!cancelled) {
|
||||
registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId });
|
||||
registry.setCatalogStatus(serverId, "ready");
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
registry.setCatalogStatus(serverId, "error");
|
||||
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
return client
|
||||
.getPluginCatalog()
|
||||
.then((catalog) => {
|
||||
if (!cancelled) {
|
||||
registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId });
|
||||
registry.setCatalogStatus(serverId, "ready");
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) {
|
||||
registry.setCatalogStatus(serverId, "error");
|
||||
console.warn(`[Plugins] Failed to load catalog for ${serverId}`, error);
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
});
|
||||
return refreshQueue;
|
||||
}
|
||||
@@ -123,7 +104,6 @@ export function syncPluginCatalog({
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
abortController.abort();
|
||||
void observation
|
||||
.release()
|
||||
.catch((error) => console.warn("[Plugins] Failed to release catalog", error));
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
|
||||
import { useEffect } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { useHostFeature, useHostFeatureAvailability } from "@/runtime/host-features";
|
||||
import { useHostFeatureAvailability } from "@/runtime/host-features";
|
||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { pluginListQueryKey } from "./plugin-list";
|
||||
import { pluginRegistry } from "./registry";
|
||||
@@ -18,7 +18,6 @@ export function PluginCatalogSync({
|
||||
const audio = useVoiceAudioEngineOptional();
|
||||
const connected = useHostRuntimeIsConnected(serverId);
|
||||
const supported = useHostFeatureAvailability(serverId, "plugins");
|
||||
const supportsProviderSnapshots = useHostFeature(serverId, "providersSnapshot");
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(
|
||||
@@ -29,13 +28,12 @@ export function PluginCatalogSync({
|
||||
audio,
|
||||
connected,
|
||||
supported,
|
||||
supportsProviderSnapshots,
|
||||
registry: pluginRegistry,
|
||||
onCatalogChanged: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: pluginListQueryKey(serverId) });
|
||||
},
|
||||
}),
|
||||
[audio, client, connected, queryClient, serverId, supported, supportsProviderSnapshots],
|
||||
[audio, client, connected, queryClient, serverId, supported],
|
||||
);
|
||||
|
||||
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
|
||||
|
||||
@@ -798,10 +798,10 @@ describe("evaluatePluginClientBundle", () => {
|
||||
const plugin = evaluatePluginClientBundle(
|
||||
"example",
|
||||
`(function(require) {
|
||||
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, StreamedText } = require("@getpaseo/plugin/client/ui");
|
||||
const { Icon, Modal, useToast, SettingsSection, SidebarRow, StreamedText } = require("@getpaseo/plugin/client/ui");
|
||||
const module = { exports: {} };
|
||||
module.exports.default = function(plugin) {
|
||||
if (typeof Icon !== "function" || typeof ProviderIcon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof StreamedText !== "function") {
|
||||
if (typeof Icon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof StreamedText !== "function") {
|
||||
throw new Error("React Native plugin UI is incomplete");
|
||||
}
|
||||
plugin.addSurface("main", function Surface() { return null; });
|
||||
|
||||
@@ -1,77 +1,14 @@
|
||||
// @vitest-environment jsdom
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { PluginIconProps } from "@getpaseo/plugin";
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { act, cleanup, renderHook } from "@testing-library/react";
|
||||
import { Bot, Settings } from "lucide-react-native";
|
||||
import { Settings } from "lucide-react-native";
|
||||
import React, { isValidElement, type ReactElement, type ReactNode } from "react";
|
||||
import Svg, { SvgXml } from "react-native-svg";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { replaceProviderSnapshotIcons } from "@/data/provider-icons";
|
||||
import { runPluginClientBundle, type PluginClientRuntime } from "./evaluate";
|
||||
import {
|
||||
Icon,
|
||||
parsePluginIcon,
|
||||
parseSerializablePluginIcon,
|
||||
PluginIconView,
|
||||
ProviderIcon,
|
||||
} from "./icons";
|
||||
import { PluginInstallationProvider } from "./installation-provider";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
import { SvgXml } from "react-native-svg";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PluginIconProps } from "@getpaseo/plugin";
|
||||
import { Icon, parsePluginIcon, parseSerializablePluginIcon, PluginIconView } from "./icons";
|
||||
|
||||
const SVG = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M4 4h16v16H4z" /></svg>';
|
||||
const SVG_ICON = { svg: SVG };
|
||||
|
||||
const GLYPHS = new Set<unknown>([Settings, Bot, Svg, SvgXml]);
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
replaceProviderSnapshotIcons("host-a", []);
|
||||
replaceProviderSnapshotIcons("host-b", []);
|
||||
});
|
||||
|
||||
function makePlugin(serverId: string): InstalledPlugin {
|
||||
return {
|
||||
id: "icons-test",
|
||||
serverId,
|
||||
clientBundle: "",
|
||||
lifetime: new AbortController(),
|
||||
locale: "en",
|
||||
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
|
||||
paseo: createPaseoApi(
|
||||
new DaemonClient({
|
||||
url: "ws://127.0.0.1:1",
|
||||
clientId: "icons-test",
|
||||
reconnect: { enabled: false },
|
||||
}),
|
||||
),
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
surfaces: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
const GLYPHS = new Set<unknown>([Settings, SvgXml]);
|
||||
|
||||
/** Expands function components down to what reaches the screen: a Lucide glyph, SvgXml, or DOM. */
|
||||
function draw(node: ReactNode): ReactElement | null {
|
||||
@@ -165,100 +102,3 @@ describe("Icon", () => {
|
||||
expect(Icon({ icon: { svg: '<svg onload="run()"></svg>' } })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ProviderIcon", () => {
|
||||
function hostWrapper(serverId: string) {
|
||||
const plugin = makePlugin(serverId);
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
return <PluginInstallationProvider plugin={plugin}>{children}</PluginInstallationProvider>;
|
||||
};
|
||||
}
|
||||
|
||||
it("renders built-in, catalog, host-scoped daemon plugin SVGs, reactive updates, and fallback icons", () => {
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId: "host-a", pluginId: "icons-test" },
|
||||
`(function(require) {
|
||||
const { ProviderIcon } = require("@getpaseo/plugin/client/ui");
|
||||
return {
|
||||
default: function(plugin) {
|
||||
plugin.addSurface("main", function() { return null; });
|
||||
plugin.__ProviderIcon = ProviderIcon;
|
||||
return function() {};
|
||||
},
|
||||
};
|
||||
})`,
|
||||
{} as PluginClientRuntime,
|
||||
);
|
||||
expect(evaluated.surfaces.map((s) => s.id)).toEqual(["main"]);
|
||||
|
||||
const hostASvg = '<svg viewBox="0 0 24 24"><path d="M4 4h16v16H4z" /></svg>';
|
||||
const hostBSvg = '<svg viewBox="0 0 24 24"><path d="M12 2L2 22h20z" /></svg>';
|
||||
replaceProviderSnapshotIcons("host-a", [{ provider: "direct-example", iconSvg: hostASvg }]);
|
||||
replaceProviderSnapshotIcons("host-b", [{ provider: "direct-example", iconSvg: hostBSvg }]);
|
||||
|
||||
const wrapper = hostWrapper("host-a");
|
||||
|
||||
// Built-in provider resolves without hostId
|
||||
const builtin = renderHook(
|
||||
() => ProviderIcon({ provider: "codex", size: 18, color: "#123456" }),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(builtin.result.current)).toMatchObject({
|
||||
type: Svg,
|
||||
props: { width: 18, height: 18, fill: "#123456" },
|
||||
});
|
||||
|
||||
// Catalog provider resolves with defaults
|
||||
const catalog = renderHook(() => ProviderIcon({ provider: "devin" }), { wrapper });
|
||||
expect(draw(catalog.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { width: 24, height: 24, color: "currentColor" },
|
||||
});
|
||||
|
||||
// Daemon-registered plugin provider defaults to enclosing installation host and reacts to updates
|
||||
const implicitHost = renderHook(
|
||||
() => ProviderIcon({ provider: "direct-example", size: 20, color: "#abcdef" }),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(implicitHost.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { xml: hostASvg, width: 20, height: 20, color: "#abcdef" },
|
||||
});
|
||||
|
||||
const updatedSvg = '<svg viewBox="0 0 24 24"><path d="M1 1h22v22H1z" /></svg>';
|
||||
act(() => {
|
||||
replaceProviderSnapshotIcons("host-a", [{ provider: "direct-example", iconSvg: updatedSvg }]);
|
||||
});
|
||||
expect(draw(implicitHost.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { xml: updatedSvg, width: 20, height: 20, color: "#abcdef" },
|
||||
});
|
||||
|
||||
// Explicit hostId targets the named host without leaking across hosts
|
||||
const explicitHost = renderHook(
|
||||
() =>
|
||||
ProviderIcon({ provider: "direct-example", hostId: "host-b", size: 16, color: "#654321" }),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(explicitHost.result.current)).toMatchObject({
|
||||
type: SvgXml,
|
||||
props: { xml: hostBSvg, width: 16, height: 16, color: "#654321" },
|
||||
});
|
||||
|
||||
// Unknown provider falls back to Bot
|
||||
const fallback = renderHook(
|
||||
() =>
|
||||
ProviderIcon({
|
||||
provider: "unknown-provider",
|
||||
hostId: "host-a",
|
||||
size: 18,
|
||||
color: "#111111",
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
expect(draw(fallback.result.current)).toMatchObject({
|
||||
type: Bot,
|
||||
props: { size: 18, color: "#111111" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,9 +8,8 @@ import {
|
||||
type PluginSvgIcon,
|
||||
} from "@getpaseo/plugin";
|
||||
import type { PluginIcon } from "@getpaseo/plugin/client";
|
||||
import type { IconProps, PluginProviderIconProps } from "@getpaseo/plugin/client/ui";
|
||||
import { SvgIcon, useProviderIcon } from "@/components/provider-icons";
|
||||
import { usePluginInstallationServerId } from "./installation-provider";
|
||||
import type { IconProps } from "@getpaseo/plugin/client/ui";
|
||||
import { SvgIcon } from "@/components/provider-icons";
|
||||
|
||||
/** Host surfaces may thin a Lucide stroke; SVG and plugin components ignore it. */
|
||||
type HostIconProps = PluginIconProps & { strokeWidth?: number };
|
||||
@@ -154,15 +153,3 @@ export function Icon(props: IconProps): ReactElement | null {
|
||||
const color = props.color ?? "currentColor";
|
||||
return createElement(PluginIconView, { icon, size, color });
|
||||
}
|
||||
|
||||
/** The kit `ProviderIcon`. Resolves built-in, catalog, or host-scoped plugin provider icons. */
|
||||
export function ProviderIcon({
|
||||
provider,
|
||||
hostId,
|
||||
size = 24,
|
||||
color = "currentColor",
|
||||
}: PluginProviderIconProps): ReactElement {
|
||||
const installationServerId = usePluginInstallationServerId();
|
||||
const icon = useProviderIcon(provider, hostId ?? installationServerId);
|
||||
return createElement(icon, { size, color });
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export { FilePanelLoading as Loading } from "@/file-panels/loading";
|
||||
// COMPAT(pluginSettingsGroup): added in v0.13.0, remove after 2027-04-20
|
||||
export { SettingsGroup } from "@/components/settings";
|
||||
|
||||
export { Icon, ProviderIcon } from "../icons";
|
||||
export { Icon } from "../icons";
|
||||
export { Action, Combobox, Select, Toggle } from "./composer-controls";
|
||||
export { Modal } from "./modal";
|
||||
export { ScrollView, FlatList } from "./scroll-view";
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Session } from "node:inspector/promises";
|
||||
import { getPluginClientApi } from "./client-state/api";
|
||||
import { filePanelTitle } from "@/file-panels/choice/presentation";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
@@ -237,27 +236,3 @@ test("locale snapshots preserve installation state and observations, then releas
|
||||
expect(listeners.size).toBe(0);
|
||||
await expect.poll(() => h.open.size).toBe(0);
|
||||
});
|
||||
|
||||
test("reloading a plugin releases the previous installation", async () => {
|
||||
const h = registry();
|
||||
const options = { client: h.client, audio };
|
||||
const entry = catalog("reloaded");
|
||||
h.plugins.installCatalog("host", [entry], options);
|
||||
// The published snapshot is a copy. Its lifetime belongs to the installation itself.
|
||||
const previous = new WeakRef(h.plugins.getSnapshot()[0]!.lifetime);
|
||||
|
||||
h.plugins.installCatalog("host", [entry], { ...options, replacePluginId: entry.id });
|
||||
expect(h.plugins.getSnapshot()[0]?.lifetime).not.toBe(previous.deref());
|
||||
|
||||
const inspector = new Session();
|
||||
inspector.connect();
|
||||
try {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await inspector.post("HeapProfiler.collectGarbage");
|
||||
expect(previous.deref() === undefined).toBe(true);
|
||||
expect(h.plugins.getSnapshot()).toHaveLength(1);
|
||||
} finally {
|
||||
inspector.disconnect();
|
||||
h.plugins.removeHost("host");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -89,15 +89,91 @@ export class PluginRegistry {
|
||||
this.publish();
|
||||
for (const plugin of removed) this.dispose(plugin);
|
||||
}
|
||||
const installed = catalog.flatMap((entry) =>
|
||||
this.installPlugin({
|
||||
serverId,
|
||||
entry,
|
||||
preserved,
|
||||
client: options.client,
|
||||
audio: options.audio,
|
||||
}),
|
||||
);
|
||||
const installed = catalog.flatMap((entry) => {
|
||||
const key = `${serverId}/${entry.id}`;
|
||||
let installation: InstalledPlugin | undefined;
|
||||
try {
|
||||
if (!entry.clientBundle) return [];
|
||||
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
|
||||
const existing = preserved.find(
|
||||
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
|
||||
);
|
||||
if (existing) {
|
||||
this.evaluationErrors.delete(key);
|
||||
return [existing];
|
||||
}
|
||||
const client = options.client;
|
||||
const lifetime = new AbortController();
|
||||
installation = {
|
||||
lifetime,
|
||||
locale: this.dependencies.localeSource.getLocale(),
|
||||
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
|
||||
paseo: createPaseoApi(client),
|
||||
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
|
||||
subscribe: createPluginSubscribe({
|
||||
client,
|
||||
pluginId: entry.id,
|
||||
lifetime: lifetime.signal,
|
||||
}),
|
||||
id: entry.id,
|
||||
serverId,
|
||||
clientBundle: entry.clientBundle,
|
||||
requirements: entry.requirements,
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
surfaces: [],
|
||||
settingsScreens: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
|
||||
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
|
||||
once: true,
|
||||
});
|
||||
const runtime = this.dependencies.createRuntime(installation, options.audio);
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId, pluginId: entry.id },
|
||||
entry.clientBundle,
|
||||
runtime,
|
||||
() => this.publish(),
|
||||
);
|
||||
Object.assign(installation, evaluated);
|
||||
const paseo = installation.paseo;
|
||||
installation.cleanup = async () => {
|
||||
const results = await Promise.allSettled([paseo.dispose(), evaluated.cleanup()]);
|
||||
const failures = results.filter((result) => result.status === "rejected");
|
||||
if (failures.length)
|
||||
throw new AggregateError(
|
||||
failures.map((result) => result.reason),
|
||||
"Plugin cleanup failed",
|
||||
);
|
||||
};
|
||||
this.evaluationErrors.delete(key);
|
||||
return [installation];
|
||||
} catch (error) {
|
||||
installation?.lifetime.abort();
|
||||
installation?.i18n.dispose();
|
||||
void installation?.paseo
|
||||
.dispose()
|
||||
.catch((failure) => console.warn(`[Plugins] API cleanup failed for ${key}`, failure));
|
||||
this.evaluationErrors.set(key, error instanceof Error ? error.message : String(error));
|
||||
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
|
||||
return [];
|
||||
}
|
||||
});
|
||||
const configuredIds = new Set(catalog.map((entry) => entry.id));
|
||||
for (const key of this.evaluationErrors.keys()) {
|
||||
if (key.startsWith(`${serverId}/`) && !configuredIds.has(key.slice(serverId.length + 1))) {
|
||||
@@ -139,104 +215,6 @@ export class PluginRegistry {
|
||||
this.publish();
|
||||
}
|
||||
|
||||
// Keep the closures for one installation out of the scope that holds the previous catalog.
|
||||
private installPlugin({
|
||||
serverId,
|
||||
entry,
|
||||
preserved,
|
||||
client,
|
||||
audio,
|
||||
}: {
|
||||
serverId: string;
|
||||
entry: CatalogPlugin;
|
||||
preserved: InstalledPlugin[];
|
||||
client: DaemonClient;
|
||||
audio: Pick<AudioEngine, "play">;
|
||||
}): InstalledPlugin[] {
|
||||
const key = `${serverId}/${entry.id}`;
|
||||
let installation: InstalledPlugin | undefined;
|
||||
try {
|
||||
if (!entry.clientBundle) return [];
|
||||
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
|
||||
const existing = preserved.find(
|
||||
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
|
||||
);
|
||||
if (existing) {
|
||||
this.evaluationErrors.delete(key);
|
||||
return [existing];
|
||||
}
|
||||
const lifetime = new AbortController();
|
||||
installation = {
|
||||
lifetime,
|
||||
locale: this.dependencies.localeSource.getLocale(),
|
||||
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
|
||||
paseo: createPaseoApi(client),
|
||||
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
|
||||
subscribe: createPluginSubscribe({
|
||||
client,
|
||||
pluginId: entry.id,
|
||||
lifetime: lifetime.signal,
|
||||
}),
|
||||
id: entry.id,
|
||||
serverId,
|
||||
clientBundle: entry.clientBundle,
|
||||
requirements: entry.requirements,
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
surfaces: [],
|
||||
settingsScreens: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
|
||||
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
|
||||
once: true,
|
||||
});
|
||||
const runtime = this.dependencies.createRuntime(installation, audio);
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId, pluginId: entry.id },
|
||||
entry.clientBundle,
|
||||
runtime,
|
||||
() => this.publish(),
|
||||
);
|
||||
Object.assign(installation, evaluated);
|
||||
const paseo = installation.paseo;
|
||||
installation.cleanup = async () => {
|
||||
const results = await Promise.allSettled([paseo.dispose(), evaluated.cleanup()]);
|
||||
const failures = results.filter((result) => result.status === "rejected");
|
||||
if (failures.length)
|
||||
throw new AggregateError(
|
||||
failures.map((result) => result.reason),
|
||||
"Plugin cleanup failed",
|
||||
);
|
||||
};
|
||||
this.evaluationErrors.delete(key);
|
||||
return [installation];
|
||||
} catch (error) {
|
||||
installation?.lifetime.abort();
|
||||
installation?.i18n.dispose();
|
||||
void installation?.paseo
|
||||
.dispose()
|
||||
.catch((failure) => console.warn(`[Plugins] API cleanup failed for ${key}`, failure));
|
||||
this.evaluationErrors.set(key, error instanceof Error ? error.message : String(error));
|
||||
console.warn(`[Plugins] Failed to evaluate ${serverId}/${entry.id}`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private hostEvaluationErrors(serverId: string): string {
|
||||
const prefix = `${serverId}/`;
|
||||
return JSON.stringify(
|
||||
|
||||
@@ -271,53 +271,6 @@ describe("AgentDirectoryReplica", () => {
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("ignores a lagging running snapshot for a turn already closed by stream_close", () => {
|
||||
const serverId = "agent-replica-stale-running-snapshot";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
replica.commitSnapshot(
|
||||
[
|
||||
entry({
|
||||
...payload("running"),
|
||||
status: "running",
|
||||
activeTurn: { turnId: "turn-1", startedAt: "2026-07-17T00:01:00.000Z" },
|
||||
}),
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
replica.applyTurnLiveness("agent", { type: "stream_close", turnId: "turn-1" });
|
||||
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
|
||||
|
||||
// An empty directory catch-up re-projects the unchanged idle agent as activeTurn: null;
|
||||
// it must preserve the closed turn marker so a lagging running delta still cannot re-open it.
|
||||
replica.commitChanges([], [], []);
|
||||
|
||||
replica.applyDelta({
|
||||
kind: "upsert",
|
||||
agent: {
|
||||
...payload("stale usage update"),
|
||||
status: "running",
|
||||
activeTurn: { turnId: "turn-1", startedAt: "2026-07-17T00:01:00.000Z" },
|
||||
},
|
||||
project: entry(payload("project")).project,
|
||||
});
|
||||
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
|
||||
|
||||
replica.applyDelta({
|
||||
kind: "upsert",
|
||||
agent: { ...payload("idle"), status: "idle", activeTurn: null },
|
||||
project: entry(payload("project")).project,
|
||||
});
|
||||
expect(selectAgentTurnPresentation(store.getSession(serverId), "agent").isActive).toBe(false);
|
||||
expect(store.getSession(serverId)?.agents.get("agent")?.turn).toMatchObject({
|
||||
phase: "idle",
|
||||
cancellationRequestId: null,
|
||||
});
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("preserves an unchanged running agent's turn identity during catch-up", () => {
|
||||
const serverId = "agent-replica-catch-up";
|
||||
const store = useSessionStore.getState();
|
||||
|
||||
@@ -200,7 +200,6 @@ interface NewWorkspaceScreenProps {
|
||||
const NO_TERMINAL_ATTACHMENTS: UserComposerAttachment[] = [];
|
||||
function noopChangeAttachments() {}
|
||||
function noopClearDraft() {}
|
||||
const getTerminalDraftRevision = () => 0;
|
||||
|
||||
// Stable reference so the keyboard-action handler doesn't re-register each render.
|
||||
const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [
|
||||
@@ -1686,7 +1685,6 @@ export function NewWorkspaceScreen({
|
||||
attachments={NO_TERMINAL_ATTACHMENTS}
|
||||
onChangeAttachments={noopChangeAttachments}
|
||||
cwd={workingDirectory ?? ""}
|
||||
getDraftRevision={getTerminalDraftRevision}
|
||||
clearDraft={noopClearDraft}
|
||||
autoFocus={terminalTakesPrompt}
|
||||
autoFocusKey={launchFocusKey}
|
||||
@@ -1718,7 +1716,6 @@ export function NewWorkspaceScreen({
|
||||
onForgeChangeRequestDetected={handleForgeChangeRequestDetected}
|
||||
onForgeChangeRequestAutoAttach={handleForgeChangeRequestAutoAttach}
|
||||
cwd={workingDirectory ?? ""}
|
||||
getDraftRevision={chatDraft.getRevision}
|
||||
clearDraft={handleClearDraft}
|
||||
autoFocus
|
||||
autoFocusKey={launchFocusKey}
|
||||
|
||||
@@ -45,7 +45,6 @@ import { hasDraftContent } from "@/composer/draft/input-draft-core";
|
||||
export type { DraftInput, DraftLifecycleState } from "./state";
|
||||
|
||||
interface DraftStoreActions {
|
||||
getDraftRevision: (draftKey: string) => number;
|
||||
getDraftInput: (draftKey: string) => DraftInput | undefined;
|
||||
hydrateDraftInput: (input: { draftKey: string }) => Promise<DraftInput | undefined>;
|
||||
saveDraftInput: (input: { draftKey: string; draft: DraftInput }) => void;
|
||||
@@ -284,11 +283,6 @@ export const useDraftStore = create<DraftStore>()(
|
||||
textReplacementRequestByDraftKey: {},
|
||||
metadataByDraftKey: {},
|
||||
|
||||
getDraftRevision: (draftKey) => {
|
||||
get().flushDraftText(draftKey);
|
||||
return get().drafts[draftKey]?.version ?? 0;
|
||||
},
|
||||
|
||||
getDraftInput: (draftKey) => {
|
||||
const record = get().drafts[draftKey];
|
||||
return toDraftInputIfReady(record);
|
||||
|
||||
@@ -28,12 +28,6 @@ describe("draft-store lifecycle", () => {
|
||||
expect(editDraftRecordText(edited, "", 3).lifecycle).toBe("active");
|
||||
expect(editDraftRecordText(undefined, "", 3).lifecycle).toBe("abandoned");
|
||||
});
|
||||
it("keeps the version when a cleared draft publishes empty text again", () => {
|
||||
const cleared = editDraftRecordText(undefined, "", 1);
|
||||
expect(editDraftRecordText(cleared, "", 2)).toBe(cleared);
|
||||
expect(editDraftRecordText(cleared, "follow-up", 2).version).toBe(cleared.version + 1);
|
||||
});
|
||||
|
||||
it("prunes finalized tombstones after TTL", () => {
|
||||
const nowMs = 1_000_000;
|
||||
const drafts = {
|
||||
|
||||
@@ -38,11 +38,7 @@ export function editDraftRecordText(
|
||||
text: string,
|
||||
now: number,
|
||||
): DraftRecord {
|
||||
if (
|
||||
record?.input.text === text &&
|
||||
(record.lifecycle === "active" || record.lifecycle === "abandoned")
|
||||
)
|
||||
return record;
|
||||
if (record?.lifecycle === "active" && record.input.text === text) return record;
|
||||
const attachments = record?.lifecycle === "active" ? record.input.attachments : [];
|
||||
return {
|
||||
input: { text, attachments },
|
||||
|
||||
@@ -75,49 +75,4 @@ describe("turn activity", () => {
|
||||
turnId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not re-open a turn from a lagging snapshot after stream_close ended it", () => {
|
||||
const open = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "stream_open",
|
||||
turn: { turnId: "turn-1", startedAt },
|
||||
});
|
||||
const closed = reduceTurnLiveness(open, { type: "stream_close", turnId: "turn-1" });
|
||||
expect(closed.phase).toBe("idle");
|
||||
|
||||
// A stale running snapshot for the just-closed turn must not flash it back to open.
|
||||
const afterStaleSnapshot = reduceTurnLiveness(closed, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "turn-1", startedAt },
|
||||
});
|
||||
expect(afterStaleSnapshot).toBe(closed);
|
||||
expect(resolveTurnPresentation(afterStaleSnapshot, false).isActive).toBe(false);
|
||||
|
||||
// An idle snapshot (including an empty directory catch-up) preserves the closed turn marker
|
||||
// so a delayed running snapshot for the same turn still cannot re-open it.
|
||||
const afterIdleSnapshot = reduceTurnLiveness(afterStaleSnapshot, {
|
||||
type: "snapshot",
|
||||
activeTurn: null,
|
||||
});
|
||||
expect(afterIdleSnapshot).toBe(closed);
|
||||
expect(
|
||||
reduceTurnLiveness(afterIdleSnapshot, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "turn-1", startedAt },
|
||||
}),
|
||||
).toBe(closed);
|
||||
|
||||
// A snapshot for a different turn still opens immediately.
|
||||
const nextStartedAt = new Date("2026-07-31T10:01:00.000Z");
|
||||
expect(
|
||||
reduceTurnLiveness(closed, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "turn-2", startedAt: nextStartedAt },
|
||||
}),
|
||||
).toEqual({
|
||||
phase: "open",
|
||||
turnId: "turn-2",
|
||||
startedAt: nextStartedAt,
|
||||
cancellationRequestId: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ export interface ActiveTurnIdentity {
|
||||
}
|
||||
|
||||
export type TurnLiveness =
|
||||
| { phase: "idle"; cancellationRequestId: number | null; closedTurnId?: string }
|
||||
| { phase: "idle"; cancellationRequestId: number | null }
|
||||
| {
|
||||
phase: "open";
|
||||
turnId: string | null;
|
||||
@@ -42,15 +42,8 @@ export function applyTurnLivenessTransition(
|
||||
const next = transitions.reduce(reduceTurnLiveness, current);
|
||||
if (next === current) return turns as Map<string, TurnLiveness>;
|
||||
const updated = new Map(turns);
|
||||
if (
|
||||
next.phase === "idle" &&
|
||||
next.cancellationRequestId === null &&
|
||||
next.closedTurnId === undefined
|
||||
) {
|
||||
updated.delete(agentId);
|
||||
} else {
|
||||
updated.set(agentId, next);
|
||||
}
|
||||
if (next.phase === "idle" && next.cancellationRequestId === null) updated.delete(agentId);
|
||||
else updated.set(agentId, next);
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -116,14 +109,7 @@ function closeTurn(current: TurnLiveness, turnId: string | null): TurnLiveness {
|
||||
turnId !== null &&
|
||||
current.turnId !== null &&
|
||||
turnId !== current.turnId;
|
||||
if (targetsDifferentIdentifiedTurn) return current;
|
||||
// Remember the closed turn id until a newer turn opens or destructive_close resets liveness,
|
||||
// so a lagging running snapshot (even after an empty directory catch-up) cannot re-open a turn
|
||||
// the stream already ended.
|
||||
const closedTurnId = turnId ?? (current.phase === "open" ? current.turnId : current.closedTurnId);
|
||||
return closedTurnId
|
||||
? { phase: "idle", cancellationRequestId: null, closedTurnId }
|
||||
: TURN_LIVENESS_IDLE;
|
||||
return targetsDifferentIdentifiedTurn ? current : TURN_LIVENESS_IDLE;
|
||||
}
|
||||
|
||||
function openTurn(current: TurnLiveness, activeTurn: ActiveTurnIdentity): TurnLiveness {
|
||||
@@ -161,24 +147,7 @@ export function reduceTurnLiveness(
|
||||
return closeTurn(current, transition.turnId);
|
||||
}
|
||||
|
||||
if (transition.type === "snapshot") {
|
||||
if (!transition.activeTurn) {
|
||||
if (current.phase === "idle") {
|
||||
return current.cancellationRequestId === null
|
||||
? current
|
||||
: { ...current, cancellationRequestId: null };
|
||||
}
|
||||
return TURN_LIVENESS_IDLE;
|
||||
}
|
||||
if (
|
||||
current.phase === "idle" &&
|
||||
current.closedTurnId !== undefined &&
|
||||
transition.activeTurn.turnId === current.closedTurnId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
return openTurn(current, transition.activeTurn);
|
||||
}
|
||||
|
||||
return openTurn(current, transition.turn);
|
||||
const activeTurn = transition.type === "snapshot" ? transition.activeTurn : transition.turn;
|
||||
if (!activeTurn) return TURN_LIVENESS_IDLE;
|
||||
return openTurn(current, activeTurn);
|
||||
}
|
||||
|
||||
@@ -81,11 +81,6 @@ describe("buildAgentLsFetchOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves empty values and punctuation in repeated label filters", () => {
|
||||
const options = buildAgentLsFetchOptions({ label: ["tag=v=1,rc", "empty="] });
|
||||
expect(options.filter?.labels).toEqual({ tag: "v=1,rc", empty: "" });
|
||||
});
|
||||
|
||||
it("asks the daemon for internal agents only with --internal", () => {
|
||||
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
|
||||
filter: { includeBackground: true },
|
||||
@@ -131,17 +126,6 @@ describe("buildAgentLsFetchOptions", () => {
|
||||
});
|
||||
|
||||
describe("runLsCommand", () => {
|
||||
it.each(["team", "=blue", " =blue"])(
|
||||
"rejects the whole listing when a label filter is malformed (%j)",
|
||||
async (label) => {
|
||||
await expect(
|
||||
listAgents({ daemonTarget, label: ["bot=worker", label] }, async () =>
|
||||
createPagingClient(),
|
||||
),
|
||||
).rejects.toMatchObject({ code: "INVALID_LABEL", message: `Invalid label format: ${label}` });
|
||||
},
|
||||
);
|
||||
|
||||
it("includes agent snapshot metadata in JSON listings", async () => {
|
||||
const result = await listAgents({ daemonTarget, global: true }, async () =>
|
||||
createPagingClient(),
|
||||
|
||||
@@ -141,20 +141,16 @@ export interface AgentLsOptions extends CommandOptions {
|
||||
}
|
||||
|
||||
function parseLabelFilters(labels: string[] | undefined): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
(labels ?? []).map((label) => {
|
||||
const separator = label.indexOf("=");
|
||||
const key = label.slice(0, separator);
|
||||
if (separator === -1 || !key.trim()) {
|
||||
throw {
|
||||
code: "INVALID_LABEL",
|
||||
message: `Invalid label format: ${label}`,
|
||||
details: "Labels must include a non-empty key in key=value format",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
return [key, label.slice(separator + 1)];
|
||||
}),
|
||||
);
|
||||
const labelFilters: Record<string, string> = {};
|
||||
for (const labelStr of labels ?? []) {
|
||||
const eqIndex = labelStr.indexOf("=");
|
||||
if (eqIndex !== -1) {
|
||||
const key = labelStr.slice(0, eqIndex);
|
||||
const value = labelStr.slice(eqIndex + 1);
|
||||
labelFilters[key] = value;
|
||||
}
|
||||
}
|
||||
return labelFilters;
|
||||
}
|
||||
|
||||
export function buildAgentLsFetchOptions(
|
||||
@@ -215,7 +211,6 @@ export async function listAgents(
|
||||
options: Parameters<typeof connectToDaemon>[0],
|
||||
) => Promise<AgentLsClient> = connectToDaemon,
|
||||
): Promise<AgentLsResult> {
|
||||
const fetchOptions = buildAgentLsFetchOptions(options);
|
||||
const client = await connect({ target: options.daemonTarget });
|
||||
|
||||
try {
|
||||
@@ -228,6 +223,8 @@ export async function listAgents(
|
||||
throw error;
|
||||
}
|
||||
|
||||
const labelFilters = parseLabelFilters(options.label);
|
||||
const fetchOptions = buildAgentLsFetchOptions(options);
|
||||
let agents = await fetchAllAgents(client, fetchOptions);
|
||||
|
||||
// By default, exclude archived agents. `-a` includes them.
|
||||
@@ -246,8 +243,7 @@ export async function listAgents(
|
||||
}
|
||||
|
||||
// Apply label filtering only when explicitly requested.
|
||||
const labelFilters = fetchOptions.filter?.labels;
|
||||
if (labelFilters) {
|
||||
if (Object.keys(labelFilters).length > 0) {
|
||||
agents = agents.filter((a) => {
|
||||
const agentLabels = a.labels;
|
||||
for (const [key, value] of Object.entries(labelFilters)) {
|
||||
|
||||
@@ -17,7 +17,11 @@ export async function connectTerminalClient(target: DaemonTarget) {
|
||||
try {
|
||||
const daemonClient = await connectToDaemon({ target });
|
||||
const terminals = createTerminalActions(daemonClient, async (workspaceId) => {
|
||||
const workspace = await daemonClient.findWorkspace(workspaceId);
|
||||
const result = await daemonClient.fetchWorkspaces({
|
||||
filter: { idPrefix: workspaceId, includeBackground: true },
|
||||
page: { limit: 10 },
|
||||
});
|
||||
const workspace = result.entries.find((entry) => entry.id === workspaceId);
|
||||
if (!workspace?.workspaceDirectory) {
|
||||
throw new Error(`Workspace ${workspaceId} is not active or has no available directory`);
|
||||
}
|
||||
|
||||
@@ -73,18 +73,6 @@ try {
|
||||
await cli(["terminal", "kill", feature.id]);
|
||||
assert.deepEqual(await cli(["terminal", "ls", "--workspace", second.id]), []);
|
||||
assert.deepEqual(await cli(["terminal", "ls", "--workspace", first.id]), [main]);
|
||||
for (let i = 0; i < 9; i++) {
|
||||
await sdk.workspaces.create({
|
||||
source: { kind: "directory", path: ctx.workDir },
|
||||
title: `extra-${i}`,
|
||||
});
|
||||
}
|
||||
const workspaces = await cli(["workspace", "ls"]);
|
||||
assert.equal(workspaces.length, 11);
|
||||
const { workspaceId, cwd } = workspaces[10];
|
||||
const created = await cli(["terminal", "create", "--workspace", workspaceId, "--name", "Older"]);
|
||||
assert.deepEqual(created, { id: created.id, name: "Older", workspaceId, cwd });
|
||||
await cli(["terminal", "kill", created.id]);
|
||||
console.log("Terminal workspace CLI: ownership, lists, input, capture, kill, and errors passed");
|
||||
} finally {
|
||||
await sdk.close();
|
||||
|
||||
@@ -669,10 +669,9 @@ async function clickGuestElement(page, client, browserId, selector) {
|
||||
}
|
||||
|
||||
async function selectDeviceSize(page, label) {
|
||||
const trigger = page.getByLabel("Device size", { exact: true });
|
||||
const item = page.getByRole("menuitem", { name: label, exact: true });
|
||||
await trigger.click();
|
||||
await item.click({ trial: true, timeout: timeoutMs });
|
||||
await page.locator('[aria-label="Device size"]').click();
|
||||
const item = page.getByText(label, { exact: true });
|
||||
await item.waitFor({ state: "visible", timeout: timeoutMs });
|
||||
const rect = await item.boundingBox();
|
||||
assert(rect, `Device size menu item ${label} had no bounds`);
|
||||
const clip = {
|
||||
@@ -686,9 +685,9 @@ async function selectDeviceSize(page, label) {
|
||||
await item.waitFor({ state: "hidden", timeout: timeoutMs });
|
||||
const closedPixels = await page.screenshot({ clip });
|
||||
|
||||
await trigger.click();
|
||||
// The reopened menu renders off-screen while measuring. Click its current position after layout.
|
||||
await item.click({ timeout: timeoutMs });
|
||||
await page.locator('[aria-label="Device size"]').click();
|
||||
await item.waitFor({ state: "visible", timeout: timeoutMs });
|
||||
await page.mouse.click(rect.x + rect.width / 2, rect.y + rect.height / 2);
|
||||
await page.keyboard.press("Escape");
|
||||
return !openPixels.equals(closedPixels);
|
||||
}
|
||||
|
||||
@@ -1009,50 +1009,3 @@ describe("tunnel provider SDK boundary", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider icon SDK boundary", () => {
|
||||
it("exposes ProviderIcon and PluginProviderIconProps from client UI and client types", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginProviderIconProps,
|
||||
PluginSurfaceProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import {
|
||||
Icon,
|
||||
ProviderIcon,
|
||||
type PluginProviderIconProps as UiProviderIconProps,
|
||||
} from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function Surface({ host, theme }: PluginSurfaceProps) {
|
||||
const explicit: PluginProviderIconProps = {
|
||||
provider: "codex",
|
||||
hostId: host.id,
|
||||
size: 18,
|
||||
color: theme.colors.foreground,
|
||||
};
|
||||
const implicit: UiProviderIconProps = {
|
||||
provider: "claude",
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Icon name="Settings" size={18} color={theme.colors.foreground} />
|
||||
<ProviderIcon {...explicit} />
|
||||
<ProviderIcon {...implicit} />
|
||||
{/* @ts-expect-error provider is required */}
|
||||
<ProviderIcon hostId={host.id} />
|
||||
{/* @ts-expect-error hostId must be a string when passed */}
|
||||
<ProviderIcon provider="codex" hostId={123} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addScreen({ id: "main", title: "Main", Component: Surface });
|
||||
return () => {};
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -159,14 +159,6 @@ export type PluginIcon<Props extends PluginIconProps = PluginIconProps> =
|
||||
| PluginSerializableIcon
|
||||
| ComponentType<Props>;
|
||||
|
||||
export interface PluginProviderIconProps {
|
||||
provider: string;
|
||||
/** Target host ID. Defaults to the current plugin installation's host. */
|
||||
hostId?: string;
|
||||
size?: number;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export type PluginPanelLocation = "workspace" | "explorer";
|
||||
|
||||
export interface PluginOpenPanelOptions {
|
||||
|
||||
@@ -22,7 +22,6 @@ export type {
|
||||
PluginWorkspaceRowBadgeItemProps,
|
||||
PluginWorkspaceRowBadgeItemContribution,
|
||||
PluginIcon,
|
||||
PluginProviderIconProps,
|
||||
PluginPanelLocation,
|
||||
PluginOpenPanelOptions,
|
||||
PluginWorkspacePanelProps,
|
||||
|
||||
@@ -19,7 +19,7 @@ import type {
|
||||
TextProps,
|
||||
} from "react-native";
|
||||
import type { PluginIconProps } from "../icons.js";
|
||||
import type { PluginIcon, PluginProviderIconProps } from "./contracts.js";
|
||||
import type { PluginIcon } from "./contracts.js";
|
||||
|
||||
export interface ModalProps {
|
||||
title: string;
|
||||
@@ -60,8 +60,6 @@ export type IconProps = Partial<PluginIconProps> &
|
||||
({ name: string; icon?: never } | { icon: PluginIcon; name?: never });
|
||||
|
||||
export declare const Icon: ComponentType<IconProps>;
|
||||
/** Renders Paseo's icon for a built-in, catalog, or plugin-provided agent provider. */
|
||||
export declare const ProviderIcon: ComponentType<PluginProviderIconProps>;
|
||||
export declare const Modal: ModalComponent;
|
||||
export declare function useToast(): ToastApi;
|
||||
export interface StreamedTextProps extends Omit<TextProps, "children"> {
|
||||
@@ -72,7 +70,6 @@ export interface StreamedTextProps extends Omit<TextProps, "children"> {
|
||||
export declare const StreamedText: ComponentType<StreamedTextProps>;
|
||||
|
||||
export type { PluginIconProps } from "../icons.js";
|
||||
export type { PluginProviderIconProps } from "./contracts.js";
|
||||
|
||||
/** React Native scrolling with the host's sheet gestures when rendered inside a sheet. */
|
||||
export declare const ScrollView: ForwardRefExoticComponent<
|
||||
|
||||
@@ -4583,7 +4583,6 @@ 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(),
|
||||
],
|
||||
]),
|
||||
@@ -4601,7 +4600,6 @@ 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
|
||||
@@ -4610,7 +4608,6 @@ 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,16 +5525,10 @@ 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: text },
|
||||
item: { type: "notification", level: urgent ? "warning" : "info", message: message.text },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { lastAssistantMessageText } from "../../../assistant-message.js";
|
||||
import { projectTimelineRows } from "../../../timeline-projection.js";
|
||||
import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js";
|
||||
import type { SessionMessageAssistant } from "@opencode/client";
|
||||
import { execFileSync } from "node:child_process";
|
||||
@@ -138,37 +136,3 @@ test.each(["delta", "snapshot"] as const)(
|
||||
expect(retainedBytesAfterStreaming(mode, chunks)).toBeLessThan(textBytes * 32);
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["snapshot", "stream"] as const)(
|
||||
"empty reasoning between two text parts keeps their paragraphs distinct in %s",
|
||||
async (mode) => {
|
||||
const timeline = new V2Timeline();
|
||||
const message = assistant([
|
||||
{ type: "text", text: "I checked content search." },
|
||||
{ type: "reasoning", text: "" },
|
||||
{ type: "text", text: "The newly named tool works." },
|
||||
]);
|
||||
const liveEvents = [];
|
||||
if (mode === "stream") {
|
||||
const commentary = { assistantMessageID: message.id, type: "text" as const, ordinal: 0 };
|
||||
timeline.startPart(commentary);
|
||||
liveEvents.push(timeline.delta({ ...commentary, delta: "I checked content search." }));
|
||||
const final = { ...commentary, ordinal: 1 };
|
||||
timeline.startPart(final);
|
||||
liveEvents.push(timeline.delta({ ...final, delta: "The newly" }));
|
||||
}
|
||||
const replayEvents = await collectTimelineSnapshot(timeline, [message]);
|
||||
const rows = [...liveEvents, ...replayEvents].flatMap((event, index) =>
|
||||
event?.type === "timeline"
|
||||
? [{ item: event.item, timestamp: event.timestamp, seq: index + 1, turnId: "turn" }]
|
||||
: [],
|
||||
);
|
||||
const replies = projectTimelineRows({ rows, mode: "projected" }).flatMap(({ item }) =>
|
||||
item.type === "assistant_message" ? [item.text] : [],
|
||||
);
|
||||
|
||||
const expected = "I checked content search.\n\nThe newly named tool works.";
|
||||
expect.soft(replies).toEqual([expected]);
|
||||
expect.soft(lastAssistantMessageText(rows)).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -49,13 +49,11 @@ export class V2Timeline {
|
||||
if (!text.startsWith(emitted))
|
||||
throw new Error("OpenCode changed previously emitted message content");
|
||||
this.content.set(key, text);
|
||||
const item = this.textItem({
|
||||
messageID: event.assistantMessageID,
|
||||
type: event.type,
|
||||
ordinal: event.ordinal,
|
||||
text,
|
||||
previous: emitted,
|
||||
});
|
||||
const suffix = detachedSuffix(text, emitted.length);
|
||||
const item: AgentTimelineItem =
|
||||
event.type === "text"
|
||||
? { type: "assistant_message", text: suffix, messageId: event.assistantMessageID }
|
||||
: { type: "reasoning", text: suffix };
|
||||
return { type: "timeline", provider: "opencode", item, timestamp: new Date().toISOString() };
|
||||
}
|
||||
|
||||
@@ -201,35 +199,10 @@ export class V2Timeline {
|
||||
if (!part.text.startsWith(previous))
|
||||
throw new Error("OpenCode changed previously emitted message content");
|
||||
this.content.set(key, part.text);
|
||||
push(this.textItem({ messageID, type: part.type, ordinal, text: part.text, previous }));
|
||||
}
|
||||
|
||||
private textItem({
|
||||
messageID,
|
||||
type,
|
||||
ordinal,
|
||||
text,
|
||||
previous,
|
||||
}: {
|
||||
messageID: string;
|
||||
type: "text" | "reasoning";
|
||||
ordinal: number;
|
||||
text: string;
|
||||
previous: string;
|
||||
}): AgentTimelineItem {
|
||||
const suffix = detachedSuffix(text, previous.length);
|
||||
if (type === "reasoning") return { type: "reasoning", text: suffix };
|
||||
|
||||
// Projection joins chunks with the same message ID. Separate OpenCode text parts
|
||||
// once, at the first emitted chunk, so live output and history replay agree.
|
||||
if (previous.length === 0) {
|
||||
for (let earlier = ordinal - 1; earlier >= 0; earlier--) {
|
||||
if (this.content.has(textPartKey(messageID, "text", earlier))) {
|
||||
return { type: "assistant_message", text: `\n\n${suffix}`, messageId: messageID };
|
||||
}
|
||||
}
|
||||
}
|
||||
return { type: "assistant_message", text: suffix, messageId: messageID };
|
||||
const suffix = detachedSuffix(part.text, previous.length);
|
||||
if (part.type === "text")
|
||||
push({ type: "assistant_message", text: suffix, messageId: messageID });
|
||||
else push({ type: "reasoning", text: suffix });
|
||||
}
|
||||
|
||||
private async toolPart(
|
||||
|
||||
@@ -422,49 +422,3 @@ 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,16 +35,8 @@ class ObservationControls implements FileObserverDependencies {
|
||||
this.interval = null;
|
||||
}
|
||||
|
||||
signalFileChange(filename: string): void {
|
||||
this.change?.(filename);
|
||||
}
|
||||
|
||||
async fileChanged(filename: string): Promise<void> {
|
||||
this.signalFileChange(filename);
|
||||
await this.flushPendingChange();
|
||||
}
|
||||
|
||||
async flushPendingChange(): Promise<void> {
|
||||
this.change?.(filename);
|
||||
const timeout = this.timeout;
|
||||
this.timeout = null;
|
||||
await timeout?.();
|
||||
@@ -90,30 +82,6 @@ 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,10 +26,8 @@ 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;
|
||||
@@ -64,27 +62,29 @@ export class FileObserver {
|
||||
const target = await resolveExplorerFilePath({ root: input.cwd, relativePath: input.path });
|
||||
let observed = this.observed.get(target);
|
||||
if (!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 = 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);
|
||||
}
|
||||
}
|
||||
const initial = await getExplorerFileVersion({
|
||||
root: input.cwd,
|
||||
relativePath: input.path,
|
||||
});
|
||||
observed.listeners.set(listener, {
|
||||
cwd: initial.cwd,
|
||||
path: initial.path,
|
||||
fingerprint: fingerprint(initial),
|
||||
});
|
||||
observed.listeners.set(listener, { cwd: initial.cwd, path: initial.path });
|
||||
observed.fingerprint = fingerprint(initial);
|
||||
|
||||
let active = true;
|
||||
return {
|
||||
@@ -148,10 +148,10 @@ export class FileObserver {
|
||||
relativePath: observed.path,
|
||||
});
|
||||
const nextFingerprint = fingerprint(version);
|
||||
for (const [listener, subscription] of observed.listeners) {
|
||||
if (nextFingerprint === subscription.fingerprint) continue;
|
||||
subscription.fingerprint = nextFingerprint;
|
||||
listener({ ...version, cwd: subscription.cwd, path: subscription.path });
|
||||
if (nextFingerprint === observed.fingerprint) return;
|
||||
observed.fingerprint = nextFingerprint;
|
||||
for (const [listener, identity] of observed.listeners) {
|
||||
listener({ ...version, ...identity });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7577,172 +7577,3 @@ 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,35 +2468,30 @@ 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;
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
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,7 +96,6 @@ 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>[] = [];
|
||||
@@ -137,10 +136,6 @@ 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(
|
||||
@@ -181,9 +176,6 @@ 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")
|
||||
@@ -803,36 +795,3 @@ 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,12 +62,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -188,7 +182,6 @@ 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,
|
||||
@@ -351,22 +344,13 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
return payload;
|
||||
}
|
||||
|
||||
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>,
|
||||
async function emitAgentUpdate(
|
||||
workspaceId: string | undefined,
|
||||
projectPayload?: () => AgentSnapshotPayload | Promise<AgentSnapshotPayload>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (hasSubscription()) await publishPayload(await projectPayload());
|
||||
if (projectPayload && hasSubscription()) await publishPayload(await projectPayload());
|
||||
if (workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId);
|
||||
} catch (error) {
|
||||
deps.logger.error({ err: error }, "Failed to emit agent update");
|
||||
}
|
||||
@@ -387,40 +371,23 @@ 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()) {
|
||||
return agent.workspaceId ? triggerWorkspaceUpdate(agent.workspaceId) : Promise.resolve();
|
||||
const workspaceId = agent.workspaceId;
|
||||
return workspaceId
|
||||
? enqueueAgentUpdate(agent.id, () => emitAgentUpdate(workspaceId))
|
||||
: Promise.resolve();
|
||||
}
|
||||
const payload = toAgentPayload(agent);
|
||||
return forwardWithWorkspaceUpdate(payload.id, payload.workspaceId, () =>
|
||||
deps.enrichAgentPayload(payload),
|
||||
return enqueueAgentUpdate(payload.id, () =>
|
||||
emitAgentUpdate(payload.workspaceId, () => deps.enrichAgentPayload(payload)),
|
||||
);
|
||||
}
|
||||
|
||||
function forwardStoredAgent(record: StoredAgentRecord): Promise<void> {
|
||||
if (!hasSubscription() && !record.workspaceId) return Promise.resolve();
|
||||
return forwardWithWorkspaceUpdate(record.id, record.workspaceId, () =>
|
||||
deps.buildStoredAgentPayload(record),
|
||||
return enqueueAgentUpdate(record.id, () =>
|
||||
emitAgentUpdate(record.workspaceId, () => deps.buildStoredAgentPayload(record)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -433,23 +400,10 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
}
|
||||
|
||||
async function flushPendingUpdates(): Promise<void> {
|
||||
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);
|
||||
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());
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
@@ -467,7 +421,6 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
emitStoredRecord,
|
||||
removeAgent,
|
||||
flushPendingUpdates,
|
||||
runAfterUpdates,
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
|
||||
+1
-130
@@ -1,7 +1,6 @@
|
||||
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,
|
||||
@@ -50,9 +49,7 @@ function flushMicrotasks(): Promise<void> {
|
||||
return new Promise((done) => setImmediate(done));
|
||||
}
|
||||
|
||||
function buildHarness(
|
||||
opts: { emitCwdRejects?: boolean; configWatchRejects?: boolean; configExists?: boolean } = {},
|
||||
) {
|
||||
function buildHarness(opts: { emitCwdRejects?: boolean } = {}) {
|
||||
const listeners = new Map<string, WorkspaceGitListener>();
|
||||
const registerCalls: string[] = [];
|
||||
const unsubscribeCalls: string[] = [];
|
||||
@@ -60,30 +57,6 @@ function buildHarness(
|
||||
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) {
|
||||
@@ -112,7 +85,6 @@ function buildHarness(
|
||||
onBranchChanged: (workspaceId, oldBranch, newBranch) => {
|
||||
branchChanges.push([workspaceId, oldBranch, newBranch]);
|
||||
},
|
||||
configObserver,
|
||||
logger: { warn: (...args: unknown[]) => warnCalls.push(args) } as unknown as pino.Logger,
|
||||
});
|
||||
|
||||
@@ -124,25 +96,9 @@ function buildHarness(
|
||||
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,
|
||||
@@ -386,88 +342,3 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
+5
-82
@@ -1,7 +1,5 @@
|
||||
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,
|
||||
@@ -34,9 +32,6 @@ 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;
|
||||
@@ -61,7 +56,6 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
oldBranch: string | null,
|
||||
newBranch: string | null,
|
||||
) => void;
|
||||
configObserver?: Pick<FileObserver, "subscribe">;
|
||||
logger: pino.Logger;
|
||||
}): WorkspaceGitObserverService {
|
||||
const {
|
||||
@@ -69,72 +63,12 @@ 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,
|
||||
@@ -161,7 +95,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
subscriptions.delete(normalizedCwd);
|
||||
}
|
||||
|
||||
function removeGitObservation(workspaceId: string): void {
|
||||
function removeForWorkspaceId(workspaceId: string): void {
|
||||
const state = workspaceStates.get(workspaceId);
|
||||
if (!state) {
|
||||
return;
|
||||
@@ -174,11 +108,6 @@ 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) {
|
||||
@@ -201,13 +130,12 @@ 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) {
|
||||
removeGitObservation(options.workspaceId);
|
||||
removeForWorkspaceId(options.workspaceId);
|
||||
}
|
||||
if (!options.isGit) {
|
||||
removeGitObservation(options.workspaceId);
|
||||
removeForWorkspaceId(options.workspaceId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -240,7 +168,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
emitStatusUpdate(normalizedCwd, snapshot);
|
||||
});
|
||||
} catch (error) {
|
||||
removeGitObservation(options.workspaceId);
|
||||
removeForWorkspaceId(options.workspaceId);
|
||||
throw error;
|
||||
}
|
||||
subscriptions.set(normalizedCwd, subscription.unsubscribe);
|
||||
@@ -259,7 +187,7 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
return {
|
||||
reconcileObservers(workspaces) {
|
||||
const retained = new Map([...workspaces].map((workspace) => [workspace.id, workspace]));
|
||||
for (const workspaceId of new Set([...workspaceStates.keys(), ...configCwds.keys()])) {
|
||||
for (const workspaceId of workspaceStates.keys()) {
|
||||
if (!retained.has(workspaceId)) removeForWorkspaceId(workspaceId);
|
||||
}
|
||||
for (const workspace of retained.values()) {
|
||||
@@ -300,11 +228,6 @@ export function createWorkspaceGitObserverService(deps: {
|
||||
subscriptions.clear();
|
||||
watchTargets.clear();
|
||||
workspaceStates.clear();
|
||||
for (const watch of configWatches.values()) {
|
||||
watch.release();
|
||||
}
|
||||
configWatches.clear();
|
||||
configCwds.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -278,7 +278,7 @@ guarantee compatibility with another host's renderer.
|
||||
|
||||
These exact module specifiers use the host's runtime instances. A client bundle that requests another host module fails with `Module "<name>" is not available in plugin client code`.
|
||||
|
||||
Do not import `lucide-react-native`, `react-native-svg`, or DOM libraries. Use the host-rendered `Icon` and `ProviderIcon` components in plugin UI. Contribution `icon` fields take a [Lucide icon name](https://lucide.dev/icons/), inline SVG, or a component; Paseo validates the icon and renders it. See [Icons](#icons).
|
||||
Do not import `lucide-react-native`, `react-native-svg`, or DOM libraries. Set contribution `icon` fields to a [Lucide icon name](https://lucide.dev/icons/), inline SVG, or a component; Paseo validates the icon and renders it. See [Icons](#icons).
|
||||
|
||||
### Cross-platform rules
|
||||
|
||||
@@ -1658,24 +1658,6 @@ not import `lucide-react-native` or `react-native-svg`.
|
||||
|
||||
An unknown name or an SVG that breaks a rule renders nothing.
|
||||
|
||||
`ProviderIcon` renders Paseo's icon for a built-in, catalog, or plugin-provided agent provider.
|
||||
When `hostId` is omitted, it uses the current plugin installation's host; pass `hostId` explicitly
|
||||
when rendering across hosts, such as in a sidebar view.
|
||||
|
||||
```tsx
|
||||
<ProviderIcon provider="codex" size={18} color={theme.colors.foreground} />
|
||||
<ProviderIcon provider="codex" hostId={host.id} size={18} color={theme.colors.foreground} />
|
||||
```
|
||||
|
||||
| Prop | Type | Required | Behavior |
|
||||
| ---------- | -------- | -------- | ------------------------------------------------------------ |
|
||||
| `provider` | `string` | Yes | Provider ID, such as `codex`, `claude`, or `cursor`. |
|
||||
| `hostId` | `string` | No | Target host ID. Defaults to the current plugin installation. |
|
||||
| `size` | `number` | No | Icon width and height. Defaults to 24. |
|
||||
| `color` | `string` | No | Icon color and SVG `currentColor`. Use a plugin theme token. |
|
||||
|
||||
Unknown providers render Paseo's standard provider fallback.
|
||||
|
||||
## Timeline items
|
||||
|
||||
A plugin can replace an agent timeline entry with its own data and React Native renderer. Both
|
||||
|
||||
@@ -228,7 +228,7 @@ Paseo 为客户端代码提供以下模块:
|
||||
|
||||
这些确切的模块标识符使用宿主的运行时实例。请求其他宿主模块的客户端包会以 `Module "<name>" is not available in plugin client code` 失败。
|
||||
|
||||
不要导入 `lucide-react-native`、`react-native-svg` 或 DOM 库。在插件 UI 中请使用宿主渲染的 `Icon` 和 `ProviderIcon` 组件。贡献的 `icon` 字段接受 [Lucide 图标名称](https://lucide.dev/icons/)、内联 SVG 或组件;Paseo 会校验图标并渲染它。参见[图标](#icons)。
|
||||
不要导入 `lucide-react-native`、`react-native-svg` 或 DOM 库。把贡献的 `icon` 字段设为一个 [Lucide 图标名称](https://lucide.dev/icons/)、内联 SVG 或组件;Paseo 会校验图标并渲染它。参见[图标](#icons)。
|
||||
|
||||
### 跨平台规则 {#cross-platform-rules}
|
||||
|
||||
@@ -1317,22 +1317,6 @@ client.addWorkspacePanel({ id: "review", title: "Review", icon: { svg: reviewIco
|
||||
|
||||
未知的名称或违反规则的 SVG 不会渲染任何内容。
|
||||
|
||||
`ProviderIcon` 用于渲染内置、目录或插件提供的 Agent Provider 图标。省略 `hostId` 时,默认使用当前插件安装所在的宿主;跨宿主渲染(例如在侧边栏视图中)时请显式传入 `hostId`。
|
||||
|
||||
```tsx
|
||||
<ProviderIcon provider="codex" size={18} color={theme.colors.foreground} />
|
||||
<ProviderIcon provider="codex" hostId={host.id} size={18} color={theme.colors.foreground} />
|
||||
```
|
||||
|
||||
| 属性 | 类型 | 是否必填 | 行为 |
|
||||
| ---------- | -------- | -------- | ---------------------------------------------------------- |
|
||||
| `provider` | `string` | 是 | Provider ID,例如 `codex`、`claude` 或 `cursor`。 |
|
||||
| `hostId` | `string` | 否 | 目标宿主 ID。默认使用当前插件安装所在的宿主。 |
|
||||
| `size` | `number` | 否 | 图标的宽度和高度。默认为 24。 |
|
||||
| `color` | `string` | 否 | 图标颜色,也是 SVG 的 `currentColor`。请使用插件主题令牌。 |
|
||||
|
||||
未知的 Provider 会渲染 Paseo 的标准 Provider 回退图标。
|
||||
|
||||
## 时间线条目 {#timeline-items}
|
||||
|
||||
插件可以用自己的数据和 React Native 渲染器替换 Agent 时间线中的条目。两项注册都是客户端贡献。Paseo 在构建渲染模型时应用转换器,包括每一次实时的流式更新。
|
||||
|
||||
@@ -16,15 +16,12 @@ 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 (--ref <git-ref> | --tag <vX.Y.Z[-beta.N]>)\n",
|
||||
);
|
||||
process.stderr.write("Usage: node scripts/reconcile-release.mjs --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") {
|
||||
@@ -32,20 +29,15 @@ 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 (Boolean(tag) === Boolean(ref)) {
|
||||
if (!tag) {
|
||||
usageAndExit(1);
|
||||
}
|
||||
return ref ? { ref } : { tag };
|
||||
return { tag };
|
||||
}
|
||||
|
||||
function splitRawEntries(content) {
|
||||
@@ -68,12 +60,12 @@ function safeParseVersion(version) {
|
||||
}
|
||||
}
|
||||
|
||||
export function mergeChangelogEntry(mainContent, releaseContent, targetVersion) {
|
||||
export function mergeChangelogEntry(mainContent, tagContent, targetVersion) {
|
||||
const target = parseReleaseVersion(targetVersion);
|
||||
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 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 mainParsed = splitRawEntries(mainContent);
|
||||
@@ -122,7 +114,7 @@ export function mergeChangelogEntry(mainContent, releaseContent, targetVersion)
|
||||
insertIndex = kept.length;
|
||||
}
|
||||
|
||||
kept.splice(insertIndex, 0, releaseBlock);
|
||||
kept.splice(insertIndex, 0, taggedBlock);
|
||||
|
||||
const parts = [];
|
||||
if (mainParsed.preamble.length > 0) {
|
||||
@@ -134,15 +126,15 @@ export function mergeChangelogEntry(mainContent, releaseContent, targetVersion)
|
||||
return `${parts.join("\n\n")}\n`;
|
||||
}
|
||||
|
||||
function defaultVerifyRef(ref, cwd) {
|
||||
execFileSync("git", ["rev-parse", "--verify", `${ref}^{commit}`], {
|
||||
function defaultVerifyTag(tag, cwd) {
|
||||
execFileSync("git", ["rev-parse", "--verify", `refs/tags/${tag}^{commit}`], {
|
||||
cwd,
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
function defaultReadRefFile(ref, filePath, cwd) {
|
||||
return execFileSync("git", ["show", `${ref}:${filePath}`], {
|
||||
function defaultReadTagFile(tag, filePath, cwd) {
|
||||
return execFileSync("git", ["show", `${tag}:${filePath}`], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
});
|
||||
@@ -177,29 +169,23 @@ function lockfileMatchesVersion(cwd, rootPackage, version) {
|
||||
|
||||
export function reconcileRelease(options, deps = {}) {
|
||||
const cwd = options.cwd ?? rootDir;
|
||||
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 tag = normalizeReleaseTag(options.tag);
|
||||
const version = tag.slice(1);
|
||||
const parsed = parseReleaseVersion(version);
|
||||
|
||||
const verifyRef = deps.verifyRef ?? ((target) => defaultVerifyRef(target, cwd));
|
||||
const readRefFile =
|
||||
deps.readRefFile ?? ((target, filePath) => defaultReadRefFile(target, filePath, cwd));
|
||||
const verifyTag = deps.verifyTag ?? ((targetTag) => defaultVerifyTag(targetTag, cwd));
|
||||
const readTagFile =
|
||||
deps.readTagFile ?? ((targetTag, filePath) => defaultReadTagFile(targetTag, filePath, cwd));
|
||||
const runNpm = deps.runNpm ?? ((args) => defaultRunNpm(args, cwd));
|
||||
const getFdroidVersionCodes = deps.getFdroidVersionCodes ?? defaultGetFdroidVersionCodes;
|
||||
|
||||
verifyRef(ref);
|
||||
|
||||
const version = tag ? tag.slice(1) : JSON.parse(readRefFile(ref, "package.json")).version;
|
||||
const parsed = parseReleaseVersion(version);
|
||||
verifyTag(tag);
|
||||
|
||||
for (const changelogFile of ["CHANGELOG.md", "CHANGELOG.zh-CN.md"]) {
|
||||
const targetPath = path.join(cwd, changelogFile);
|
||||
const mainContent = readFileSync(targetPath, "utf8");
|
||||
const refContent = readRefFile(ref, changelogFile);
|
||||
const merged = mergeChangelogEntry(mainContent, refContent, version);
|
||||
const tagContent = readTagFile(tag, changelogFile);
|
||||
const merged = mergeChangelogEntry(mainContent, tagContent, version);
|
||||
writeFileSync(targetPath, merged);
|
||||
}
|
||||
|
||||
@@ -214,7 +200,7 @@ export function reconcileRelease(options, deps = {}) {
|
||||
"changelogs",
|
||||
`${versionCode}.txt`,
|
||||
);
|
||||
const content = readRefFile(ref, relativePath.replaceAll("\\", "/"));
|
||||
const content = readTagFile(tag, relativePath.replaceAll("\\", "/"));
|
||||
const destination = path.join(cwd, relativePath);
|
||||
mkdirSync(path.dirname(destination), { recursive: true });
|
||||
writeFileSync(destination, content);
|
||||
@@ -246,7 +232,7 @@ export function reconcileRelease(options, deps = {}) {
|
||||
console.log(`Kept main version at ${currentMainVersion} (newer than or equal to ${version}).`);
|
||||
}
|
||||
|
||||
return { ref, version, versionUpdated, fdroidFiles };
|
||||
return { tag, 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 },
|
||||
],
|
||||
readRefFile(_ref, filePath) {
|
||||
readTagFile(_tag, filePath) {
|
||||
if (!tagFiles.has(filePath)) {
|
||||
throw new Error(`Missing ${filePath}`);
|
||||
}
|
||||
return tagFiles.get(filePath);
|
||||
},
|
||||
verifyRef: () => {},
|
||||
verifyTag: () => {},
|
||||
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 }],
|
||||
readRefFile(_ref, filePath) {
|
||||
readTagFile(_tag, filePath) {
|
||||
return tagFiles.get(filePath);
|
||||
},
|
||||
verifyRef: () => {},
|
||||
verifyTag: () => {},
|
||||
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 },
|
||||
{
|
||||
readRefFile: (_ref, filePath) => tagFiles.get(filePath),
|
||||
verifyRef: () => {},
|
||||
readTagFile: (_tag, filePath) => tagFiles.get(filePath),
|
||||
verifyTag: () => {},
|
||||
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 },
|
||||
{
|
||||
readRefFile: (_ref, filePath) => tagFiles.get(filePath),
|
||||
verifyRef: () => {},
|
||||
readTagFile: (_tag, filePath) => tagFiles.get(filePath),
|
||||
verifyTag: () => {},
|
||||
runNpm(args) {
|
||||
ranCommands.push(args);
|
||||
},
|
||||
@@ -287,109 +287,3 @@ 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