mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-06 07:06:16 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47f784aaa0 | ||
|
|
7afeffc712 | ||
|
|
774e2024a9 | ||
|
|
11e98262ce | ||
|
|
7734caec13 | ||
|
|
c7fda6b141 | ||
|
|
f8422d956a | ||
|
|
47bf732a05 |
@@ -67,6 +67,8 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
packages: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
@@ -79,6 +81,14 @@ jobs:
|
||||
shell: bash
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify attestation source
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$(git rev-parse HEAD)" != "$GITHUB_SHA" ]]; then
|
||||
echo "::error::Run this workflow from the release tag so provenance names the checked-out commit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -142,9 +152,18 @@ jobs:
|
||||
echo "asset_name=$asset_name" >> "$GITHUB_OUTPUT"
|
||||
echo "asset_path=$asset_path" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Attest Android APK
|
||||
uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3
|
||||
with:
|
||||
subject-path: ${{ steps.artifact.outputs.asset_path }}
|
||||
|
||||
- name: Generate Android checksum
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: sha256sum "${{ steps.artifact.outputs.asset_name }}" > SHA256SUMS-android.txt
|
||||
|
||||
- name: Upload APK to GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
|
||||
gh release upload "$release_lookup" "${{ steps.artifact.outputs.asset_path }}" --clobber --repo "${{ github.repository }}"
|
||||
gh release upload "$release_lookup" "${{ steps.artifact.outputs.asset_path }}" "${{ runner.temp }}/SHA256SUMS-android.txt" --clobber --repo "${{ github.repository }}"
|
||||
|
||||
@@ -59,7 +59,7 @@ jobs:
|
||||
filters: .github/ci-paths.yml
|
||||
|
||||
- name: Validate CI contracts
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/release-checksums.test.mjs scripts/precompress-assets.test.mjs
|
||||
|
||||
quality:
|
||||
name: quality
|
||||
|
||||
@@ -110,6 +110,8 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
packages: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
runs-on: ${{ matrix.runner }}
|
||||
|
||||
steps:
|
||||
@@ -122,6 +124,15 @@ jobs:
|
||||
shell: bash
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify attestation source
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$(git rev-parse HEAD)" != "$GITHUB_SHA" || "$(git rev-parse "refs/tags/${SOURCE_TAG#refs/tags/}^{commit}")" != "$GITHUB_SHA" ]]; then
|
||||
echo "::error::Run this workflow from the checked-out release ref so provenance names the built commit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -190,6 +201,10 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Generate desktop checksums
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
run: node scripts/release-checksums.mjs "${{ env.DESKTOP_PACKAGE_PATH }}/release" "SHA256SUMS-desktop-macos-${{ matrix.electron_arch }}.txt"
|
||||
|
||||
- name: Upload desktop artifacts to release
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
env:
|
||||
@@ -201,6 +216,19 @@ jobs:
|
||||
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
|
||||
node scripts/upload-release-assets.mjs "$release_lookup" "$release_dir" "${{ github.repository }}"
|
||||
|
||||
- name: Attest desktop binaries
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3
|
||||
with:
|
||||
subject-path: |
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.dmg
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.zip
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.exe
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.AppImage
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.deb
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.rpm
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.tar.gz
|
||||
|
||||
- name: Upload desktop artifacts to workflow
|
||||
if: env.SHOULD_PUBLISH != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -223,6 +251,8 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
packages: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
@@ -235,6 +265,15 @@ jobs:
|
||||
shell: bash
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify attestation source
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$(git rev-parse HEAD)" != "$GITHUB_SHA" || "$(git rev-parse "refs/tags/${SOURCE_TAG#refs/tags/}^{commit}")" != "$GITHUB_SHA" ]]; then
|
||||
echo "::error::Run this workflow from the checked-out release ref so provenance names the built commit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -291,6 +330,10 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Generate desktop checksums
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
run: node scripts/release-checksums.mjs "${{ env.DESKTOP_PACKAGE_PATH }}/release" "SHA256SUMS-desktop-linux.txt"
|
||||
|
||||
- name: Upload desktop artifacts to release
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
env:
|
||||
@@ -302,6 +345,19 @@ jobs:
|
||||
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
|
||||
node scripts/upload-release-assets.mjs "$release_lookup" "$release_dir" "${{ github.repository }}"
|
||||
|
||||
- name: Attest desktop binaries
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3
|
||||
with:
|
||||
subject-path: |
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.dmg
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.zip
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.exe
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.AppImage
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.deb
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.rpm
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.tar.gz
|
||||
|
||||
- name: Upload desktop artifacts to workflow
|
||||
if: env.SHOULD_PUBLISH != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -324,6 +380,8 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
packages: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
@@ -336,6 +394,15 @@ jobs:
|
||||
shell: bash
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify attestation source
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$(git rev-parse HEAD)" != "$GITHUB_SHA" || "$(git rev-parse "refs/tags/${SOURCE_TAG#refs/tags/}^{commit}")" != "$GITHUB_SHA" ]]; then
|
||||
echo "::error::Run this workflow from the checked-out release ref so provenance names the built commit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -389,6 +456,10 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Generate desktop checksums
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
run: node scripts/release-checksums.mjs "${{ env.DESKTOP_PACKAGE_PATH }}/release" "SHA256SUMS-desktop-windows.txt"
|
||||
|
||||
- name: Upload desktop artifacts to release
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
env:
|
||||
@@ -400,6 +471,19 @@ jobs:
|
||||
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
|
||||
node scripts/upload-release-assets.mjs "$release_lookup" "$release_dir" "${{ github.repository }}"
|
||||
|
||||
- name: Attest desktop binaries
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3
|
||||
with:
|
||||
subject-path: |
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.dmg
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.zip
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.exe
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.AppImage
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.deb
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.rpm
|
||||
${{ env.DESKTOP_PACKAGE_PATH }}/release/*.tar.gz
|
||||
|
||||
- name: Upload desktop artifacts to workflow
|
||||
if: env.SHOULD_PUBLISH != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -434,11 +518,21 @@ jobs:
|
||||
package-lock.json
|
||||
scripts
|
||||
ref: ${{ env.CHECKOUT_REF }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Resolve release tag
|
||||
shell: bash
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify release source
|
||||
if: env.IS_SMOKE_TAG != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$(git rev-parse HEAD)" != "$GITHUB_SHA" || "$(git rev-parse "refs/tags/${SOURCE_TAG#refs/tags/}^{commit}")" != "$GITHUB_SHA" ]]; then
|
||||
echo "::error::Run this workflow from the release tag so provenance names the built commit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
name: NPM Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
package:
|
||||
description: Package to publish
|
||||
type: choice
|
||||
default: "@getpaseo/highlight"
|
||||
options:
|
||||
- "@getpaseo/highlight"
|
||||
- all
|
||||
canary_suffix:
|
||||
description: "Canary suffix (default: canary.<run_id>.<run_attempt>)"
|
||||
type: string
|
||||
required: false
|
||||
dry_run:
|
||||
description: Preview publication without publishing
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
concurrency:
|
||||
group: npm-release
|
||||
queue: max
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Require main for manual runs
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
REF: ${{ github.ref }}
|
||||
run: test "$REF" = refs/heads/main
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
|
||||
with:
|
||||
node-version: "22.20.0"
|
||||
package-manager-cache: false
|
||||
- name: Install npm with trusted publishing support
|
||||
run: npm install --global npm@11.21.0
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Stamp canary versions
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
CANARY_SUFFIX: ${{ inputs.canary_suffix }}
|
||||
PACKAGE: ${{ inputs.package }}
|
||||
run: node scripts/publish-release-packages.mjs --prepare-canary --canary-suffix "${CANARY_SUFFIX:-canary.$GITHUB_RUN_ID.$GITHUB_RUN_ATTEMPT}" --package "$PACKAGE"
|
||||
- name: Build packages
|
||||
run: npm run build:server
|
||||
- name: Publish canary packages
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
CANARY_SUFFIX: ${{ inputs.canary_suffix }}
|
||||
PACKAGE: ${{ inputs.package }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
run: |
|
||||
args=(--canary-suffix "${CANARY_SUFFIX:-canary.$GITHUB_RUN_ID.$GITHUB_RUN_ATTEMPT}" --package "$PACKAGE" --tag canary)
|
||||
if [ "$DRY_RUN" = true ]; then args+=(--dry-run); fi
|
||||
node scripts/publish-release-packages.mjs "${args[@]}"
|
||||
- name: Publish packages
|
||||
if: github.event_name == 'push'
|
||||
run: node scripts/publish-release-packages.mjs --tag "$GITHUB_REF_NAME"
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.2 - 2026-12-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal `/skill` text instead of loading the skill ([#12142](https://github.com/getpaseo/paseo/pull/12142))
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading ([#12143](https://github.com/getpaseo/paseo/pull/12143))
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends ([#12082](https://github.com/getpaseo/paseo/pull/12082))
|
||||
|
||||
## 0.19.1 - 2026-12-03
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.2 - 2026-12-05
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 OpenCode v2 中在消息中间、带附件或运行中选择的 Skill 被当作字面 `/skill` 文本发送而未加载的问题 ([#12142](https://github.com/getpaseo/paseo/pull/12142))
|
||||
- 修复 Codex 中在消息中间、带附件或运行中选择的 Skill 未加载的问题 ([#12143](https://github.com/getpaseo/paseo/pull/12143))
|
||||
- 修复桌面端图片附件在多窗口、切换标签页和排队发送追问消息时丢失的问题 ([#12082](https://github.com/getpaseo/paseo/pull/12082))
|
||||
|
||||
## 0.19.1 - 2026-12-03
|
||||
|
||||
### 变更
|
||||
|
||||
+49
-35
@@ -24,8 +24,8 @@ Preparation is reversible and runs on the release branch before the user authori
|
||||
|
||||
Ship starts after the user says "go ahead". All tag-triggered GitHub Actions workflows and EAS workflows build from the checked-out tag commit with local workspace packages, so none of them install `@getpaseo/*` from the public npm registry.
|
||||
|
||||
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.
|
||||
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 `NPM Release`, `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. Watch `NPM Release`. It publishes the seven `@getpaseo/*` packages through Trusted Publishing and checks npm visibility after publishing all packages.
|
||||
3. Check the green [reconcile `main`](#reconcile-main) PR against the pushed tag, then merge it right after `npm run release:push` finishes, in parallel with npm publication and the release builds. Wait for its checks only if the tag check produced changes.
|
||||
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
|
||||
|
||||
@@ -34,7 +34,7 @@ Ship starts after the user says "go ahead". All tag-triggered GitHub Actions wor
|
||||
Wait until every gate below passes before deleting the remote release branch or reporting the release as shipped:
|
||||
|
||||
- All seven `@getpaseo/*` npm packages are visible on `latest` (stable) or `beta` (beta), and on stable the `beta` dist-tag points to the shipped version unless an active newer beta exists.
|
||||
- All tag-triggered GitHub Actions workflows are green (`Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` for stable), and `Deploy Website` ran after stable publication.
|
||||
- All tag-triggered GitHub Actions workflows are green (`NPM Release`, `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` for stable), and `Deploy Website` ran after stable publication.
|
||||
- The GitHub Release is published and non-draft (marked prerelease for beta) with the synced changelog body, all macOS, Linux, and Windows assets, the Android APK asset, and all three channel manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml` for stable; `beta-mac.yml`, `beta-linux.yml`, `beta.yml` for beta).
|
||||
- The matching EAS workflow is green (`Release Mobile` with all six build, distribution, screenshot, and review-submission jobs for stable; `Release iOS Beta` for beta).
|
||||
- The reconcile PR is merged into `main`.
|
||||
@@ -50,6 +50,29 @@ Rules that apply to both steps:
|
||||
- An approval the user already gave covers what it names, such as an explicit PR selection or authorization to release autonomously. Do not ask for it again.
|
||||
- If the user asks for a release preview, show the prospective changelog/release contents and answer questions, but do not commit, tag, publish, or run release commands until they explicitly authorize the release.
|
||||
|
||||
## npm Trusted Publishing setup
|
||||
|
||||
Before the first release using this workflow, configure each of `@getpaseo/highlight`, `@getpaseo/relay`, `@getpaseo/protocol`, `@getpaseo/client`, `@getpaseo/plugin`, `@getpaseo/server`, and `@getpaseo/cli` on npmjs.com:
|
||||
|
||||
1. Add a GitHub Actions trusted publisher with organization `getpaseo`, repository `paseo`, and workflow filename `npm-release.yml`.
|
||||
2. Enable **Allow npm dist-tag** for the publisher.
|
||||
3. Set publishing access to **Require two-factor authentication and disallow tokens**.
|
||||
4. Publish within two days of adding the publisher, or recreate it before the first publish.
|
||||
|
||||
The tag push starts `NPM Release`. Rerun the failed workflow from GitHub Actions if publication fails. npm generates provenance for successful trusted publishes.
|
||||
|
||||
For manual Desktop or Android release runs, select the release tag as the workflow ref. The checked-out commit must match the workflow commit for the GitHub attestation. The Android attestation records the workflow that requested and downloaded the EAS build; it does not independently attest the EAS builder.
|
||||
|
||||
### Test Trusted Publishing with a canary
|
||||
|
||||
In GitHub Actions, open **NPM Release** and select **Run workflow** on `main`.
|
||||
Choose `@getpaseo/highlight` or `all`, then run the workflow. The default suffix uses the run ID and attempt.
|
||||
Set `dry_run` to preview publication without publishing. For a live run, verify provenance on npmjs.com.
|
||||
|
||||
To clean up, run `npm dist-tag rm <pkg> canary` for each published package.
|
||||
Check [npm's unpublish policy](https://docs.npmjs.com/policies/unpublish/) before running `npm unpublish <pkg>@<version>`.
|
||||
If npm does not permit removal, run `npm deprecate <pkg>@<version> "Canary test"` instead.
|
||||
|
||||
## Main stays open
|
||||
|
||||
Merge normal PRs into `main` at any time, including while a beta soaks or a release is being
|
||||
@@ -128,16 +151,15 @@ An explicit user instruction can select another base.
|
||||
6. After go-ahead, push the tag first with `npm run release:push` so remote builds start right away.
|
||||
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
|
||||
`release:push` before `release:publish`, so tag builds never wait behind npm.)
|
||||
7. After `npm run release:push` finishes, merge the green [reconcile `main`](#reconcile-main) PR and create the release heartbeat. Watch `NPM Release` alongside the other release workflows.
|
||||
|
||||
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
|
||||
`release/**` workflow triggers existed (for example `v0.17.0-beta.1`), either cherry-pick the
|
||||
release-tooling commit onto the release branch (leaving product code unchanged) or follow the
|
||||
older tag's scripts (`version:all:*`, manual `gh workflow run ci.yml --ref <branch>`,
|
||||
`release:push`, and `release:publish`) until the next tag carries the new tooling.
|
||||
When a release starts from an older tag, check for the npm workflow before pushing the release tag:
|
||||
|
||||
```bash
|
||||
git cat-file -e HEAD:.github/workflows/npm-release.yml
|
||||
```
|
||||
|
||||
If the check fails, cherry-pick the release publishing tooling from `main` onto the release branch before preparation and CI. The release tag must include the workflow and package repository metadata.
|
||||
|
||||
A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3`
|
||||
shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line
|
||||
@@ -146,7 +168,7 @@ computes that from a prerelease, so run `npm run release:check`, bump with
|
||||
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
|
||||
push the release branch for `CI` and `Desktop Packages`, and complete the
|
||||
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
|
||||
`npm run release:push` and `npm run release:publish:beta` (or `npm run release:ship:beta`).
|
||||
`npm run release:push`.
|
||||
Record the tested beta tag as its source so its soak still counts for the unchanged content.
|
||||
|
||||
## Release inventory
|
||||
@@ -201,7 +223,7 @@ 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.
|
||||
- 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 Release` and the tag builds. If it shows changes, push them and wait for the PR checks before merging.
|
||||
|
||||
Delete the remote release branch
|
||||
(`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`) only after the reconcile PR
|
||||
@@ -266,10 +288,8 @@ git push -u origin HEAD
|
||||
# 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.
|
||||
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
|
||||
# 4. Merge the green reconcile/vX.Y.Z PR and create the release heartbeat.
|
||||
# Watch NPM Release and the other tag workflows.
|
||||
```
|
||||
|
||||
`scripts/push-current-release-tag.mjs` refuses non-`release/*` branches, checks that `HEAD` matches `origin/release/*`, tags `HEAD` with `vX.Y.Z`, and pushes the tag. Because `HEAD` is already on the pushed release branch, no second branch CI run starts.
|
||||
@@ -282,9 +302,9 @@ npm run release:publish
|
||||
4. Wave 4: `@getpaseo/server` (depends on `@getpaseo/client`, `@getpaseo/highlight`, `@getpaseo/plugin`, `@getpaseo/protocol`, and `@getpaseo/relay`).
|
||||
5. Wave 5: `@getpaseo/cli` (depends on `@getpaseo/client`, `@getpaseo/protocol`, and `@getpaseo/server`).
|
||||
|
||||
After each `npm publish`, the script polls `npm view` (up to 12 checks, 5 seconds apart) until the published version is visible on npm before moving to the next package. Waiting for registry visibility prevents dependent publishes and manual retries from hitting `E409` conflicts or `E404` propagation lag. On stable releases, the script also checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable version across all seven packages whenever the stable version is newer than `beta` (leaving `beta` untouched during a stable hotfix on an older line).
|
||||
After publishing all packages, the script checks their direct version endpoints in parallel for up to 10 minutes. This avoids stale packument caches delaying the publish wave. On stable releases, the script also checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable version across all seven packages whenever the stable version is newer than `beta` (leaving `beta` untouched during a stable hotfix on an older line).
|
||||
|
||||
The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` (`app.paseo.sh`, stable tags only) on GitHub Actions. `Desktop Release` and `Release Notes Sync` create the GitHub Release as a draft while builds and release-note sync run. `Deploy Website` triggers later on `release: published` when `Desktop Release` publishes the non-draft stable GitHub Release. EAS picks up the same tag through the EAS GitHub app and starts `Release Mobile` (iOS and Android store builds) in parallel, with no mobile-release workflow under `.github/workflows`. None of these workflows install `@getpaseo/*` from the public npm registry because all of them build from the checked-out tag commit and workspace packages.
|
||||
The tag push triggers `NPM Release`, `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` (`app.paseo.sh`, stable tags only) on GitHub Actions. `Desktop Release` and `Release Notes Sync` create the GitHub Release as a draft while builds and release-note sync run. `Deploy Website` triggers later on `release: published` when `Desktop Release` publishes the non-draft stable GitHub Release. EAS picks up the same tag through the EAS GitHub app and starts `Release Mobile` (iOS and Android store builds) in parallel, with no mobile-release workflow under `.github/workflows`. None of these workflows install `@getpaseo/*` from the public npm registry because all of them build from the checked-out tag commit and workspace packages.
|
||||
|
||||
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
|
||||
|
||||
@@ -308,7 +328,6 @@ git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
|
||||
# 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.
|
||||
```
|
||||
|
||||
@@ -326,10 +345,8 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
|
||||
git push -u origin HEAD
|
||||
# Wait for CI + Desktop Packages to pass and complete the pre-release dependency checks.
|
||||
|
||||
# 3. After go-ahead: push the tag first, then run npm publish, merge the reconcile PR, and heartbeat in parallel:
|
||||
# 3. After go-ahead, push the tag, merge the reconcile PR, and create the heartbeat:
|
||||
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.)
|
||||
|
||||
# Later, after soak, promote on release/vX.Y.Z:
|
||||
npm run release:prep:promote
|
||||
@@ -338,7 +355,6 @@ git push -u origin HEAD
|
||||
# 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.
|
||||
```
|
||||
|
||||
@@ -484,10 +500,11 @@ Do not leave the fix as a paced release. The installs that took the bad release
|
||||
|
||||
### Custom ramp on a manually-dispatched build
|
||||
|
||||
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to rebuild an existing tag (retry a failed release, force a rebuild on a different ref). On that path, you can stamp a different ramp directly:
|
||||
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to rebuild an existing tag. On that path, you can stamp a different ramp directly:
|
||||
|
||||
```bash
|
||||
gh workflow run desktop-release.yml \
|
||||
--ref v0.1.43 \
|
||||
-f tag=v0.1.43 \
|
||||
-f rollout_hours=6
|
||||
```
|
||||
@@ -670,9 +687,9 @@ The GitHub Release body is populated automatically by the `Release Notes Sync` w
|
||||
|
||||
**NEVER bump the version to fix a build problem.** New versions are reserved for meaningful product changes (features, fixes, improvements). Build/CI failures are fixed on the current version.
|
||||
|
||||
If `npm run release:publish` or `npm run release:publish:beta` fails after `npm run release:push` pushed the tag, fix the npm authentication, OTP, or local build issue and rerun the publish command on the same commit. Do not move or force-push the `v*` tag, because `scripts/publish-release-packages.mjs` skips packages already visible on npm and resumes from the remaining packages.
|
||||
If `NPM Release` fails after `npm run release:push` pushed the tag, fix the cause and rerun the failed workflow on the same tag. Do not move or force-push the `v*` tag, because `scripts/publish-release-packages.mjs` skips packages already visible on npm and resumes from the remaining packages. If a newer beta is already published, the script refuses an older beta retry to protect the `beta` dist-tag.
|
||||
|
||||
**Do not rely on `workflow_dispatch` for tagged code fixes.** The `workflow_dispatch` trigger runs the workflow file from the default branch but checks out the code at the tag ref (`ref: ${{ inputs.tag }}`). That means fixes committed to `main` won't change the tagged source tree being built. `workflow_dispatch` only helps when the fix lives in the workflow file itself.
|
||||
For a manual Desktop or Android rebuild, dispatch the workflow from the release tag. The workflow and checked-out commit must match the tag. A code fix on `main` does not change the tagged source.
|
||||
|
||||
For Docker-only retries, **do not push or force-push a `v*` release tag**.
|
||||
`v*` tag pushes rebuild desktop assets, the Android APK, Docker, release notes,
|
||||
@@ -719,14 +736,11 @@ git tag -f desktop-windows-v0.1.28 HEAD && git push origin desktop-windows-v0.1.
|
||||
|
||||
# Android APK
|
||||
git tag -f android-v0.1.28 HEAD && git push origin android-v0.1.28 --force
|
||||
|
||||
# Beta
|
||||
git tag -f v0.1.29-beta.2 HEAD && git push origin v0.1.29-beta.2 --force
|
||||
```
|
||||
|
||||
This ensures the checkout ref matches the code you want built, with the fix included.
|
||||
|
||||
- `vX.Y.Z` or `vX.Y.Z-beta.N` rebuilds the full tagged release
|
||||
- Never move a `vX.Y.Z` or `vX.Y.Z-beta.N` tag. Use a new version for code changes that affect npm packages.
|
||||
- `desktop-vX.Y.Z` rebuilds desktop for all desktop platforms only
|
||||
- `desktop-macos-vX.Y.Z`, `desktop-linux-vX.Y.Z`, and `desktop-windows-vX.Y.Z` rebuild only that desktop platform
|
||||
- `android-vX.Y.Z` rebuilds the Android APK release only
|
||||
@@ -756,7 +770,7 @@ intentionally unavailable to desktop updater clients.
|
||||
- The npm `version` lifecycle regenerates F-Droid changelog files from `CHANGELOG.md` for stable releases only (`npm run fdroid:changelogs`) and stages them, so the release commit and tag carry them. Betas are a no-op. A stable run **aborts the release** if `CHANGELOG.md` has no entry for the version being cut — commit the changelog entry first. See [docs/android.md](android.md) for why these files are generated per ABI.
|
||||
- `release:prepare` refreshes workspace `node_modules` links to prevent stale types.
|
||||
- `npm run dev:desktop` and `npm run build:desktop` target the Electron desktop package in `packages/desktop`.
|
||||
- `release:publish` and `release:publish:beta` run `scripts/publish-release-packages.mjs`. They publish the seven `@getpaseo/*` packages in dependency waves, skip versions already visible on npm, retry transient registry errors, and poll `npm view` between packages so dependents do not hit `E409` or `E404` propagation lag. `release:ship` and `release:ship:beta` run `release:push` before `release:publish` or `release:publish:beta`.
|
||||
- `NPM Release` runs `scripts/publish-release-packages.mjs` for the pushed tag. It skips versions already visible on npm, retries transient registry errors, and waits for registry propagation. `release:ship` and `release:ship:beta` run `release:push`.
|
||||
- The website uses GitHub's latest published release API for download links, so published beta prereleases do not replace the stable download target.
|
||||
|
||||
## Changelog format
|
||||
@@ -1017,7 +1031,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] 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
|
||||
- [ ] 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 Release`, the merge of the green `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
|
||||
- [ ] All seven `@getpaseo/*` npm packages show the version under the `beta` dist-tag, not `latest`
|
||||
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
|
||||
@@ -1041,7 +1055,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] 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
|
||||
- [ ] 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 Release`, the merge of the green `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
|
||||
- [ ] All seven `@getpaseo/*` npm packages show `latest` at the new stable, and `beta` at the new stable too unless an active newer beta holds `beta`
|
||||
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
Generated
+29
-29
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37552,7 +37552,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39705,13 +39705,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/server": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/server": "0.19.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39961,11 +39961,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/relay": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/relay": "0.19.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39977,7 +39977,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40221,7 +40221,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40267,7 +40267,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40297,7 +40297,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40305,8 +40305,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40316,8 +40316,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40339,7 +40339,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40366,7 +40366,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40382,7 +40382,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40604,17 +40604,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/highlight": "0.19.1",
|
||||
"@getpaseo/plugin": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/relay": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/highlight": "0.19.2",
|
||||
"@getpaseo/plugin": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/relay": "0.19.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
@@ -41579,7 +41579,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43205,7 +43205,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
@@ -127,8 +127,8 @@
|
||||
"release:publish": "node scripts/publish-release-packages.mjs",
|
||||
"release:publish:beta": "node scripts/publish-release-packages.mjs --beta",
|
||||
"release:push": "node scripts/push-current-release-tag.mjs",
|
||||
"release:ship": "npm run release:push && npm run release:publish",
|
||||
"release:ship:beta": "npm run release:push && npm run release:publish:beta",
|
||||
"release:ship": "npm run release:push",
|
||||
"release:ship:beta": "npm run release:push",
|
||||
"release:reconcile": "node scripts/reconcile-release.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
|
||||
import { collectRetainedAttachmentIds } from "@/attachments/gc-retention";
|
||||
import {
|
||||
collectRetainedAttachmentIds,
|
||||
retainAttachmentForGarbageCollection,
|
||||
} from "@/attachments/gc-retention";
|
||||
import { getAttachmentStore } from "@/attachments/store";
|
||||
import type { AttachmentMetadata, SaveAttachmentInput } from "@/attachments/types";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
@@ -95,6 +98,25 @@ export async function persistAttachmentFromFileUri(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function withRetainedAttachments<T>(
|
||||
attachments: readonly AttachmentMetadata[] | undefined,
|
||||
run: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return await run();
|
||||
}
|
||||
const releases = attachments.map((attachment) =>
|
||||
retainAttachmentForGarbageCollection(attachment.id),
|
||||
);
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
for (const release of releases) {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function encodeAttachmentsForSend(
|
||||
attachments: readonly AttachmentMetadata[] | undefined,
|
||||
): Promise<Array<{ data: string; mimeType: string }> | undefined> {
|
||||
@@ -102,29 +124,31 @@ export async function encodeAttachmentsForSend(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const store = await getAttachmentStore();
|
||||
const encoded = await Promise.all(
|
||||
attachments.map(async (attachment) => {
|
||||
try {
|
||||
const data = await store.encodeBase64({ attachment });
|
||||
return {
|
||||
data,
|
||||
mimeType: attachment.mimeType,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[attachments] Failed to encode attachment for send", {
|
||||
id: attachment.id,
|
||||
error,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return await withRetainedAttachments(attachments, async () => {
|
||||
const store = await getAttachmentStore();
|
||||
const encoded = await Promise.all(
|
||||
attachments.map(async (attachment) => {
|
||||
try {
|
||||
const data = await store.encodeBase64({ attachment });
|
||||
return {
|
||||
data,
|
||||
mimeType: attachment.mimeType,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[attachments] Failed to encode attachment for send", {
|
||||
id: attachment.id,
|
||||
error,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const valid = encoded.filter(
|
||||
(entry): entry is { data: string; mimeType: string } => entry !== null,
|
||||
);
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
const valid = encoded.filter(
|
||||
(entry): entry is { data: string; mimeType: string } => entry !== null,
|
||||
);
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
});
|
||||
}
|
||||
|
||||
const DEFAULT_UPLOAD_EXTENSION_BY_MIME: Record<string, string> = {
|
||||
@@ -180,28 +204,30 @@ export async function uploadImageAttachments(input: {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const uploaded: UploadedFileAttachment[] = [];
|
||||
for (const attachment of input.images) {
|
||||
const fileName = resolveUploadedImageFileName(attachment);
|
||||
const bytes = await readAttachmentBytes(attachment);
|
||||
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
|
||||
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
|
||||
return await withRetainedAttachments(input.images, async () => {
|
||||
const uploaded: UploadedFileAttachment[] = [];
|
||||
for (const attachment of input.images ?? []) {
|
||||
const fileName = resolveUploadedImageFileName(attachment);
|
||||
const bytes = await readAttachmentBytes(attachment);
|
||||
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
|
||||
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
|
||||
}
|
||||
const response = await input.client.uploadFile({
|
||||
fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
bytes,
|
||||
});
|
||||
if (response.error || !response.file) {
|
||||
throw new Error(response.error ?? "Upload failed.");
|
||||
}
|
||||
uploaded.push({
|
||||
...response.file,
|
||||
role: "image",
|
||||
});
|
||||
}
|
||||
const response = await input.client.uploadFile({
|
||||
fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
bytes,
|
||||
});
|
||||
if (response.error || !response.file) {
|
||||
throw new Error(response.error ?? "Upload failed.");
|
||||
}
|
||||
uploaded.push({
|
||||
...response.file,
|
||||
role: "image",
|
||||
});
|
||||
}
|
||||
|
||||
return uploaded;
|
||||
return uploaded;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createLocalFileAttachmentStore } from "@/attachments/local-file-attachment-store";
|
||||
import { garbageCollectAttachments, persistAttachmentFromBytes } from "@/attachments/service";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import { createTestAttachmentFileSystem } from "@/attachments/test-attachment-file-system";
|
||||
import type {
|
||||
AgentAttachment,
|
||||
ForgeSearchItem,
|
||||
@@ -739,6 +743,60 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
});
|
||||
|
||||
describe("enqueueComposerAgentMessage", () => {
|
||||
it("keeps all queued images available when garbage collection runs during upload", async () => {
|
||||
const fileSystem = createTestAttachmentFileSystem();
|
||||
const store = createLocalFileAttachmentStore({
|
||||
storageType: "native-file",
|
||||
baseDirectoryName: "attachments",
|
||||
fileSystem,
|
||||
resolvePreviewUrl: async (attachment) => attachment.storageKey,
|
||||
});
|
||||
__setAttachmentStoreForTests(store);
|
||||
try {
|
||||
const first = await persistAttachmentFromBytes({
|
||||
id: "first",
|
||||
bytes: new Uint8Array([1]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
const second = await persistAttachmentFromBytes({
|
||||
id: "second",
|
||||
bytes: new Uint8Array([2]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
const client = createFakeSendClient();
|
||||
|
||||
await enqueueComposerAgentMessage({
|
||||
client: {
|
||||
...client,
|
||||
async uploadFile(input) {
|
||||
if (client.uploadCalls.length === 0) {
|
||||
// Draft has already been cleared before the queue action runs.
|
||||
await garbageCollectAttachments({ referencedIds: new Set() });
|
||||
}
|
||||
return await client.uploadFile(input);
|
||||
},
|
||||
},
|
||||
agentId: "agent",
|
||||
text: "follow up",
|
||||
attachments: [
|
||||
{ kind: "image", metadata: first },
|
||||
{ kind: "image", metadata: second },
|
||||
],
|
||||
});
|
||||
|
||||
expect(client.uploadCalls.map(({ bytes }) => Array.from(bytes))).toEqual([[1], [2]]);
|
||||
expect(client.calls[0]?.options).toMatchObject({
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [{ role: "image" }, { role: "image" }],
|
||||
});
|
||||
|
||||
await garbageCollectAttachments({ referencedIds: new Set() });
|
||||
expect(fileSystem.files.size).toBe(0);
|
||||
} finally {
|
||||
__setAttachmentStoreForTests(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("hands a trimmed message to the host queue without adding a timeline row", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const review = reviewWorkspaceAttachment("Queued review.");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend, withRetainedAttachments } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { optimisticEnqueueAgentMessage } from "@/agent-queue";
|
||||
@@ -324,8 +324,10 @@ async function prepareImagePayload(
|
||||
input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
|
||||
images: AttachmentMetadata[],
|
||||
) {
|
||||
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
|
||||
return await prepareImageAttachmentsForSend({ client: input.client, images });
|
||||
return await withRetainedAttachments(images, async () => {
|
||||
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
|
||||
return await prepareImageAttachmentsForSend({ client: input.client, images });
|
||||
});
|
||||
}
|
||||
|
||||
/** Images the host already holds render as images, the way its timeline echo does. */
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createLocalFileAttachmentStore } from "@/attachments/local-file-attachment-store";
|
||||
import {
|
||||
garbageCollectAttachments,
|
||||
persistAttachmentFromBytes,
|
||||
readAttachmentBytes,
|
||||
} from "@/attachments/service";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import { createTestAttachmentFileSystem } from "@/attachments/test-attachment-file-system";
|
||||
import type { UserComposerAttachment } from "@/attachments/types";
|
||||
import { submitAgentInput } from "./submit";
|
||||
|
||||
function createDeferredPromise<T>() {
|
||||
@@ -333,4 +342,133 @@ describe("submitAgentInput", () => {
|
||||
});
|
||||
expect(clearDraft).toHaveBeenCalledWith("sent");
|
||||
});
|
||||
|
||||
it("keeps queued image files on disk when draft clearing schedules GC and restores them intact if queueing fails", async () => {
|
||||
const fileSystem = createTestAttachmentFileSystem();
|
||||
const store = createLocalFileAttachmentStore({
|
||||
storageType: "native-file",
|
||||
baseDirectoryName: "attachments",
|
||||
fileSystem,
|
||||
resolvePreviewUrl: async (attachment) => attachment.storageKey,
|
||||
});
|
||||
__setAttachmentStoreForTests(store);
|
||||
|
||||
try {
|
||||
const first = await persistAttachmentFromBytes({
|
||||
id: "queued-1",
|
||||
bytes: new Uint8Array([10, 20]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
const second = await persistAttachmentFromBytes({
|
||||
id: "queued-2",
|
||||
bytes: new Uint8Array([30, 40]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
|
||||
let draftAttachments: UserComposerAttachment[] = [
|
||||
{ kind: "image", metadata: first },
|
||||
{ kind: "image", metadata: second },
|
||||
];
|
||||
let revision = 0;
|
||||
const pendingGcs: Promise<void>[] = [];
|
||||
const runScheduledGc = async () => {
|
||||
await Promise.resolve();
|
||||
const referencedIds = new Set<string>();
|
||||
for (const entry of draftAttachments) {
|
||||
if (entry.kind === "image") {
|
||||
referencedIds.add(entry.metadata.id);
|
||||
}
|
||||
}
|
||||
await garbageCollectAttachments({ referencedIds });
|
||||
};
|
||||
const scheduleGc = () => {
|
||||
pendingGcs.push(runScheduledGc());
|
||||
};
|
||||
|
||||
const result = await submitAgentInput<UserComposerAttachment>({
|
||||
message: "queued follow-up",
|
||||
attachments: draftAttachments,
|
||||
isAgentRunning: true,
|
||||
canSubmit: true,
|
||||
queueMessage: async ({ attachments }) => {
|
||||
// Yield to let the microtask GC triggered by setAttachments([]) run before reads.
|
||||
await Promise.all(pendingGcs);
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.kind === "image") {
|
||||
await readAttachmentBytes(attachment.metadata);
|
||||
}
|
||||
}
|
||||
throw new Error("Host disconnected");
|
||||
},
|
||||
submitMessage: vi.fn(),
|
||||
getDraftRevision: () => revision,
|
||||
clearDraft: vi.fn(),
|
||||
setUserInput: vi.fn(),
|
||||
setAttachments: (next) => {
|
||||
draftAttachments = next;
|
||||
revision += 1;
|
||||
scheduleGc();
|
||||
},
|
||||
setSendError: vi.fn(),
|
||||
setIsProcessing: vi.fn(),
|
||||
});
|
||||
|
||||
await Promise.all(pendingGcs);
|
||||
|
||||
expect(result).toBe("failed");
|
||||
expect(draftAttachments).toHaveLength(2);
|
||||
await expect(readAttachmentBytes(first)).resolves.toEqual(new Uint8Array([10, 20]));
|
||||
await expect(readAttachmentBytes(second)).resolves.toEqual(new Uint8Array([30, 40]));
|
||||
} finally {
|
||||
__setAttachmentStoreForTests(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("releases queued image holds after a successful queue submission so unreferenced files can be collected", async () => {
|
||||
const fileSystem = createTestAttachmentFileSystem();
|
||||
const store = createLocalFileAttachmentStore({
|
||||
storageType: "native-file",
|
||||
baseDirectoryName: "attachments",
|
||||
fileSystem,
|
||||
resolvePreviewUrl: async (attachment) => attachment.storageKey,
|
||||
});
|
||||
__setAttachmentStoreForTests(store);
|
||||
|
||||
try {
|
||||
const image = await persistAttachmentFromBytes({
|
||||
id: "queued-success",
|
||||
bytes: new Uint8Array([7, 8, 9]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
let draftAttachments: UserComposerAttachment[] = [{ kind: "image", metadata: image }];
|
||||
let revision = 0;
|
||||
|
||||
const result = await submitAgentInput<UserComposerAttachment>({
|
||||
message: "queued ok",
|
||||
attachments: draftAttachments,
|
||||
isAgentRunning: true,
|
||||
canSubmit: true,
|
||||
queueMessage: async () => {
|
||||
await garbageCollectAttachments({ referencedIds: new Set() });
|
||||
await expect(readAttachmentBytes(image)).resolves.toEqual(new Uint8Array([7, 8, 9]));
|
||||
},
|
||||
submitMessage: vi.fn(),
|
||||
getDraftRevision: () => revision,
|
||||
clearDraft: vi.fn(),
|
||||
setUserInput: vi.fn(),
|
||||
setAttachments: (next) => {
|
||||
draftAttachments = next;
|
||||
revision += 1;
|
||||
},
|
||||
setSendError: vi.fn(),
|
||||
setIsProcessing: vi.fn(),
|
||||
});
|
||||
|
||||
expect(result).toBe("queued");
|
||||
await garbageCollectAttachments({ referencedIds: new Set() });
|
||||
expect(fileSystem.files.size).toBe(0);
|
||||
} finally {
|
||||
__setAttachmentStoreForTests(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,42 @@
|
||||
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export type AgentInputSubmitResult = "noop" | "queued" | "submitted" | "failed";
|
||||
|
||||
function collectManagedAttachmentIds(attachments: readonly unknown[]): string[] {
|
||||
const ids: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (typeof attachment !== "object" || attachment === null || !("kind" in attachment)) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
attachment.kind === "image" &&
|
||||
"metadata" in attachment &&
|
||||
typeof attachment.metadata === "object" &&
|
||||
attachment.metadata !== null &&
|
||||
"id" in attachment.metadata &&
|
||||
typeof attachment.metadata.id === "string"
|
||||
) {
|
||||
ids.push(attachment.metadata.id);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
attachment.kind === "browser_element" &&
|
||||
"attachment" in attachment &&
|
||||
typeof attachment.attachment === "object" &&
|
||||
attachment.attachment !== null &&
|
||||
"screenshot" in attachment.attachment &&
|
||||
typeof attachment.attachment.screenshot === "object" &&
|
||||
attachment.attachment.screenshot !== null &&
|
||||
"id" in attachment.attachment.screenshot &&
|
||||
typeof attachment.attachment.screenshot.id === "string"
|
||||
) {
|
||||
ids.push(attachment.attachment.screenshot.id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export interface AgentInputSubmitActionInput<TAttachment> {
|
||||
message: string;
|
||||
attachments: TAttachment[];
|
||||
@@ -46,35 +81,48 @@ export async function submitAgentInput<TAttachment>(
|
||||
|
||||
const shouldQueue = input.isAgentRunning && !input.forceSend;
|
||||
|
||||
// Clear immediately so the submitted timeline row and composer state stay in sync.
|
||||
if (shouldClearOnSubmit) {
|
||||
input.setUserInput("");
|
||||
input.setAttachments([]);
|
||||
}
|
||||
const submittedRevision = shouldClearOnSubmit ? input.getDraftRevision() : null;
|
||||
input.setSendError(null);
|
||||
input.setIsProcessing(true);
|
||||
// Retain local attachment files before clearing the draft so scheduled GC cannot
|
||||
// delete them while delivery is in flight (especially queued sends that add no
|
||||
// timeline row) or before a failed send restores them to the composer.
|
||||
const releaseAttachments = collectManagedAttachmentIds(attachments).map((id) =>
|
||||
retainAttachmentForGarbageCollection(id),
|
||||
);
|
||||
|
||||
try {
|
||||
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
|
||||
await deliver({ message: trimmedMessage, attachments });
|
||||
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
|
||||
input.clearDraft("sent");
|
||||
// Clear immediately so the submitted timeline row and composer state stay in sync.
|
||||
if (shouldClearOnSubmit) {
|
||||
input.setUserInput("");
|
||||
input.setAttachments([]);
|
||||
}
|
||||
input.setIsProcessing(false);
|
||||
return shouldQueue ? "queued" : "submitted";
|
||||
} catch (error) {
|
||||
input.onSubmitError?.(error);
|
||||
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
|
||||
input.setUserInput(trimmedMessage);
|
||||
input.setAttachments(attachments);
|
||||
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.setIsProcessing(false);
|
||||
return shouldQueue ? "queued" : "submitted";
|
||||
} catch (error) {
|
||||
input.onSubmitError?.(error);
|
||||
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
|
||||
input.setUserInput(trimmedMessage);
|
||||
input.setAttachments(attachments);
|
||||
}
|
||||
input.setSendError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
|
||||
);
|
||||
input.setIsProcessing(false);
|
||||
return "failed";
|
||||
}
|
||||
} finally {
|
||||
for (const release of releaseAttachments) {
|
||||
release();
|
||||
}
|
||||
input.setSendError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
|
||||
);
|
||||
input.setIsProcessing(false);
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { DaemonClient, FileReadResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { FileVersion } from "@getpaseo/protocol/messages";
|
||||
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
|
||||
import {
|
||||
persistAttachmentFromBytes,
|
||||
releaseAttachmentPreviewUrl,
|
||||
@@ -84,10 +85,18 @@ export function createDaemonFileSession(
|
||||
mimeType,
|
||||
fileName: getFileNameFromPath(target.path),
|
||||
});
|
||||
const url = await resolveAttachmentPreviewUrl(attachment);
|
||||
const releaseRetention = retainAttachmentForGarbageCollection(attachment.id);
|
||||
let url: string;
|
||||
try {
|
||||
url = await resolveAttachmentPreviewUrl(attachment);
|
||||
} catch (error) {
|
||||
releaseRetention();
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
url,
|
||||
release() {
|
||||
releaseRetention();
|
||||
void releaseAttachmentPreviewUrl({ attachment, url });
|
||||
},
|
||||
};
|
||||
|
||||
@@ -219,6 +219,7 @@ export class AgentStoreProjection {
|
||||
useSessionStore.getState().setAgentDetails(this.serverId, withoutAgent(agentId));
|
||||
useDraftStore.getState().clearDraftInput({
|
||||
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
|
||||
lifecycle: "abandoned",
|
||||
});
|
||||
// Leaving the active list does not release the transcript: an archived chat open in
|
||||
// History stays readable. The viewed timeline owner releases it once nobody shows it.
|
||||
|
||||
@@ -18,9 +18,11 @@ import {
|
||||
editDraftRecordText,
|
||||
collectReferencedAttachmentIdsFromState,
|
||||
DRAFT_STORE_VERSION,
|
||||
DraftStoreStateSchema,
|
||||
isAttachmentMetadata,
|
||||
isCanonicalDraftInput,
|
||||
isLegacyDraftImage,
|
||||
mergeDraftStoreStates,
|
||||
normalizeComposerAttachment,
|
||||
pruneFinalizedDraftRecords,
|
||||
toDraftInputIfReady,
|
||||
@@ -29,6 +31,7 @@ import {
|
||||
type DraftRecord,
|
||||
type DraftStoreState,
|
||||
} from "./state";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import {
|
||||
migrateDraftInput,
|
||||
migratePersistedState,
|
||||
@@ -105,6 +108,8 @@ function cancelStagedDraftText(draftKey: string): void {
|
||||
stagedDraftText.delete(draftKey);
|
||||
}
|
||||
|
||||
const DRAFT_STORE_STORAGE_KEY = "paseo-drafts";
|
||||
|
||||
let gcScheduled = false;
|
||||
const draftPersistStorage = createDraftPersistStorage(
|
||||
createValidatedPersistStorage(AsyncStorage, PersistedDraftStoreSchema),
|
||||
@@ -441,12 +446,29 @@ export const useDraftStore = create<DraftStore>()(
|
||||
|
||||
discardOrphanedWorkspaceDrafts: (openDraftKeys) => {
|
||||
const { drafts } = get();
|
||||
const retained = Object.entries(drafts).filter(
|
||||
([key, record]) =>
|
||||
record.lifecycle !== "active" || !isWorkspaceTabDraftKey(key) || openDraftKeys.has(key),
|
||||
);
|
||||
if (retained.length === Object.keys(drafts).length) return false;
|
||||
set({ drafts: Object.fromEntries(retained) });
|
||||
const nowMs = Date.now();
|
||||
let changed = false;
|
||||
const nextDrafts: Record<string, DraftRecord> = { ...drafts };
|
||||
for (const [key, record] of Object.entries(drafts)) {
|
||||
if (
|
||||
record.lifecycle !== "active" ||
|
||||
!isWorkspaceTabDraftKey(key) ||
|
||||
openDraftKeys.has(key)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const tombstone = applyClearDraftRecord({
|
||||
record,
|
||||
lifecycle: "abandoned",
|
||||
nowMs,
|
||||
});
|
||||
if (tombstone) {
|
||||
nextDrafts[key] = tombstone;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) return false;
|
||||
set({ drafts: nextDrafts });
|
||||
scheduleAttachmentGc();
|
||||
return true;
|
||||
},
|
||||
@@ -522,7 +544,7 @@ export const useDraftStore = create<DraftStore>()(
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "paseo-drafts",
|
||||
name: DRAFT_STORE_STORAGE_KEY,
|
||||
version: DRAFT_STORE_VERSION,
|
||||
storage: draftPersistStorage,
|
||||
partialize: ({ drafts, createModalDraft }) => ({ drafts, createModalDraft }),
|
||||
@@ -533,10 +555,105 @@ export const useDraftStore = create<DraftStore>()(
|
||||
}),
|
||||
onRehydrateStorage: () => {
|
||||
return () => {
|
||||
void migrateAllLegacyDrafts();
|
||||
scheduleAttachmentGc();
|
||||
void migrateAllLegacyDrafts().finally(() => {
|
||||
scheduleAttachmentGc();
|
||||
});
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
function parsePersistedDraftEnvelope(rawValue: string | null): DraftStoreState | null {
|
||||
if (!rawValue) {
|
||||
return null;
|
||||
}
|
||||
let parsedEnvelope: unknown;
|
||||
try {
|
||||
parsedEnvelope = JSON.parse(rawValue);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
typeof parsedEnvelope !== "object" ||
|
||||
parsedEnvelope === null ||
|
||||
!("version" in parsedEnvelope) ||
|
||||
parsedEnvelope.version !== DRAFT_STORE_VERSION ||
|
||||
!("state" in parsedEnvelope)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const parsedState = DraftStoreStateSchema.safeParse(parsedEnvelope.state);
|
||||
return parsedState.success ? parsedState.data : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges a serialized `paseo-drafts` payload written by another window/tab into
|
||||
* this window's draft store so drafts and their active attachment references stay
|
||||
* intact even if the originating window closes.
|
||||
*/
|
||||
export function applyPersistedDraftStorageUpdate(rawValue: string | null): boolean {
|
||||
const incoming = parsePersistedDraftEnvelope(rawValue);
|
||||
if (!incoming) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Flush any locally staged keystrokes for keys present in the incoming update so
|
||||
// recent typing is compared at its current timestamp instead of being overwritten.
|
||||
for (const draftKey of Object.keys(incoming.drafts)) {
|
||||
if (stagedDraftText.has(draftKey)) {
|
||||
useDraftStore.getState().flushDraftText(draftKey);
|
||||
}
|
||||
}
|
||||
|
||||
const state = useDraftStore.getState();
|
||||
const current: DraftStoreState = {
|
||||
drafts: state.drafts,
|
||||
createModalDraft: state.createModalDraft,
|
||||
};
|
||||
const merged = mergeDraftStoreStates(current, incoming);
|
||||
if (merged === current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let nextTextReplacementRequests = state.textReplacementRequestByDraftKey;
|
||||
let textReplacementChanged = false;
|
||||
for (const [draftKey, nextRecord] of Object.entries(merged.drafts)) {
|
||||
const previousRecord = current.drafts[draftKey];
|
||||
if (previousRecord === nextRecord) {
|
||||
continue;
|
||||
}
|
||||
const previousText = previousRecord?.lifecycle === "active" ? previousRecord.input.text : "";
|
||||
const nextText = nextRecord.lifecycle === "active" ? nextRecord.input.text : "";
|
||||
if (previousText !== nextText) {
|
||||
cancelStagedDraftText(draftKey);
|
||||
if (!textReplacementChanged) {
|
||||
nextTextReplacementRequests = { ...state.textReplacementRequestByDraftKey };
|
||||
textReplacementChanged = true;
|
||||
}
|
||||
nextTextReplacementRequests[draftKey] = (nextTextReplacementRequests[draftKey] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
useDraftStore.setState({
|
||||
drafts: merged.drafts,
|
||||
createModalDraft: merged.createModalDraft,
|
||||
...(textReplacementChanged
|
||||
? { textReplacementRequestByDraftKey: nextTextReplacementRequests }
|
||||
: {}),
|
||||
});
|
||||
scheduleAttachmentGc();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isWeb && typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
||||
window.addEventListener("storage", (event) => {
|
||||
if (event.key !== DRAFT_STORE_STORAGE_KEY) {
|
||||
return;
|
||||
}
|
||||
applyPersistedDraftStorageUpdate(event.newValue);
|
||||
});
|
||||
window.addEventListener("pagehide", () => {
|
||||
void flushDraftPersistStorage();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { useDraftStore } from "./index";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildDraftStoreKey } from "@/stores/draft-keys";
|
||||
import { applyPersistedDraftStorageUpdate, useDraftStore } from "./index";
|
||||
import { DRAFT_STORE_VERSION } from "./state";
|
||||
|
||||
const draftKey = "draft:metadata";
|
||||
|
||||
describe("a draft's plugin metadata", () => {
|
||||
beforeEach(() => {
|
||||
useDraftStore.setState({ drafts: {}, metadataByDraftKey: {} });
|
||||
useDraftStore.setState({
|
||||
drafts: {},
|
||||
createModalDraft: null,
|
||||
metadataByDraftKey: {},
|
||||
textReplacementRequestByDraftKey: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("is there when the draft's composer mounts again", () => {
|
||||
@@ -33,3 +40,132 @@ describe("a draft's plugin metadata", () => {
|
||||
expect(useDraftStore.getState().metadataByDraftKey[draftKey]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-window draft storage sync", () => {
|
||||
beforeEach(() => {
|
||||
useDraftStore.setState({
|
||||
drafts: {},
|
||||
createModalDraft: null,
|
||||
metadataByDraftKey: {},
|
||||
textReplacementRequestByDraftKey: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("skips setState on no-op storage updates and notifies mounted editors when peer text changes", () => {
|
||||
useDraftStore.setState({
|
||||
drafts: {
|
||||
agentA: {
|
||||
input: { text: "old text", attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 100,
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = useDraftStore.subscribe(listener);
|
||||
try {
|
||||
const sameEnvelope = JSON.stringify({
|
||||
version: DRAFT_STORE_VERSION,
|
||||
state: {
|
||||
drafts: {
|
||||
agentA: {
|
||||
input: { text: "old text", attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 100,
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
createModalDraft: null,
|
||||
},
|
||||
});
|
||||
expect(applyPersistedDraftStorageUpdate(sameEnvelope)).toBe(false);
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
|
||||
const updatedEnvelope = JSON.stringify({
|
||||
version: DRAFT_STORE_VERSION,
|
||||
state: {
|
||||
drafts: {
|
||||
agentA: {
|
||||
input: { text: "from peer window", attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 200,
|
||||
version: 2,
|
||||
},
|
||||
},
|
||||
createModalDraft: null,
|
||||
},
|
||||
});
|
||||
expect(applyPersistedDraftStorageUpdate(updatedEnvelope)).toBe(true);
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(useDraftStore.getState().getDraftInput("agentA")?.text).toBe("from peer window");
|
||||
expect(useDraftStore.getState().textReplacementRequestByDraftKey.agentA).toBe(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it("writes abandoned tombstones when discarding orphaned workspace drafts so peers do not resurrect them", () => {
|
||||
const orphanKey = buildDraftStoreKey({
|
||||
serverId: "srv-1",
|
||||
agentId: "",
|
||||
draftId: "orphan-1",
|
||||
});
|
||||
useDraftStore.setState({
|
||||
drafts: {
|
||||
[orphanKey]: {
|
||||
input: { text: "stale tab draft", attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 100,
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(useDraftStore.getState().discardOrphanedWorkspaceDrafts(new Set())).toBe(true);
|
||||
expect(useDraftStore.getState().drafts[orphanKey]).toMatchObject({
|
||||
lifecycle: "abandoned",
|
||||
input: { text: "", attachments: [] },
|
||||
});
|
||||
// Subsequent sweeps treat the tombstone as already discarded.
|
||||
expect(useDraftStore.getState().discardOrphanedWorkspaceDrafts(new Set())).toBe(false);
|
||||
});
|
||||
|
||||
it("flushes locally staged typing before merging a delayed peer storage update", () => {
|
||||
const store = useDraftStore.getState();
|
||||
useDraftStore.setState({
|
||||
drafts: {
|
||||
agentA: {
|
||||
input: { text: "hel", attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 100,
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// User types before the next paint commits the staged edit.
|
||||
store.stageDraftText({ draftKey: "agentA", text: "hello" });
|
||||
|
||||
// A delayed peer update with an older timestamp arrives before paint.
|
||||
const delayedPeerUpdate = JSON.stringify({
|
||||
version: DRAFT_STORE_VERSION,
|
||||
state: {
|
||||
drafts: {
|
||||
agentA: {
|
||||
input: { text: "from peer earlier", attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: Date.now() - 10_000,
|
||||
version: 2,
|
||||
},
|
||||
},
|
||||
createModalDraft: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(applyPersistedDraftStorageUpdate(delayedPeerUpdate)).toBe(false);
|
||||
expect(useDraftStore.getState().getDraftInput("agentA")?.text).toBe("hello");
|
||||
expect(useDraftStore.getState().textReplacementRequestByDraftKey.agentA).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyClearDraftRecord,
|
||||
mergeDraftStoreStates,
|
||||
pruneFinalizedDraftRecords,
|
||||
toDraftInputIfReady,
|
||||
editDraftRecordText,
|
||||
type DraftRecord,
|
||||
type DraftStoreState,
|
||||
} from "./state";
|
||||
|
||||
describe("draft-store lifecycle", () => {
|
||||
@@ -100,6 +102,71 @@ describe("draft-store lifecycle", () => {
|
||||
version: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("merges drafts from another window without clobbering local drafts and honors newer tombstones", () => {
|
||||
const imgA = {
|
||||
kind: "image" as const,
|
||||
metadata: {
|
||||
id: "att_window_a",
|
||||
mimeType: "image/png",
|
||||
storageType: "desktop-file" as const,
|
||||
storageKey: "/tmp/att_window_a.png",
|
||||
createdAt: 1,
|
||||
},
|
||||
};
|
||||
const imgB = {
|
||||
kind: "image" as const,
|
||||
metadata: {
|
||||
id: "att_window_b",
|
||||
mimeType: "image/png",
|
||||
storageType: "desktop-file" as const,
|
||||
storageKey: "/tmp/att_window_b.png",
|
||||
createdAt: 2,
|
||||
},
|
||||
};
|
||||
const local: DraftStoreState = {
|
||||
drafts: {
|
||||
agentA: {
|
||||
input: { text: "from A", attachments: [imgA] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 100,
|
||||
version: 1,
|
||||
},
|
||||
agentShared: {
|
||||
input: { text: "old draft", attachments: [imgA] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 50,
|
||||
version: 1,
|
||||
},
|
||||
},
|
||||
createModalDraft: null,
|
||||
};
|
||||
const incoming: DraftStoreState = {
|
||||
drafts: {
|
||||
agentB: {
|
||||
input: { text: "from B", attachments: [imgB] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 120,
|
||||
version: 1,
|
||||
},
|
||||
agentShared: {
|
||||
input: { text: "", attachments: [] },
|
||||
lifecycle: "sent",
|
||||
updatedAt: 200,
|
||||
version: 2,
|
||||
},
|
||||
},
|
||||
createModalDraft: null,
|
||||
};
|
||||
|
||||
const merged = mergeDraftStoreStates(local, incoming);
|
||||
expect(merged.drafts.agentA).toBe(local.drafts.agentA);
|
||||
expect(merged.drafts.agentB).toBe(incoming.drafts.agentB);
|
||||
expect(merged.drafts.agentShared).toBe(incoming.drafts.agentShared);
|
||||
// Re-merging identical or older state is a referential no-op.
|
||||
expect(mergeDraftStoreStates(merged, incoming)).toBe(merged);
|
||||
expect(mergeDraftStoreStates(merged, local)).toBe(merged);
|
||||
});
|
||||
});
|
||||
|
||||
describe("draft-store normalization", () => {
|
||||
|
||||
@@ -273,3 +273,57 @@ export function applyClearDraftRecord(input: {
|
||||
version: input.record.version + 1,
|
||||
};
|
||||
}
|
||||
|
||||
function isIncomingDraftRecordNewer(
|
||||
local: DraftRecord | null | undefined,
|
||||
incoming: DraftRecord,
|
||||
): boolean {
|
||||
if (!local) {
|
||||
return true;
|
||||
}
|
||||
if (incoming.updatedAt !== local.updatedAt) {
|
||||
return incoming.updatedAt > local.updatedAt;
|
||||
}
|
||||
return incoming.version > local.version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Joins persisted draft state from another window with local state by taking the
|
||||
* newest record per draft key (including `"sent"` / `"abandoned"` tombstones).
|
||||
* Preserves local references when nothing newer arrived.
|
||||
*/
|
||||
export function mergeDraftStoreStates(
|
||||
local: DraftStoreState,
|
||||
incoming: DraftStoreState,
|
||||
): DraftStoreState {
|
||||
let nextDrafts = local.drafts;
|
||||
let draftsChanged = false;
|
||||
for (const [draftKey, incomingRecord] of Object.entries(incoming.drafts)) {
|
||||
if (!isIncomingDraftRecordNewer(local.drafts[draftKey], incomingRecord)) {
|
||||
continue;
|
||||
}
|
||||
if (!draftsChanged) {
|
||||
nextDrafts = { ...local.drafts };
|
||||
draftsChanged = true;
|
||||
}
|
||||
nextDrafts[draftKey] = incomingRecord;
|
||||
}
|
||||
|
||||
let nextCreateModalDraft = local.createModalDraft;
|
||||
let createModalChanged = false;
|
||||
if (
|
||||
incoming.createModalDraft &&
|
||||
isIncomingDraftRecordNewer(local.createModalDraft, incoming.createModalDraft)
|
||||
) {
|
||||
nextCreateModalDraft = incoming.createModalDraft;
|
||||
createModalChanged = true;
|
||||
}
|
||||
|
||||
if (!draftsChanged && !createModalChanged) {
|
||||
return local;
|
||||
}
|
||||
return {
|
||||
drafts: nextDrafts,
|
||||
createModalDraft: nextCreateModalDraft,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/cli"
|
||||
},
|
||||
"bin": {
|
||||
"paseo": "bin/paseo"
|
||||
},
|
||||
@@ -29,9 +34,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/server": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/server": "0.19.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/client"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
@@ -57,8 +62,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/relay": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/relay": "0.19.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { hostname, tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createDesktopAttachmentManager } from "../features/attachments";
|
||||
import { DEFAULT_DESKTOP_SETTINGS } from "../settings/desktop-settings";
|
||||
import { ExternalCliCommandError } from "./cli/external";
|
||||
import {
|
||||
@@ -358,4 +359,43 @@ describe("desktop stops and terminals", () => {
|
||||
).rejects.toThrow("unreachable");
|
||||
expect(harness.stops).toEqual([{ keepTerminals: true }]);
|
||||
});
|
||||
|
||||
it("scopes attachment writes and garbage collection by sender webContentsId", async () => {
|
||||
const originalPaseoHome = process.env.PASEO_HOME;
|
||||
const tempHome = mkdtempSync(path.join(tmpdir(), "paseo-daemon-attachments-"));
|
||||
process.env.PASEO_HOME = tempHome;
|
||||
try {
|
||||
const attachments = createDesktopAttachmentManager();
|
||||
attachments.registerWindow(10);
|
||||
attachments.registerWindow(20);
|
||||
const handlers = createDaemonCommandHandlers({ attachments });
|
||||
|
||||
const written = (await handlers.write_attachment_bytes(
|
||||
{ attachmentId: "att_win10", bytes: new Uint8Array([1, 2, 3]), extension: ".png" },
|
||||
{ senderWebContentsId: 10 },
|
||||
)) as { path: string };
|
||||
await handlers.garbage_collect_attachment_files(
|
||||
{ referencedIds: ["att_win10"] },
|
||||
{ senderWebContentsId: 10 },
|
||||
);
|
||||
|
||||
// Window 20 sweeps with no references; window 10's file must remain readable.
|
||||
await expect(
|
||||
handlers.garbage_collect_attachment_files(
|
||||
{ referencedIds: [] },
|
||||
{ senderWebContentsId: 20 },
|
||||
),
|
||||
).resolves.toBe(0);
|
||||
await expect(
|
||||
handlers.read_file_base64({ path: written.path }, { senderWebContentsId: 10 }),
|
||||
).resolves.toBe(Buffer.from([1, 2, 3]).toString("base64"));
|
||||
} finally {
|
||||
if (originalPaseoHome === undefined) {
|
||||
delete process.env.PASEO_HOME;
|
||||
} else {
|
||||
process.env.PASEO_HOME = originalPaseoHome;
|
||||
}
|
||||
rmSync(tempHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,12 +13,8 @@ import {
|
||||
type DaemonInstance,
|
||||
} from "@getpaseo/server/daemon-control";
|
||||
import {
|
||||
copyAttachmentFileToManagedStorage,
|
||||
deleteManagedAttachmentFile,
|
||||
garbageCollectManagedAttachmentFiles,
|
||||
readManagedFileBase64,
|
||||
writeAttachmentBase64,
|
||||
writeAttachmentBytes,
|
||||
createDesktopAttachmentManager,
|
||||
type DesktopAttachmentManager,
|
||||
} from "../features/attachments.js";
|
||||
import {
|
||||
checkForAppUpdate,
|
||||
@@ -505,7 +501,10 @@ async function resolveRequestedReleaseChannel(
|
||||
// IPC registration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createDaemonCommandHandlers(): Record<string, DesktopCommandHandler> {
|
||||
export function createDaemonCommandHandlers(options?: {
|
||||
attachments?: DesktopAttachmentManager;
|
||||
}): Record<string, DesktopCommandHandler> {
|
||||
const attachments = options?.attachments ?? createDesktopAttachmentManager();
|
||||
return {
|
||||
...createDesktopSettingsCommandHandlers({ settingsStore: getDesktopSettingsStore() }),
|
||||
desktop_get_runtime_info: () => ({
|
||||
@@ -536,12 +535,18 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
|
||||
desktop_update_diagnostics: () => getDesktopUpdaterDiagnostics(),
|
||||
desktop_get_system_idle_time: () => powerMonitor.getSystemIdleTime() * 1000,
|
||||
cli_daemon_status: () => getCliDaemonStatus(),
|
||||
write_attachment_base64: (args) => writeAttachmentBase64(args ?? {}),
|
||||
write_attachment_bytes: (args) => writeAttachmentBytes(args ?? {}),
|
||||
copy_attachment_file: (args) => copyAttachmentFileToManagedStorage(args ?? {}),
|
||||
read_file_base64: (args) => readManagedFileBase64(args ?? {}),
|
||||
delete_attachment_file: (args) => deleteManagedAttachmentFile(args ?? {}),
|
||||
garbage_collect_attachment_files: (args) => garbageCollectManagedAttachmentFiles(args ?? {}),
|
||||
write_attachment_base64: (args, context) =>
|
||||
attachments.writeAttachmentBase64(args ?? {}, context?.senderWebContentsId),
|
||||
write_attachment_bytes: (args, context) =>
|
||||
attachments.writeAttachmentBytes(args ?? {}, context?.senderWebContentsId),
|
||||
copy_attachment_file: (args, context) =>
|
||||
attachments.copyAttachmentFileToManagedStorage(args ?? {}, context?.senderWebContentsId),
|
||||
read_file_base64: (args, context) =>
|
||||
attachments.readManagedFileBase64(args ?? {}, context?.senderWebContentsId),
|
||||
delete_attachment_file: (args, context) =>
|
||||
attachments.deleteManagedAttachmentFile(args ?? {}, context?.senderWebContentsId),
|
||||
garbage_collect_attachment_files: (args, context) =>
|
||||
attachments.garbageCollectManagedAttachmentFiles(args ?? {}, context?.senderWebContentsId),
|
||||
open_local_daemon_transport: async (args) => await openLocalTransportSession(args),
|
||||
send_local_daemon_transport_message: async (args) => {
|
||||
await sendLocalTransportMessage(
|
||||
@@ -583,17 +588,14 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
|
||||
};
|
||||
}
|
||||
|
||||
export function registerDaemonManager(): void {
|
||||
const handlers = createDaemonCommandHandlers();
|
||||
export function registerDaemonManager(options?: { attachments?: DesktopAttachmentManager }): void {
|
||||
const handlers = createDaemonCommandHandlers(options);
|
||||
|
||||
ipcMain.handle(
|
||||
"paseo:invoke",
|
||||
async (_event, command: string, args?: Record<string, unknown>) => {
|
||||
const handler = handlers[command];
|
||||
if (!handler) {
|
||||
throw new Error(`Unknown desktop command: ${command}`);
|
||||
}
|
||||
return await handler(args);
|
||||
},
|
||||
);
|
||||
ipcMain.handle("paseo:invoke", async (event, command: string, args?: Record<string, unknown>) => {
|
||||
const handler = handlers[command];
|
||||
if (!handler) {
|
||||
throw new Error(`Unknown desktop command: ${command}`);
|
||||
}
|
||||
return await handler(args, { senderWebContentsId: event.sender.id });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { copyAttachmentFileToManagedStorage } from "./attachments";
|
||||
import { copyAttachmentFileToManagedStorage, createDesktopAttachmentManager } from "./attachments";
|
||||
|
||||
const originalPaseoHome = process.env.PASEO_HOME;
|
||||
let testHome: string | null = null;
|
||||
@@ -62,4 +62,152 @@ describe("desktop attachment files", () => {
|
||||
});
|
||||
await expect(readFile(result.path, "utf8")).resolves.toBe("# Report\n");
|
||||
});
|
||||
|
||||
it("keeps another window's draft and sent-message attachments when one window runs GC", async () => {
|
||||
await useTempPaseoHome();
|
||||
const manager = createDesktopAttachmentManager();
|
||||
manager.registerWindow(1);
|
||||
manager.registerWindow(2);
|
||||
|
||||
const w1Draft = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_w1_draft", bytes: new Uint8Array([1, 2, 3]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
const w1Sent = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_w1_sent", bytes: new Uint8Array([4, 5, 6]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
const w2Draft = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_w2_draft", bytes: new Uint8Array([7, 8, 9]), extension: ".png" },
|
||||
2,
|
||||
);
|
||||
const orphan = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_orphan", bytes: new Uint8Array([0]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
|
||||
// Window 1 reports its draft and sent image (dropping att_orphan).
|
||||
// Window 2 has not reported yet, so GC must defer deletion.
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles(
|
||||
{ referencedIds: ["att_w1_draft", "att_w1_sent"] },
|
||||
1,
|
||||
),
|
||||
).resolves.toBe(0);
|
||||
await expect(stat(orphan.path)).resolves.toBeDefined();
|
||||
|
||||
// Window 2 reports only its own draft. Only att_orphan is unreferenced across all windows.
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles({ referencedIds: ["att_w2_draft"] }, 2),
|
||||
).resolves.toBe(1);
|
||||
|
||||
await expect(readFile(w1Draft.path)).resolves.toEqual(Buffer.from([1, 2, 3]));
|
||||
await expect(readFile(w1Sent.path)).resolves.toEqual(Buffer.from([4, 5, 6]));
|
||||
await expect(readFile(w2Draft.path)).resolves.toEqual(Buffer.from([7, 8, 9]));
|
||||
await expect(stat(orphan.path)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("protects attachments written by window 1 before window 1 sends a new GC report", async () => {
|
||||
await useTempPaseoHome();
|
||||
const manager = createDesktopAttachmentManager();
|
||||
manager.registerWindow(1);
|
||||
manager.registerWindow(2);
|
||||
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 1);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2);
|
||||
|
||||
// Window 1 writes a daemon-uploaded image cache or newly pasted draft image without running GC yet.
|
||||
const w1Preview = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "daemon-upload-local-1", bytes: new Uint8Array([9, 9]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
|
||||
// Window 2 runs GC with an empty set. Window 1's newly written file must stay on disk.
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2),
|
||||
).resolves.toBe(0);
|
||||
await expect(readFile(w1Preview.path)).resolves.toEqual(Buffer.from([9, 9]));
|
||||
|
||||
// Once window 1 itself reports without that ID, it is reclaimed.
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 1),
|
||||
).resolves.toBe(1);
|
||||
await expect(stat(w1Preview.path)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("defers pruning while another window is reloading and reclaims after a window closes", async () => {
|
||||
await useTempPaseoHome();
|
||||
const manager = createDesktopAttachmentManager();
|
||||
manager.registerWindow(1);
|
||||
manager.registerWindow(2);
|
||||
|
||||
const w1File = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_reload", bytes: new Uint8Array([42]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: ["att_reload"] }, 1);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2);
|
||||
|
||||
// Window 1 starts reloading; window 2 must not sweep while window 1 is loading.
|
||||
manager.windowLoading(1);
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2),
|
||||
).resolves.toBe(0);
|
||||
await expect(readFile(w1File.path)).resolves.toEqual(Buffer.from([42]));
|
||||
|
||||
// Window 1 closes; once window 2 sweeps without att_reload, the file is reclaimed.
|
||||
manager.unregisterWindow(1);
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2),
|
||||
).resolves.toBe(1);
|
||||
await expect(stat(w1File.path)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("protects attachments recently read by another window before that window sweeps again", async () => {
|
||||
await useTempPaseoHome();
|
||||
const manager = createDesktopAttachmentManager();
|
||||
manager.registerWindow(1);
|
||||
manager.registerWindow(2);
|
||||
|
||||
const file = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_shared_read", bytes: new Uint8Array([5, 6]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: ["att_shared_read"] }, 1);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2);
|
||||
|
||||
// Window 2 reads the file (e.g. previewing or preparing upload) before window 1 drops it.
|
||||
await expect(manager.readManagedFileBase64({ path: file.path }, 2)).resolves.toBe(
|
||||
Buffer.from([5, 6]).toString("base64"),
|
||||
);
|
||||
|
||||
// Window 1 drops the reference; window 2's recent read keeps the file on disk.
|
||||
await expect(
|
||||
manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 1),
|
||||
).resolves.toBe(0);
|
||||
await expect(readFile(file.path)).resolves.toEqual(Buffer.from([5, 6]));
|
||||
});
|
||||
|
||||
it("keeps reads that arrive after a GC report was queued behind another window's sweep", async () => {
|
||||
await useTempPaseoHome();
|
||||
const manager = createDesktopAttachmentManager();
|
||||
manager.registerWindow(1);
|
||||
manager.registerWindow(2);
|
||||
|
||||
const preview = await manager.writeAttachmentBytes(
|
||||
{ attachmentId: "att_queued_read", bytes: new Uint8Array([9, 8, 7]), extension: ".png" },
|
||||
1,
|
||||
);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: ["att_queued_read"] }, 1);
|
||||
await manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2);
|
||||
|
||||
// Window 1 starts a sweep dropping att_queued_read, and window 2 queues an empty sweep behind it.
|
||||
const w1Sweep = manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 1);
|
||||
const w2QueuedSweep = manager.garbageCollectManagedAttachmentFiles({ referencedIds: [] }, 2);
|
||||
// While window 2's sweep is queued behind window 1, window 2 reads the preview.
|
||||
const w2Read = manager.readManagedFileBase64({ path: preview.path }, 2);
|
||||
|
||||
await Promise.all([w1Sweep, w2QueuedSweep, w2Read]);
|
||||
await expect(readFile(preview.path)).resolves.toEqual(Buffer.from([9, 8, 7]));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,12 +5,57 @@ import { resolvePaseoHome } from "@getpaseo/server/daemon-control";
|
||||
const ATTACHMENTS_DIRNAME = "desktop-attachments";
|
||||
const ATTACHMENT_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
|
||||
const EXTENSION_PATTERN = /^\.[A-Za-z0-9]{1,16}$/;
|
||||
const DEFAULT_WINDOW_ID = 0;
|
||||
|
||||
interface AttachmentFileResult {
|
||||
export interface AttachmentFileResult {
|
||||
path: string;
|
||||
byteSize: number;
|
||||
}
|
||||
|
||||
interface WindowAttachmentState {
|
||||
/**
|
||||
* Last complete set of referenced attachment IDs reported by this window.
|
||||
* `null` means the window is open or reloading and has not reported yet, so
|
||||
* pruning must wait rather than deleting attachments that window still needs.
|
||||
*/
|
||||
reportedIds: Set<string> | null;
|
||||
/**
|
||||
* Monotonic sequence incremented on every read/write touch by this window.
|
||||
* A queued GC report captures the sequence when it arrives so later reads or
|
||||
* writes that occur while it waits behind another sweep are never cleared.
|
||||
*/
|
||||
touchSeq: number;
|
||||
/**
|
||||
* Attachment IDs written or read by this window since its last report, mapped
|
||||
* to the `touchSeq` of the most recent touch.
|
||||
*/
|
||||
touchedAt: Map<string, number>;
|
||||
}
|
||||
|
||||
export interface DesktopAttachmentManager {
|
||||
registerWindow(windowId: number): void;
|
||||
windowLoading(windowId: number): void;
|
||||
unregisterWindow(windowId: number): void;
|
||||
writeAttachmentBase64(
|
||||
input: { attachmentId?: unknown; base64?: unknown; extension?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<AttachmentFileResult>;
|
||||
writeAttachmentBytes(
|
||||
input: { attachmentId?: unknown; bytes?: unknown; extension?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<AttachmentFileResult>;
|
||||
copyAttachmentFileToManagedStorage(
|
||||
input: { attachmentId?: unknown; sourcePath?: unknown; extension?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<AttachmentFileResult>;
|
||||
readManagedFileBase64(input: { path?: unknown }, windowId?: number): Promise<string>;
|
||||
deleteManagedAttachmentFile(input: { path?: unknown }, windowId?: number): Promise<boolean>;
|
||||
garbageCollectManagedAttachmentFiles(
|
||||
input: { referencedIds?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<number>;
|
||||
}
|
||||
|
||||
function attachmentsDirPath(): string {
|
||||
return path.join(resolvePaseoHome(process.env), ATTACHMENTS_DIRNAME);
|
||||
}
|
||||
@@ -47,16 +92,6 @@ function normalizeExtension(value: unknown): string {
|
||||
return extension;
|
||||
}
|
||||
|
||||
async function buildManagedAttachmentPath(input: {
|
||||
attachmentId: unknown;
|
||||
extension: unknown;
|
||||
}): Promise<string> {
|
||||
const dirPath = await ensureAttachmentsDir();
|
||||
const attachmentId = normalizeAttachmentId(input.attachmentId);
|
||||
const extension = normalizeExtension(input.extension);
|
||||
return path.join(dirPath, `${attachmentId}${extension}`);
|
||||
}
|
||||
|
||||
function resolveManagedAttachmentPath(inputPath: unknown): string {
|
||||
if (typeof inputPath !== "string" || inputPath.trim().length === 0) {
|
||||
throw new Error("Attachment path is required.");
|
||||
@@ -69,26 +104,9 @@ function resolveManagedAttachmentPath(inputPath: unknown): string {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
export async function writeAttachmentBase64(input: {
|
||||
attachmentId?: unknown;
|
||||
base64?: unknown;
|
||||
extension?: unknown;
|
||||
}): Promise<AttachmentFileResult> {
|
||||
const base64 = typeof input.base64 === "string" ? input.base64.trim() : "";
|
||||
if (base64.length === 0) {
|
||||
throw new Error("Attachment base64 payload is required.");
|
||||
}
|
||||
|
||||
const targetPath = await buildManagedAttachmentPath({
|
||||
attachmentId: input.attachmentId,
|
||||
extension: input.extension,
|
||||
});
|
||||
await writeFile(targetPath, Buffer.from(base64, "base64"));
|
||||
const fileInfo = await stat(targetPath);
|
||||
return {
|
||||
path: targetPath,
|
||||
byteSize: fileInfo.size,
|
||||
};
|
||||
function parseAttachmentIdFromPath(filePath: string): string | null {
|
||||
const stem = path.parse(filePath).name;
|
||||
return ATTACHMENT_ID_PATTERN.test(stem) ? stem : null;
|
||||
}
|
||||
|
||||
function normalizeBytes(value: unknown): Uint8Array {
|
||||
@@ -104,81 +122,285 @@ function normalizeBytes(value: unknown): Uint8Array {
|
||||
throw new Error("Attachment byte payload is required.");
|
||||
}
|
||||
|
||||
export async function writeAttachmentBytes(input: {
|
||||
attachmentId?: unknown;
|
||||
bytes?: unknown;
|
||||
extension?: unknown;
|
||||
}): Promise<AttachmentFileResult> {
|
||||
const bytes = normalizeBytes(input.bytes);
|
||||
const targetPath = await buildManagedAttachmentPath({
|
||||
attachmentId: input.attachmentId,
|
||||
extension: input.extension,
|
||||
});
|
||||
await writeFile(targetPath, bytes);
|
||||
const fileInfo = await stat(targetPath);
|
||||
return {
|
||||
path: targetPath,
|
||||
byteSize: fileInfo.size,
|
||||
};
|
||||
}
|
||||
|
||||
export async function copyAttachmentFileToManagedStorage(input: {
|
||||
attachmentId?: unknown;
|
||||
sourcePath?: unknown;
|
||||
extension?: unknown;
|
||||
}): Promise<AttachmentFileResult> {
|
||||
if (typeof input.sourcePath !== "string" || input.sourcePath.trim().length === 0) {
|
||||
throw new Error("Attachment source path is required.");
|
||||
function parseReferencedIds(value: unknown): Set<string> {
|
||||
if (!Array.isArray(value)) {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
const sourcePath = path.resolve(input.sourcePath.trim());
|
||||
const targetPath = await buildManagedAttachmentPath({
|
||||
attachmentId: input.attachmentId,
|
||||
extension: input.extension,
|
||||
});
|
||||
|
||||
if (sourcePath !== targetPath) {
|
||||
await copyFile(sourcePath, targetPath);
|
||||
}
|
||||
|
||||
const fileInfo = await stat(targetPath);
|
||||
return {
|
||||
path: targetPath,
|
||||
byteSize: fileInfo.size,
|
||||
};
|
||||
}
|
||||
|
||||
export async function readManagedFileBase64(input: { path?: unknown }): Promise<string> {
|
||||
const filePath = resolveManagedAttachmentPath(input.path);
|
||||
const bytes = await readFile(filePath);
|
||||
return bytes.toString("base64");
|
||||
}
|
||||
|
||||
export async function deleteManagedAttachmentFile(input: { path?: unknown }): Promise<boolean> {
|
||||
const filePath = resolveManagedAttachmentPath(input.path);
|
||||
await rm(filePath, { force: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function garbageCollectManagedAttachmentFiles(input: {
|
||||
referencedIds?: unknown;
|
||||
}): Promise<number> {
|
||||
const dirPath = await ensureAttachmentsDir();
|
||||
const referencedIds = Array.isArray(input.referencedIds)
|
||||
? new Set(
|
||||
input.referencedIds
|
||||
.filter((value): value is string => typeof value === "string")
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => ATTACHMENT_ID_PATTERN.test(value)),
|
||||
)
|
||||
: new Set<string>();
|
||||
|
||||
const entries = await readdir(dirPath, { withFileTypes: true });
|
||||
const toDelete = entries.filter(
|
||||
(entry) => entry.isFile() && !referencedIds.has(path.parse(entry.name).name),
|
||||
return new Set(
|
||||
value
|
||||
.filter((entry): entry is string => typeof entry === "string")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => ATTACHMENT_ID_PATTERN.test(entry)),
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(toDelete.map((entry) => rm(path.join(dirPath, entry.name), { force: true })));
|
||||
/**
|
||||
* Owns `~/.paseo/desktop-attachments/` across all Electron renderer windows.
|
||||
* Each window reports only what lives in its own renderer memory; pruning deletes
|
||||
* a file only when every live window has reported and none reference or touched it.
|
||||
*/
|
||||
export function createDesktopAttachmentManager(): DesktopAttachmentManager {
|
||||
const windows = new Map<number, WindowAttachmentState>();
|
||||
const inFlightWriteCounts = new Map<string, number>();
|
||||
const pendingDeletes = new Map<string, Promise<void>>();
|
||||
let gcTail: Promise<void> = Promise.resolve();
|
||||
|
||||
return toDelete.length;
|
||||
function getOrCreateWindow(windowId: number): WindowAttachmentState {
|
||||
let state = windows.get(windowId);
|
||||
if (!state) {
|
||||
state = { reportedIds: null, touchSeq: 0, touchedAt: new Map() };
|
||||
windows.set(windowId, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function touchWindowAttachment(windowId: number, attachmentId: string): void {
|
||||
const state = getOrCreateWindow(windowId);
|
||||
state.touchSeq += 1;
|
||||
state.touchedAt.set(attachmentId, state.touchSeq);
|
||||
}
|
||||
|
||||
async function withInFlightWrite<T>(
|
||||
windowId: number,
|
||||
attachmentId: string,
|
||||
write: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
touchWindowAttachment(windowId, attachmentId);
|
||||
inFlightWriteCounts.set(attachmentId, (inFlightWriteCounts.get(attachmentId) ?? 0) + 1);
|
||||
try {
|
||||
const deleting = pendingDeletes.get(attachmentId);
|
||||
if (deleting) {
|
||||
await deleting.catch(() => undefined);
|
||||
}
|
||||
return await write();
|
||||
} finally {
|
||||
const nextCount = (inFlightWriteCounts.get(attachmentId) ?? 1) - 1;
|
||||
if (nextCount <= 0) {
|
||||
inFlightWriteCounts.delete(attachmentId);
|
||||
} else {
|
||||
inFlightWriteCounts.set(attachmentId, nextCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collectProtectedIds(): Set<string> {
|
||||
const protectedIds = new Set<string>();
|
||||
for (const state of windows.values()) {
|
||||
if (state.reportedIds) {
|
||||
for (const id of state.reportedIds) {
|
||||
protectedIds.add(id);
|
||||
}
|
||||
}
|
||||
for (const id of state.touchedAt.keys()) {
|
||||
protectedIds.add(id);
|
||||
}
|
||||
}
|
||||
for (const id of inFlightWriteCounts.keys()) {
|
||||
protectedIds.add(id);
|
||||
}
|
||||
return protectedIds;
|
||||
}
|
||||
|
||||
function hasUnreportedWindow(): boolean {
|
||||
for (const state of windows.values()) {
|
||||
if (state.reportedIds === null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
registerWindow(windowId) {
|
||||
getOrCreateWindow(windowId);
|
||||
},
|
||||
|
||||
windowLoading(windowId) {
|
||||
const state = getOrCreateWindow(windowId);
|
||||
state.reportedIds = null;
|
||||
},
|
||||
|
||||
unregisterWindow(windowId) {
|
||||
windows.delete(windowId);
|
||||
},
|
||||
|
||||
async writeAttachmentBase64(input, windowId = DEFAULT_WINDOW_ID) {
|
||||
const base64 = typeof input.base64 === "string" ? input.base64.trim() : "";
|
||||
if (base64.length === 0) {
|
||||
throw new Error("Attachment base64 payload is required.");
|
||||
}
|
||||
const attachmentId = normalizeAttachmentId(input.attachmentId);
|
||||
const extension = normalizeExtension(input.extension);
|
||||
|
||||
return await withInFlightWrite(windowId, attachmentId, async () => {
|
||||
const dirPath = await ensureAttachmentsDir();
|
||||
const targetPath = path.join(dirPath, `${attachmentId}${extension}`);
|
||||
await writeFile(targetPath, Buffer.from(base64, "base64"));
|
||||
const fileInfo = await stat(targetPath);
|
||||
return {
|
||||
path: targetPath,
|
||||
byteSize: fileInfo.size,
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
async writeAttachmentBytes(input, windowId = DEFAULT_WINDOW_ID) {
|
||||
const bytes = normalizeBytes(input.bytes);
|
||||
const attachmentId = normalizeAttachmentId(input.attachmentId);
|
||||
const extension = normalizeExtension(input.extension);
|
||||
|
||||
return await withInFlightWrite(windowId, attachmentId, async () => {
|
||||
const dirPath = await ensureAttachmentsDir();
|
||||
const targetPath = path.join(dirPath, `${attachmentId}${extension}`);
|
||||
await writeFile(targetPath, bytes);
|
||||
const fileInfo = await stat(targetPath);
|
||||
return {
|
||||
path: targetPath,
|
||||
byteSize: fileInfo.size,
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
async copyAttachmentFileToManagedStorage(input, windowId = DEFAULT_WINDOW_ID) {
|
||||
if (typeof input.sourcePath !== "string" || input.sourcePath.trim().length === 0) {
|
||||
throw new Error("Attachment source path is required.");
|
||||
}
|
||||
const sourcePath = path.resolve(input.sourcePath.trim());
|
||||
const attachmentId = normalizeAttachmentId(input.attachmentId);
|
||||
const extension = normalizeExtension(input.extension);
|
||||
|
||||
return await withInFlightWrite(windowId, attachmentId, async () => {
|
||||
const dirPath = await ensureAttachmentsDir();
|
||||
const targetPath = path.join(dirPath, `${attachmentId}${extension}`);
|
||||
if (sourcePath !== targetPath) {
|
||||
await copyFile(sourcePath, targetPath);
|
||||
}
|
||||
const fileInfo = await stat(targetPath);
|
||||
return {
|
||||
path: targetPath,
|
||||
byteSize: fileInfo.size,
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
async readManagedFileBase64(input, windowId = DEFAULT_WINDOW_ID) {
|
||||
const filePath = resolveManagedAttachmentPath(input.path);
|
||||
const attachmentId = parseAttachmentIdFromPath(filePath);
|
||||
if (attachmentId) {
|
||||
touchWindowAttachment(windowId, attachmentId);
|
||||
}
|
||||
const bytes = await readFile(filePath);
|
||||
return bytes.toString("base64");
|
||||
},
|
||||
|
||||
async deleteManagedAttachmentFile(input, windowId = DEFAULT_WINDOW_ID) {
|
||||
const filePath = resolveManagedAttachmentPath(input.path);
|
||||
const attachmentId = parseAttachmentIdFromPath(filePath);
|
||||
const windowState = windows.get(windowId);
|
||||
if (attachmentId && windowState) {
|
||||
windowState.touchedAt.delete(attachmentId);
|
||||
windowState.reportedIds?.delete(attachmentId);
|
||||
}
|
||||
await rm(filePath, { force: true });
|
||||
return true;
|
||||
},
|
||||
|
||||
async garbageCollectManagedAttachmentFiles(input, windowId = DEFAULT_WINDOW_ID) {
|
||||
const referencedIds = parseReferencedIds(input.referencedIds);
|
||||
const windowState = getOrCreateWindow(windowId);
|
||||
const snapshotTouchSeq = windowState.touchSeq;
|
||||
const previous = gcTail;
|
||||
let deletedCount = 0;
|
||||
|
||||
const current = (async () => {
|
||||
await previous;
|
||||
if (windows.get(windowId) !== windowState) {
|
||||
return;
|
||||
}
|
||||
windowState.reportedIds = referencedIds;
|
||||
for (const [id, touchedSeq] of windowState.touchedAt) {
|
||||
if (touchedSeq <= snapshotTouchSeq && !inFlightWriteCounts.has(id)) {
|
||||
windowState.touchedAt.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasUnreportedWindow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dirPath = await ensureAttachmentsDir();
|
||||
const entries = await readdir(dirPath, { withFileTypes: true });
|
||||
// Re-check after async readdir in case another window opened, reloaded, or wrote.
|
||||
if (hasUnreportedWindow()) {
|
||||
return;
|
||||
}
|
||||
const protectedIds = collectProtectedIds();
|
||||
const toDelete = entries.filter(
|
||||
(entry) => entry.isFile() && !protectedIds.has(path.parse(entry.name).name),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
toDelete.map((entry) => {
|
||||
const id = path.parse(entry.name).name;
|
||||
const deletion = rm(path.join(dirPath, entry.name), { force: true }).finally(() => {
|
||||
if (pendingDeletes.get(id) === deletion) {
|
||||
pendingDeletes.delete(id);
|
||||
}
|
||||
});
|
||||
pendingDeletes.set(id, deletion);
|
||||
return deletion;
|
||||
}),
|
||||
);
|
||||
deletedCount = toDelete.length;
|
||||
})();
|
||||
|
||||
gcTail = current.catch(() => undefined);
|
||||
await current;
|
||||
return deletedCount;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const defaultDesktopAttachmentManager = createDesktopAttachmentManager();
|
||||
|
||||
export function writeAttachmentBase64(
|
||||
input: { attachmentId?: unknown; base64?: unknown; extension?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<AttachmentFileResult> {
|
||||
return defaultDesktopAttachmentManager.writeAttachmentBase64(input, windowId);
|
||||
}
|
||||
|
||||
export function writeAttachmentBytes(
|
||||
input: { attachmentId?: unknown; bytes?: unknown; extension?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<AttachmentFileResult> {
|
||||
return defaultDesktopAttachmentManager.writeAttachmentBytes(input, windowId);
|
||||
}
|
||||
|
||||
export function copyAttachmentFileToManagedStorage(
|
||||
input: { attachmentId?: unknown; sourcePath?: unknown; extension?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<AttachmentFileResult> {
|
||||
return defaultDesktopAttachmentManager.copyAttachmentFileToManagedStorage(input, windowId);
|
||||
}
|
||||
|
||||
export function readManagedFileBase64(
|
||||
input: { path?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<string> {
|
||||
return defaultDesktopAttachmentManager.readManagedFileBase64(input, windowId);
|
||||
}
|
||||
|
||||
export function deleteManagedAttachmentFile(
|
||||
input: { path?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<boolean> {
|
||||
return defaultDesktopAttachmentManager.deleteManagedAttachmentFile(input, windowId);
|
||||
}
|
||||
|
||||
export function garbageCollectManagedAttachmentFiles(
|
||||
input: { referencedIds?: unknown },
|
||||
windowId?: number,
|
||||
): Promise<number> {
|
||||
return defaultDesktopAttachmentManager.garbageCollectManagedAttachmentFiles(input, windowId);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
webContents,
|
||||
} from "electron";
|
||||
import { registerDaemonManager } from "./daemon/daemon-manager.js";
|
||||
import { createDesktopAttachmentManager } from "./features/attachments.js";
|
||||
import { parsePassthroughCliArgsFromArgv, runPassthroughCli } from "./daemon/cli/passthrough.js";
|
||||
import { closeAllTransportSessions } from "./daemon/local-transport.js";
|
||||
import {
|
||||
@@ -142,6 +143,7 @@ const DESKTOP_WINDOW_CHROME_MODE = resolveDesktopWindowChromeMode({
|
||||
const UPDATE_QUIT_DEADLINE_MS = 5_000;
|
||||
const pendingBrowserWindowOpenRequests = new PendingBrowserWindowOpenRequests();
|
||||
const agentNavigationInbox = new AgentNavigationInbox();
|
||||
const desktopAttachments = createDesktopAttachmentManager();
|
||||
|
||||
// A second-instance launch can arrive before the packaged protocol handler,
|
||||
// IPC handlers, and first window exist. Wait for full bootstrap, not just
|
||||
@@ -842,15 +844,21 @@ async function createWindow(
|
||||
applyDesktopWindowChromeMode({ win: mainWindow, mode: DESKTOP_WINDOW_CHROME_MODE });
|
||||
|
||||
const webContentsId = mainWindow.webContents.id;
|
||||
desktopAttachments.registerWindow(webContentsId);
|
||||
options.onCreated?.(webContentsId);
|
||||
mainWindow.webContents.on("did-start-navigation", (_event, _url, isSameDocument, isMainFrame) => {
|
||||
if (isMainFrame && !isSameDocument) {
|
||||
agentNavigationInbox.windowLoading(webContentsId);
|
||||
desktopAttachments.windowLoading(webContentsId);
|
||||
}
|
||||
});
|
||||
mainWindow.webContents.once("destroyed", () => {
|
||||
desktopAttachments.unregisterWindow(webContentsId);
|
||||
});
|
||||
mainWindow.on("closed", () => {
|
||||
options.onClosed?.(webContentsId);
|
||||
agentNavigationInbox.removeWindow(webContentsId);
|
||||
desktopAttachments.unregisterWindow(webContentsId);
|
||||
unregisterPaseoBrowserHost(webContentsId);
|
||||
browserKeyboard.detachHost(webContentsId);
|
||||
});
|
||||
@@ -1124,7 +1132,7 @@ async function bootstrap(): Promise<void> {
|
||||
},
|
||||
});
|
||||
ensureNotificationCenterRegistration();
|
||||
registerDaemonManager();
|
||||
registerDaemonManager({ attachments: desktopAttachments });
|
||||
registerWindowManager({ mode: DESKTOP_WINDOW_CHROME_MODE });
|
||||
registerDialogHandlers();
|
||||
registerNotificationHandlers();
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import type { DesktopSettingsStore } from "./desktop-settings.js";
|
||||
|
||||
export type DesktopCommandHandler = (args?: Record<string, unknown>) => unknown;
|
||||
export interface DesktopCommandContext {
|
||||
senderWebContentsId?: number;
|
||||
}
|
||||
|
||||
export type DesktopCommandHandler = (
|
||||
args?: Record<string, unknown>,
|
||||
context?: DesktopCommandContext,
|
||||
) => unknown;
|
||||
|
||||
export function createDesktopSettingsCommandHandlers({
|
||||
settingsStore,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/highlight"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/plugin"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map"
|
||||
@@ -83,8 +88,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -94,8 +99,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/protocol"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-native-enriched-markdown",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"description": "Markdown-based Rich Text solution for React Native",
|
||||
"main": "./lib/module/index",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/relay"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map"
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "Paseo backend server",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/getpaseo/paseo.git",
|
||||
"directory": "packages/server"
|
||||
},
|
||||
"files": [
|
||||
"dist/server",
|
||||
"dist/src",
|
||||
@@ -114,11 +119,11 @@
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/highlight": "0.19.1",
|
||||
"@getpaseo/plugin": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/relay": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/highlight": "0.19.2",
|
||||
"@getpaseo/plugin": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/relay": "0.19.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
|
||||
@@ -497,6 +497,182 @@ describe("Codex active-turn steering admission", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("returns unavailable when a steered prompt mentions an enabled Codex skill inline", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("Answer briefly. /marker-skill", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
}),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when a steered prompt with attachments mentions an enabled Codex skill", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Earlier turn context",
|
||||
},
|
||||
{ type: "text", text: "Check this with /marker-skill." },
|
||||
],
|
||||
{ expectedTurnId: paseoTurnId },
|
||||
),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers normally without listing skills when the prompt only contains a file path", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
const skillListsBeforeSteer = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "skills/list").length;
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("Check /docs/api.md next", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
}),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "skills/list").length,
|
||||
).toBe(skillListsBeforeSteer);
|
||||
expect(appServer.requests().find((request) => request.method === "turn/steer")).toMatchObject(
|
||||
{
|
||||
params: {
|
||||
input: [{ type: "text", text: "Check /docs/api.md next", text_elements: [] }],
|
||||
},
|
||||
},
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not steer B when A completes while skill lookup is pending", async () => {
|
||||
const skillLookup = deferred<{ data: [] }>();
|
||||
const skillLookupEntered = deferred<void>();
|
||||
let holdSkillLookup = false;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => {
|
||||
if (!holdSkillLookup) {
|
||||
return { data: [] };
|
||||
}
|
||||
skillLookupEntered.resolve();
|
||||
return skillLookup.promise;
|
||||
},
|
||||
"turn/steer": () => ({ turn: { id: "native-B" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
holdSkillLookup = true;
|
||||
try {
|
||||
const steer = session.steerActiveTurn!("Check /unknown-token", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
clientMessageId: "steer-skill-race",
|
||||
});
|
||||
await skillLookupEntered.promise;
|
||||
appServer.completeTurn({ threadId: "thread-1" });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const startedB = await session.startTurn("second");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-B" });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
skillLookup.resolve({ data: [] });
|
||||
|
||||
await expect(steer).resolves.toEqual({ status: "unavailable" });
|
||||
expect(startedB.turnId).not.toBe(paseoTurnId);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when steering a built-in /compact command", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("/compact", { expectedTurnId: paseoTurnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["method unavailable", -32601, "method not found", undefined, "unavailable"],
|
||||
["no active turn", -32600, "no active turn to steer", undefined, "unavailable"],
|
||||
@@ -4113,6 +4289,326 @@ describe("Codex app-server provider", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves inline, repeated, and punctuated Codex skill mentions into app-server skill input", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "second-skill",
|
||||
description: "Second skill.",
|
||||
path: "/workspace/skills/second-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn(
|
||||
"Answer briefly using /marker-skill, then /second-skill. Re-check /marker-skill!",
|
||||
);
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "skill",
|
||||
name: "second-skill",
|
||||
path: "/workspace/skills/second-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Answer briefly using $marker-skill, then $second-skill. Re-check $marker-skill!",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves Codex skill mentions in prompts carrying attachments without touching chat_history or attachment text", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "history-skill",
|
||||
description: "History skill.",
|
||||
path: "/workspace/skills/history-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous conversation mentioned /history-skill",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "/marker-skill inspect this screenshot",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: ONE_BY_ONE_PNG_BASE64,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Snippet",
|
||||
text: "Attached note mentioning /history-skill",
|
||||
},
|
||||
]);
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
const input = (turnStart?.params as { input?: Array<Record<string, unknown>> })?.input ?? [];
|
||||
const localImage = input.find((item) => item.type === "localImage");
|
||||
try {
|
||||
expect(input).toEqual([
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Previous conversation mentioned /history-skill",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "$marker-skill inspect this screenshot",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "localImage",
|
||||
path: expect.any(String),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Attached note mentioning /history-skill",
|
||||
text_elements: [],
|
||||
},
|
||||
]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
if (typeof localImage?.path === "string") {
|
||||
rmSync(localImage.path, { force: true });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves file paths like /docs/api.md untouched and skips skills/list when no mention candidate exists", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.connect();
|
||||
const skillListsBeforeTurn = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "skills/list").length;
|
||||
|
||||
await session.startTurn("Check /docs/api.md before replying.");
|
||||
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "skills/list").length,
|
||||
).toBe(skillListsBeforeTurn);
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Check /docs/api.md before replying.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not resolve disabled Codex skills mentioned inline", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "disabled-skill",
|
||||
description: "Disabled skill.",
|
||||
path: "/workspace/skills/disabled-skill/SKILL.md",
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Use /disabled-skill please.");
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Use /disabled-skill please.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves Codex skill mentions in /prompts:* arguments while keeping saved template text literal", async () => {
|
||||
const codexHome = await mkdtemp(path.join(tmpdir(), "codex-custom-prompt-skill-"));
|
||||
mkdirSync(path.join(codexHome, "prompts"), { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(codexHome, "prompts", "review.md"),
|
||||
"---\ndescription: Review with args\n---\n\nKeep /docs literal and review: $ARGUMENTS\n",
|
||||
"utf8",
|
||||
);
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
{ codexHome },
|
||||
);
|
||||
try {
|
||||
await session.startTurn("/prompts:review Use /marker-skill.");
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: expect.stringContaining("Keep /docs literal and review: Use $marker-skill."),
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
rmSync(codexHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("lists project skill commands when app-server receives the project cwd in cwds", async () => {
|
||||
const commands = await listCommandsFromFakeCodex([
|
||||
{
|
||||
|
||||
@@ -2,6 +2,13 @@ import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { applyProviderOptionsPatch } from "../option-controls.js";
|
||||
import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js";
|
||||
import { CodexBackgroundInventory } from "./codex/background-inventory.js";
|
||||
import {
|
||||
type CodexPromptInput,
|
||||
type CodexSkillPromptBlock,
|
||||
hasCodexSkillMentionCandidate,
|
||||
resolveCodexSkillMentions,
|
||||
type ResolvedCodexSkillMentions,
|
||||
} from "./codex/skill-mentions.js";
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
@@ -20,7 +27,6 @@ import {
|
||||
type AgentPermissionResponse,
|
||||
type AgentPermissionResult,
|
||||
type AgentProviderNotice,
|
||||
type AgentPromptContentBlock,
|
||||
type AgentPromptInput,
|
||||
type AgentRunOptions,
|
||||
type AgentRunResult,
|
||||
@@ -3588,12 +3594,6 @@ async function readCodexConfiguredDefaults(
|
||||
return mergeCodexConfiguredDefaults(savedConfigDefaults, configReadDefaults);
|
||||
}
|
||||
|
||||
interface CodexSkillPromptBlock {
|
||||
type: "skill";
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
function enabledCodexSkills(
|
||||
entries: unknown[],
|
||||
): Array<{ name: string; description: string; path: string }> {
|
||||
@@ -3618,8 +3618,6 @@ function enabledCodexSkills(
|
||||
return Array.from(skillsByName.values());
|
||||
}
|
||||
|
||||
type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
|
||||
type CodexPromptInput = string | CodexPromptContentBlock[];
|
||||
interface CodexTextElement {
|
||||
byteRange: {
|
||||
start: number;
|
||||
@@ -3948,6 +3946,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
name: string;
|
||||
} | null = null;
|
||||
private cachedSkills: Array<{ name: string; description: string; path: string }> | null = null;
|
||||
private pendingLiteralFollowUpPrompt: string | null = null;
|
||||
|
||||
private readonly usageSessionKey = randomUUID();
|
||||
private readonly harnessEnvironment: Record<string, string>;
|
||||
@@ -4709,12 +4708,12 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
return null;
|
||||
}
|
||||
const parsed = this.parseSlashCommandInput(prompt);
|
||||
if (!parsed) {
|
||||
if (!parsed || !parsed.commandName.startsWith("prompts:")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const commands = await this.listCommands();
|
||||
return commands.some((command) => command.name === parsed.commandName) ? parsed : null;
|
||||
const prompts = await listCodexCustomPrompts(this.codexHome);
|
||||
return prompts.some((command) => command.name === parsed.commandName) ? parsed : null;
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
{ err: error, commandName: parsed.commandName },
|
||||
@@ -4728,31 +4727,30 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
commandName: string,
|
||||
args?: string,
|
||||
): Promise<CodexPromptInput> {
|
||||
if (commandName.startsWith("prompts:")) {
|
||||
const promptName = commandName.slice("prompts:".length);
|
||||
const promptPath = path.join(this.codexHome, "prompts", `${promptName}.md`);
|
||||
const raw = await fs.readFile(promptPath, "utf8");
|
||||
const parsed = parseFrontMatter(raw);
|
||||
return expandCodexCustomPrompt(parsed.body, args);
|
||||
const promptName = commandName.slice("prompts:".length);
|
||||
const promptPath = path.join(this.codexHome, "prompts", `${promptName}.md`);
|
||||
const raw = await fs.readFile(promptPath, "utf8");
|
||||
const parsed = parseFrontMatter(raw);
|
||||
const resolvedArgs = args ? await this.resolveMentionedSkills(args) : null;
|
||||
const expandedArgs =
|
||||
resolvedArgs && resolvedArgs.skills.length > 0 && Array.isArray(resolvedArgs.prompt)
|
||||
? (resolvedArgs.prompt.find((block) => block.type === "text")?.text ?? args)
|
||||
: args;
|
||||
const expandedBody = expandCodexCustomPrompt(parsed.body, expandedArgs);
|
||||
if (!resolvedArgs || resolvedArgs.skills.length === 0) {
|
||||
return expandedBody;
|
||||
}
|
||||
return [...resolvedArgs.skills, { type: "text", text: expandedBody }];
|
||||
}
|
||||
|
||||
if (this.connectionState === "disconnected") {
|
||||
await this.connect();
|
||||
} else {
|
||||
await this.loadSkills();
|
||||
private async resolveMentionedSkills(
|
||||
prompt: AgentPromptInput,
|
||||
): Promise<ResolvedCodexSkillMentions> {
|
||||
if (!hasCodexSkillMentionCandidate(prompt)) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
const skill = this.cachedSkills?.find((entry) => entry.name === commandName);
|
||||
if (skill) {
|
||||
const trimmedArgs = args?.trim() ?? "";
|
||||
const text = trimmedArgs ? `$${skill.name} ${trimmedArgs}` : `$${skill.name}`;
|
||||
const input: CodexPromptContentBlock[] = [
|
||||
{ type: "skill", name: skill.name, path: skill.path },
|
||||
{ type: "text", text },
|
||||
];
|
||||
return input;
|
||||
}
|
||||
|
||||
return args ? `$${commandName} ${args}` : `$${commandName}`;
|
||||
await this.loadSkills();
|
||||
return resolveCodexSkillMentions(prompt, this.cachedSkills ?? []);
|
||||
}
|
||||
|
||||
private async buildTurnStartParams(
|
||||
@@ -4948,10 +4946,19 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
throw new Error("Codex client not initialized");
|
||||
}
|
||||
|
||||
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
||||
const effectivePrompt = slashCommand
|
||||
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
||||
: prompt;
|
||||
const isLiteralFollowUp =
|
||||
typeof prompt === "string" &&
|
||||
this.pendingLiteralFollowUpPrompt !== null &&
|
||||
prompt === this.pendingLiteralFollowUpPrompt;
|
||||
this.pendingLiteralFollowUpPrompt = null;
|
||||
|
||||
let effectivePrompt: CodexPromptInput = prompt;
|
||||
if (!isLiteralFollowUp) {
|
||||
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
||||
effectivePrompt = slashCommand
|
||||
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
||||
: (await this.resolveMentionedSkills(prompt)).prompt;
|
||||
}
|
||||
|
||||
if (this.currentThreadId) {
|
||||
await this.ensureThreadLoaded();
|
||||
@@ -5007,16 +5014,44 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async steerActiveTurn(
|
||||
private async canSteerPrompt(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
},
|
||||
): Promise<boolean> {
|
||||
if (this.tryHandleOutOfBand(prompt)) {
|
||||
return false;
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) {
|
||||
return false;
|
||||
}
|
||||
if (!this.matchesSteerAdmission(admission)) {
|
||||
return false;
|
||||
}
|
||||
// Codex app-server only resolves skills at turn start (turn/steer ignores skill items and
|
||||
// $skill mentions), so fall back to turn replacement whenever a steered prompt mentions a skill.
|
||||
if ((await this.resolveMentionedSkills(prompt)).skills.length > 0) {
|
||||
return false;
|
||||
}
|
||||
return this.matchesSteerAdmission(admission);
|
||||
}
|
||||
|
||||
private async resolveSteerAdmission(expectedTurnId: string): Promise<{
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
} | null> {
|
||||
const client = this.client;
|
||||
const threadId = this.currentThreadId;
|
||||
let nativeTurnId = this.currentTurnId;
|
||||
const foregroundTurnId = this.activeForegroundTurnId;
|
||||
if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
if (!client || !threadId || foregroundTurnId !== expectedTurnId) {
|
||||
return null;
|
||||
}
|
||||
const pendingIdentification = this.pendingForegroundTurnIdentification;
|
||||
// The start acknowledgement precedes the notification that identifies the native
|
||||
@@ -5024,23 +5059,29 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) {
|
||||
nativeTurnId = await pendingIdentification.promise;
|
||||
}
|
||||
if (!nativeTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" };
|
||||
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return nativeTurnId ? { client, threadId, nativeTurnId, foregroundTurnId } : null;
|
||||
}
|
||||
|
||||
private async submitTurnSteer(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
},
|
||||
): Promise<SteerResult> {
|
||||
const input = await this.buildUserInput(prompt);
|
||||
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
|
||||
if (!this.matchesSteerAdmission(admission)) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
try {
|
||||
const response = await client.request(
|
||||
const response = await admission.client.request(
|
||||
"turn/steer",
|
||||
{
|
||||
threadId,
|
||||
expectedTurnId: nativeTurnId,
|
||||
threadId: admission.threadId,
|
||||
expectedTurnId: admission.nativeTurnId,
|
||||
input,
|
||||
...(options.clientMessageId ? { clientUserMessageId: options.clientMessageId } : {}),
|
||||
},
|
||||
@@ -5049,7 +5090,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
const record = toObjectRecord(response);
|
||||
const turn = record ? toObjectRecord(record.turn) : null;
|
||||
const acknowledgedTurnId = nonEmptyString(record?.turnId) ?? nonEmptyString(turn?.id);
|
||||
if (acknowledgedTurnId !== nativeTurnId) {
|
||||
if (acknowledgedTurnId !== admission.nativeTurnId) {
|
||||
throw new Error("Codex returned an invalid steer acknowledgement");
|
||||
}
|
||||
if (options.clearPendingPermissions) {
|
||||
@@ -5062,6 +5103,17 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async steerActiveTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
const admission = await this.resolveSteerAdmission(options.expectedTurnId);
|
||||
if (!admission || !(await this.canSteerPrompt(prompt, admission))) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return this.submitTurnSteer(prompt, options, admission);
|
||||
}
|
||||
|
||||
private matchesSteerAdmission(admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
@@ -5403,10 +5455,16 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
let followUpPrompt = prepared.prompt;
|
||||
const expectedTurnId = this.activeForegroundTurnId;
|
||||
if (prepared.prompt && expectedTurnId) {
|
||||
const result = await this.steerActiveTurn(prepared.prompt, {
|
||||
expectedTurnId,
|
||||
clientMessageId: randomUUID(),
|
||||
});
|
||||
// Async question answers are structured replies to the active turn, not composer slash
|
||||
// prompts, so steer them directly without composer command/skill interception.
|
||||
const admission = await this.resolveSteerAdmission(expectedTurnId);
|
||||
const result = admission
|
||||
? await this.submitTurnSteer(
|
||||
prepared.prompt,
|
||||
{ expectedTurnId, clientMessageId: randomUUID() },
|
||||
admission,
|
||||
)
|
||||
: { status: "unavailable" as const };
|
||||
if (result.status !== "accepted") {
|
||||
throw new Error("The active Codex turn changed. Retry sending your answer.");
|
||||
}
|
||||
@@ -5419,7 +5477,11 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
requestId,
|
||||
resolution: response,
|
||||
});
|
||||
return followUpPrompt ? { followUpPrompt } : undefined;
|
||||
if (followUpPrompt) {
|
||||
this.pendingLiteralFollowUpPrompt = followUpPrompt;
|
||||
return { followUpPrompt };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private handlePlanPermissionResponse(params: {
|
||||
@@ -5438,6 +5500,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
|
||||
this.resolvePlanPermission(requestId, response);
|
||||
if (followUpPrompt) {
|
||||
this.pendingLiteralFollowUpPrompt = followUpPrompt;
|
||||
return { followUpPrompt };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,3 +460,137 @@ test("restores unanswered questions and does not reopen answered questions on du
|
||||
await resumed.session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers an async answer containing an enabled Codex skill token without failing", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turnId: "native-turn" }),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Ask me a question.");
|
||||
const started = waitForNextEvent(session, "turn_started");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
|
||||
await started;
|
||||
const shown = waitForTimelineToolCall(session, questionItem.id);
|
||||
appServer.child.stdout.write(
|
||||
JSON.stringify({
|
||||
method: "item/completed",
|
||||
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
|
||||
}) + "\n",
|
||||
);
|
||||
await shown;
|
||||
const [permission] = session.getPendingPermissions();
|
||||
expect(permission).toBeDefined();
|
||||
|
||||
await session.respondToPermission(permission!.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { "0": "Use /marker-skill" } },
|
||||
});
|
||||
|
||||
expect(session.getPendingPermissions()).toEqual([]);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toMatchObject(
|
||||
[
|
||||
{
|
||||
params: {
|
||||
expectedTurnId: "native-turn",
|
||||
input: [{ type: "text", text: expect.stringContaining("Use /marker-skill") }],
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps a late async answer containing an enabled Codex skill token literal on the follow-up turn", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Ask me a question.");
|
||||
const started = waitForNextEvent(session, "turn_started");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
|
||||
await started;
|
||||
const shown = waitForTimelineToolCall(session, questionItem.id);
|
||||
appServer.child.stdout.write(
|
||||
JSON.stringify({
|
||||
method: "item/completed",
|
||||
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
|
||||
}) + "\n",
|
||||
);
|
||||
await shown;
|
||||
const completed = waitForNextEvent(session, "turn_completed");
|
||||
appServer.completeTurn({ threadId: "thread-1" });
|
||||
await completed;
|
||||
|
||||
const [permission] = session.getPendingPermissions();
|
||||
expect(permission).toBeDefined();
|
||||
const result = await session.respondToPermission(permission!.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { "0": "Show /marker-skill in the example." } },
|
||||
});
|
||||
expect(result?.followUpPrompt).toBe(
|
||||
"Answers to your questions:\n\nWhich color?\nShow /marker-skill in the example.",
|
||||
);
|
||||
|
||||
await session.startTurn(result!.followUpPrompt!);
|
||||
|
||||
const turnStarts = appServer.requests().filter((request) => request.method === "turn/start");
|
||||
expect(turnStarts[turnStarts.length - 1]?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Answers to your questions:\n\nWhich color?\nShow /marker-skill in the example.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { AgentPromptContentBlock } from "../../agent-sdk-types.js";
|
||||
import {
|
||||
type CodexSkillDescriptor,
|
||||
hasCodexSkillMentionCandidate,
|
||||
resolveCodexSkillMentions,
|
||||
} from "./skill-mentions.js";
|
||||
|
||||
const SKILLS: CodexSkillDescriptor[] = [
|
||||
{ name: "marker-skill", path: "/workspace/.agents/skills/marker-skill/SKILL.md" },
|
||||
{ name: "second-skill", path: "/workspace/.agents/skills/second-skill/SKILL.md" },
|
||||
{ name: "docs", path: "/workspace/.agents/skills/docs/SKILL.md" },
|
||||
];
|
||||
|
||||
describe("hasCodexSkillMentionCandidate", () => {
|
||||
test("detects leading, inline, and punctuated slash candidates in user text", () => {
|
||||
expect(hasCodexSkillMentionCandidate("/marker-skill")).toBe(true);
|
||||
expect(hasCodexSkillMentionCandidate("Use /marker-skill.")).toBe(true);
|
||||
expect(hasCodexSkillMentionCandidate("Check /docs/api.md then /marker-skill")).toBe(true);
|
||||
expect(
|
||||
hasCodexSkillMentionCandidate([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "No candidate here",
|
||||
},
|
||||
{ type: "text", text: "Now run /marker-skill!" },
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("returns false for plain text, file paths, URLs, bare slashes, and non-user blocks", () => {
|
||||
expect(hasCodexSkillMentionCandidate("Answer briefly: what is 2+2?")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Read /docs/api.md before replying")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Read /docs/api.md.")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("See https://example.com/marker-skill")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Path foo/marker-skill")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Ratio a/b and bare / or /.")).toBe(false);
|
||||
expect(
|
||||
hasCodexSkillMentionCandidate([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Prior message used /marker-skill",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Note",
|
||||
text: "Attached snippet with /marker-skill",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "AAAA",
|
||||
},
|
||||
{
|
||||
type: "github_issue",
|
||||
mimeType: "application/github-issue",
|
||||
number: 5008,
|
||||
title: "Fix /marker-skill",
|
||||
url: "https://github.com/getpaseo/paseo/issues/5008",
|
||||
},
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCodexSkillMentions", () => {
|
||||
test("resolves leading, inline, multiple, deduplicated, and punctuated mentions", () => {
|
||||
expect(resolveCodexSkillMentions("/marker-skill Answer briefly.", SKILLS)).toEqual({
|
||||
skills: [{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path }],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "text", text: "$marker-skill Answer briefly." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveCodexSkillMentions(
|
||||
"Use /second-skill, then /marker-skill; finally (/second-skill or /marker-skill!).",
|
||||
SKILLS,
|
||||
),
|
||||
).toEqual({
|
||||
skills: [
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
],
|
||||
prompt: [
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{
|
||||
type: "text",
|
||||
text: "Use $second-skill, then $marker-skill; finally (/second-skill or $marker-skill!).",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveCodexSkillMentions(
|
||||
"Try /marker-skill? /second-skill: [use /docs] {and /docs}",
|
||||
SKILLS,
|
||||
),
|
||||
).toEqual({
|
||||
skills: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "docs", path: SKILLS[2]!.path },
|
||||
],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "docs", path: SKILLS[2]!.path },
|
||||
{
|
||||
type: "text",
|
||||
text: "Try $marker-skill? $second-skill: [use $docs] {and $docs}",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("never corrupts file paths, extensions, suffixes, or unknown slash tokens", () => {
|
||||
const prompt =
|
||||
"Check /docs/api.md, /docs/api.md., /docs.md, /docs-extra, /docs_v2, path/docs, and /unknown.";
|
||||
const result = resolveCodexSkillMentions(prompt, SKILLS);
|
||||
expect(result).toEqual({ skills: [], prompt });
|
||||
expect(result.prompt).toBe(prompt);
|
||||
});
|
||||
|
||||
test("scans only user text blocks and leaves images, chat_history, and attachments untouched", () => {
|
||||
const chatHistory: AgentPromptContentBlock = {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "History mentioned /docs",
|
||||
};
|
||||
const textAttachment: AgentPromptContentBlock = {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Pasted text",
|
||||
text: "Attachment mentioned /second-skill",
|
||||
};
|
||||
const image: AgentPromptContentBlock = {
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "AAAA",
|
||||
};
|
||||
const blocks: AgentPromptContentBlock[] = [
|
||||
chatHistory,
|
||||
{ type: "text", text: "Please run /marker-skill on /docs/api.md." },
|
||||
image,
|
||||
textAttachment,
|
||||
];
|
||||
|
||||
const result = resolveCodexSkillMentions(blocks, SKILLS);
|
||||
expect(result).toEqual({
|
||||
skills: [{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path }],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
chatHistory,
|
||||
{ type: "text", text: "Please run $marker-skill on /docs/api.md." },
|
||||
image,
|
||||
textAttachment,
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { AgentPromptContentBlock, AgentPromptInput } from "../../agent-sdk-types.js";
|
||||
|
||||
export interface CodexSkillDescriptor {
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface CodexSkillPromptBlock {
|
||||
type: "skill";
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
|
||||
export type CodexPromptInput = string | CodexPromptContentBlock[];
|
||||
|
||||
export interface ResolvedCodexSkillMentions {
|
||||
skills: CodexSkillPromptBlock[];
|
||||
prompt: CodexPromptInput;
|
||||
}
|
||||
|
||||
// Match a whitespace- or start-delimited `/token` across the full non-whitespace token so a
|
||||
// trailing path segment like `/docs/api.md` or extension like `/docs.md` never matches `/docs`.
|
||||
const SLASH_TOKEN_PATTERN = /(^|\s)\/(\S+)/g;
|
||||
const TRAILING_BOUNDARY_PUNCTUATION_PATTERN = /[.,!?;:)\]}]+$/;
|
||||
const DISALLOWED_CANDIDATE_CHARS_PATTERN = /[/"']/;
|
||||
|
||||
function isUserTextBlock(block: AgentPromptContentBlock): block is { type: "text"; text: string } {
|
||||
return block.type === "text" && !("contextKind" in block) && !("mimeType" in block);
|
||||
}
|
||||
|
||||
function parseSlashMentionToken(rawToken: string): { name: string; trailing: string } | null {
|
||||
const trailingMatch = TRAILING_BOUNDARY_PUNCTUATION_PATTERN.exec(rawToken);
|
||||
const name = trailingMatch ? rawToken.slice(0, trailingMatch.index) : rawToken;
|
||||
const trailing = trailingMatch ? trailingMatch[0] : "";
|
||||
if (name.length === 0 || DISALLOWED_CANDIDATE_CHARS_PATTERN.test(name)) {
|
||||
return null;
|
||||
}
|
||||
return { name, trailing };
|
||||
}
|
||||
|
||||
function textHasSlashMentionCandidate(text: string): boolean {
|
||||
if (!text.includes("/")) {
|
||||
return false;
|
||||
}
|
||||
for (const match of text.matchAll(SLASH_TOKEN_PATTERN)) {
|
||||
const rawToken = match[2];
|
||||
if (rawToken && parseSlashMentionToken(rawToken)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function hasCodexSkillMentionCandidate(prompt: AgentPromptInput): boolean {
|
||||
if (typeof prompt === "string") {
|
||||
return textHasSlashMentionCandidate(prompt);
|
||||
}
|
||||
return prompt.some((block) => isUserTextBlock(block) && textHasSlashMentionCandidate(block.text));
|
||||
}
|
||||
|
||||
export function resolveCodexSkillMentions(
|
||||
prompt: AgentPromptInput,
|
||||
skills: ReadonlyArray<CodexSkillDescriptor>,
|
||||
): ResolvedCodexSkillMentions {
|
||||
if (skills.length === 0 || !hasCodexSkillMentionCandidate(prompt)) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
|
||||
const skillsByName = new Map<string, CodexSkillDescriptor>();
|
||||
for (const skill of skills) {
|
||||
if (!skillsByName.has(skill.name)) {
|
||||
skillsByName.set(skill.name, skill);
|
||||
}
|
||||
}
|
||||
|
||||
const mentioned = new Map<string, CodexSkillPromptBlock>();
|
||||
const rewriteUserText = (text: string): string => {
|
||||
if (!text.includes("/")) {
|
||||
return text;
|
||||
}
|
||||
return text.replace(SLASH_TOKEN_PATTERN, (fullMatch, prefix: string, rawToken: string) => {
|
||||
const parsed = parseSlashMentionToken(rawToken);
|
||||
if (!parsed) {
|
||||
return fullMatch;
|
||||
}
|
||||
const skill = skillsByName.get(parsed.name);
|
||||
if (!skill) {
|
||||
return fullMatch;
|
||||
}
|
||||
if (!mentioned.has(skill.name)) {
|
||||
mentioned.set(skill.name, {
|
||||
type: "skill",
|
||||
name: skill.name,
|
||||
path: skill.path,
|
||||
});
|
||||
}
|
||||
return `${prefix}$${skill.name}${parsed.trailing}`;
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof prompt === "string") {
|
||||
const rewrittenText = rewriteUserText(prompt);
|
||||
if (mentioned.size === 0) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
const skillBlocks = Array.from(mentioned.values());
|
||||
return {
|
||||
skills: skillBlocks,
|
||||
prompt: [...skillBlocks, { type: "text", text: rewrittenText }],
|
||||
};
|
||||
}
|
||||
|
||||
const rewrittenBlocks = prompt.map((block): AgentPromptContentBlock => {
|
||||
if (!isUserTextBlock(block)) {
|
||||
return block;
|
||||
}
|
||||
const rewrittenText = rewriteUserText(block.text);
|
||||
return rewrittenText === block.text ? block : { ...block, text: rewrittenText };
|
||||
});
|
||||
|
||||
if (mentioned.size === 0) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
|
||||
const skillBlocks = Array.from(mentioned.values());
|
||||
return {
|
||||
skills: skillBlocks,
|
||||
prompt: [...skillBlocks, ...rewrittenBlocks],
|
||||
};
|
||||
}
|
||||
@@ -3258,3 +3258,345 @@ describe("OpenCode v2 rewind", () => {
|
||||
expect(stages).toEqual([expect.objectContaining({ messageID: "msg_1", files: true })]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode v2 slash commands and skill mentions", () => {
|
||||
function createSkillHarness() {
|
||||
const harness = new V2Harness();
|
||||
const location = { directory: "/tmp/project" };
|
||||
let commandListCalls = 0;
|
||||
let skillListCalls = 0;
|
||||
harness.api.command.list = async () => {
|
||||
commandListCalls += 1;
|
||||
return {
|
||||
location,
|
||||
data: [{ name: "review", description: "Review changes", source: "command" }],
|
||||
} as unknown as Awaited<ReturnType<V2Api["command"]["list"]>>;
|
||||
};
|
||||
harness.api.skill.list = async () => {
|
||||
skillListCalls += 1;
|
||||
return {
|
||||
location,
|
||||
data: [
|
||||
{ id: "grill-with-docs", description: "Grill with docs" },
|
||||
{ id: "review-docs", description: "Review docs" },
|
||||
{ id: "docs", description: "Docs skill" },
|
||||
{ id: "mcp:check", description: "MCP skill with colon" },
|
||||
],
|
||||
} as unknown as Awaited<ReturnType<V2Api["skill"]["list"]>>;
|
||||
};
|
||||
const sentPrompts: Array<Parameters<V2Api["session"]["prompt"]>[0]> = [];
|
||||
const sentCommands: Array<Parameters<V2Api["session"]["command"]>[0]> = [];
|
||||
const sentCompacts: Array<Parameters<V2Api["session"]["compact"]>[0]> = [];
|
||||
const origPrompt = harness.prompt;
|
||||
harness.prompt = async (input, options) => {
|
||||
sentPrompts.push(input);
|
||||
await origPrompt(input, options);
|
||||
};
|
||||
harness.api.session.command = async (input) => {
|
||||
sentCommands.push(input);
|
||||
if (harness.autoComplete) harness.finishExecution();
|
||||
};
|
||||
harness.api.session.compact = async (input) => {
|
||||
sentCompacts.push(input);
|
||||
if (harness.autoComplete) harness.finishExecution();
|
||||
};
|
||||
return {
|
||||
harness,
|
||||
sentPrompts,
|
||||
sentCommands,
|
||||
sentCompacts,
|
||||
get commandListCalls() {
|
||||
return commandListCalls;
|
||||
},
|
||||
get skillListCalls() {
|
||||
return skillListCalls;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("resolves inline skill mention on idle turn with @mention and exact offset", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("Answer briefly: what is 2+2? /grill-with-docs");
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.text).toBe("Answer briefly: what is 2+2? @grill-with-docs");
|
||||
expect(sent.skills).toEqual([
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 29, end: 45, text: "@grill-with-docs" },
|
||||
},
|
||||
]);
|
||||
expect(sent.text.slice(29, 45)).toBe("@grill-with-docs");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves leading skill with prose, standalone skill, and trailing-space-only skill", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("/grill-with-docs check the plan");
|
||||
expect(h.sentPrompts[0]).toMatchObject({
|
||||
text: "@grill-with-docs check the plan",
|
||||
skills: [
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 0, end: 16, text: "@grill-with-docs" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await session.run("/grill-with-docs ");
|
||||
expect(h.sentPrompts[1]).toMatchObject({
|
||||
text: "Use the grill-with-docs skill.",
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves multiple skills, punctuation boundaries, colon IDs, and deduplicates by id", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run(
|
||||
"Use /grill-with-docs, /mcp:check. Then /review-docs! Repeat /grill-with-docs.",
|
||||
);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.text).toBe(
|
||||
"Use @grill-with-docs, @mcp:check. Then @review-docs! Repeat @grill-with-docs.",
|
||||
);
|
||||
expect(sent.skills).toEqual([
|
||||
{ id: "grill-with-docs", mention: { start: 4, end: 20, text: "@grill-with-docs" } },
|
||||
{ id: "mcp:check", mention: { start: 22, end: 32, text: "@mcp:check" } },
|
||||
{ id: "review-docs", mention: { start: 39, end: 51, text: "@review-docs" } },
|
||||
]);
|
||||
for (const skill of sent.skills ?? []) {
|
||||
expect(sent.text.slice(skill.mention!.start, skill.mention!.end)).toBe(skill.mention!.text);
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves skills alongside attachments without scanning chat_history or text attachments", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous chat mentioned /review-docs",
|
||||
},
|
||||
{ type: "text", text: "/grill-with-docs inspect this image" },
|
||||
{ type: "image", mimeType: "image/png", data: "AAAA" },
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
text: "Attached note with /docs",
|
||||
},
|
||||
]);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.files).toEqual([{ uri: "data:image/png;base64,AAAA" }]);
|
||||
expect(sent.text).toContain("Previous chat mentioned /review-docs");
|
||||
expect(sent.text).toContain("Attached note with /docs");
|
||||
expect(sent.text).toContain("@grill-with-docs inspect this image");
|
||||
expect(sent.skills).toHaveLength(1);
|
||||
const [skill] = sent.skills!;
|
||||
expect(skill?.id).toBe("grill-with-docs");
|
||||
expect(sent.text.slice(skill!.mention!.start, skill!.mention!.end)).toBe("@grill-with-docs");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves file paths untouched and skips command lookup when no slash mention candidate exists", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("Compare /docs/api.md and src/docs/index.ts with /docs.ts");
|
||||
expect(h.sentPrompts[0]?.text).toBe(
|
||||
"Compare /docs/api.md and src/docs/index.ts with /docs.ts",
|
||||
);
|
||||
expect(h.sentPrompts[0]?.skills).toBeUndefined();
|
||||
// /docs.ts is a single-segment candidate so lookup ran once; /docs/api.md alone skips lookup.
|
||||
const callsBeforePathOnly = h.skillListCalls;
|
||||
await session.run("Read /docs/api.md and packages/app/index.ts");
|
||||
expect(h.skillListCalls).toBe(callsBeforePathOnly);
|
||||
expect(h.sentPrompts[1]?.text).toBe("Read /docs/api.md and packages/app/index.ts");
|
||||
expect(h.sentPrompts[1]?.skills).toBeUndefined();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("attaches skills selected inside leading command arguments and ignores code blocks", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("/review src/index.ts /docs");
|
||||
expect(h.sentCommands).toEqual([
|
||||
{
|
||||
sessionID: "session",
|
||||
name: "review",
|
||||
text: "src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 13, end: 18, text: "@docs" } }],
|
||||
},
|
||||
]);
|
||||
|
||||
const fenced = "Explain:\n```sh\nls /docs\n```";
|
||||
await session.run(fenced);
|
||||
expect(h.sentPrompts[0]?.text).toBe(fenced);
|
||||
expect(h.sentPrompts[0]?.skills).toBeUndefined();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers leading and inline skills natively into a running turn", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("/grill-with-docs the plan", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(h.sentPrompts[1]).toMatchObject({
|
||||
text: "@grill-with-docs the plan",
|
||||
skills: [
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 0, end: 16, text: "@grill-with-docs" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
});
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("Also apply /review-docs.", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(h.sentPrompts[2]).toMatchObject({
|
||||
text: "Also apply @review-docs.",
|
||||
skills: [
|
||||
{
|
||||
id: "review-docs",
|
||||
mention: { start: 11, end: 23, text: "@review-docs" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable on steer for /compact, /summarize, and provider commands", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("/compact", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(
|
||||
session.steerActiveTurn!(" /summarize ", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(
|
||||
session.steerActiveTurn!("/review now", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
expect(h.sentCommands).toHaveLength(0);
|
||||
expect(h.sentCompacts).toHaveLength(0);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when the active turn ends during async skill resolution on steer", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
let releaseSkills!: () => void;
|
||||
const origSkillList = h.harness.api.skill.list;
|
||||
h.harness.api.skill.list = async (input) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseSkills = resolve;
|
||||
});
|
||||
return origSkillList(input);
|
||||
};
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
let completed = false;
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_completed") completed = true;
|
||||
});
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
const steering = session.steerActiveTurn!("Use /grill-with-docs", {
|
||||
expectedTurnId: turnId,
|
||||
});
|
||||
await expect.poll(() => Boolean(releaseSkills)).toBe(true);
|
||||
h.harness.finishExecution();
|
||||
await expect.poll(() => completed).toBe(true);
|
||||
releaseSkills();
|
||||
|
||||
await expect(steering).resolves.toEqual({ status: "unavailable" });
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { AgentSlashCommand } from "../../../agent-sdk-types.js";
|
||||
import { prepareOpenCodePrompt } from "./prompt-input.js";
|
||||
|
||||
const COMMANDS: readonly AgentSlashCommand[] = [
|
||||
{ name: "compact", description: "Compact", argumentHint: "", kind: "command" },
|
||||
{ name: "summarize", description: "Summarize", argumentHint: "", kind: "command" },
|
||||
{ name: "review", description: "Review", argumentHint: "", kind: "command" },
|
||||
{ name: "nested/docs", description: "Nested command", argumentHint: "", kind: "command" },
|
||||
{ name: "docs", description: "Docs skill", argumentHint: "", kind: "skill" },
|
||||
{ name: "grill-with-docs", description: "Grill", argumentHint: "", kind: "skill" },
|
||||
{ name: "mcp:tool", description: "MCP skill", argumentHint: "", kind: "skill" },
|
||||
];
|
||||
|
||||
describe("prepareOpenCodePrompt", () => {
|
||||
test("recognizes compact and summarize without loading commands", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
expect(await prepareOpenCodePrompt("/compact", load)).toEqual({ kind: "compact" });
|
||||
expect(await prepareOpenCodePrompt(" /summarize now ", load)).toEqual({ kind: "compact" });
|
||||
expect(loads).toBe(0);
|
||||
});
|
||||
|
||||
test("dispatches leading non-skill slash commands with args and attachments", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
[
|
||||
{ type: "text", text: " /review src/index.ts" },
|
||||
{ type: "image", mimeType: "image/png", data: "BBBB" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "src/index.ts",
|
||||
files: [{ uri: "data:image/png;base64,BBBB" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("skips loading commands when user text has no slash mention candidate", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
expect(await prepareOpenCodePrompt("Inspect /docs/api.md and a/docs/b", load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Inspect /docs/api.md and a/docs/b",
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
});
|
||||
|
||||
test("rewrites standalone single and multiple skills to fallback prose", async () => {
|
||||
expect(await prepareOpenCodePrompt(" /grill-with-docs ", async () => COMMANDS)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use the grill-with-docs skill.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
|
||||
expect(
|
||||
await prepareOpenCodePrompt(
|
||||
"/grill-with-docs /mcp:tool /grill-with-docs",
|
||||
async () => COMMANDS,
|
||||
),
|
||||
).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use the grill-with-docs, mcp:tool skills.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }, { id: "mcp:tool" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves punctuation boundaries and rejects path or word continuations", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
"Use /docs, /mcp:tool. Keep /docs/api.md, /docs.ts, foo/docs, and /unknown.",
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use @docs, @mcp:tool. Keep /docs/api.md, /docs.ts, foo/docs, and /unknown.",
|
||||
files: [],
|
||||
skills: [
|
||||
{ id: "docs", mention: { start: 4, end: 9, text: "@docs" } },
|
||||
{ id: "mcp:tool", mention: { start: 11, end: 20, text: "@mcp:tool" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps fallback text alongside preceding chat_history attachment", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "History with /docs",
|
||||
},
|
||||
{ type: "text", text: "/grill-with-docs " },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "prompt",
|
||||
text: "History with /docs\nUse the grill-with-docs skill.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("resolves skill mentions inside leading command arguments", async () => {
|
||||
const result = await prepareOpenCodePrompt("/review src/index.ts /docs", async () => COMMANDS);
|
||||
expect(result).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 13, end: 18, text: "@docs" } }],
|
||||
});
|
||||
|
||||
const skillOnlyArg = await prepareOpenCodePrompt("/review /docs", async () => COMMANDS);
|
||||
expect(skillOnlyArg).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "@docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 0, end: 5, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves literal paths inside fenced code blocks and inline code spans", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
const fencedOnly = "Explain this command:\n```sh\nls /docs\n```";
|
||||
expect(await prepareOpenCodePrompt(fencedOnly, load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: fencedOnly,
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
|
||||
const inlineCodeOnly = "Run `ls /docs` or `ls`/docs";
|
||||
expect(await prepareOpenCodePrompt(inlineCodeOnly, load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: inlineCodeOnly,
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
|
||||
const mixed = "Explain `ls /docs` and:\n```sh\nls /docs\n```\nThen use /docs.";
|
||||
const mixedResult = await prepareOpenCodePrompt(mixed, load);
|
||||
expect(mixedResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Explain `ls /docs` and:\n```sh\nls /docs\n```\nThen use @docs.",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 52, end: 57, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
|
||||
test("dispatches slash-separated subdirectory commands while keeping unmatched leading paths literal", async () => {
|
||||
expect(await prepareOpenCodePrompt("/nested/docs details /docs", async () => COMMANDS)).toEqual(
|
||||
{
|
||||
kind: "command",
|
||||
name: "nested/docs",
|
||||
text: "details @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 8, end: 13, text: "@docs" } }],
|
||||
},
|
||||
);
|
||||
|
||||
expect(await prepareOpenCodePrompt("/docs/api.md", async () => COMMANDS)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "/docs/api.md",
|
||||
files: [],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves the regular prompt path when chat history precedes /compact or a provider command", async () => {
|
||||
const compactResult = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous conversation transcript",
|
||||
},
|
||||
{ type: "text", text: "/compact" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(compactResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Previous conversation transcript\n/compact",
|
||||
files: [],
|
||||
});
|
||||
|
||||
const commandResult = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Earlier conversation about README.md",
|
||||
},
|
||||
{ type: "text", text: "/review src/index.ts /docs" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(commandResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Earlier conversation about README.md\n/review src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 58, end: 63, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
import type { AgentPromptInput, AgentSlashCommand } from "../../../agent-sdk-types.js";
|
||||
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
|
||||
|
||||
export interface OpenCodeSkillMention {
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface OpenCodeSkillAttachment {
|
||||
id: string;
|
||||
mention?: OpenCodeSkillMention;
|
||||
}
|
||||
|
||||
export type PreparedOpenCodePrompt =
|
||||
| { kind: "compact" }
|
||||
| {
|
||||
kind: "command";
|
||||
name: string;
|
||||
text: string;
|
||||
files: Array<{ uri: string }>;
|
||||
skills?: OpenCodeSkillAttachment[];
|
||||
}
|
||||
| {
|
||||
kind: "prompt";
|
||||
text: string;
|
||||
files: Array<{ uri: string }>;
|
||||
skills?: OpenCodeSkillAttachment[];
|
||||
};
|
||||
|
||||
interface PromptSegment {
|
||||
text: string;
|
||||
isUserText: boolean;
|
||||
}
|
||||
|
||||
interface TextPiece {
|
||||
text: string;
|
||||
isCode: boolean;
|
||||
precededByBoundary: boolean;
|
||||
}
|
||||
|
||||
interface MatchedSegment {
|
||||
text: string;
|
||||
hasOtherProse: boolean;
|
||||
mentions: Array<{ id: string; start: number; end: number; text: string }>;
|
||||
}
|
||||
|
||||
type RewrittenSegment = PromptSegment & { mentions?: MatchedSegment["mentions"] };
|
||||
|
||||
const LEADING_SLASH_COMMAND = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
|
||||
const SLASH_TOKEN = /(^|\s)\/([^\s]+)/g;
|
||||
const TRAILING_PUNCTUATION = /[.,!?;:)\]}]+$/;
|
||||
const OPENING_FENCE = /^ {0,3}(`{3,}|~{3,})/;
|
||||
|
||||
function splitPrompt(prompt: AgentPromptInput): {
|
||||
segments: PromptSegment[];
|
||||
files: Array<{ uri: string }>;
|
||||
} {
|
||||
if (typeof prompt === "string") {
|
||||
return { segments: [{ text: prompt, isUserText: true }], files: [] };
|
||||
}
|
||||
const segments: PromptSegment[] = [];
|
||||
const files: Array<{ uri: string }> = [];
|
||||
for (const part of prompt) {
|
||||
if (part.type === "image") {
|
||||
files.push({ uri: `data:${part.mimeType};base64,${part.data}` });
|
||||
} else if (part.type === "text") {
|
||||
segments.push({
|
||||
text: part.text,
|
||||
isUserText: !("mimeType" in part) && !("contextKind" in part),
|
||||
});
|
||||
} else {
|
||||
segments.push({ text: renderPromptAttachmentAsText(part), isUserText: false });
|
||||
}
|
||||
}
|
||||
return { segments, files };
|
||||
}
|
||||
|
||||
function joinSegments(segments: readonly PromptSegment[]): string {
|
||||
return segments.map((segment) => segment.text).join("\n");
|
||||
}
|
||||
|
||||
function findFenceClose(text: string, from: number, char: string, minLength: number): number {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const newline = text.indexOf("\n", cursor);
|
||||
const lineEnd = newline === -1 ? text.length : newline;
|
||||
const line = text.slice(cursor, lineEnd).replace(/\r$/, "");
|
||||
const closeMatch = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
|
||||
if (closeMatch && closeMatch[1]![0] === char && closeMatch[1]!.length >= minLength) {
|
||||
return newline === -1 ? text.length : newline + 1;
|
||||
}
|
||||
if (newline === -1) return text.length;
|
||||
cursor = newline + 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
function findInlineCodeEnd(text: string, from: number, tickCount: number): number {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const tick = text.indexOf("`", cursor);
|
||||
if (tick === -1) return -1;
|
||||
let runEnd = tick + 1;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd += 1;
|
||||
if (runEnd - tick === tickCount) return runEnd;
|
||||
cursor = runEnd;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function splitProseAndCode(text: string): TextPiece[] {
|
||||
const pieces: TextPiece[] = [];
|
||||
let proseStart = 0;
|
||||
let i = 0;
|
||||
|
||||
const pushProse = (end: number) => {
|
||||
if (end <= proseStart) return;
|
||||
pieces.push({
|
||||
text: text.slice(proseStart, end),
|
||||
isCode: false,
|
||||
precededByBoundary: proseStart === 0 || /\s/.test(text[proseStart - 1]!),
|
||||
});
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
const atLineStart = i === 0 || text[i - 1] === "\n";
|
||||
if (atLineStart) {
|
||||
const newline = text.indexOf("\n", i);
|
||||
const lineEnd = newline === -1 ? text.length : newline;
|
||||
const opening = text.slice(i, lineEnd).match(OPENING_FENCE);
|
||||
const fence = opening?.[1];
|
||||
const infoString = opening ? text.slice(i + opening[0].length, lineEnd) : "";
|
||||
if (fence && (fence[0] !== "`" || !infoString.includes("`"))) {
|
||||
pushProse(i);
|
||||
const bodyStart = newline === -1 ? text.length : newline + 1;
|
||||
const fenceEnd = findFenceClose(text, bodyStart, fence[0]!, fence.length);
|
||||
pieces.push({ text: text.slice(i, fenceEnd), isCode: true, precededByBoundary: true });
|
||||
i = fenceEnd;
|
||||
proseStart = i;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (text[i] === "`") {
|
||||
let runEnd = i + 1;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd += 1;
|
||||
const closeEnd = findInlineCodeEnd(text, runEnd, runEnd - i);
|
||||
if (closeEnd !== -1) {
|
||||
pushProse(i);
|
||||
pieces.push({ text: text.slice(i, closeEnd), isCode: true, precededByBoundary: false });
|
||||
i = closeEnd;
|
||||
proseStart = i;
|
||||
continue;
|
||||
}
|
||||
i = runEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
pushProse(text.length);
|
||||
return pieces;
|
||||
}
|
||||
|
||||
function hasSlashCandidate(segments: readonly PromptSegment[]): boolean {
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText || !segment.text.includes("/")) continue;
|
||||
for (const piece of splitProseAndCode(segment.text)) {
|
||||
if (piece.isCode || !piece.text.includes("/")) continue;
|
||||
SLASH_TOKEN.lastIndex = 0;
|
||||
for (
|
||||
let match = SLASH_TOKEN.exec(piece.text);
|
||||
match !== null;
|
||||
match = SLASH_TOKEN.exec(piece.text)
|
||||
) {
|
||||
if (match.index === 0 && match[1] === "" && !piece.precededByBoundary) continue;
|
||||
const rawToken = match[2] ?? "";
|
||||
// Multi-segment tokens such as `/docs/api.md` are file paths, never slash names.
|
||||
if (rawToken.includes("/")) continue;
|
||||
if (rawToken.replace(TRAILING_PUNCTUATION, "").length > 0) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function matchSkillToken(
|
||||
rawToken: string,
|
||||
skillIds: ReadonlySet<string>,
|
||||
): { id: string; trailing: string } | null {
|
||||
if (rawToken.includes("/")) return null;
|
||||
if (skillIds.has(rawToken)) return { id: rawToken, trailing: "" };
|
||||
const stripped = rawToken.replace(TRAILING_PUNCTUATION, "");
|
||||
if (stripped.length > 0 && stripped.length < rawToken.length && skillIds.has(stripped)) {
|
||||
return { id: stripped, trailing: rawToken.slice(stripped.length) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function rewriteUserSegment(text: string, skillIds: ReadonlySet<string>): MatchedSegment {
|
||||
let rewritten = "";
|
||||
let outsideMatches = "";
|
||||
let hasCode = false;
|
||||
const mentions: MatchedSegment["mentions"] = [];
|
||||
|
||||
for (const piece of splitProseAndCode(text)) {
|
||||
if (piece.isCode) {
|
||||
rewritten += piece.text;
|
||||
hasCode = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
SLASH_TOKEN.lastIndex = 0;
|
||||
for (
|
||||
let match = SLASH_TOKEN.exec(piece.text);
|
||||
match !== null;
|
||||
match = SLASH_TOKEN.exec(piece.text)
|
||||
) {
|
||||
const prefix = match[1] ?? "";
|
||||
if (match.index === 0 && prefix === "" && !piece.precededByBoundary) continue;
|
||||
const rawToken = match[2] ?? "";
|
||||
const resolved = matchSkillToken(rawToken, skillIds);
|
||||
if (!resolved) continue;
|
||||
|
||||
const tokenStart = match.index + prefix.length;
|
||||
const tokenEnd = match.index + match[0].length;
|
||||
const before = piece.text.slice(cursor, tokenStart);
|
||||
rewritten += before;
|
||||
outsideMatches += before;
|
||||
|
||||
const mentionText = `@${resolved.id}`;
|
||||
const mentionStart = rewritten.length;
|
||||
rewritten += mentionText;
|
||||
const mentionEnd = rewritten.length;
|
||||
rewritten += resolved.trailing;
|
||||
outsideMatches += resolved.trailing;
|
||||
|
||||
mentions.push({ id: resolved.id, start: mentionStart, end: mentionEnd, text: mentionText });
|
||||
cursor = tokenEnd;
|
||||
}
|
||||
|
||||
const tail = piece.text.slice(cursor);
|
||||
rewritten += tail;
|
||||
outsideMatches += tail;
|
||||
}
|
||||
|
||||
return {
|
||||
text: rewritten,
|
||||
hasOtherProse: hasCode || outsideMatches.trim().length > 0,
|
||||
mentions,
|
||||
};
|
||||
}
|
||||
|
||||
function fallbackSkillPromptText(ids: readonly string[]): string {
|
||||
if (ids.length === 1) return `Use the ${ids[0]} skill.`;
|
||||
return `Use the ${ids.join(", ")} skills.`;
|
||||
}
|
||||
|
||||
function buildFallbackSkillContent(rewrittenSegments: readonly RewrittenSegment[]): {
|
||||
text: string;
|
||||
skills: OpenCodeSkillAttachment[];
|
||||
} {
|
||||
const uniqueIds: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const segment of rewrittenSegments) {
|
||||
for (const mention of segment.mentions ?? []) {
|
||||
if (seen.has(mention.id)) continue;
|
||||
seen.add(mention.id);
|
||||
uniqueIds.push(mention.id);
|
||||
}
|
||||
}
|
||||
let fallbackInserted = false;
|
||||
const outputParts: string[] = [];
|
||||
for (const segment of rewrittenSegments) {
|
||||
if (!segment.isUserText) {
|
||||
outputParts.push(segment.text);
|
||||
} else if (!fallbackInserted) {
|
||||
outputParts.push(fallbackSkillPromptText(uniqueIds));
|
||||
fallbackInserted = true;
|
||||
}
|
||||
}
|
||||
return {
|
||||
text: outputParts.join("\n"),
|
||||
skills: uniqueIds.map((id) => ({ id })),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMentionedSkillContent(rewrittenSegments: readonly RewrittenSegment[]): {
|
||||
text: string;
|
||||
skills: OpenCodeSkillAttachment[];
|
||||
} {
|
||||
const skills: OpenCodeSkillAttachment[] = [];
|
||||
const seen = new Set<string>();
|
||||
const outputParts: string[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const segment of rewrittenSegments) {
|
||||
if (outputParts.length > 0) offset += 1;
|
||||
for (const mention of segment.mentions ?? []) {
|
||||
if (seen.has(mention.id)) continue;
|
||||
seen.add(mention.id);
|
||||
skills.push({
|
||||
id: mention.id,
|
||||
mention: {
|
||||
start: offset + mention.start,
|
||||
end: offset + mention.end,
|
||||
text: mention.text,
|
||||
},
|
||||
});
|
||||
}
|
||||
outputParts.push(segment.text);
|
||||
offset += segment.text.length;
|
||||
}
|
||||
|
||||
return {
|
||||
text: outputParts.join("\n"),
|
||||
skills,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveSkillContent(
|
||||
segments: readonly PromptSegment[],
|
||||
skillIds: ReadonlySet<string>,
|
||||
options: { allowFallback: boolean },
|
||||
): { text: string; skills?: OpenCodeSkillAttachment[] } {
|
||||
if (skillIds.size === 0) {
|
||||
return { text: joinSegments(segments) };
|
||||
}
|
||||
|
||||
const rewrittenSegments: RewrittenSegment[] = [];
|
||||
let matchedAnySkill = false;
|
||||
let hasUserProse = false;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText) {
|
||||
rewrittenSegments.push(segment);
|
||||
continue;
|
||||
}
|
||||
const result = rewriteUserSegment(segment.text, skillIds);
|
||||
if (result.mentions.length > 0) matchedAnySkill = true;
|
||||
if (result.hasOtherProse) hasUserProse = true;
|
||||
rewrittenSegments.push({ text: result.text, isUserText: true, mentions: result.mentions });
|
||||
}
|
||||
|
||||
if (!matchedAnySkill) {
|
||||
return { text: joinSegments(segments) };
|
||||
}
|
||||
|
||||
if (!hasUserProse && options.allowFallback) {
|
||||
return buildFallbackSkillContent(rewrittenSegments);
|
||||
}
|
||||
return buildMentionedSkillContent(rewrittenSegments);
|
||||
}
|
||||
|
||||
function stripLeadingCommandFromSegments(
|
||||
segments: readonly PromptSegment[],
|
||||
commandName: string,
|
||||
): PromptSegment[] {
|
||||
const prefixPattern = new RegExp(
|
||||
`^\\s*/${commandName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s+)?`,
|
||||
);
|
||||
const result: PromptSegment[] = [];
|
||||
let stripped = false;
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText || stripped) {
|
||||
if (segment.text.length > 0) result.push(segment);
|
||||
continue;
|
||||
}
|
||||
if (segment.text.trim().length === 0) continue;
|
||||
const remainder = segment.text.replace(prefixPattern, "");
|
||||
stripped = true;
|
||||
if (remainder.length > 0) result.push({ text: remainder, isUserText: true });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function prepareOpenCodePrompt(
|
||||
prompt: AgentPromptInput,
|
||||
loadCommands: () => Promise<readonly AgentSlashCommand[]>,
|
||||
): Promise<PreparedOpenCodePrompt> {
|
||||
const { segments, files } = splitPrompt(prompt);
|
||||
const userText = segments
|
||||
.filter((segment) => segment.isUserText)
|
||||
.map((segment) => segment.text)
|
||||
.join("\n")
|
||||
.trim();
|
||||
|
||||
// Only treat a leading /command or /compact as a slash command when the message starts with
|
||||
// user text. Preceding attachments (such as chat_history) keep the regular prompt path while
|
||||
// still scanning user text blocks for skill mentions.
|
||||
const leading = segments[0]?.isUserText ? userText.match(LEADING_SLASH_COMMAND) : null;
|
||||
if (leading?.[1] === "compact" || leading?.[1] === "summarize") {
|
||||
return { kind: "compact" };
|
||||
}
|
||||
|
||||
if (!leading && !hasSlashCandidate(segments)) {
|
||||
return { kind: "prompt", text: joinSegments(segments), files };
|
||||
}
|
||||
|
||||
const available = await loadCommands();
|
||||
const skillIds = new Set(
|
||||
available.filter((item) => item.kind === "skill").map((item) => item.name),
|
||||
);
|
||||
|
||||
if (leading) {
|
||||
const selected = available.find((item) => item.name === leading[1]);
|
||||
if (selected && selected.kind !== "skill") {
|
||||
const commandSegments = stripLeadingCommandFromSegments(segments, selected.name);
|
||||
const content = resolveSkillContent(commandSegments, skillIds, { allowFallback: false });
|
||||
return {
|
||||
kind: "command",
|
||||
name: selected.name,
|
||||
text: content.text,
|
||||
files,
|
||||
...(content.skills ? { skills: content.skills } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const content = resolveSkillContent(segments, skillIds, { allowFallback: true });
|
||||
return {
|
||||
kind: "prompt",
|
||||
text: content.text,
|
||||
files,
|
||||
...(content.skills ? { skills: content.skills } : {}),
|
||||
};
|
||||
}
|
||||
@@ -14,12 +14,11 @@ import type {
|
||||
|
||||
import { toDiagnosticErrorMessage } from "../../diagnostic-utils.js";
|
||||
|
||||
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
|
||||
|
||||
import { usageFromV2 } from "./mapping.js";
|
||||
import { latestTurnMetrics } from "./metrics.js";
|
||||
|
||||
import { commands } from "./commands.js";
|
||||
import { prepareOpenCodePrompt } from "./prompt-input.js";
|
||||
|
||||
import type { V2Api } from "./api.js";
|
||||
|
||||
@@ -235,7 +234,6 @@ export class SessionTurns {
|
||||
await this.stopping;
|
||||
if (this.options.signal.aborted) throw new Error("OpenCode session is closed");
|
||||
if (this.turn) throw new Error("OpenCode session already has an active turn");
|
||||
const input = this.promptInput(prompt);
|
||||
let accept!: () => void;
|
||||
const submitted = new Promise<void>((resolve) => {
|
||||
accept = resolve;
|
||||
@@ -243,12 +241,12 @@ export class SessionTurns {
|
||||
const output =
|
||||
options?.outputSchema === undefined ? undefined : structuredOutput(options.outputSchema);
|
||||
const turn = this.createTurn(submitted, false, output);
|
||||
void this.submit(turn, input, accept, options);
|
||||
void this.submit(turn, prompt, accept, options);
|
||||
return { turnId: turn.id };
|
||||
}
|
||||
private async submit(
|
||||
turn: Turn,
|
||||
input: ReturnType<SessionTurns["promptInput"]>,
|
||||
prompt: AgentPromptInput,
|
||||
accept: () => void,
|
||||
options?: AgentRunOptions,
|
||||
) {
|
||||
@@ -265,7 +263,7 @@ export class SessionTurns {
|
||||
} catch {
|
||||
// Keep the cached baselineIdleTime if the pre-dispatch read fails transiently.
|
||||
}
|
||||
await this.dispatch(input, options, turn.output);
|
||||
await this.dispatch(turn, prompt, options, turn.output);
|
||||
if (this.turn !== turn) return;
|
||||
turn.accepted = true;
|
||||
this.revision += 1;
|
||||
@@ -472,65 +470,57 @@ export class SessionTurns {
|
||||
if (this.turn === turn) this.fail(new Error(toDiagnosticErrorMessage(error)));
|
||||
}
|
||||
}
|
||||
private preparePrompt(prompt: AgentPromptInput) {
|
||||
return prepareOpenCodePrompt(prompt, () => commands(this.options.client(), this.options.cwd));
|
||||
}
|
||||
private async dispatch(
|
||||
input: ReturnType<SessionTurns["promptInput"]>,
|
||||
turn: Turn,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
output?: ReturnType<typeof structuredOutput>,
|
||||
) {
|
||||
const command = input.text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);
|
||||
if (command?.[1] === "compact" || command?.[1] === "summarize") {
|
||||
const prepared = await this.preparePrompt(prompt);
|
||||
if (this.turn !== turn) return;
|
||||
if (prepared.kind === "compact") {
|
||||
await this.options.client().session.compact({ sessionID: this.options.id });
|
||||
return;
|
||||
}
|
||||
const selected = command
|
||||
? (await commands(this.options.client(), this.options.cwd)).find(
|
||||
(item) => item.name === command[1],
|
||||
)
|
||||
: undefined;
|
||||
if (selected && selected.kind !== "skill") {
|
||||
if (prepared.kind === "command") {
|
||||
await this.options.client().session.command({
|
||||
sessionID: this.options.id,
|
||||
name: selected.name,
|
||||
text: command?.[2] ?? "",
|
||||
files: input.files,
|
||||
name: prepared.name,
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.options.client().session.prompt({
|
||||
sessionID: this.options.id,
|
||||
...input,
|
||||
...(selected?.kind === "skill"
|
||||
? {
|
||||
skills: [{ id: selected.name }],
|
||||
text: command?.[2] ?? `Use the ${selected.name} skill.`,
|
||||
}
|
||||
: {}),
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
metadata: {
|
||||
...(options?.clientMessageId ? { paseoClientMessageId: options.clientMessageId } : {}),
|
||||
...(output ? { paseoOutputSchema: output.schema } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
private promptInput(prompt: AgentPromptInput) {
|
||||
if (typeof prompt === "string") return { text: prompt, files: [] };
|
||||
const text: string[] = [];
|
||||
const files: Array<{ uri: string }> = [];
|
||||
for (const part of prompt) {
|
||||
if (part.type === "text") text.push(part.text);
|
||||
else if (part.type === "image")
|
||||
files.push({ uri: `data:${part.mimeType};base64,${part.data}` });
|
||||
else text.push(renderPromptAttachmentAsText(part));
|
||||
}
|
||||
return { text: text.join("\n"), files };
|
||||
}
|
||||
async steerActiveTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
if (this.turn?.id !== options.expectedTurnId || this.stopping) return { status: "unavailable" };
|
||||
const prepared = await this.preparePrompt(prompt);
|
||||
// Commands (including compact/summarize) cannot be steered into a running turn; let
|
||||
// AgentManager replace the turn so dispatch() executes them. Skills steer natively.
|
||||
if (prepared.kind !== "prompt") return { status: "unavailable" };
|
||||
if (this.turn?.id !== options.expectedTurnId || this.stopping) return { status: "unavailable" };
|
||||
await this.options.client().session.prompt({
|
||||
sessionID: this.options.id,
|
||||
...this.promptInput(prompt),
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
delivery: "steer",
|
||||
metadata: options.clientMessageId
|
||||
? { paseoClientMessageId: options.clientMessageId }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -164,14 +164,8 @@ test("superseded CI and packaging runs cancel everywhere except main", () => {
|
||||
test("published npm packages declare and ship the repository license", () => {
|
||||
const rootManifest = JSON.parse(readFileSync(new URL("package.json", repoRoot), "utf8"));
|
||||
assert.match(rootManifest.scripts["release:publish"], /scripts\/publish-release-packages\.mjs/);
|
||||
assert.match(
|
||||
rootManifest.scripts["release:ship"],
|
||||
/^npm run release:push && npm run release:publish$/,
|
||||
);
|
||||
assert.match(
|
||||
rootManifest.scripts["release:ship:beta"],
|
||||
/^npm run release:push && npm run release:publish:beta$/,
|
||||
);
|
||||
assert.match(rootManifest.scripts["release:ship"], /^npm run release:push$/);
|
||||
assert.match(rootManifest.scripts["release:ship:beta"], /^npm run release:push$/);
|
||||
const workspaceArgs = PUBLISH_WORKSPACES.map((workspace) => `--workspace=${workspace}`);
|
||||
const packed = JSON.parse(
|
||||
execFileSync("npm", ["pack", "--dry-run", "--ignore-scripts", "--json", ...workspaceArgs], {
|
||||
@@ -1115,3 +1109,122 @@ test("Nix desktop packaging resolves the workspace-local builder", () => {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("npm release uses pinned actions and OIDC without credentials or cache", () => {
|
||||
const workflow = readFileSync(new URL(".github/workflows/npm-release.yml", repoRoot), "utf8");
|
||||
assert.match(workflow, /tags:\s*\n\s*- ["']v\*["']/);
|
||||
assert.match(workflow, /contents: read/);
|
||||
assert.match(workflow, /id-token: write/);
|
||||
assert.match(workflow, /runs-on: ubuntu-latest/);
|
||||
assert.match(workflow, /package-manager-cache: false/);
|
||||
assert.doesNotMatch(workflow, /NPM_TOKEN|NODE_AUTH_TOKEN|registry-url:|cache: ["']npm/);
|
||||
assert.match(workflow, /npm@11\.21\.0/);
|
||||
assert.match(workflow, /publish-release-packages\.mjs --tag "\$GITHUB_REF_NAME"/);
|
||||
for (const line of workflow.match(/^\s*-?\s*uses:.*$/gm))
|
||||
assert.match(line, /@[a-f0-9]{40}\s+# /);
|
||||
});
|
||||
|
||||
test("release workflows attest binaries and publish separate checksums", () => {
|
||||
for (const [file, checksum] of [
|
||||
["desktop-release.yml", "SHA256SUMS-desktop"],
|
||||
["android-apk-release.yml", "SHA256SUMS-android.txt"],
|
||||
]) {
|
||||
const workflow = readFileSync(new URL(`.github/workflows/${file}`, repoRoot), "utf8");
|
||||
assert.match(workflow, /attestations: write/);
|
||||
assert.match(workflow, /id-token: write/);
|
||||
assert.match(workflow, /actions\/attest-build-provenance@[a-f0-9]{40}\s+# /);
|
||||
assert.ok(workflow.includes(checksum));
|
||||
assert.match(workflow, /sha256/i);
|
||||
}
|
||||
});
|
||||
|
||||
test("each desktop release job attests and checksums its uploaded assets", () => {
|
||||
const workflow = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8");
|
||||
const jobs = jobBlocks(workflow);
|
||||
for (const [job, suffix] of [
|
||||
["publish-macos", "macos-"],
|
||||
["publish-linux", "linux"],
|
||||
["publish-windows", "windows"],
|
||||
]) {
|
||||
const source = jobs.get(job).join("\n");
|
||||
assert.match(source, /id-token: write/);
|
||||
assert.match(source, /attestations: write/);
|
||||
assert.match(source, /actions\/attest-build-provenance@[a-f0-9]{40}/);
|
||||
assert.ok(source.includes(`SHA256SUMS-desktop-${suffix}`));
|
||||
assert.match(source, /release-checksums\.mjs/);
|
||||
assert.match(source, /upload-release-assets\.mjs/);
|
||||
}
|
||||
for (const extension of ["dmg", "zip", "exe", "AppImage", "deb", "rpm", "tar.gz"]) {
|
||||
assert.ok(workflow.includes(`release/*.${extension}`));
|
||||
}
|
||||
});
|
||||
|
||||
test("release attestation jobs require checkout to match the workflow commit", () => {
|
||||
for (const [file, names] of [
|
||||
["desktop-release.yml", ["publish-macos", "publish-linux", "publish-windows"]],
|
||||
["android-apk-release.yml", ["publish-android-apk"]],
|
||||
]) {
|
||||
const jobs = jobBlocks(readFileSync(new URL(`.github/workflows/${file}`, repoRoot), "utf8"));
|
||||
for (const name of names) {
|
||||
const job = jobs.get(name).join("\n");
|
||||
assert.match(job, /git rev-parse HEAD/);
|
||||
assert.match(job, /GITHUB_SHA/);
|
||||
assert.ok(job.indexOf("git rev-parse HEAD") < job.indexOf("attest-build-provenance"));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("npm publication serializes releases and runs checksum tests in CI", () => {
|
||||
const workflow = readFileSync(new URL(".github/workflows/npm-release.yml", repoRoot), "utf8");
|
||||
assert.match(workflow, /concurrency:\s*\n\s*group: npm-release\s*\n\s*queue: max/);
|
||||
const ci = readFileSync(ciWorkflowPath, "utf8");
|
||||
assert.match(ci, /Validate CI contracts\n\s*run:.*scripts\/release-checksums\.test\.mjs/);
|
||||
});
|
||||
|
||||
test("desktop rollout validates the release tag before changing manifests", () => {
|
||||
const jobs = jobBlocks(
|
||||
readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"),
|
||||
);
|
||||
for (const name of ["publish-macos", "publish-linux", "publish-windows", "finalize-rollout"]) {
|
||||
const source = jobs.get(name).join("\n");
|
||||
assert.match(source, /git rev-parse.*SOURCE_TAG/);
|
||||
assert.ok(
|
||||
source.indexOf("git rev-parse") <
|
||||
(name === "finalize-rollout"
|
||||
? source.indexOf("gh release delete-asset")
|
||||
: source.indexOf("attest-build-provenance")),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("desktop attestation runs after release asset upload", () => {
|
||||
const jobs = jobBlocks(
|
||||
readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8"),
|
||||
);
|
||||
for (const name of ["publish-macos", "publish-linux", "publish-windows"]) {
|
||||
const source = jobs.get(name).join("\n");
|
||||
assert.ok(
|
||||
source.indexOf("upload-release-assets.mjs") < source.indexOf("attest-build-provenance"),
|
||||
);
|
||||
assert.match(source, /SOURCE_TAG#refs\/tags\//);
|
||||
}
|
||||
});
|
||||
|
||||
test("npm release offers a main-only canary with trusted publishing", () => {
|
||||
const workflow = readFileSync(new URL(".github/workflows/npm-release.yml", repoRoot), "utf8");
|
||||
assert.match(workflow, /workflow_dispatch:/);
|
||||
assert.match(
|
||||
workflow,
|
||||
/if: github\.event_name == 'workflow_dispatch'[\s\S]*?REF: \${{ github\.ref }}[\s\S]*?run: test "\$REF" = refs\/heads\/main/,
|
||||
);
|
||||
assert.match(workflow, /default: "@getpaseo\/highlight"/);
|
||||
assert.match(workflow, /dry_run:[\s\S]*?default: false/);
|
||||
assert.match(workflow, /--tag canary/);
|
||||
assert.match(workflow, /id-token: write/);
|
||||
assert.match(workflow, /contents: read/);
|
||||
assert.match(workflow, /package-manager-cache: false/);
|
||||
assert.doesNotMatch(workflow, /NPM_TOKEN/);
|
||||
const actions = [...workflow.matchAll(/uses:\s*([^\s#]+)/g)];
|
||||
assert.ok(actions.length > 0);
|
||||
for (const [, action] of actions) assert.match(action, /@[a-f0-9]{40}$/);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -21,25 +21,34 @@ export const PUBLISH_WORKSPACES = [
|
||||
|
||||
const PUBLISH_ATTEMPTS = 4;
|
||||
const PUBLISH_BACKOFF_MS = 15_000;
|
||||
const VISIBILITY_ATTEMPTS = 12;
|
||||
const VISIBILITY_ATTEMPTS = 121;
|
||||
const VISIBILITY_POLL_MS = 5_000;
|
||||
const VIEW_ATTEMPTS = 3;
|
||||
|
||||
function usageAndExit(code = 1) {
|
||||
process.stderr.write(
|
||||
"Usage: node scripts/publish-release-packages.mjs [--beta] [--dry-run] [--otp <code>]\n",
|
||||
"Usage: node scripts/publish-release-packages.mjs [--beta] [--dry-run] [--tag <tag>] [--otp <code>]\n",
|
||||
);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { beta: false, dryRun: false, otp: "" };
|
||||
const args = { beta: false, dryRun: false, otp: "", tag: "" };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--beta") {
|
||||
args.beta = true;
|
||||
} else if (arg === "--dry-run") {
|
||||
args.dryRun = true;
|
||||
} else if (arg === "--tag") {
|
||||
args.tag = argv[++index] ?? "";
|
||||
if (!args.tag) usageAndExit(1);
|
||||
} else if (arg === "--canary-suffix" || arg === "--package") {
|
||||
const value = argv[++index];
|
||||
if (value === undefined) usageAndExit(1);
|
||||
args[arg === "--package" ? "package" : "canarySuffix"] = value;
|
||||
} else if (arg === "--prepare-canary") {
|
||||
args.prepareCanary = true;
|
||||
} else if (arg === "--otp") {
|
||||
args.otp = argv[index + 1] ?? "";
|
||||
if (!args.otp) {
|
||||
@@ -75,6 +84,7 @@ function defaultRunNpm(args, options = {}) {
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
stdio: getNpmStdio(options),
|
||||
timeout: options.timeout,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
@@ -101,7 +111,9 @@ function isNotFoundOutput(text) {
|
||||
}
|
||||
|
||||
function isAlreadyPublishedConflict(text) {
|
||||
return /EPUBLISHCONFLICT|cannot publish over the previously published versions/i.test(text);
|
||||
return /\bE409\b|EPUBLISHCONFLICT|cannot publish over the previously published versions/i.test(
|
||||
text,
|
||||
);
|
||||
}
|
||||
|
||||
function isTransientNpmError(text) {
|
||||
@@ -110,10 +122,25 @@ function isTransientNpmError(text) {
|
||||
);
|
||||
}
|
||||
|
||||
async function isPackageVersionPublished(pkg, version, { runNpm, sleep }) {
|
||||
async function defaultVersionCheck(pkg, version) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://registry.npmjs.org/${encodeURIComponent(pkg)}/${encodeURIComponent(version)}`,
|
||||
{ signal: AbortSignal.timeout(15_000) },
|
||||
);
|
||||
if (response.status === 404) return { status: 1, stdout: "", stderr: "E404" };
|
||||
if (!response.ok) return { status: 1, stdout: "", stderr: `HTTP ${response.status}` };
|
||||
const data = await response.json();
|
||||
return { status: 0, stdout: JSON.stringify(data.version), stderr: "" };
|
||||
} catch (error) {
|
||||
return { status: 1, stdout: "", stderr: `FETCH_ERROR ${error.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function isPackageVersionPublished(pkg, version, { checkVersion, sleep }) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
for (let attempt = 1; attempt <= VIEW_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(["view", spec, "version", "--json"]);
|
||||
const result = await checkVersion(pkg, version);
|
||||
if (result.status === 0) {
|
||||
try {
|
||||
const parsed = JSON.parse(result.stdout.trim());
|
||||
@@ -143,33 +170,63 @@ async function isPackageVersionPublished(pkg, version, { runNpm, sleep }) {
|
||||
return false;
|
||||
}
|
||||
|
||||
async function waitForPackageVisibility(pkg, version, { runNpm, sleep }) {
|
||||
async function waitForPackageVisibility(
|
||||
pkg,
|
||||
version,
|
||||
{
|
||||
checkVersion,
|
||||
sleep,
|
||||
now = Date.now,
|
||||
visibilityAttempts = VISIBILITY_ATTEMPTS,
|
||||
visibilityPollMs = VISIBILITY_POLL_MS,
|
||||
visibilityTimeoutMs = 600_000,
|
||||
},
|
||||
) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
for (let attempt = 1; attempt <= VISIBILITY_ATTEMPTS; attempt += 1) {
|
||||
if (await isPackageVersionPublished(pkg, version, { runNpm, sleep })) {
|
||||
return;
|
||||
}
|
||||
if (attempt < VISIBILITY_ATTEMPTS) {
|
||||
console.log(`Waiting for ${spec} to appear on npm (${attempt}/${VISIBILITY_ATTEMPTS})...`);
|
||||
await sleep(VISIBILITY_POLL_MS);
|
||||
const deadline = now() + visibilityTimeoutMs;
|
||||
for (let attempt = 1; attempt <= visibilityAttempts; attempt += 1) {
|
||||
const result = await checkVersion(pkg, version);
|
||||
if (result.status === 0 && JSON.parse(result.stdout) === version) return;
|
||||
const combined = outputOf(result);
|
||||
if (result.status !== 0 && !isNotFoundOutput(combined) && !isTransientNpmError(combined)) {
|
||||
throw new Error(`Failed checking whether ${spec} is published:\n${combined}`);
|
||||
}
|
||||
const remaining = deadline - now();
|
||||
if (attempt === visibilityAttempts || remaining <= 0) break;
|
||||
console.log(`Waiting for ${spec} to appear on npm (${attempt}/${visibilityAttempts})...`);
|
||||
await sleep(Math.min(visibilityPollMs, remaining));
|
||||
if (now() >= deadline) break;
|
||||
}
|
||||
throw new Error(`${spec} did not become visible on npm after ${VISIBILITY_ATTEMPTS} checks.`);
|
||||
throw new Error(
|
||||
`${spec} did not become visible on npm after ${visibilityAttempts} checks or the visibility timeout.`,
|
||||
);
|
||||
}
|
||||
|
||||
async function publishOnePackage(pkg, version, { beta, dryRun, otp }, { runNpm, sleep }) {
|
||||
async function verifyVisibility(packages, version, dryRun, deps) {
|
||||
if (!dryRun)
|
||||
await Promise.all(packages.map((pkg) => waitForPackageVisibility(pkg, version, deps)));
|
||||
}
|
||||
|
||||
async function publishOnePackage(
|
||||
pkg,
|
||||
version,
|
||||
{ beta, canary, dryRun, otp },
|
||||
{ runNpm, sleep, checkVersion, writeStdout, writeStderr },
|
||||
) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
if (!dryRun && (await isPackageVersionPublished(pkg, version, { runNpm, sleep }))) {
|
||||
if (!dryRun && (await isPackageVersionPublished(pkg, version, { checkVersion, sleep }))) {
|
||||
if (canary) throw new Error(`Canary ${spec} is already published; choose a fresh suffix.`);
|
||||
console.log(`Already published ${spec}; skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const args = ["publish", `--workspace=${pkg}`, "--access", "public"];
|
||||
if (beta) {
|
||||
args.push("--tag", "beta");
|
||||
if (canary || beta) {
|
||||
args.push("--tag", canary ? "canary" : "beta");
|
||||
}
|
||||
if (dryRun) {
|
||||
args.push("--dry-run");
|
||||
// npm 11 rejects already published versions even in dry runs unless forced.
|
||||
args.push("--dry-run", "--force");
|
||||
}
|
||||
if (otp) {
|
||||
args.push(`--otp=${otp}`);
|
||||
@@ -179,18 +236,15 @@ async function publishOnePackage(pkg, version, { beta, dryRun, otp }, { runNpm,
|
||||
const result = runNpm(args, { interactive: !dryRun });
|
||||
if (result.status === 0) {
|
||||
if (result.stdout) {
|
||||
process.stdout.write(result.stdout);
|
||||
}
|
||||
if (!dryRun) {
|
||||
await waitForPackageVisibility(pkg, version, { runNpm, sleep });
|
||||
writeStdout(result.stdout);
|
||||
}
|
||||
if (result.stderr) writeStderr(result.stderr);
|
||||
return;
|
||||
}
|
||||
|
||||
const combined = outputOf(result);
|
||||
if (!dryRun && isAlreadyPublishedConflict(combined)) {
|
||||
await waitForPackageVisibility(pkg, version, { runNpm, sleep });
|
||||
console.log(`Confirmed ${spec} is published after conflict response.`);
|
||||
if (!dryRun && !canary && isAlreadyPublishedConflict(combined)) {
|
||||
console.log(`Publish conflict for ${spec}; verifying after the publish wave.`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -207,7 +261,53 @@ async function publishOnePackage(pkg, version, { beta, dryRun, otp }, { runNpm,
|
||||
}
|
||||
}
|
||||
|
||||
async function syncBetaDistTags(version, { otp }, { runNpm, sleep }) {
|
||||
async function moveBetaDistTag(
|
||||
pkg,
|
||||
version,
|
||||
otp,
|
||||
{
|
||||
runNpm,
|
||||
sleep,
|
||||
writeStdout,
|
||||
writeStderr,
|
||||
now = Date.now,
|
||||
distTagTimeoutMs = 600_000,
|
||||
distTagAttempts = VISIBILITY_ATTEMPTS,
|
||||
distTagPollMs = VISIBILITY_POLL_MS,
|
||||
},
|
||||
) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
const distTagArgs = ["dist-tag", "add", spec, "beta"];
|
||||
if (otp) {
|
||||
distTagArgs.push(`--otp=${otp}`);
|
||||
}
|
||||
const deadline = now() + distTagTimeoutMs;
|
||||
for (let attempt = 1; attempt <= distTagAttempts; attempt += 1) {
|
||||
const result = runNpm(distTagArgs, {
|
||||
interactive: true,
|
||||
timeout: Math.max(1, deadline - now()),
|
||||
});
|
||||
if (result.status === 0) {
|
||||
if (result.stdout) writeStdout(result.stdout);
|
||||
if (result.stderr) writeStderr(result.stderr);
|
||||
break;
|
||||
}
|
||||
const combined = outputOf(result);
|
||||
const remaining = deadline - now();
|
||||
if (
|
||||
attempt < distTagAttempts &&
|
||||
remaining > 0 &&
|
||||
(isTransientNpmError(combined) || isNotFoundOutput(combined) || /\bE409\b/.test(combined))
|
||||
) {
|
||||
await sleep(Math.min(distTagPollMs, remaining));
|
||||
if (now() < deadline) continue;
|
||||
}
|
||||
throw new Error(`Failed to move beta dist-tag for ${spec}:\n${combined}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function syncBetaDistTags(version, { otp }, deps) {
|
||||
const { runNpm, sleep } = deps;
|
||||
let distTags = {};
|
||||
for (let attempt = 1; attempt <= VIEW_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(["view", "@getpaseo/cli", "dist-tags", "--json"]);
|
||||
@@ -230,37 +330,100 @@ async function syncBetaDistTags(version, { otp }, { runNpm, sleep }) {
|
||||
}
|
||||
|
||||
for (const pkg of PUBLISH_WORKSPACES) {
|
||||
const spec = `${pkg}@${version}`;
|
||||
const distTagArgs = ["dist-tag", "add", spec, "beta"];
|
||||
if (otp) {
|
||||
distTagArgs.push(`--otp=${otp}`);
|
||||
}
|
||||
for (let attempt = 1; attempt <= PUBLISH_ATTEMPTS; attempt += 1) {
|
||||
const result = runNpm(distTagArgs, { interactive: true });
|
||||
if (result.status === 0) {
|
||||
break;
|
||||
}
|
||||
const combined = outputOf(result);
|
||||
if (attempt < PUBLISH_ATTEMPTS && isTransientNpmError(combined)) {
|
||||
await sleep(attempt * PUBLISH_BACKOFF_MS);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Failed to move beta dist-tag for ${spec}:\n${combined}`);
|
||||
}
|
||||
await moveBetaDistTag(pkg, version, otp, deps);
|
||||
}
|
||||
console.log(`Moved npm beta dist-tag to ${version} across all published packages.`);
|
||||
}
|
||||
|
||||
export async function publishReleasePackages(options = {}, deps = {}) {
|
||||
const runNpm = deps.runNpm ?? defaultRunNpm;
|
||||
const sleep = deps.sleep ?? defaultSleep;
|
||||
const beta = Boolean(options.beta);
|
||||
const dryRun = Boolean(options.dryRun);
|
||||
const otp = typeof options.otp === "string" ? options.otp.trim() : "";
|
||||
const version =
|
||||
options.version ?? JSON.parse(readFileSync(path.join(rootDir, "package.json"), "utf8")).version;
|
||||
async function assertBetaNotSuperseded(version, { runNpm, sleep }) {
|
||||
for (const pkg of PUBLISH_WORKSPACES) {
|
||||
let result;
|
||||
for (let attempt = 1; attempt <= VIEW_ATTEMPTS; attempt += 1) {
|
||||
result = runNpm(["view", pkg, "dist-tags", "--json"]);
|
||||
if (result.status === 0 || isNotFoundOutput(outputOf(result))) break;
|
||||
if (attempt === VIEW_ATTEMPTS || !isTransientNpmError(outputOf(result))) {
|
||||
throw new Error(`Failed to read ${pkg} dist-tags:\n${outputOf(result)}`);
|
||||
}
|
||||
await sleep(attempt * 5_000);
|
||||
}
|
||||
if (result.status !== 0) continue;
|
||||
const current = JSON.parse(result.stdout.trim()).beta;
|
||||
if (current && compareReleaseVersions(current, version) > 0) {
|
||||
throw new Error(`Refusing to publish ${version}: ${pkg} already has newer beta ${current}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateCanary(suffix, target) {
|
||||
if (
|
||||
typeof suffix !== "string" ||
|
||||
!/^canary\.[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*$/.test(suffix) ||
|
||||
suffix.split(".").some((part) => /^0[0-9]+$/.test(part))
|
||||
) {
|
||||
throw new Error("Invalid canary suffix.");
|
||||
}
|
||||
if (target !== "all" && target !== "@getpaseo/highlight") {
|
||||
throw new Error("Invalid canary package target.");
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareCanary(suffix, target, directory = rootDir) {
|
||||
validateCanary(suffix, target);
|
||||
const packagePath = path.join(directory, "package.json");
|
||||
const rootPackage = JSON.parse(readFileSync(packagePath, "utf8"));
|
||||
const base = parseReleaseVersion(rootPackage.version).version.split("-")[0];
|
||||
const version = `${base}-${suffix}`;
|
||||
rootPackage.version = version;
|
||||
writeFileSync(packagePath, `${JSON.stringify(rootPackage, null, 2)}\n`);
|
||||
for (const workspace of rootPackage.workspaces) {
|
||||
const workspacePath = path.join(directory, workspace, "package.json");
|
||||
const pkg = JSON.parse(readFileSync(workspacePath, "utf8"));
|
||||
if (!PUBLISH_WORKSPACES.includes(pkg.name)) continue;
|
||||
pkg.version = version;
|
||||
for (const section of [
|
||||
"dependencies",
|
||||
"devDependencies",
|
||||
"peerDependencies",
|
||||
"optionalDependencies",
|
||||
]) {
|
||||
for (const name of Object.keys(pkg[section] ?? {})) {
|
||||
if (PUBLISH_WORKSPACES.includes(name)) pkg[section][name] = version;
|
||||
}
|
||||
}
|
||||
writeFileSync(workspacePath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
async function publishCanary(options, version, { dryRun, otp }, deps) {
|
||||
validateCanary(options.canarySuffix, options.package);
|
||||
if (
|
||||
options.beta ||
|
||||
(options.tag !== undefined && options.tag !== "" && options.tag !== "canary") ||
|
||||
!new RegExp(`^\\d+\\.\\d+\\.\\d+-${options.canarySuffix.replaceAll(".", "\\.")}$`).test(version)
|
||||
) {
|
||||
throw new Error("Canary version or options do not match the requested canary.");
|
||||
}
|
||||
const packages = options.package === "all" ? PUBLISH_WORKSPACES : [options.package];
|
||||
for (const pkg of packages) {
|
||||
await publishOnePackage(pkg, version, { canary: true, dryRun, otp }, deps);
|
||||
}
|
||||
await verifyVisibility(packages, version, dryRun, deps);
|
||||
}
|
||||
|
||||
function validatePublishOptions(options) {
|
||||
if (options.package !== undefined && options.canarySuffix === undefined) {
|
||||
throw new Error("A package selector requires a canary suffix.");
|
||||
}
|
||||
}
|
||||
|
||||
function releaseIsBeta(version, options) {
|
||||
let beta = Boolean(options.beta);
|
||||
const parsed = parseReleaseVersion(version);
|
||||
if (options.tag) {
|
||||
if (options.tag !== `v${version}`)
|
||||
throw new Error(`Release tag ${options.tag} does not match package version ${version}.`);
|
||||
beta = parsed.isPrerelease;
|
||||
}
|
||||
if (parsed.isPrerelease && !beta) {
|
||||
throw new Error(
|
||||
`Refusing to publish prerelease version ${version} to latest. Pass --beta instead.`,
|
||||
@@ -272,16 +435,47 @@ export async function publishReleasePackages(options = {}, deps = {}) {
|
||||
);
|
||||
}
|
||||
|
||||
return beta;
|
||||
}
|
||||
|
||||
export async function publishReleasePackages(options = {}, deps = {}) {
|
||||
validatePublishOptions(options);
|
||||
const runNpm = deps.runNpm ?? defaultRunNpm;
|
||||
const sleep = deps.sleep ?? defaultSleep;
|
||||
const runtime = {
|
||||
...deps,
|
||||
runNpm,
|
||||
sleep,
|
||||
checkVersion: deps.checkVersion ?? defaultVersionCheck,
|
||||
writeStdout: deps.writeStdout ?? ((text) => process.stdout.write(text)),
|
||||
writeStderr: deps.writeStderr ?? ((text) => process.stderr.write(text)),
|
||||
};
|
||||
let beta = Boolean(options.beta);
|
||||
const dryRun = Boolean(options.dryRun);
|
||||
const otp = typeof options.otp === "string" ? options.otp.trim() : "";
|
||||
const version =
|
||||
options.version ?? JSON.parse(readFileSync(path.join(rootDir, "package.json"), "utf8")).version;
|
||||
|
||||
if (options.canarySuffix !== undefined) {
|
||||
return publishCanary(options, version, { dryRun, otp }, runtime);
|
||||
}
|
||||
|
||||
beta = releaseIsBeta(version, options);
|
||||
|
||||
if (beta && !dryRun) await assertBetaNotSuperseded(version, { runNpm, sleep });
|
||||
|
||||
for (const pkg of PUBLISH_WORKSPACES) {
|
||||
await publishOnePackage(pkg, version, { beta, dryRun, otp }, { runNpm, sleep });
|
||||
await publishOnePackage(pkg, version, { beta, dryRun, otp }, runtime);
|
||||
}
|
||||
|
||||
if (!beta && !dryRun) {
|
||||
await syncBetaDistTags(version, { otp }, { runNpm, sleep });
|
||||
await syncBetaDistTags(version, { otp }, runtime);
|
||||
}
|
||||
await verifyVisibility(PUBLISH_WORKSPACES, version, dryRun, runtime);
|
||||
}
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
await publishReleasePackages(args);
|
||||
if (args.prepareCanary) prepareCanary(args.canarySuffix, args.package);
|
||||
else await publishReleasePackages(args);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
PUBLISH_WORKSPACES,
|
||||
getNpmStdio,
|
||||
publishReleasePackages,
|
||||
prepareCanary,
|
||||
publishReleasePackages as publish,
|
||||
} from "./publish-release-packages.mjs";
|
||||
|
||||
function publishReleasePackages(options, deps = {}) {
|
||||
return publish(options, {
|
||||
...deps,
|
||||
checkVersion:
|
||||
deps.checkVersion ??
|
||||
((pkg, version) => deps.runNpm(["view", `${pkg}@${version}`, "version", "--json"])),
|
||||
});
|
||||
}
|
||||
|
||||
const noSleep = () => Promise.resolve();
|
||||
|
||||
function ok(stdout = "") {
|
||||
@@ -76,6 +88,7 @@ test("skips already-published packages cleanly so partial failures can be rerun"
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "dist-tags") return ok("{}");
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
return published.has(args[1])
|
||||
? ok(JSON.stringify("0.17.0-beta.2"))
|
||||
@@ -113,6 +126,7 @@ test("retries transient publish errors, waits for delayed registry propagation,
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "dist-tags") return ok("{}");
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
const spec = args[1];
|
||||
if (!published.has(spec)) {
|
||||
@@ -168,6 +182,7 @@ test("does not retry deterministic npm auth errors", async () => {
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "dist-tags") return ok("{}");
|
||||
if (args[0] === "view") {
|
||||
return fail("npm error code E404");
|
||||
}
|
||||
@@ -256,6 +271,7 @@ test("dry-run skips registry queries, propagation polling, and dist-tag sync", a
|
||||
for (const args of calls) {
|
||||
assert.equal(args[0], "publish");
|
||||
assert.ok(args.includes("--dry-run"));
|
||||
assert.ok(args.includes("--force"));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -316,3 +332,351 @@ test("marks publish and dist-tag invocations interactive and forwards --otp when
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("published workspaces identify their repository and directory", () => {
|
||||
for (const workspace of PUBLISH_WORKSPACES) {
|
||||
const directory = `packages/${workspace.split("/")[1]}`;
|
||||
const pkg = JSON.parse(readFileSync(new URL(`../${directory}/package.json`, import.meta.url)));
|
||||
assert.deepEqual(pkg.repository, {
|
||||
type: "git",
|
||||
url: "git+https://github.com/getpaseo/paseo.git",
|
||||
directory,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("tagged releases select the channel and reject a mismatched tag", async () => {
|
||||
const calls = [];
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0-beta.2", tag: "v0.17.0-beta.2", dryRun: true },
|
||||
{
|
||||
runNpm: (args) => {
|
||||
calls.push(args);
|
||||
return ok();
|
||||
},
|
||||
sleep: noSleep,
|
||||
},
|
||||
);
|
||||
assert.ok(calls.every((args) => args.includes("beta")));
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0", tag: "v0.17.1", dryRun: true },
|
||||
{ runNpm: () => ok(), sleep: noSleep },
|
||||
),
|
||||
/tag.*version/i,
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses an older beta retry before it can move any newer beta tag backward", async () => {
|
||||
const calls = [];
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0-beta.1", beta: true },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
calls.push(args);
|
||||
if (args[0] === "view" && args[2] === "dist-tags")
|
||||
return ok(
|
||||
JSON.stringify({
|
||||
beta: args[1] === "@getpaseo/client" ? "0.17.0-beta.2" : "0.17.0-beta.1",
|
||||
}),
|
||||
);
|
||||
throw new Error("must not publish");
|
||||
},
|
||||
},
|
||||
),
|
||||
/newer.*beta/i,
|
||||
);
|
||||
assert.ok(calls.every((args) => args[0] === "view"));
|
||||
});
|
||||
|
||||
test("canary publishes selected workspaces only with the canary tag", async () => {
|
||||
for (const target of ["@getpaseo/highlight", "all"]) {
|
||||
const calls = [];
|
||||
const version = "0.17.0-canary.123";
|
||||
const published = new Set();
|
||||
await publishReleasePackages(
|
||||
{ version, canarySuffix: "canary.123", package: target },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
calls.push(args);
|
||||
if (args[0] === "view" && args[2] === "version") {
|
||||
return published.has(args[1]) ? ok(JSON.stringify(version)) : fail("E404");
|
||||
}
|
||||
if (args[0] === "publish") {
|
||||
published.add(
|
||||
`${args.find((arg) => arg.startsWith("--workspace=")).slice(12)}@${version}`,
|
||||
);
|
||||
return ok();
|
||||
}
|
||||
throw new Error(`Unexpected npm call: ${args.join(" ")}`);
|
||||
},
|
||||
},
|
||||
);
|
||||
const publishes = calls.filter((args) => args[0] === "publish");
|
||||
assert.deepEqual(
|
||||
publishes.map((args) => args[1].slice(12)),
|
||||
target === "all" ? PUBLISH_WORKSPACES : [target],
|
||||
);
|
||||
for (const args of publishes) assert.deepEqual(args.slice(-2), ["--tag", "canary"]);
|
||||
assert.ok(calls.every((args) => args[0] !== "dist-tag" && args[2] !== "dist-tags"));
|
||||
}
|
||||
});
|
||||
|
||||
test("canary rejects unsafe suffixes and non-leaf targets", async () => {
|
||||
for (const suffix of ["", "beta.1", "canary.1;echo", "canary..1"]) {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages({
|
||||
version: `0.17.0-${suffix}`,
|
||||
canarySuffix: suffix,
|
||||
package: "all",
|
||||
}),
|
||||
/canary/i,
|
||||
);
|
||||
}
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages({
|
||||
version: "0.17.0-canary.1",
|
||||
canarySuffix: "canary.1",
|
||||
package: "@getpaseo/cli",
|
||||
}),
|
||||
/package/i,
|
||||
);
|
||||
});
|
||||
|
||||
test("canary stamping leaves private app versions intact and updates published dependencies", () => {
|
||||
mkdirSync(path.join(process.cwd(), ".artifacts"), { recursive: true });
|
||||
const dir = mkdtempSync(path.join(process.cwd(), ".artifacts", "canary-test-"));
|
||||
try {
|
||||
const write = (file, value) => {
|
||||
const target = path.join(dir, file);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, JSON.stringify(value));
|
||||
};
|
||||
write("package.json", {
|
||||
version: "0.17.0",
|
||||
workspaces: ["packages/app", "packages/highlight", "packages/client"],
|
||||
});
|
||||
write("packages/app/package.json", { name: "@getpaseo/app", private: true, version: "0.17.0" });
|
||||
write("packages/highlight/package.json", { name: "@getpaseo/highlight", version: "0.17.0" });
|
||||
write("packages/client/package.json", {
|
||||
name: "@getpaseo/client",
|
||||
version: "0.17.0",
|
||||
dependencies: { "@getpaseo/highlight": "0.17.0" },
|
||||
});
|
||||
prepareCanary("canary.123", "all", dir);
|
||||
const read = (file) => JSON.parse(readFileSync(path.join(dir, file), "utf8"));
|
||||
assert.equal(read("packages/app/package.json").version, "0.17.0");
|
||||
assert.equal(read("packages/highlight/package.json").version, "0.17.0-canary.123");
|
||||
assert.equal(
|
||||
read("packages/client/package.json").dependencies["@getpaseo/highlight"],
|
||||
"0.17.0-canary.123",
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("canary rejects an existing version rather than reporting a successful publish", async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0-canary.1", canarySuffix: "canary.1", package: "@getpaseo/highlight" },
|
||||
{ runNpm: () => ok(JSON.stringify("0.17.0-canary.1")), sleep: noSleep },
|
||||
),
|
||||
/already published/i,
|
||||
);
|
||||
});
|
||||
|
||||
test("canary reports a publish conflict instead of accepting an existing version", async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0-canary.1", canarySuffix: "canary.1", package: "@getpaseo/highlight" },
|
||||
{
|
||||
runNpm: (args) => (args[0] === "view" ? fail("E404") : fail("EPUBLISHCONFLICT")),
|
||||
sleep: noSleep,
|
||||
},
|
||||
),
|
||||
/EPUBLISHCONFLICT/,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects a package selector without a canary suffix before invoking npm", async () => {
|
||||
let called = false;
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0", package: "@getpaseo/highlight" },
|
||||
{
|
||||
runNpm() {
|
||||
called = true;
|
||||
return ok();
|
||||
},
|
||||
sleep: noSleep,
|
||||
},
|
||||
),
|
||||
/canary suffix/i,
|
||||
);
|
||||
assert.equal(called, false);
|
||||
});
|
||||
|
||||
test("publishes the whole wave before checking visibility through extended lag", async () => {
|
||||
const published = new Set();
|
||||
const checks = new Map();
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0-beta.2", beta: true },
|
||||
{
|
||||
sleep: noSleep,
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "dist-tags") return ok("{}");
|
||||
if (args[0] === "publish") {
|
||||
published.add(args[1].slice(12));
|
||||
return ok();
|
||||
}
|
||||
if (args[0] === "view") {
|
||||
if (published.size < 7) return fail("E404");
|
||||
const count = (checks.get(args[1]) ?? 0) + 1;
|
||||
checks.set(args[1], count);
|
||||
return count > 15 ? ok(JSON.stringify("0.17.0-beta.2")) : fail("E404");
|
||||
}
|
||||
throw new Error("unexpected call");
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(published.size, 7);
|
||||
assert.equal(checks.size, 7);
|
||||
});
|
||||
|
||||
test("surfaces successful publish and dist-tag notices and retries indexing errors", async () => {
|
||||
const published = new Set();
|
||||
const attempts = new Map();
|
||||
let stderr = "";
|
||||
await publishReleasePackages(
|
||||
{ version: "0.17.0" },
|
||||
{
|
||||
sleep: noSleep,
|
||||
writeStderr: (chunk) => {
|
||||
stderr += chunk;
|
||||
},
|
||||
runNpm(args) {
|
||||
if (args[0] === "view" && args[2] === "dist-tags") return ok("{}");
|
||||
if (args[0] === "view") return published.has(args[1]) ? ok('"0.17.0"') : fail("E404");
|
||||
if (args[0] === "publish") {
|
||||
published.add(`${args[1].slice(12)}@0.17.0`);
|
||||
return { ...ok(), stderr: "Signed provenance statement\n" };
|
||||
}
|
||||
const count = (attempts.get(args[2]) ?? 0) + 1;
|
||||
attempts.set(args[2], count);
|
||||
if (count < 3) return fail(count === 1 ? "E404" : "E409");
|
||||
return { ...ok(), stderr: "dist-tag notice\n" };
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.match(stderr, /Signed provenance statement/);
|
||||
assert.match(stderr, /dist-tag notice/);
|
||||
assert.deepEqual([...attempts.values()], Array(7).fill(3));
|
||||
});
|
||||
|
||||
test("final visibility checks run concurrently and exhaust the configured window", async () => {
|
||||
let published = 0;
|
||||
let checks = 0;
|
||||
let sleeps = 0;
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0-canary.123", canarySuffix: "canary.123", package: "all" },
|
||||
{
|
||||
visibilityAttempts: 4,
|
||||
sleep: async () => {
|
||||
sleeps++;
|
||||
},
|
||||
checkVersion: async () => {
|
||||
if (published === 7) checks++;
|
||||
return fail("E404");
|
||||
},
|
||||
runNpm(args) {
|
||||
assert.equal(args[0], "publish");
|
||||
published++;
|
||||
return ok();
|
||||
},
|
||||
},
|
||||
),
|
||||
/did not become visible/,
|
||||
);
|
||||
assert.equal(published, 7);
|
||||
assert.equal(checks, 28);
|
||||
assert.equal(sleeps, 21);
|
||||
});
|
||||
|
||||
test("visibility timeout includes time spent in registry requests", async () => {
|
||||
let time = 0;
|
||||
let published = false;
|
||||
let checks = 0;
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{
|
||||
version: "0.17.0-canary.123",
|
||||
canarySuffix: "canary.123",
|
||||
package: "@getpaseo/highlight",
|
||||
},
|
||||
{
|
||||
now: () => time,
|
||||
sleep: async (ms) => {
|
||||
time += ms;
|
||||
},
|
||||
visibilityTimeoutMs: 600_000,
|
||||
checkVersion: async () => {
|
||||
if (published) {
|
||||
checks++;
|
||||
time += 15_000;
|
||||
}
|
||||
return fail(published ? "ETIMEDOUT" : "E404");
|
||||
},
|
||||
runNpm() {
|
||||
published = true;
|
||||
return ok();
|
||||
},
|
||||
},
|
||||
),
|
||||
/visibility timeout/,
|
||||
);
|
||||
assert.ok(time <= 615_000);
|
||||
assert.ok(checks < 121);
|
||||
});
|
||||
|
||||
test("dist-tag retry deadline includes time spent in npm", async () => {
|
||||
let time = 0;
|
||||
let attempts = 0;
|
||||
await assert.rejects(
|
||||
() =>
|
||||
publishReleasePackages(
|
||||
{ version: "0.17.0" },
|
||||
{
|
||||
now: () => time,
|
||||
sleep: async (ms) => {
|
||||
time += ms;
|
||||
},
|
||||
checkVersion: async () => fail("E404"),
|
||||
runNpm(args, options) {
|
||||
if (args[0] === "view") return ok("{}");
|
||||
if (args[0] === "publish") return ok();
|
||||
attempts++;
|
||||
assert.ok(options.timeout <= 600_000 - time);
|
||||
time += Math.min(75_000, options.timeout);
|
||||
return fail("E503");
|
||||
},
|
||||
},
|
||||
),
|
||||
/Failed to move beta dist-tag/,
|
||||
);
|
||||
assert.ok(attempts < 121);
|
||||
assert.equal(time, 600_000);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { isMainModule } from "./is-main-module.mjs";
|
||||
import { collectAssets } from "./upload-release-assets.mjs";
|
||||
|
||||
export async function writeChecksums(directory, name) {
|
||||
const files = collectAssets(directory).filter(
|
||||
(file) => !path.basename(file).startsWith("SHA256SUMS-"),
|
||||
);
|
||||
if (!files.length) throw new Error(`No release assets in ${directory}`);
|
||||
const lines = [];
|
||||
for (const file of files) {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(file)) hash.update(chunk);
|
||||
lines.push(`${hash.digest("hex")} ${path.basename(file)}`);
|
||||
}
|
||||
writeFileSync(path.join(directory, name), `${lines.join("\n")}\n`);
|
||||
}
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
const [directory, name] = process.argv.slice(2);
|
||||
if (!directory || !name)
|
||||
throw new Error("Usage: node scripts/release-checksums.mjs <directory> <name>");
|
||||
await writeChecksums(directory, name);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { writeChecksums } from "./release-checksums.mjs";
|
||||
|
||||
test("checksums every uploaded asset without including manifests or itself", async () => {
|
||||
const artifacts = path.join(process.cwd(), ".artifacts");
|
||||
mkdirSync(artifacts, { recursive: true });
|
||||
const dir = mkdtempSync(path.join(artifacts, "checksums-"));
|
||||
try {
|
||||
writeFileSync(path.join(dir, "Paseo file.zip"), "abc");
|
||||
writeFileSync(path.join(dir, "latest.yml"), "manifest");
|
||||
await writeChecksums(dir, "SHA256SUMS-desktop.txt");
|
||||
assert.equal(
|
||||
readFileSync(path.join(dir, "SHA256SUMS-desktop.txt"), "utf8"),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad Paseo file.zip\n",
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user