mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 14:45:25 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47f784aaa0 | ||
|
|
7afeffc712 | ||
|
|
774e2024a9 | ||
|
|
11e98262ce | ||
|
|
7734caec13 | ||
|
|
c7fda6b141 | ||
|
|
f8422d956a | ||
|
|
47bf732a05 | ||
|
|
a9a803be52 | ||
|
|
e7f2913109 | ||
|
|
6e071b60f2 | ||
|
|
8a8bc76cc6 | ||
|
|
a246b931ed | ||
|
|
8c2c5d5103 | ||
|
|
b1ce00192d |
@@ -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"
|
||||
+50
-2
@@ -1,22 +1,44 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.0-beta.1 - 2026-12-02
|
||||
## 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
|
||||
|
||||
- Changed agent messages and subagent finish notifications to default to `steer`, falling back to `queue` on providers that cannot steer mid-turn instead of interrupting the active turn ([#11915](https://github.com/getpaseo/paseo/pull/11915))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed direct `steer` and `interrupt` prompts clearing queued messages and finish notifications from the queue ([#11915](https://github.com/getpaseo/paseo/pull/11915))
|
||||
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts ([#11915](https://github.com/getpaseo/paseo/pull/11915))
|
||||
- Fixed parent agents missing the follow-up completion notice when Claude runs a queued steer as a separate turn ([#11872](https://github.com/getpaseo/paseo/pull/11872))
|
||||
|
||||
## 0.19.0 - 2026-12-03
|
||||
|
||||
- **Switch providers mid-chat:** Switch a chat to another provider and keep the conversation, with chat history now stored on the host. ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- **Queue survives restarts:** Queued messages now live on the host, so they survive app reloads, device switches and daemon restarts. ([#11424](https://github.com/getpaseo/paseo/pull/11424), [#11566](https://github.com/getpaseo/paseo/pull/11566), [#11740](https://github.com/getpaseo/paseo/pull/11740))
|
||||
- **One switch for agent tools:** Agent tools now sit behind one Enable tools setting with orchestration, schedules, PR watching and browser groups, and are on by default. ([#11189](https://github.com/getpaseo/paseo/pull/11189))
|
||||
- **Connected devices list:** Settings → Devices now shows which clients and hosts are connected and what each one can access. ([#11209](https://github.com/getpaseo/paseo/pull/11209))
|
||||
- **Plugin scorecards:** Plugin pages in the app and on paseo.sh show a scorecard, update history, related plugins and sponsor links. ([#11563](https://github.com/getpaseo/paseo/pull/11563), [#11674](https://github.com/getpaseo/paseo/pull/11674), [#11691](https://github.com/getpaseo/paseo/pull/11691))
|
||||
- **Plugin approval prompt:** The app now asks once per host before it runs a plugin's code, and a General setting turns the prompt off. ([#11717](https://github.com/getpaseo/paseo/pull/11717))
|
||||
- **Share services through tunnels:** Share a running workspace service at a public URL from the Scripts menu, and dev servers keep their live-reload connections. Services now open at `localhost:<port>`, and `*.localhost` service URLs are removed. ([#11490](https://github.com/getpaseo/paseo/pull/11490))
|
||||
- **Lower CPU while agents run:** Running agents use far less CPU, GPU and battery, with lighter status rings, loaders and tool-call animations. ([#11456](https://github.com/getpaseo/paseo/pull/11456), [#11474](https://github.com/getpaseo/paseo/pull/11474), [#11564](https://github.com/getpaseo/paseo/pull/11564), [#11586](https://github.com/getpaseo/paseo/pull/11586), [#11591](https://github.com/getpaseo/paseo/pull/11591) by [@djbclark](https://github.com/djbclark), [@luoph](https://github.com/luoph), [@mariotaku](https://github.com/mariotaku))
|
||||
- **Steadier streaming replies:** Streaming replies show their final formatting as they arrive, and long replies no longer get slower to render as they grow. ([#11572](https://github.com/getpaseo/paseo/pull/11572), [#11582](https://github.com/getpaseo/paseo/pull/11582) by [@luoph](https://github.com/luoph))
|
||||
- **Faster mobile launch:** The mobile app shows your last workspace sooner after a cold launch, about 0.7 seconds on Android. ([#11390](https://github.com/getpaseo/paseo/pull/11390) by [@luoph](https://github.com/luoph), [@maci0](https://github.com/maci0))
|
||||
- **Desktop browser profiles:** Desktop browser tabs can use separate colored profiles, so you can stay signed in to two accounts on one site. ([#10357](https://github.com/getpaseo/paseo/pull/10357) by [@clkao](https://github.com/clkao))
|
||||
- **Desktop browser profiles:** Desktop browser tabs can use separate colored profiles, so you can stay signed in to two accounts on one site. ([#10357](https://github.com/getpaseo/paseo/pull/10357), [#11772](https://github.com/getpaseo/paseo/pull/11772) by [@clkao](https://github.com/clkao))
|
||||
- **Swipe away the iOS keyboard:** Drag the chat down to hide the iOS keyboard, and chat controls now work on the first tap while it is open. ([#11625](https://github.com/getpaseo/paseo/pull/11625))
|
||||
|
||||
### Breaking
|
||||
|
||||
- Paseo CLI and daemon now require Node.js 22.16.0 or later ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- Relay connections now require [protected end-to-end encryption](https://paseo.sh/docs/security) by default, so apps older than 0.13.0 cannot connect through the relay ([#11864](https://github.com/getpaseo/paseo/pull/11864))
|
||||
|
||||
### Added
|
||||
|
||||
@@ -37,6 +59,7 @@
|
||||
- Served the desktop app's web UI with Brotli and gzip compression instead of an uncompressed 25 MB bundle ([#10635](https://github.com/getpaseo/paseo/pull/10635) by [@djbclark](https://github.com/djbclark))
|
||||
- Changed chat loading to one steady spinner that reveals the chat and composer together, without an Updating messages flash ([#11575](https://github.com/getpaseo/paseo/pull/11575))
|
||||
- Kept the Restoring screen up until a restored workspace is ready ([#11486](https://github.com/getpaseo/paseo/pull/11486))
|
||||
- Resized the mobile app icon to match other Home Screen icons, with Android themed icons and iOS Liquid Glass ([#11851](https://github.com/getpaseo/paseo/pull/11851))
|
||||
- Showed a spinner on a worktree row while archive checks for uncommitted changes ([#11519](https://github.com/getpaseo/paseo/pull/11519), [#11574](https://github.com/getpaseo/paseo/pull/11574) by [@cxroop](https://github.com/cxroop))
|
||||
- Showed each host's icon with a status dot on host selectors ([#11568](https://github.com/getpaseo/paseo/pull/11568))
|
||||
- Sent the prompt with hardware-keyboard Return on iPhone, as on iPad ([#11537](https://github.com/getpaseo/paseo/pull/11537))
|
||||
@@ -45,12 +68,17 @@
|
||||
### Changed
|
||||
|
||||
- Changed archiving to keep a worktree that has uncommitted changes unless you confirm removal ([#11430](https://github.com/getpaseo/paseo/pull/11430))
|
||||
- Changed Import session on the New workspace screen to create a new workspace ([#11845](https://github.com/getpaseo/paseo/pull/11845))
|
||||
- Changed closing a New Agent tab with an unsent draft to ask before discarding it ([#11660](https://github.com/getpaseo/paseo/pull/11660))
|
||||
- Changed Cmd/Ctrl+click on a sidebar workspace to open it instead of entering select mode ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- Changed agents that already reported to their caller with `send_agent_prompt` to skip the extra finished notice ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed thinking level, mode and model changes on a running agent snapping back to the old value ([#11850](https://github.com/getpaseo/paseo/pull/11850))
|
||||
- Fixed finished agents flashing back to running for a moment ([#11764](https://github.com/getpaseo/paseo/pull/11764))
|
||||
- Fixed Send now on a queued message cancelling the running turn instead of steering it ([#11827](https://github.com/getpaseo/paseo/pull/11827))
|
||||
- Fixed a failed or finished send replacing a follow-up draft typed while it was sending ([#11448](https://github.com/getpaseo/paseo/pull/11448) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed an attached image over 2000 px breaking every later turn in its chat ([#5119](https://github.com/getpaseo/paseo/pull/5119) by [@RUIIIOVO](https://github.com/RUIIIOVO))
|
||||
- Fixed voice mode agents never speaking back when Paseo tools were off ([#11161](https://github.com/getpaseo/paseo/pull/11161))
|
||||
- Fixed turning off voice mode without a daemon connection leaving the microphone on ([#11587](https://github.com/getpaseo/paseo/pull/11587) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
@@ -61,18 +89,25 @@
|
||||
- Fixed terminal output stopping after a reconnect reused its subscription ([#10433](https://github.com/getpaseo/paseo/pull/10433) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed Files showing Host is not connected when the app launched before the host connected ([#11679](https://github.com/getpaseo/paseo/pull/11679))
|
||||
- Fixed Created and Last prompt sorting disappearing while a host is offline ([#11728](https://github.com/getpaseo/paseo/pull/11728))
|
||||
- Fixed sideways swipes on horizontal scroll areas opening or closing the side panels on iOS and Android ([#11841](https://github.com/getpaseo/paseo/pull/11841))
|
||||
- Fixed iOS header taps scrolling the chat, Explorer or workspace list to the top ([#11262](https://github.com/getpaseo/paseo/pull/11262) by [@yzim](https://github.com/yzim))
|
||||
- Fixed a file sheet dismissed while opening leaving an invisible backdrop that blocked taps ([#11317](https://github.com/getpaseo/paseo/pull/11317) by [@LiebeLee](https://github.com/LiebeLee))
|
||||
- Fixed bottom sheets staying open when dismissed before their open animation started ([#11632](https://github.com/getpaseo/paseo/pull/11632))
|
||||
- Fixed Android attaching nothing when the app was recreated during image selection ([#7734](https://github.com/getpaseo/paseo/pull/7734))
|
||||
- Fixed middle-clicking a tab on Linux pasting the selection into the terminal ([#11818](https://github.com/getpaseo/paseo/pull/11818))
|
||||
- Fixed Find dropping the first keys typed right after Cmd/Ctrl+F ([#11812](https://github.com/getpaseo/paseo/pull/11812))
|
||||
- Fixed pasting a file into the web composer inserting its path instead of attaching it ([#11718](https://github.com/getpaseo/paseo/pull/11718))
|
||||
- Fixed Content font size not applying to existing user messages in web chat ([#11469](https://github.com/getpaseo/paseo/pull/11469) by [@bearyjd](https://github.com/bearyjd))
|
||||
- Fixed `<br>` in a Markdown table cell splitting the table row ([#9587](https://github.com/getpaseo/paseo/pull/9587) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed hidden chat rows shifting the reading position on web ([#11538](https://github.com/getpaseo/paseo/pull/11538) by [@kogekiplay](https://github.com/kogekiplay))
|
||||
- Fixed links to outside folders without a trailing slash opening as a broken file tab ([#11786](https://github.com/getpaseo/paseo/pull/11786))
|
||||
- Fixed the Scripts menu staying stale after `paseo.json` changes ([#11768](https://github.com/getpaseo/paseo/pull/11768) by [@odoo-mvds](https://github.com/odoo-mvds))
|
||||
- Fixed the empty tool call details text touching the screen edge ([#9129](https://github.com/getpaseo/paseo/pull/9129) by [@ilteoood](https://github.com/ilteoood))
|
||||
- Fixed a plugin slash command with an attachment being sent to the agent as a message ([#11483](https://github.com/getpaseo/paseo/pull/11483) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Archive finished subagents skipping closed subagents ([#10865](https://github.com/getpaseo/paseo/pull/10865) by [@sbhas2k](https://github.com/sbhas2k))
|
||||
- Fixed Import Session missing the newest ACP sessions ([#10675](https://github.com/getpaseo/paseo/pull/10675))
|
||||
- Fixed Import Session hiding the provider error while Retry runs ([#11654](https://github.com/getpaseo/paseo/pull/11654))
|
||||
- Fixed Import session failing to open chats from older custom Codex providers ([#11852](https://github.com/getpaseo/paseo/pull/11852))
|
||||
- Fixed setup dropping project suggestions from providers that answer after 60 seconds ([#11438](https://github.com/getpaseo/paseo/pull/11438) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Open in file manager showing for workspaces on remote hosts ([#11463](https://github.com/getpaseo/paseo/pull/11463) by [@sleroq](https://github.com/sleroq))
|
||||
- Fixed Reveal in Finder for workspaces rooted at `/` ([#11206](https://github.com/getpaseo/paseo/pull/11206) by [@suniceman](https://github.com/suniceman))
|
||||
@@ -85,6 +120,7 @@
|
||||
- Fixed turns Claude starts on its own staying hidden in reopened chats until Reload ([#11405](https://github.com/getpaseo/paseo/pull/11405))
|
||||
- Fixed Claude Code system notices being dropped from the chat ([#11419](https://github.com/getpaseo/paseo/pull/11419) by [@minamorl](https://github.com/minamorl))
|
||||
- Fixed Claude Code's Goal set reply missing from imported chats ([#11733](https://github.com/getpaseo/paseo/pull/11733))
|
||||
- Fixed Claude Code Stop hook warnings telling you to press a shortcut that opens Add project in Paseo ([#11792](https://github.com/getpaseo/paseo/pull/11792))
|
||||
- Fixed listing commands in an archived Claude chat starting Claude Code ([#11521](https://github.com/getpaseo/paseo/pull/11521) by [@RawSalmon69](https://github.com/RawSalmon69))
|
||||
- Fixed Stop failing on unresponsive Pi and OMP agents ([#11618](https://github.com/getpaseo/paseo/pull/11618) by [@LouisDeconinck](https://github.com/LouisDeconinck))
|
||||
- Fixed Pi turns never finishing when an extension handles the prompt ([#10572](https://github.com/getpaseo/paseo/pull/10572) by [@jsilhan](https://github.com/jsilhan))
|
||||
@@ -92,12 +128,16 @@
|
||||
- Fixed Pi showing the prompt twice when an extension sends context before the reply ([#11533](https://github.com/getpaseo/paseo/pull/11533) by [@Stelath](https://github.com/Stelath))
|
||||
- Fixed Pi chats skipping project skills and settings in trusted workspaces ([#11527](https://github.com/getpaseo/paseo/pull/11527) by [@patrick-motard](https://github.com/patrick-motard))
|
||||
- Fixed new Pi agents failing with an old extension error after the conflict was fixed ([#11642](https://github.com/getpaseo/paseo/pull/11642))
|
||||
- Fixed Pi receiving a cancellation when an agent approved its prompt with a chosen option ([#11814](https://github.com/getpaseo/paseo/pull/11814) by [@djbclark](https://github.com/djbclark))
|
||||
- Fixed the OMP Fast toggle missing before the first prompt ([#11553](https://github.com/getpaseo/paseo/pull/11553))
|
||||
- Fixed finished OMP form questions losing the question and chosen answer ([#11697](https://github.com/getpaseo/paseo/pull/11697), [#11706](https://github.com/getpaseo/paseo/pull/11706) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- Fixed a failed Codex startup crashing the daemon ([#11847](https://github.com/getpaseo/paseo/pull/11847) by [@xilinshancun](https://github.com/xilinshancun))
|
||||
- Fixed idle Codex agents never releasing their resources after Codex exits ([#11839](https://github.com/getpaseo/paseo/pull/11839) by [@michaelmwu](https://github.com/michaelmwu))
|
||||
- Fixed Codex sends reporting failure after 60 seconds while Codex was still starting ([#11547](https://github.com/getpaseo/paseo/pull/11547) by [@nonononull](https://github.com/nonononull))
|
||||
- Fixed Codex features staying hidden behind a wrapper command such as `env codex` ([#11221](https://github.com/getpaseo/paseo/pull/11221) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed answers to Codex async questions being rejected ([#11225](https://github.com/getpaseo/paseo/pull/11225) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed reopening a Codex chat resetting its last-activity time ([#10760](https://github.com/getpaseo/paseo/pull/10760) by [@Juns-g](https://github.com/Juns-g))
|
||||
- Fixed OpenCode reply paragraphs running together ([#11745](https://github.com/getpaseo/paseo/pull/11745))
|
||||
- Fixed Antigravity subagent tool calls splitting streamed replies mid-word ([#11535](https://github.com/getpaseo/paseo/pull/11535) by [@Suhail](https://github.com/Suhail))
|
||||
- Fixed Antigravity turns ending as completed after an internal executor error ([#10885](https://github.com/getpaseo/paseo/pull/10885) by [@vecyang1](https://github.com/vecyang1), [@luoph](https://github.com/luoph))
|
||||
- Fixed ACP chats failing to reopen when the provider rejects the saved thinking level ([#10333](https://github.com/getpaseo/paseo/pull/10333))
|
||||
@@ -123,12 +163,17 @@
|
||||
- Fixed a queued message running in the mode of a prompt sent after it ([#11722](https://github.com/getpaseo/paseo/pull/11722))
|
||||
- Fixed `paseo ls --json` dropping timestamps and background work ([#11423](https://github.com/getpaseo/paseo/pull/11423) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed `paseo inspect` and `paseo ls` hiding the model for Cursor Auto ([#11693](https://github.com/getpaseo/paseo/pull/11693))
|
||||
- Fixed `paseo ls --label` with a malformed label listing every agent ([#11707](https://github.com/getpaseo/paseo/pull/11707) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed `paseo terminal capture` and `paseo terminal send-keys` ignoring `--json` ([#11710](https://github.com/getpaseo/paseo/pull/11710) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed `paseo terminal create --workspace` failing for workspaces past the first ten ([#11799](https://github.com/getpaseo/paseo/pull/11799) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed `paseo schedule update --model` failing unless the provider was repeated ([#11796](https://github.com/getpaseo/paseo/pull/11796) by [@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- Fixed `paseo workspace ls` reporting a wrong password as a stopped daemon ([#11676](https://github.com/getpaseo/paseo/pull/11676) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed `paseo daemon status` leaving out unconfirmed terminal cleanup ([#11658](https://github.com/getpaseo/paseo/pull/11658) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed CLI archive, detach and reload scanning all agent history for a full agent ID ([#11617](https://github.com/getpaseo/paseo/pull/11617) by [@maci0](https://github.com/maci0))
|
||||
|
||||
### Security
|
||||
|
||||
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
@@ -138,8 +183,11 @@
|
||||
### Plugins
|
||||
|
||||
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
|
||||
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
|
||||
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
+50
-2
@@ -1,22 +1,44 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.0-beta.1 - 2026-12-02
|
||||
## 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
|
||||
|
||||
### 变更
|
||||
|
||||
- 将 Agent 消息和子 Agent 完成通知的默认行为改为 `steer`,在不支持运行中转向的 Provider 上回退到 `queue` 而不中断当前轮次 ([#11915](https://github.com/getpaseo/paseo/pull/11915))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复直接发送 `steer` 或 `interrupt` 消息时清空队列中的消息和完成通知的问题 ([#11915](https://github.com/getpaseo/paseo/pull/11915))
|
||||
- 修复排队消息批次在临时派发错误或启动超时后被丢弃而不是保留的问题 ([#11915](https://github.com/getpaseo/paseo/pull/11915))
|
||||
- 修复 Claude 将排队的 steer 作为独立轮次执行后,父 Agent 漏收后续完成通知的问题 ([#11872](https://github.com/getpaseo/paseo/pull/11872))
|
||||
|
||||
## 0.19.0 - 2026-12-03
|
||||
|
||||
- **对话中切换 Provider**:可将对话切换到其他 Provider 并保留对话内容,对话记录现在存储在主机上。([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- **排队消息重启不丢失**:排队消息现在保存在主机上,应用重新加载、切换设备或 daemon 重启后都不会丢失。([#11424](https://github.com/getpaseo/paseo/pull/11424), [#11566](https://github.com/getpaseo/paseo/pull/11566), [#11740](https://github.com/getpaseo/paseo/pull/11740))
|
||||
- **一键开关 Agent 工具**:Agent 工具现在由一个 **启用工具** 设置统一控制,包含编排、定时任务、PR 监控和浏览器分组,并默认开启。([#11189](https://github.com/getpaseo/paseo/pull/11189))
|
||||
- **已连接设备列表**:**设置 → 设备** 现在会显示哪些客户端和主机已连接,以及各自可以访问的内容。([#11209](https://github.com/getpaseo/paseo/pull/11209))
|
||||
- **插件评分卡**:应用和 paseo.sh 上的插件页面现在会显示评分卡、更新历史、相关插件和赞助链接。([#11563](https://github.com/getpaseo/paseo/pull/11563), [#11674](https://github.com/getpaseo/paseo/pull/11674), [#11691](https://github.com/getpaseo/paseo/pull/11691))
|
||||
- **插件运行确认**:应用现在会在首次运行某个主机上插件的代码前询问一次,也可以在 **通用** 设置中关闭此提示。([#11717](https://github.com/getpaseo/paseo/pull/11717))
|
||||
- **通过隧道共享服务**:可从 Scripts 菜单将正在运行的工作区服务共享到公网地址,开发服务器也会保留实时重载连接。服务现在通过 `localhost:<port>` 打开,`*.localhost` 服务地址已移除。([#11490](https://github.com/getpaseo/paseo/pull/11490))
|
||||
- **Agent 运行时更省资源**:运行中的 Agent 占用的 CPU、GPU 和电量大幅减少,状态环、加载指示器和工具调用动画也更轻量。([#11456](https://github.com/getpaseo/paseo/pull/11456), [#11474](https://github.com/getpaseo/paseo/pull/11474), [#11564](https://github.com/getpaseo/paseo/pull/11564), [#11586](https://github.com/getpaseo/paseo/pull/11586), [#11591](https://github.com/getpaseo/paseo/pull/11591),贡献者:[@djbclark](https://github.com/djbclark), [@luoph](https://github.com/luoph), [@mariotaku](https://github.com/mariotaku))
|
||||
- **更稳定的流式回复**:流式回复在到达时即显示最终格式,长回复的渲染也不再随长度增长而变慢。([#11572](https://github.com/getpaseo/paseo/pull/11572), [#11582](https://github.com/getpaseo/paseo/pull/11582),贡献者:[@luoph](https://github.com/luoph))
|
||||
- **更快的移动端启动**:移动端冷启动后会更快显示上次的工作区,在 Android 上约快 0.7 秒。([#11390](https://github.com/getpaseo/paseo/pull/11390),贡献者:[@luoph](https://github.com/luoph), [@maci0](https://github.com/maci0))
|
||||
- **桌面端浏览器配置文件**:桌面端浏览器标签页可以使用不同颜色的独立配置文件,便于在同一网站上同时登录两个账号。([#10357](https://github.com/getpaseo/paseo/pull/10357),贡献者:[@clkao](https://github.com/clkao))
|
||||
- **桌面端浏览器配置文件**:桌面端浏览器标签页可以使用不同颜色的独立配置文件,便于在同一网站上同时登录两个账号。([#10357](https://github.com/getpaseo/paseo/pull/10357), [#11772](https://github.com/getpaseo/paseo/pull/11772),贡献者:[@clkao](https://github.com/clkao))
|
||||
- **下滑收起 iOS 键盘**:向下拖动对话即可收起 iOS 键盘,键盘打开时对话控件首次点击即可生效。([#11625](https://github.com/getpaseo/paseo/pull/11625))
|
||||
|
||||
### 破坏性变更
|
||||
|
||||
- Paseo CLI 和 daemon 现在需要 Node.js 22.16.0 或更高版本 ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- 中继连接现在默认要求[受保护的端到端加密](https://paseo.sh/zh-CN/docs/security),因此 0.13.0 之前的应用无法再通过中继连接 ([#11864](https://github.com/getpaseo/paseo/pull/11864))
|
||||
|
||||
### 新增
|
||||
|
||||
@@ -37,6 +59,7 @@
|
||||
- 桌面应用的网页界面改用 Brotli 和 gzip 压缩传输,不再发送未压缩的 25 MB 包 ([#10635](https://github.com/getpaseo/paseo/pull/10635),贡献者:[@djbclark](https://github.com/djbclark))
|
||||
- 对话加载改为显示一个稳定的加载指示器,并同时显示对话和 Composer,不再闪现 **正在更新消息** ([#11575](https://github.com/getpaseo/paseo/pull/11575))
|
||||
- 恢复工作区时保持 Restoring 界面,直到工作区就绪 ([#11486](https://github.com/getpaseo/paseo/pull/11486))
|
||||
- 调整移动端应用图标大小,使其与主屏幕上的其他图标一致,并支持 Android 主题图标和 iOS Liquid Glass ([#11851](https://github.com/getpaseo/paseo/pull/11851))
|
||||
- 归档检查未提交的更改时,在 worktree 行上显示加载指示器 ([#11519](https://github.com/getpaseo/paseo/pull/11519), [#11574](https://github.com/getpaseo/paseo/pull/11574),贡献者:[@cxroop](https://github.com/cxroop))
|
||||
- 在主机选择器上显示各主机的图标和状态圆点 ([#11568](https://github.com/getpaseo/paseo/pull/11568))
|
||||
- iPhone 上按硬件键盘的 Return 键即可发送提示词,与 iPad 一致 ([#11537](https://github.com/getpaseo/paseo/pull/11537))
|
||||
@@ -45,12 +68,17 @@
|
||||
### 变更
|
||||
|
||||
- 归档时如果 worktree 有未提交的更改,除非确认删除,否则保留该 worktree ([#11430](https://github.com/getpaseo/paseo/pull/11430))
|
||||
- **新建工作区** 界面中的 **导入会话** 改为创建新的工作区 ([#11845](https://github.com/getpaseo/paseo/pull/11845))
|
||||
- 关闭带有未发送草稿的 **新建 Agent** 标签页时,会先询问是否丢弃草稿 ([#11660](https://github.com/getpaseo/paseo/pull/11660))
|
||||
- 在侧边栏中 Cmd/Ctrl+点击工作区改为打开该工作区,而不再进入选择模式 ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- 已通过 `send_agent_prompt` 向调用方汇报的 Agent 不再额外发送完成通知 ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复更改运行中 Agent 的思考强度、模式和模型后又跳回旧值的问题 ([#11850](https://github.com/getpaseo/paseo/pull/11850))
|
||||
- 修复已完成的 Agent 短暂闪回运行中状态的问题 ([#11764](https://github.com/getpaseo/paseo/pull/11764))
|
||||
- 修复对排队消息使用 **立即发送** 时取消正在运行的轮次、而不是引导该轮次的问题 ([#11827](https://github.com/getpaseo/paseo/pull/11827))
|
||||
- 修复发送失败或完成后,覆盖发送期间输入的后续草稿的问题 ([#11448](https://github.com/getpaseo/paseo/pull/11448),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复附加超过 2000 px 的图片后,该对话之后的每一轮都失败的问题 ([#5119](https://github.com/getpaseo/paseo/pull/5119),贡献者:[@RUIIIOVO](https://github.com/RUIIIOVO))
|
||||
- 修复关闭 Paseo 工具时语音模式 Agent 始终不回话的问题 ([#11161](https://github.com/getpaseo/paseo/pull/11161))
|
||||
- 修复在没有 daemon 连接时关闭语音模式后麦克风仍保持开启的问题 ([#11587](https://github.com/getpaseo/paseo/pull/11587),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
@@ -61,18 +89,25 @@
|
||||
- 修复重连复用订阅后终端输出停止的问题 ([#10433](https://github.com/getpaseo/paseo/pull/10433),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复应用在主机连接前启动时 **文件** 显示 **Host 未连接** 的问题 ([#11679](https://github.com/getpaseo/paseo/pull/11679))
|
||||
- 修复主机离线时 **创建时间** 和 **最近提示词** 排序选项消失的问题 ([#11728](https://github.com/getpaseo/paseo/pull/11728))
|
||||
- 修复在 iOS 和 Android 上横向滑动水平滚动区域时打开或关闭侧边面板的问题 ([#11841](https://github.com/getpaseo/paseo/pull/11841))
|
||||
- 修复在 iOS 上点击标题栏会将对话、Explorer 或工作区列表滚动到顶部的问题 ([#11262](https://github.com/getpaseo/paseo/pull/11262),贡献者:[@yzim](https://github.com/yzim))
|
||||
- 修复文件面板在打开过程中被关闭后,留下阻挡点击的不可见遮罩的问题 ([#11317](https://github.com/getpaseo/paseo/pull/11317),贡献者:[@LiebeLee](https://github.com/LiebeLee))
|
||||
- 修复底部面板在打开动画开始前被关闭后仍保持打开的问题 ([#11632](https://github.com/getpaseo/paseo/pull/11632))
|
||||
- 修复 Android 在选择图片期间重建应用后未附加任何内容的问题 ([#7734](https://github.com/getpaseo/paseo/pull/7734))
|
||||
- 修复在 Linux 上中键点击标签页时将选中内容粘贴到终端的问题 ([#11818](https://github.com/getpaseo/paseo/pull/11818))
|
||||
- 修复按下 Cmd/Ctrl+F 后立即输入时 **查找** 丢失前几个按键的问题 ([#11812](https://github.com/getpaseo/paseo/pull/11812))
|
||||
- 修复在网页版 Composer 中粘贴文件时插入文件路径而不是添加附件的问题 ([#11718](https://github.com/getpaseo/paseo/pull/11718))
|
||||
- 修复 **内容字体大小** 未应用到网页端对话中已有用户消息的问题 ([#11469](https://github.com/getpaseo/paseo/pull/11469),贡献者:[@bearyjd](https://github.com/bearyjd))
|
||||
- 修复 Markdown 表格单元格中的 `<br>` 拆分表格行的问题 ([#9587](https://github.com/getpaseo/paseo/pull/9587),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复网页端隐藏的对话行导致阅读位置偏移的问题 ([#11538](https://github.com/getpaseo/paseo/pull/11538),贡献者:[@kogekiplay](https://github.com/kogekiplay))
|
||||
- 修复不带结尾斜杠的工作区外文件夹链接被打开为损坏的文件标签页的问题 ([#11786](https://github.com/getpaseo/paseo/pull/11786))
|
||||
- 修复 `paseo.json` 变更后 Scripts 菜单未更新的问题 ([#11768](https://github.com/getpaseo/paseo/pull/11768),贡献者:[@odoo-mvds](https://github.com/odoo-mvds))
|
||||
- 修复工具调用详情的空状态文字紧贴屏幕边缘的问题 ([#9129](https://github.com/getpaseo/paseo/pull/9129),贡献者:[@ilteoood](https://github.com/ilteoood))
|
||||
- 修复带附件的插件斜杠命令被当作消息发送给 Agent 的问题 ([#11483](https://github.com/getpaseo/paseo/pull/11483),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 **归档已完成的 subagent** 跳过已关闭子 Agent 的问题 ([#10865](https://github.com/getpaseo/paseo/pull/10865),贡献者:[@sbhas2k](https://github.com/sbhas2k))
|
||||
- 修复 **导入会话** 遗漏最新 ACP 会话的问题 ([#10675](https://github.com/getpaseo/paseo/pull/10675))
|
||||
- 修复 **导入会话** 在 **重试** 期间隐藏 Provider 错误的问题 ([#11654](https://github.com/getpaseo/paseo/pull/11654))
|
||||
- 修复 **导入会话** 无法打开旧版自定义 Codex Provider 对话的问题 ([#11852](https://github.com/getpaseo/paseo/pull/11852))
|
||||
- 修复设置时丢弃 60 秒后才响应的 Provider 所给出的项目建议的问题 ([#11438](https://github.com/getpaseo/paseo/pull/11438),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复远程主机上的工作区显示 Open in file manager 的问题 ([#11463](https://github.com/getpaseo/paseo/pull/11463),贡献者:[@sleroq](https://github.com/sleroq))
|
||||
- 修复根目录为 `/` 的工作区无法使用 Reveal in Finder 的问题 ([#11206](https://github.com/getpaseo/paseo/pull/11206),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
@@ -85,6 +120,7 @@
|
||||
- 修复 Claude 自行开始的轮次在重新打开的对话中被隐藏、直到 **重新加载** 才显示的问题 ([#11405](https://github.com/getpaseo/paseo/pull/11405))
|
||||
- 修复 Claude Code 系统通知从对话中丢失的问题 ([#11419](https://github.com/getpaseo/paseo/pull/11419),贡献者:[@minamorl](https://github.com/minamorl))
|
||||
- 修复导入的 Claude Code 对话中缺少 Goal set 回复的问题 ([#11733](https://github.com/getpaseo/paseo/pull/11733))
|
||||
- 修复 Claude Code Stop hook 警告提示按下一个在 Paseo 中会打开 **添加项目** 的快捷键的问题 ([#11792](https://github.com/getpaseo/paseo/pull/11792))
|
||||
- 修复在已归档的 Claude 对话中列出命令时启动 Claude Code 的问题 ([#11521](https://github.com/getpaseo/paseo/pull/11521),贡献者:[@RawSalmon69](https://github.com/RawSalmon69))
|
||||
- 修复 **停止** 对无响应的 Pi 和 OMP Agent 无效的问题 ([#11618](https://github.com/getpaseo/paseo/pull/11618),贡献者:[@LouisDeconinck](https://github.com/LouisDeconinck))
|
||||
- 修复扩展处理提示词时 Pi 轮次永远无法结束的问题 ([#10572](https://github.com/getpaseo/paseo/pull/10572),贡献者:[@jsilhan](https://github.com/jsilhan))
|
||||
@@ -92,12 +128,16 @@
|
||||
- 修复扩展在回复前发送上下文时 Pi 重复显示提示词的问题 ([#11533](https://github.com/getpaseo/paseo/pull/11533),贡献者:[@Stelath](https://github.com/Stelath))
|
||||
- 修复在受信任的工作区中 Pi 对话跳过项目技能和设置的问题 ([#11527](https://github.com/getpaseo/paseo/pull/11527),贡献者:[@patrick-motard](https://github.com/patrick-motard))
|
||||
- 修复冲突解决后新建 Pi Agent 仍报旧扩展错误的问题 ([#11642](https://github.com/getpaseo/paseo/pull/11642))
|
||||
- 修复 Agent 以所选选项批准 Pi 提示时 Pi 收到取消的问题 ([#11814](https://github.com/getpaseo/paseo/pull/11814),贡献者:[@djbclark](https://github.com/djbclark))
|
||||
- 修复首次发送提示词前缺少 OMP **快速** 开关的问题 ([#11553](https://github.com/getpaseo/paseo/pull/11553))
|
||||
- 修复已完成的 OMP 表单提问不再显示提问内容和所选答案的问题 ([#11697](https://github.com/getpaseo/paseo/pull/11697), [#11706](https://github.com/getpaseo/paseo/pull/11706),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- 修复 Codex 启动失败导致 daemon 崩溃的问题 ([#11847](https://github.com/getpaseo/paseo/pull/11847),贡献者:[@xilinshancun](https://github.com/xilinshancun))
|
||||
- 修复 Codex 退出后空闲的 Codex Agent 始终不释放资源的问题 ([#11839](https://github.com/getpaseo/paseo/pull/11839),贡献者:[@michaelmwu](https://github.com/michaelmwu))
|
||||
- 修复 Codex 仍在启动时发送消息于 60 秒后报告失败的问题 ([#11547](https://github.com/getpaseo/paseo/pull/11547),贡献者:[@nonononull](https://github.com/nonononull))
|
||||
- 修复通过 `env codex` 等包装命令启动时 Codex 功能被隐藏的问题 ([#11221](https://github.com/getpaseo/paseo/pull/11221),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 Codex 异步提问的回答被拒绝的问题 ([#11225](https://github.com/getpaseo/paseo/pull/11225),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复重新打开 Codex 对话时重置其最近活动时间的问题 ([#10760](https://github.com/getpaseo/paseo/pull/10760),贡献者:[@Juns-g](https://github.com/Juns-g))
|
||||
- 修复 OpenCode 回复的段落连在一起的问题 ([#11745](https://github.com/getpaseo/paseo/pull/11745))
|
||||
- 修复 Antigravity 子 Agent 工具调用将流式回复从单词中间截断的问题 ([#11535](https://github.com/getpaseo/paseo/pull/11535),贡献者:[@Suhail](https://github.com/Suhail))
|
||||
- 修复 Antigravity 轮次在内部执行器出错后仍以完成状态结束的问题 ([#10885](https://github.com/getpaseo/paseo/pull/10885),贡献者:[@vecyang1](https://github.com/vecyang1), [@luoph](https://github.com/luoph))
|
||||
- 修复 Provider 拒绝已保存的思考强度时 ACP 对话无法重新打开的问题 ([#10333](https://github.com/getpaseo/paseo/pull/10333))
|
||||
@@ -123,12 +163,17 @@
|
||||
- 修复排队消息以之后发送的提示词的模式运行的问题 ([#11722](https://github.com/getpaseo/paseo/pull/11722))
|
||||
- 修复 `paseo ls --json` 丢失时间戳和后台任务的问题 ([#11423](https://github.com/getpaseo/paseo/pull/11423),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复 `paseo inspect` 和 `paseo ls` 隐藏 Cursor Auto 模型的问题 ([#11693](https://github.com/getpaseo/paseo/pull/11693))
|
||||
- 修复 `paseo ls --label` 使用格式错误的标签时列出所有 Agent 的问题 ([#11707](https://github.com/getpaseo/paseo/pull/11707),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复 `paseo terminal capture` 和 `paseo terminal send-keys` 忽略 `--json` 的问题 ([#11710](https://github.com/getpaseo/paseo/pull/11710),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复 `paseo terminal create --workspace` 对排在前十个之后的工作区失败的问题 ([#11799](https://github.com/getpaseo/paseo/pull/11799),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复 `paseo schedule update --model` 必须重复指定 Provider 才能成功的问题 ([#11796](https://github.com/getpaseo/paseo/pull/11796),贡献者:[@KiritoXDone](https://github.com/KiritoXDone))
|
||||
- 修复 `paseo workspace ls` 将密码错误报告为 daemon 已停止的问题 ([#11676](https://github.com/getpaseo/paseo/pull/11676),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复 `paseo daemon status` 遗漏未确认的终端清理的问题 ([#11658](https://github.com/getpaseo/paseo/pull/11658),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复 CLI 归档、分离和重新加载时为匹配完整 Agent ID 而扫描全部 Agent 历史记录的问题 ([#11617](https://github.com/getpaseo/paseo/pull/11617),贡献者:[@maci0](https://github.com/maci0))
|
||||
|
||||
### 安全
|
||||
|
||||
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
@@ -138,8 +183,11 @@
|
||||
### 插件
|
||||
|
||||
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
|
||||
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
|
||||
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
+15
-15
@@ -154,15 +154,15 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders and finish notifications default to `steer` (falling back to `queue` on providers without `steerActiveTurn`); non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt` (or `steer` in composer settings). Each kind of prompt is released this way:
|
||||
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. Finish notifications and change-request updates always queue.
|
||||
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
|
||||
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages.
|
||||
- **`steer`** from an agent sender enters the running turn without cutting it, carrying earlier agent-queued messages ahead of it while leaving human-queued items untouched in the queue. Finish notifications batch across the two-second quiet window before steering so parallel completions arrive together. If the provider cannot steer (`canSteer` is false, e.g., ACP agents) or rejects steering mid-turn without ending the turn, the daemon keeps the message queued until the turn ends rather than interrupting it.
|
||||
- **`interrupt`** is dispatched at admission the same way, replacing the running turn and carrying earlier non-human-queued messages ahead of it.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) runs immediately by itself and does **not** sweep queued messages. Queued messages stay intact in the queue track and dispatch once the turn settles, unless the queue is behind a staged provider switch (where the switch queues behind items meant for the current provider). When a non-command, non-resume direct human prompt succeeds on a held queue (after Stop or a refused start), it reopens the held queue so remaining queued items resume after the turn ends.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. Held items wait until reopened by a direct non-command prompt, a newly admitted message, or explicit Send now (`promote`). A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because an agent follow-up carries earlier agent-queued messages ahead of it. On non-steering providers, queued `steer` reports as `queue` and notes that `steer` waits until the turn ends. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
|
||||
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
|
||||
|
||||
@@ -173,8 +173,8 @@ One provider prompt has one session mode. A batch released by a steer, an interr
|
||||
A provider switch can wait in the queue too (`agent.provider.switch.request` with
|
||||
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
|
||||
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
|
||||
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
|
||||
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
what follows go to the target. A direct provider switch queues right behind any items queued for
|
||||
the current provider so those items dispatch first. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
@@ -184,10 +184,10 @@ queue holds references. An empty message is refused, and a recipient holds at mo
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
|
||||
also holds the queue: retrying by itself would be refused again and would add the prompt to the
|
||||
history each time. A message that cannot be sent is removed so that it does not block the ones
|
||||
behind it.
|
||||
admits it. A dispatch that fails transiently (busy/non-steering turn, run-start timeout, mode/RPC
|
||||
error, or rejected start) returns the batch to the queue rather than deleting it; non-busy failures
|
||||
also hold the queue until the next prompt reopens it. Only pre-dispatch unresolvable payloads (such
|
||||
as missing local attachments) or rejected out-of-band commands are discarded so they do not block later messages.
|
||||
|
||||
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
|
||||
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
|
||||
@@ -456,8 +456,8 @@ Rows take these commands:
|
||||
already started sending the row, the draft stays as it is.
|
||||
- **Cancel** withdraws the row.
|
||||
|
||||
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
|
||||
text.
|
||||
A message you send directly (`steer` or `interrupt`) runs right away without sweeping the queue track;
|
||||
queued rows stay visible in place and dispatch after the turn ends (unless held by Stop).
|
||||
|
||||
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
|
||||
row names the target.
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
|
||||
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the [queue track](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn, and a person's direct steer leaves queued rows in the queue track. Agent senders and finish notifications default to `steer` (falling back to `queue` when the provider cannot steer) and never sweep human-queued items. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
|
||||
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
|
||||
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
|
||||
|
||||
+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,5 @@
|
||||
- Switch providers mid-chat: Switch a chat to another provider and keep the conversation, with chat history now stored on the host.
|
||||
- Queue survives restarts: Queued messages now live on the host, so they survive app reloads, device switches and daemon restarts.
|
||||
- One switch for agent tools: Agent tools now sit behind one Enable tools setting with orchestration, schedules, PR watching and browser groups, and are on by default.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,5 @@
|
||||
- Switch providers mid-chat: Switch a chat to another provider and keep the conversation, with chat history now stored on the host.
|
||||
- Queue survives restarts: Queued messages now live on the host, so they survive app reloads, device switches and daemon restarts.
|
||||
- One switch for agent tools: Agent tools now sit behind one Enable tools setting with orchestration, schedules, PR watching and browser groups, and are on by default.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,5 @@
|
||||
- Switch providers mid-chat: Switch a chat to another provider and keep the conversation, with chat history now stored on the host.
|
||||
- Queue survives restarts: Queued messages now live on the host, so they survive app reloads, device switches and daemon restarts.
|
||||
- One switch for agent tools: Agent tools now sit behind one Enable tools setting with orchestration, schedules, PR watching and browser groups, and are on by default.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,5 @@
|
||||
- Switch providers mid-chat: Switch a chat to another provider and keep the conversation, with chat history now stored on the host.
|
||||
- Queue survives restarts: Queued messages now live on the host, so they survive app reloads, device switches and daemon restarts.
|
||||
- One switch for agent tools: Agent tools now sit behind one Enable tools setting with orchestration, schedules, PR watching and browser groups, and are on by default.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Changed
|
||||
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
|
||||
|
||||
Fixed
|
||||
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
|
||||
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Changed
|
||||
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
|
||||
|
||||
Fixed
|
||||
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
|
||||
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Changed
|
||||
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
|
||||
|
||||
Fixed
|
||||
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
|
||||
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Changed
|
||||
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
|
||||
|
||||
Fixed
|
||||
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
|
||||
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
|
||||
|
||||
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
|
||||
@@ -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.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.19.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37552,7 +37552,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.19.0-beta.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.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/server": "0.19.0-beta.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.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.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.0-beta.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.0-beta.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.0-beta.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.0-beta.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.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.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.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.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.0-beta.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.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40382,7 +40382,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.19.0-beta.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.0-beta.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.0-beta.1",
|
||||
"@getpaseo/highlight": "0.19.0-beta.1",
|
||||
"@getpaseo/plugin": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.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.0-beta.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.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.19.0-beta.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": {
|
||||
|
||||
@@ -1370,7 +1370,7 @@ test.describe("Agent message submission", () => {
|
||||
).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("tapping Send still steers and takes the queued row along", async () => {
|
||||
await test.step("tapping Send still steers without sweeping the queued row", async () => {
|
||||
const steeredPrompt = "Steer this turn with a tap.";
|
||||
await fillComposerDraft(page, steeredPrompt);
|
||||
await page.getByRole("button", { name: "Send and steer", exact: true }).click();
|
||||
@@ -1379,13 +1379,13 @@ test.describe("Agent message submission", () => {
|
||||
expect(request.text).toBe(steeredPrompt);
|
||||
expect(request.activeTurnBehavior).toBe("steer");
|
||||
gate.accept(1);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
|
||||
).toHaveCount(1);
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
|
||||
const steeredMessage = page.getByTestId("user-message").filter({ hasText: steeredPrompt });
|
||||
await expect(steeredMessage).toHaveCount(1);
|
||||
await expect(steeredMessage).toHaveAttribute("aria-busy", "false");
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(1);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
|
||||
).toHaveCount(1);
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.19.0-beta.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.0-beta.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.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/server": "0.19.0-beta.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",
|
||||
|
||||
@@ -50,7 +50,7 @@ export function addSendOptions(cmd: Command): Command {
|
||||
.addOption(
|
||||
new Option(
|
||||
"--behavior <behavior>",
|
||||
"Leave out unless the message cannot wait. From an agent (PASEO_AGENT_ID set): queue (default) waits for the running turn to end, steer joins it, interrupt replaces it. From a person: interrupt (default), steer, or queue",
|
||||
"From an agent (PASEO_AGENT_ID set): steer (default) joins the running turn or waits until it ends if the provider cannot steer, queue waits for the running turn to end, interrupt replaces it. From a person: interrupt (default), steer, or queue",
|
||||
).choices(["queue", "steer", "interrupt"]),
|
||||
)
|
||||
.option("--no-wait", "Return immediately without waiting for completion");
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.19.0-beta.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.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.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.0-beta.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.0-beta.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.0-beta.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.0-beta.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.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.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.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.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.0-beta.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.0-beta.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.0-beta.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.0-beta.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.0-beta.1",
|
||||
"@getpaseo/highlight": "0.19.0-beta.1",
|
||||
"@getpaseo/plugin": "0.19.0-beta.1",
|
||||
"@getpaseo/protocol": "0.19.0-beta.1",
|
||||
"@getpaseo/relay": "0.19.0-beta.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",
|
||||
|
||||
@@ -18408,3 +18408,267 @@ test.each([
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("streamAgent throws AgentTurnBusyError and non-replacing steerOrReplaceActiveTurn returns busy without replacing an active turn", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-non-replacing-steer-"));
|
||||
class RejectingSteerSession extends SteeringTestSession {
|
||||
cancelCalls = 0;
|
||||
override async steerActiveTurn() {
|
||||
return { status: "unavailable" as const };
|
||||
}
|
||||
override async cancelRun() {
|
||||
this.cancelCalls += 1;
|
||||
await super.cancelRun();
|
||||
}
|
||||
}
|
||||
const session = new RejectingSteerSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
try {
|
||||
await startAgentRun(manager, agent.id, "initial turn", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
await providerStarted;
|
||||
|
||||
expect(() => manager.streamAgent(agent.id, "competing turn")).toThrow(AgentTurnBusyError);
|
||||
|
||||
const steerResult = await manager.steerOrReplaceActiveTurn(agent.id, "mid-turn steer", {
|
||||
allowReplace: false,
|
||||
});
|
||||
expect(steerResult).toEqual({ status: "busy" });
|
||||
expect(session.cancelCalls).toBe(0);
|
||||
expect(session.startPrompts).toEqual(["initial turn"]);
|
||||
|
||||
await expect(
|
||||
sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "mid-turn steer",
|
||||
activeTurnBehavior: "steer",
|
||||
replaceRunning: false,
|
||||
logger,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AgentTurnBusyError);
|
||||
|
||||
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
|
||||
|
||||
await expect(
|
||||
manager.steerOrReplaceActiveTurn(agent.id, "after settle", { allowReplace: false }),
|
||||
).resolves.toEqual({ status: "inactive" });
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("bundled user messages keep distinct row messageIds while preserving outer providerMessageId for rewind", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-bundled-rewind-"));
|
||||
const rewindMessageIds: string[] = [];
|
||||
class BundledRewindSession extends SteeringTestSession {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsRewindFiles: true,
|
||||
};
|
||||
readonly history: AgentStreamEvent[] = [];
|
||||
override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
|
||||
this.startPrompts.push(prompt);
|
||||
const turnId = `active-turn-${++this.startCount}`;
|
||||
const text = typeof prompt === "string" ? prompt : "structured";
|
||||
this.history.push({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
item: { type: "user_message", text, messageId: "provider-msg-bundle" },
|
||||
});
|
||||
setTimeout(() => {
|
||||
this.pushEvent({ type: "turn_started", provider: this.provider, turnId });
|
||||
this.pushEvent({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
text,
|
||||
messageId: "provider-msg-bundle",
|
||||
clientMessageId: "user-1",
|
||||
},
|
||||
});
|
||||
this.pushEvent({ type: "turn_completed", provider: this.provider, turnId });
|
||||
}, 0);
|
||||
return { turnId };
|
||||
}
|
||||
override async *streamHistory() {
|
||||
for (const event of this.history) yield event;
|
||||
}
|
||||
override async revertFiles({ messageId }: { messageId: string }) {
|
||||
rewindMessageIds.push(messageId);
|
||||
}
|
||||
}
|
||||
const session = new BundledRewindSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
const bundled = [
|
||||
formatAgentMessage({ id: "user-1", source: null, text: "First bundled prompt" }),
|
||||
formatAgentMessage({ id: "user-2", source: null, text: "Second bundled prompt" }),
|
||||
].join("\n\n");
|
||||
await startAgentRun(manager, agent.id, bundled, logger, {
|
||||
runOptions: { clientMessageId: "user-1" },
|
||||
});
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
|
||||
|
||||
const rows = (await manager.getTimeline(agent.id)).filter(
|
||||
(item): item is Extract<typeof item, { type: "user_message" }> =>
|
||||
item.type === "user_message",
|
||||
);
|
||||
expect(rows.map((item) => ({ messageId: item.messageId, text: item.text }))).toEqual([
|
||||
{ messageId: "user-1", text: "First bundled prompt" },
|
||||
{ messageId: "user-2", text: "Second bundled prompt" },
|
||||
]);
|
||||
|
||||
await manager.rewind(agent.id, "user-2", "files");
|
||||
expect(rewindMessageIds).toEqual(["provider-msg-bundle"]);
|
||||
|
||||
session.history.push(
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "Third prompt", messageId: "provider-msg-3" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "Third reply" },
|
||||
},
|
||||
);
|
||||
expect(await manager.reconcileProviderHistory(agent.id)).toEqual({ kind: "appended" });
|
||||
const reconciledTexts = (await manager.getTimeline(agent.id))
|
||||
.filter((item) => item.type === "user_message" || item.type === "assistant_message")
|
||||
.map((item) => item.text);
|
||||
expect(reconciledTexts).toEqual([
|
||||
"First bundled prompt",
|
||||
"Second bundled prompt",
|
||||
"Third prompt",
|
||||
"Third reply",
|
||||
]);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("initialTimeline preserves outer providerMessageId across split bundled user messages for rewind and history sync", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-imported-bundled-rewind-"));
|
||||
const rewindMessageIds: string[] = [];
|
||||
const bundled = [
|
||||
formatAgentMessage({ id: "user-1", source: null, text: "First imported prompt" }),
|
||||
formatAgentMessage({ id: "user-2", source: null, text: "Second imported prompt" }),
|
||||
].join("\n\n");
|
||||
const history: AgentStreamEvent[] = [
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: bundled, messageId: "provider-imported-bundle" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "Imported reply" },
|
||||
},
|
||||
];
|
||||
class ImportedBundledSession extends TestAgentSession {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsRewindFiles: true,
|
||||
};
|
||||
readonly initialTimeline = history.flatMap((event) =>
|
||||
event.type === "timeline" ? [{ item: event.item }] : [],
|
||||
);
|
||||
override async *streamHistory() {
|
||||
for (const event of history) yield event;
|
||||
}
|
||||
override async revertFiles({ messageId }: { messageId: string }) {
|
||||
rewindMessageIds.push(messageId);
|
||||
}
|
||||
}
|
||||
const session = new ImportedBundledSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
const importedRows = (await manager.getTimeline(agent.id)).filter(
|
||||
(item): item is Extract<typeof item, { type: "user_message" }> =>
|
||||
item.type === "user_message",
|
||||
);
|
||||
expect(
|
||||
importedRows.map((item) => ({
|
||||
messageId: item.messageId,
|
||||
clientMessageId: item.clientMessageId,
|
||||
text: item.text,
|
||||
})),
|
||||
).toEqual([
|
||||
{
|
||||
messageId: "provider-imported-bundle",
|
||||
clientMessageId: "user-1",
|
||||
text: "First imported prompt",
|
||||
},
|
||||
{
|
||||
messageId: "provider-imported-bundle",
|
||||
clientMessageId: "user-2",
|
||||
text: "Second imported prompt",
|
||||
},
|
||||
]);
|
||||
|
||||
await manager.rewind(agent.id, "provider-imported-bundle", "files");
|
||||
expect(rewindMessageIds).toEqual(["provider-imported-bundle"]);
|
||||
|
||||
history.push(
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: "Next prompt", messageId: "provider-next" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: "Next reply" },
|
||||
},
|
||||
);
|
||||
expect(await manager.reconcileProviderHistory(agent.id)).toEqual({ kind: "appended" });
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -583,7 +583,7 @@ export interface AgentManagerOptions {
|
||||
}
|
||||
|
||||
export type ActiveTurnSteerDispatchResult =
|
||||
| { status: "inactive" | "steered" }
|
||||
| { status: "inactive" | "steered" | "busy" }
|
||||
| { status: "replaced"; iterator: AsyncGenerator<AgentStreamEvent> };
|
||||
|
||||
export interface AgentPromptSubmissionOptions extends AgentRunOptions {
|
||||
@@ -594,13 +594,15 @@ export interface AgentPromptSubmissionOptions extends AgentRunOptions {
|
||||
export interface AgentPromptSteerOptions extends AgentSteerOptions {
|
||||
/** Daemon timeline metadata for uploaded image attachments; never forwarded to providers. */
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
/** Whether unavailable/rejected mid-turn steering may cancel and replace the running turn. */
|
||||
allowReplace?: boolean;
|
||||
}
|
||||
|
||||
function stripSteerOptions(
|
||||
options?: AgentPromptSteerOptions,
|
||||
): AgentPromptSubmissionOptions | undefined {
|
||||
if (!options) return undefined;
|
||||
const { clearPendingPermissions: _, ...runOptions } = options;
|
||||
const { clearPendingPermissions: _, allowReplace: _allowReplace, ...runOptions } = options;
|
||||
return runOptions;
|
||||
}
|
||||
|
||||
@@ -612,7 +614,7 @@ function toProviderRunOptions(options?: AgentPromptSubmissionOptions): AgentRunO
|
||||
|
||||
function toProviderSteerOptions(options?: AgentPromptSteerOptions): AgentSteerOptions | undefined {
|
||||
if (!options) return undefined;
|
||||
const { uploadedImages: _, ...providerOptions } = options;
|
||||
const { uploadedImages: _, allowReplace: _allowReplace, ...providerOptions } = options;
|
||||
return providerOptions;
|
||||
}
|
||||
|
||||
@@ -4877,7 +4879,7 @@ export class AgentManager {
|
||||
},
|
||||
"agent.manager.stream.reject",
|
||||
);
|
||||
throw new Error(`Agent ${agentId} already has an active run`);
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} already has an active run`);
|
||||
}
|
||||
|
||||
const agent = existingAgent;
|
||||
@@ -5130,6 +5132,7 @@ export class AgentManager {
|
||||
options?: AgentPromptSteerOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<ActiveTurnSteerDispatchResult> {
|
||||
const allowReplace = options?.allowReplace ?? true;
|
||||
// A turn that is still starting has no id to steer yet. Replacing it would drop its
|
||||
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
|
||||
await this.runs.waitForForegroundStart(agentId);
|
||||
@@ -5168,6 +5171,11 @@ export class AgentManager {
|
||||
return { status: "inactive" };
|
||||
}
|
||||
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
if (!allowReplace) {
|
||||
return { status: "busy" };
|
||||
}
|
||||
|
||||
await this.beforeSteerUnavailableFallback?.({ agentId, expectedTurnId });
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return {
|
||||
@@ -7638,17 +7646,21 @@ export class AgentManager {
|
||||
text: submittedPromptText(prompt),
|
||||
clientMessageId,
|
||||
...(images.length > 0 ? { images } : {}),
|
||||
...(options?.messageId ? { messageId: options.messageId } : {}),
|
||||
});
|
||||
const providerPromptText = options?.providerPromptText ?? renderProviderPromptText(prompt);
|
||||
const writes: Promise<void>[] = [];
|
||||
for (const item of items) {
|
||||
// Human attempts stay in history on rejection; delivery notifications require acceptance.
|
||||
if (outcome === "rejected" && item.type !== "user_message") continue;
|
||||
// Give each projected user row its own submitted display ID rather than cloning one shared outer ID.
|
||||
const submittedItem =
|
||||
item.type === "user_message" && options?.messageId
|
||||
? { ...item, messageId: item.clientMessageId ?? options.messageId }
|
||||
: item;
|
||||
writes.push(
|
||||
this.recordSubmittedPromptItem(agent, item, {
|
||||
this.recordSubmittedPromptItem(agent, submittedItem, {
|
||||
...options,
|
||||
...(item.type === "user_message" ? { providerPromptText } : {}),
|
||||
...(submittedItem.type === "user_message" ? { providerPromptText } : {}),
|
||||
...(outcome === "rejected" ? { rejected: true } : {}),
|
||||
}),
|
||||
);
|
||||
@@ -7685,8 +7697,9 @@ export class AgentManager {
|
||||
agent: ActiveManagedAgent,
|
||||
item: Extract<AgentTimelineItem, { type: "user_message" }>,
|
||||
turnId?: string,
|
||||
providerMessageId = item.messageId,
|
||||
): Promise<boolean> {
|
||||
const { clientMessageId, messageId } = item;
|
||||
const { clientMessageId } = item;
|
||||
if (!clientMessageId) return false;
|
||||
const scope: TimelineScope = { agentId: agent.id };
|
||||
const existing = await this.timeline.findSubmittedPrompt(scope, clientMessageId);
|
||||
@@ -7700,7 +7713,7 @@ export class AgentManager {
|
||||
messageId: clientMessageId,
|
||||
},
|
||||
{
|
||||
...(messageId ? { providerMessageId: messageId } : {}),
|
||||
...(providerMessageId ? { providerMessageId } : {}),
|
||||
providerPromptText: item.text,
|
||||
...(turnId ? { turnId } : {}),
|
||||
},
|
||||
@@ -7708,8 +7721,8 @@ export class AgentManager {
|
||||
return true;
|
||||
}
|
||||
if (existing.item.type !== "user_message") return false;
|
||||
if (messageId) {
|
||||
await this.timeline.attachProviderMessageId(scope, clientMessageId, messageId, {
|
||||
if (providerMessageId) {
|
||||
await this.timeline.attachProviderMessageId(scope, clientMessageId, providerMessageId, {
|
||||
providerPromptText: item.text,
|
||||
});
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
AgentTurnBusyError,
|
||||
AgentTurnChangedError,
|
||||
AgentTurnStartRejectedError,
|
||||
type PromptDispatchDisposition,
|
||||
type PromptDispatchResult,
|
||||
} from "../agent-prompt.js";
|
||||
@@ -73,6 +72,8 @@ interface Admitted extends QueuedContent {
|
||||
urgency: QueuedMessageUrgency | null;
|
||||
/** A Stop found it in the queue. It waits for a prompt admitted after that Stop. */
|
||||
held: boolean;
|
||||
/** True when explicitly released by Send now (`promote`) and allowed to replace a non-steering turn. */
|
||||
promoted: boolean;
|
||||
outOfBandDeclined: boolean;
|
||||
/** Settles once the store holds it. Nothing dispatches it before that. */
|
||||
saved: Promise<void>;
|
||||
@@ -107,7 +108,7 @@ interface Inbox {
|
||||
restoring: boolean;
|
||||
/** The quiet window while collecting, the busy retry while waiting. */
|
||||
cancelTimer(): void;
|
||||
cancelCap(): void;
|
||||
cancelCap: (() => void) | null;
|
||||
/** A polling queue step is already in line behind the recipient's current operation. */
|
||||
advancing: boolean;
|
||||
/** Stops seen. A queue step reserved before a Stop is void, whatever is admitted afterwards. */
|
||||
@@ -120,6 +121,8 @@ interface DispatchRequest {
|
||||
uploadedImages: readonly UploadedImage[];
|
||||
activeTurnBehavior: "steer" | "interrupt";
|
||||
idleOnly: boolean;
|
||||
/** True when this batch may interrupt/replace an active turn if steering is unavailable. */
|
||||
replaceRunning: boolean;
|
||||
/**
|
||||
* Claim this exact prompt at provider admission. A withdrawn message or a Stop that reached
|
||||
* the recipient first invalidates it.
|
||||
@@ -206,15 +209,15 @@ export interface AgentMessageDelivery {
|
||||
}): Promise<void>;
|
||||
/**
|
||||
* Admit a message and resolve once it is saved. A queued one waits for the running turn to
|
||||
* end; a steer or an interrupt releases at once, with everything queued before it.
|
||||
* end; a steer or an interrupt releases at once, and human or promoted ones take queued items
|
||||
* ahead of them.
|
||||
*/
|
||||
enqueue(message: Message): Promise<AgentMessageReceipt>;
|
||||
/**
|
||||
* Send a prompt that does not wait its turn. Compatible messages admitted before it go ahead
|
||||
* of it in the same provider prompt, so none starts a turn of its own afterwards. When a
|
||||
* boundary (conflicting session mode, queued non-agent command, or provider switch) prevents
|
||||
* coalescing, the prompt is queued behind those messages and releases the first group at once.
|
||||
* A direct command or restart-resume travels alone.
|
||||
* Send a prompt directly without sweeping queued messages. Queued messages remain in the queue
|
||||
* and dispatch once the turn settles. A non-command prompt that starts after a Stop reopens any
|
||||
* Stop-held queue so it drains after this turn. A direct provider switch behind queued messages
|
||||
* for the current provider queues behind them so they run on the current provider first.
|
||||
*/
|
||||
sendDirect<Result extends PromptDispatchResult>(
|
||||
direct: DirectPrompt,
|
||||
@@ -261,6 +264,12 @@ export interface AgentMessageDelivery {
|
||||
const isQueued = (message: Admitted): boolean => message.state === "queued";
|
||||
const isWithdrawn = (message: Admitted): boolean => message.state === "withdrawn";
|
||||
const isUrgent = (message: Admitted): boolean => isQueued(message) && message.urgency !== null;
|
||||
const isHumanQueued = (message: Admitted): boolean =>
|
||||
message.source === null && message.urgency === null;
|
||||
const isDirectUrgent = (message: Admitted): boolean =>
|
||||
isUrgent(message) && (message.promoted || message.source === null);
|
||||
const canInterruptOrDirectSteer = (message: Admitted): boolean =>
|
||||
isUrgent(message) && (message.urgency === "interrupt" || isDirectUrgent(message));
|
||||
const isOfferable = (message: Admitted): boolean =>
|
||||
isQueued(message) &&
|
||||
!message.outOfBandDeclined &&
|
||||
@@ -376,39 +385,10 @@ function boundaryOfAdmitted(message: Admitted): DispatchBoundary {
|
||||
};
|
||||
}
|
||||
|
||||
function boundaryOfDirect(input: {
|
||||
direct: DirectPrompt;
|
||||
includeProviderSwitch: boolean;
|
||||
}): DispatchBoundary {
|
||||
return {
|
||||
prompt: input.direct.prompt,
|
||||
source: input.direct.source,
|
||||
sessionMode: input.direct.sessionMode,
|
||||
...(input.includeProviderSwitch ? { providerSwitch: input.direct.providerSwitch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function modeGroups(messages: readonly Admitted[]): Admitted[][] {
|
||||
return dispatchGroups({ entries: messages, boundaryOf: boundaryOfAdmitted });
|
||||
}
|
||||
|
||||
function canCoalesceDirect(input: { ahead: readonly Admitted[]; direct: DirectPrompt }): boolean {
|
||||
// A direct provider switch only carries a Stop-held queue when every held message has no
|
||||
// explicit sessionMode and the switch itself requests no mode override. Any unheld message
|
||||
// or explicit mode belongs to the current provider and must not move across providers.
|
||||
const carriesHeldSwitch =
|
||||
Boolean(input.direct.providerSwitch) &&
|
||||
!input.direct.providerSwitch?.modeId &&
|
||||
input.direct.sessionMode === undefined &&
|
||||
input.ahead.length > 0 &&
|
||||
input.ahead.every((message) => message.held && message.sessionMode === undefined);
|
||||
const entries: DispatchBoundary[] = [
|
||||
...input.ahead.map(boundaryOfAdmitted),
|
||||
boundaryOfDirect({ direct: input.direct, includeProviderSwitch: !carriesHeldSwitch }),
|
||||
];
|
||||
return dispatchGroups({ entries, boundaryOf: (entry) => entry }).length <= 1;
|
||||
}
|
||||
|
||||
function toUploadedImageAttachments(
|
||||
uploadedImages: readonly UploadedImage[] | undefined,
|
||||
): Array<UploadedFileAttachment & { role: "image" }> {
|
||||
@@ -488,6 +468,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
|
||||
const isRunning = (recipientId: string): boolean =>
|
||||
Boolean(dependencies.isRunning?.(recipientId));
|
||||
const canSteer = (recipientId: string): boolean =>
|
||||
dependencies.canSteer ? dependencies.canSteer(recipientId) : true;
|
||||
const isHeld = (recipientId: string): boolean => inboxes.get(recipientId)?.phase === "held";
|
||||
|
||||
function report(error: unknown, recipientId: string, messageIds: readonly string[] = []): void {
|
||||
@@ -544,11 +526,18 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
function requestFor(
|
||||
recipientId: string,
|
||||
batch: Ready[],
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
options: {
|
||||
idleOnly: boolean;
|
||||
activeTurnBehavior?: QueuedMessageUrgency;
|
||||
allowReplace?: boolean;
|
||||
},
|
||||
): DispatchRequest {
|
||||
const { idleOnly, activeTurnBehavior, allowReplace = false } = options;
|
||||
const messages = messagesOf(batch);
|
||||
const resolvedBehavior =
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer");
|
||||
return {
|
||||
recipientId,
|
||||
idleOnly,
|
||||
@@ -561,9 +550,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
prompt: formatBatch(batch),
|
||||
uploadedImages: uploadedImagesOf(batch),
|
||||
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
|
||||
activeTurnBehavior:
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
|
||||
activeTurnBehavior: resolvedBehavior,
|
||||
replaceRunning: !idleOnly && (resolvedBehavior === "interrupt" || allowReplace),
|
||||
// Every message in a batch belongs to one compatible mode group.
|
||||
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
providerSwitch: messages[0]?.providerSwitch,
|
||||
@@ -572,9 +560,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
};
|
||||
}
|
||||
|
||||
function clearCap(inbox: Inbox): void {
|
||||
inbox.cancelCap?.();
|
||||
inbox.cancelCap = null;
|
||||
}
|
||||
|
||||
function retire(recipientId: string, inbox: Inbox): void {
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
clearCap(inbox);
|
||||
if (inboxes.get(recipientId) === inbox) inboxes.delete(recipientId);
|
||||
}
|
||||
|
||||
@@ -713,13 +706,68 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
|
||||
}
|
||||
|
||||
async function clearUrgency(recipientId: string, messages: Admitted[]): Promise<void> {
|
||||
if (!messages.length) return;
|
||||
for (const message of messages) {
|
||||
message.urgency = null;
|
||||
message.promoted = false;
|
||||
}
|
||||
const ids = idsOf(messages);
|
||||
await write(store.clearUrgency(recipientId, ids), recipientId, ids);
|
||||
}
|
||||
|
||||
/** Return `"retry"` to loop with remaining messages, or `"done"` once handled. */
|
||||
async function handleDispatchError(input: {
|
||||
error: unknown;
|
||||
recipientId: string;
|
||||
messages: Admitted[];
|
||||
request: DispatchRequest;
|
||||
stopped: () => boolean;
|
||||
}): Promise<"retry" | "done"> {
|
||||
const { error, recipientId, messages, request, stopped } = input;
|
||||
// A Stop reached the recipient before the provider admitted the prompt.
|
||||
if (stopped()) {
|
||||
await handBack(recipientId, messages);
|
||||
return "done";
|
||||
}
|
||||
// A withdrawal invalidated this exact prompt, or a steer's turn ended first: try again.
|
||||
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
|
||||
await handBack(recipientId, messages);
|
||||
return "retry";
|
||||
}
|
||||
if (error instanceof AgentTurnBusyError) {
|
||||
await handBack(recipientId, messages);
|
||||
// A non-replacing steer that found a busy/non-steering turn drops its urgency so it
|
||||
// waits for turn end rather than spinning immediately.
|
||||
if (!request.idleOnly && !request.replaceRunning && request.activeTurnBehavior === "steer") {
|
||||
await clearUrgency(recipientId, messages);
|
||||
}
|
||||
return "done";
|
||||
}
|
||||
// Shutdown cut this dispatch off. The next start tries it again.
|
||||
if (closed) {
|
||||
await handBack(recipientId, messages);
|
||||
return "done";
|
||||
}
|
||||
// Transient timeouts, non-fatal RPC failures, and rejected turn starts stay queued
|
||||
// and hold until the next user prompt instead of dropping batches.
|
||||
await handBack(recipientId, messages);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox) hold(recipientId, inbox);
|
||||
report(error, recipientId, request.messageIds);
|
||||
return "done";
|
||||
}
|
||||
|
||||
/** Dispatch one batch. A batch that finds the recipient stopped, or busy when idle-only, stays queued. */
|
||||
async function deliver(
|
||||
recipientId: string,
|
||||
batch: Admitted[],
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
options: {
|
||||
idleOnly: boolean;
|
||||
activeTurnBehavior?: QueuedMessageUrgency;
|
||||
allowReplace?: boolean;
|
||||
},
|
||||
): Promise<void> {
|
||||
for (;;) {
|
||||
const prepared = await prepare(recipientId, batch);
|
||||
@@ -732,35 +780,22 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
|
||||
let disposition: PromptDispatchDisposition;
|
||||
const request = requestFor(recipientId, dispatching, stopped, options);
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
disposition = await dependencies.dispatch(request);
|
||||
const disposition = await dependencies.dispatch(request);
|
||||
return complete(recipientId, messages, disposition);
|
||||
} catch (error) {
|
||||
// A Stop reached the recipient before the provider admitted the prompt.
|
||||
if (stopped()) return handBack(recipientId, messages);
|
||||
// A withdrawal invalidated this exact prompt; the rest goes again without it.
|
||||
// A steer whose turn ended first goes again, into the next turn or as a new one.
|
||||
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
if (error instanceof AgentTurnBusyError && request.idleOnly)
|
||||
return handBack(recipientId, messages);
|
||||
// The provider refused to start a turn. Retrying by itself would refuse again and add
|
||||
// the prompt to the history each time, so the queue waits for the next prompt.
|
||||
if (error instanceof AgentTurnStartRejectedError) {
|
||||
await handBack(recipientId, messages);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox) hold(recipientId, inbox);
|
||||
return report(error, recipientId, request.messageIds);
|
||||
}
|
||||
// Shutdown cut this dispatch off. The next start tries it again.
|
||||
if (closed) return handBack(recipientId, messages);
|
||||
return discard(recipientId, messages, error);
|
||||
const outcome = await handleDispatchError({
|
||||
error,
|
||||
recipientId,
|
||||
messages,
|
||||
request,
|
||||
stopped,
|
||||
});
|
||||
if (outcome === "retry") continue;
|
||||
return;
|
||||
}
|
||||
return complete(recipientId, messages, disposition);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,7 +821,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await handBack(recipientId, [message]);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, dispatching, true, stopped);
|
||||
const request = requestFor(recipientId, dispatching, stopped, { idleOnly: true });
|
||||
try {
|
||||
const accepted = await tryRunOutOfBand(request, () => {
|
||||
if (!request.admit()) throw new Error("Queued agent message was withdrawn");
|
||||
@@ -818,26 +853,44 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<boolean> {
|
||||
const last = ahead.findLastIndex(isUrgent);
|
||||
if (last < 0) return false;
|
||||
const released = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = released;
|
||||
const prefix = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = prefix;
|
||||
if (!first) return false;
|
||||
// Only releasing the switch itself replaces the running turn with it.
|
||||
if (first.providerSwitch && !isUrgent(first)) return false;
|
||||
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
|
||||
const behavior: QueuedMessageUrgency = released.some(
|
||||
(message) => message.urgency === "interrupt",
|
||||
)
|
||||
// Do not jump over a queued provider switch ahead of urgent items.
|
||||
const segment = first.providerSwitch ? prefix : beforeSwitch(prefix);
|
||||
const behavior: QueuedMessageUrgency = prefix.some((message) => message.urgency === "interrupt")
|
||||
? "interrupt"
|
||||
: "steer";
|
||||
const sweepsHumanQueued = prefix.some(isDirectUrgent);
|
||||
const replaceActiveTurn = behavior === "interrupt" || sweepsHumanQueued;
|
||||
const running = isRunning(recipientId);
|
||||
// While a turn is running, agent steers and interrupts leave human-queued items untouched.
|
||||
// Once idle, release in strict FIFO order so agent steers never overtake waiting human items.
|
||||
const released =
|
||||
sweepsHumanQueued || !running
|
||||
? segment
|
||||
: segment.filter((message) => !isHumanQueued(message));
|
||||
const [head] = released;
|
||||
if (!head) return false;
|
||||
const now = head.providerSwitch ? [head] : (modeGroups(released)[0] ?? []);
|
||||
// A non-steering provider keeps agent/finish steer messages queued until turn end rather
|
||||
// than interrupting it. Human promotions ("Send now") and interrupts still replace it.
|
||||
if (running && behavior === "steer" && !replaceActiveTurn && !canSteer(recipientId)) {
|
||||
await clearUrgency(recipientId, released);
|
||||
return false;
|
||||
}
|
||||
// The rest follows when the turn these start ends. Persist the downgrade before dispatching
|
||||
// so a daemon restart while the first group runs does not revive consumed urgency.
|
||||
const deferred = released.slice(now.length);
|
||||
if (deferred.length) {
|
||||
for (const message of deferred) message.urgency = null;
|
||||
const deferredIds = idsOf(deferred);
|
||||
await write(store.clearUrgency(recipientId, deferredIds), recipientId, deferredIds);
|
||||
}
|
||||
await deliver(recipientId, now, false, stopped, behavior);
|
||||
const nowIds = new Set(idsOf(now));
|
||||
const deferred = prefix.filter((message) => isUrgent(message) && !nowIds.has(message.id));
|
||||
await clearUrgency(recipientId, deferred);
|
||||
await deliver(recipientId, now, stopped, {
|
||||
idleOnly: !replaceActiveTurn && isHumanQueued(head),
|
||||
activeTurnBehavior: behavior,
|
||||
allowReplace: replaceActiveTurn,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -866,7 +919,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (running()) await offerOutOfBand(recipientId, beforeSwitch(ahead), stopped, running);
|
||||
// Later mode groups stay queued for the turn ends that follow.
|
||||
if (waiting() && !isRunning(recipientId))
|
||||
await deliver(recipientId, modeGroups(ahead.filter(isQueued))[0] ?? [], true, stopped);
|
||||
await deliver(recipientId, modeGroups(ahead.filter(isQueued))[0] ?? [], stopped, {
|
||||
idleOnly: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -896,12 +951,16 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (closed || !inbox || inbox.phase === "held" || inbox.restoring) return;
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
clearCap(inbox);
|
||||
inbox.phase = "waiting";
|
||||
const running = isRunning(recipientId);
|
||||
if (running) inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
|
||||
const nothingToOffer = !dependencies.tryRunOutOfBand || !inbox.messages.some(isOfferable);
|
||||
if (running && nothingToOffer) return;
|
||||
const hasSteerableUrgent = inbox.messages.some(
|
||||
(message) =>
|
||||
canInterruptOrDirectSteer(message) || (isUrgent(message) && canSteer(recipientId)),
|
||||
);
|
||||
const hasOfferable = Boolean(dependencies.tryRunOutOfBand) && inbox.messages.some(isOfferable);
|
||||
if (running && !hasOfferable && !hasSteerableUrgent) return;
|
||||
nudge(recipientId, inbox);
|
||||
}
|
||||
|
||||
@@ -911,7 +970,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
phase: "waiting",
|
||||
restoring: false,
|
||||
cancelTimer: () => {},
|
||||
cancelCap: () => {},
|
||||
cancelCap: null,
|
||||
advancing: false,
|
||||
stops: 0,
|
||||
};
|
||||
@@ -926,10 +985,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
|
||||
else inbox.messages.push(item);
|
||||
inbox.cancelTimer();
|
||||
if (item.urgency) {
|
||||
// A steer or an interrupt does not wait: it closes the window and takes the queue along. Its place
|
||||
// is reserved now, so a prompt admitted after it cannot take it away.
|
||||
inbox.cancelCap();
|
||||
const batchesInQuietWindow =
|
||||
item.source?.kind === "agent-notification" && item.urgency !== "interrupt";
|
||||
if (item.urgency && !batchesInQuietWindow) {
|
||||
// A steer or an interrupt closes the window and releases at once without waiting for the
|
||||
// quiet spell; reserving its place now stops a later prompt from overtaking it.
|
||||
clearCap(inbox);
|
||||
inbox.phase = "waiting";
|
||||
lineUp(item.recipientId, inbox);
|
||||
return;
|
||||
@@ -937,15 +998,19 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (!item.source) {
|
||||
// A non-agent queued message skips the coalescing quiet window: it starts a turn now if the
|
||||
// recipient is idle, or waits for the running turn to end.
|
||||
inbox.cancelCap();
|
||||
clearCap(inbox);
|
||||
inbox.phase = "waiting";
|
||||
attempt(item.recipientId);
|
||||
return;
|
||||
}
|
||||
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(item.recipientId));
|
||||
if (inbox.phase === "collecting") return;
|
||||
// A new window. It closes after a quiet spell, and no later than the cap.
|
||||
inbox.phase = "collecting";
|
||||
const hasWaitingHuman =
|
||||
inbox.phase === "waiting" &&
|
||||
inbox.messages.some((entry) => isQueued(entry) && entry.source === null);
|
||||
if (inbox.phase === "collecting" || (hasWaitingHuman && inbox.cancelCap)) return;
|
||||
// Keep `waiting` intact when a human prompt is waiting so turn end drains immediately, while
|
||||
// still capping continuous finish reports at MAX_COLLECTING_MS.
|
||||
if (!hasWaitingHuman) inbox.phase = "collecting";
|
||||
inbox.cancelCap = schedule(MAX_COLLECTING_MS, () => attempt(item.recipientId));
|
||||
}
|
||||
|
||||
@@ -968,6 +1033,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
resolve,
|
||||
reject,
|
||||
state: "queued",
|
||||
promoted: false,
|
||||
outOfBandDeclined: false,
|
||||
saved: Promise.resolve(),
|
||||
persisted: false,
|
||||
@@ -984,7 +1050,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
guidance: describeAgentMessage({
|
||||
activeTurnBehavior,
|
||||
running: isRunning(recipientId),
|
||||
canSteer: Boolean(dependencies.canSteer?.(recipientId)),
|
||||
canSteer: canSteer(recipientId),
|
||||
immediateWhenIdle: !source,
|
||||
}),
|
||||
};
|
||||
@@ -1043,74 +1109,49 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
}
|
||||
}
|
||||
|
||||
function join(riders: Ready[], direct: DirectPrompt): JoinedPrompt {
|
||||
if (!riders.length) {
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
};
|
||||
}
|
||||
// Sharing a prompt with queued messages, each entry needs its own marker to stay
|
||||
// a separate row with its own identity.
|
||||
const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId);
|
||||
const queued = messagesOf(riders);
|
||||
function prepareDirectPrompt(direct: DirectPrompt): JoinedPrompt {
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: combine([...riders.map(envelopeEntry), own.prompt]),
|
||||
uploadedImages: [...uploadedImagesOf(riders), ...(direct.uploadedImages ?? [])],
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode:
|
||||
direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
unarchive: direct.unarchive !== false || queued.some((message) => message.unarchive),
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Messages that rode a direct prompt are delivered when the provider admits that prompt.
|
||||
* Until it answers, nothing later may pass them.
|
||||
*/
|
||||
async function ride(
|
||||
recipientId: string,
|
||||
riders: Admitted[],
|
||||
result: PromptDispatchResult,
|
||||
): Promise<void> {
|
||||
if (!riders.length) return;
|
||||
if (result.disposition === "turn_started") {
|
||||
try {
|
||||
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
|
||||
} catch {
|
||||
// The provider rejected the prompt that carried them. They go again, in their place.
|
||||
return handBack(recipientId, riders);
|
||||
}
|
||||
}
|
||||
await complete(recipientId, riders, result.disposition);
|
||||
}
|
||||
|
||||
/**
|
||||
* The stopped recipient stays stopped. Its queue, steers and interrupts included, goes with whatever
|
||||
* prompts it next.
|
||||
* The stopped recipient stays stopped. Its queue, steers and interrupts included, waits until
|
||||
* a later prompt reopens it or a queued item is promoted.
|
||||
*/
|
||||
function hold(recipientId: string, inbox: Inbox): void {
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
clearCap(inbox);
|
||||
inbox.phase = "held";
|
||||
inbox.stops++;
|
||||
for (const message of inbox.messages) {
|
||||
message.urgency = null;
|
||||
message.promoted = false;
|
||||
message.held = true;
|
||||
}
|
||||
void write(store.markHeld(recipientId), recipientId);
|
||||
}
|
||||
|
||||
/** A prompt admitted after a Stop releases what it left in the queue. */
|
||||
function reopen(recipientId: string, messages: Admitted[]): void {
|
||||
/** A prompt admitted after a Stop unpauses any held queue so it drains after this turn. */
|
||||
async function reopenHeld(recipientId: string, stopped: () => boolean): Promise<void> {
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox?.phase !== "held") return;
|
||||
for (const message of messages) message.held = false;
|
||||
if (closed || stopped() || !inbox) return;
|
||||
if (inbox.phase !== "held" && !inbox.messages.some((message) => message.held)) return;
|
||||
for (const message of inbox.messages) message.held = false;
|
||||
inbox.phase = "waiting";
|
||||
if (inbox.messages.length) {
|
||||
await write(store.clearHeld(recipientId), recipientId);
|
||||
} else {
|
||||
changed(recipientId);
|
||||
}
|
||||
if (!closed && !stopped() && !isRunning(recipientId)) {
|
||||
attempt(recipientId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Without a message admitted since the Stop, the queue is held again. */
|
||||
@@ -1219,7 +1260,11 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await queued.saved;
|
||||
return queued.receipt;
|
||||
}
|
||||
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const requestedBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const activeTurnBehavior: AgentMessageBehavior =
|
||||
requestedBehavior === "steer" && isRunning(recipientId) && !canSteer(recipientId)
|
||||
? "queue"
|
||||
: requestedBehavior;
|
||||
const source = message.source ?? null;
|
||||
const item = createAdmitted(
|
||||
{
|
||||
@@ -1310,7 +1355,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<DirectSendResult<Result>> {
|
||||
const { recipientId } = direct;
|
||||
// A retried direct send whose earlier attempt was queued must return that queued entry
|
||||
// rather than coalescing with itself or interrupting the turn ahead of it.
|
||||
// rather than duplicating or interrupting the turn ahead of it.
|
||||
if (direct.messageId) {
|
||||
const existing = inboxes
|
||||
.get(recipientId)
|
||||
@@ -1322,56 +1367,56 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
return { disposition: "queued", receipt: existing.receipt };
|
||||
}
|
||||
}
|
||||
// Its place in line is decided now: what is queued goes with it, what comes later follows.
|
||||
// A queued provider switch, and what follows it, waits for the turn this prompt starts.
|
||||
const takesQueue = !closed && !direct.resumesTurn && !isCommand(direct.prompt);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
const queued = takesQueue ? [...(inbox?.messages ?? [])] : [];
|
||||
const ahead = beforeSwitch(queued);
|
||||
const behind = queued.slice(ahead.length);
|
||||
const stopped = inbox ? watchForStop(inbox) : () => false;
|
||||
|
||||
// When queued messages ahead of this prompt cross a boundary (conflicting sessionMode or
|
||||
// queued non-agent command), insert this prompt immediately after `ahead` with urgency so
|
||||
// the earlier group runs first under its own mode and this prompt follows on its own turn
|
||||
// before any queued provider switch or later arrival.
|
||||
if (takesQueue && !canCoalesceDirect({ ahead: ahead.filter(isQueued), direct })) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId: behind[0]?.id });
|
||||
const stopsBefore = inboxes.get(recipientId)?.stops ?? 0;
|
||||
const stopped = () => (inboxes.get(recipientId)?.stops ?? 0) !== stopsBefore;
|
||||
const hasHeldMessages = (): boolean =>
|
||||
Boolean(inboxes.get(recipientId)?.messages.some((message) => message.held));
|
||||
const queuedBehindCurrentProvider = (): { insertBeforeId: string | undefined } | null => {
|
||||
if (closed || !direct.providerSwitch) return null;
|
||||
const current = [...(inboxes.get(recipientId)?.messages ?? [])];
|
||||
const ahead = beforeSwitch(current);
|
||||
return ahead.some(isQueued) ? { insertBeforeId: current[ahead.length]?.id } : null;
|
||||
};
|
||||
|
||||
// A direct provider switch must not move queued messages meant for the current provider
|
||||
// onto the target provider, so queue it right after them and release them first.
|
||||
const boundary = queuedBehindCurrentProvider();
|
||||
if (boundary) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId: boundary.insertBeforeId });
|
||||
return { disposition: "queued", receipt };
|
||||
}
|
||||
|
||||
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
|
||||
run(recipientId, async () => {
|
||||
let riders: Admitted[] = [];
|
||||
let result: Result;
|
||||
try {
|
||||
const pending = closed ? [] : await prepare(recipientId, ahead);
|
||||
if (
|
||||
!closed &&
|
||||
takesQueue &&
|
||||
!canCoalesceDirect({ ahead: messagesOf(pending), direct })
|
||||
) {
|
||||
const aheadSet = new Set(ahead);
|
||||
const insertBeforeId = inboxes
|
||||
.get(recipientId)
|
||||
?.messages.find((entry) => !aheadSet.has(entry))?.id;
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId });
|
||||
const deferredBoundary = queuedBehindCurrentProvider();
|
||||
if (deferredBoundary) {
|
||||
const receipt = await enqueueDirect({
|
||||
direct,
|
||||
insertBeforeId: deferredBoundary.insertBeforeId,
|
||||
});
|
||||
resolve({ disposition: "queued", receipt });
|
||||
return;
|
||||
}
|
||||
const dispatching = await markDispatching(recipientId, pending);
|
||||
riders = messagesOf(dispatching);
|
||||
for (const message of riders) message.state = "claimed";
|
||||
for (const message of riders) message.beforeDispatch?.();
|
||||
result = await send(join(dispatching, direct));
|
||||
result = await send(prepareDirectPrompt(direct));
|
||||
} catch (error) {
|
||||
await handBack(recipientId, riders);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
await ride(recipientId, riders, result);
|
||||
if (behind.length && !stopped()) reopen(recipientId, behind);
|
||||
const mayReopenHeld = !direct.resumesTurn && !isCommand(direct.prompt);
|
||||
if (mayReopenHeld && hasHeldMessages() && result.disposition === "turn_started") {
|
||||
try {
|
||||
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (mayReopenHeld) {
|
||||
await reopenHeld(recipientId, stopped);
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
@@ -1412,9 +1457,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (!promoted.has(message.id)) continue;
|
||||
message.urgency = urgency;
|
||||
message.held = false;
|
||||
message.promoted = true;
|
||||
}
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
clearCap(inbox);
|
||||
inbox.phase = "waiting";
|
||||
lineUp(recipientId, inbox);
|
||||
return "promoted";
|
||||
@@ -1501,7 +1547,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
unsubscribeStop?.();
|
||||
for (const inbox of inboxes.values()) {
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
clearCap(inbox);
|
||||
}
|
||||
closing = drain();
|
||||
return closing;
|
||||
|
||||
@@ -305,16 +305,16 @@ test("Stop holds the queue across a restart until it is promoted", async () => {
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
test("a prompt sent after a restart carries the held messages", async () => {
|
||||
test("a prompt sent after a restart runs alone, clears the hold, and delivers held messages after the turn ends", async () => {
|
||||
const home = await createHome();
|
||||
const first = openDaemon(home, { running: true });
|
||||
await queue(first.delivery, "held");
|
||||
await first.stop();
|
||||
await first.delivery.close();
|
||||
|
||||
const second = openDaemon(home);
|
||||
await second.delivery.start();
|
||||
let prompt: AgentPromptInput = "";
|
||||
const second = openDaemon(home, { running: true });
|
||||
await second.delivery.start();
|
||||
await second.delivery.sendDirect(
|
||||
{ recipientId: "parent", prompt: "continue", messageId: "next" },
|
||||
async (joined) => {
|
||||
@@ -323,7 +323,12 @@ test("a prompt sent after a restart carries the held messages", async () => {
|
||||
},
|
||||
);
|
||||
await second.settle();
|
||||
expect(String(prompt)).toContain('message-id="held"');
|
||||
expect(prompt).toBe("continue");
|
||||
expect(await second.saved("parent")).toEqual([{ id: "held", state: "queued", held: false }]);
|
||||
expect(second.ids()).toEqual([]);
|
||||
|
||||
await second.endTurn();
|
||||
expect(second.ids()).toEqual([["held"]]);
|
||||
expect(await second.saved("parent")).toEqual([]);
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
@@ -79,6 +79,28 @@ describe("trailing marker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the outer provider messageId across split bundled user messages", () => {
|
||||
const text = [
|
||||
formatAgentMessage({ id: "user-1", source: null, text: "First question" }),
|
||||
formatAgentMessage({ id: "user-2", source: null, text: "Second question" }),
|
||||
].join("\n\n");
|
||||
|
||||
expect(project(text, "provider-echo")).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: "First question",
|
||||
clientMessageId: "user-1",
|
||||
messageId: "provider-echo",
|
||||
},
|
||||
{
|
||||
type: "user_message",
|
||||
text: "Second question",
|
||||
clientMessageId: "user-2",
|
||||
messageId: "provider-echo",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("a body with leading whitespace replays the same after a provider trims the prompt", () => {
|
||||
const source = { kind: "agent-message" as const, agentId: "lead", title: "Lead" };
|
||||
for (const text of ["\n indented code", " - list"]) {
|
||||
|
||||
@@ -277,7 +277,8 @@ export function envelopeMessage(
|
||||
export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem[] {
|
||||
if (item.type !== "user_message") return [item];
|
||||
const messages = parseAgentMessages(item.text);
|
||||
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
|
||||
if (!messages) return [item];
|
||||
return messages.map((message) => projectAgentMessage(item, message));
|
||||
}
|
||||
|
||||
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
|
||||
@@ -302,7 +303,9 @@ function projectAgentMessage(
|
||||
message: AgentMessage,
|
||||
): AgentTimelineItem {
|
||||
const { source } = message;
|
||||
if (!source) return { ...item, text: message.text, clientMessageId: message.id };
|
||||
if (!source) {
|
||||
return { ...item, text: message.text, clientMessageId: message.id };
|
||||
}
|
||||
switch (source.kind) {
|
||||
case "schedule":
|
||||
return {
|
||||
|
||||
@@ -32,7 +32,7 @@ export function describeAgentMessage(admission: Admission): string {
|
||||
"Queued, not delivered yet. The agent is working and reads your message when its current turn ends.";
|
||||
const followUp = canSteer
|
||||
? 'If the message cannot wait, send a short follow-up with activeTurnBehavior "steer" (it joins the running turn) or "interrupt" (it stops the turn and starts a new one).'
|
||||
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also stops the turn.';
|
||||
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also waits until the current turn ends.';
|
||||
return `${waiting} ${followUp} ${DO_NOT_REPEAT}`;
|
||||
}
|
||||
if (!running) return "The agent is idle, so your message starts a turn now.";
|
||||
@@ -40,5 +40,5 @@ export function describeAgentMessage(admission: Admission): string {
|
||||
return "Interrupting the running turn. A new turn starts with your message.";
|
||||
return canSteer
|
||||
? "Steering the running turn. The agent reads your message at its next step and keeps working."
|
||||
: "This agent's provider cannot steer, so your message interrupts the running turn. A new turn starts with your message.";
|
||||
: "This agent's provider cannot steer, so your message is queued until the running turn ends.";
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js";
|
||||
import {
|
||||
assertValidRecipientId,
|
||||
clearHeldInQueue,
|
||||
clearQueue,
|
||||
clearUrgencyInQueue,
|
||||
cloneQueuedMessage,
|
||||
@@ -62,6 +63,7 @@ export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
|
||||
revertDispatching: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
|
||||
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
|
||||
clearHeld: (recipientId) => mutate(recipientId, (current) => clearHeldInQueue(current)),
|
||||
clearUrgency: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => clearUrgencyInQueue(current, ids)),
|
||||
promote: (recipientId, targetId, urgency) =>
|
||||
|
||||
@@ -322,6 +322,32 @@ export function markHeldInQueue(
|
||||
};
|
||||
}
|
||||
|
||||
export function clearHeldInQueue(current: RecipientQueueState): TransitionOutcome<void> {
|
||||
if (current.items.length === 0) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
const nextItems = current.items.map((item) => {
|
||||
const copy = cloneQueuedMessage(item);
|
||||
if (copy.held) {
|
||||
copy.held = false;
|
||||
changed = true;
|
||||
}
|
||||
return copy;
|
||||
});
|
||||
|
||||
if (!changed) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
return {
|
||||
nextState: { nextSeq: current.nextSeq, items: nextItems },
|
||||
changed: true,
|
||||
result: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function promoteInQueue(
|
||||
current: RecipientQueueState,
|
||||
targetId: string,
|
||||
|
||||
@@ -391,6 +391,16 @@ export function createSqliteAgentMessageQueueStore(
|
||||
});
|
||||
},
|
||||
|
||||
async clearHeld(recipientId: string): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
database.write((sql) => {
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items SET held = 0 WHERE recipient_id = ? AND held = 1",
|
||||
recipientId,
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
async clearUrgency(recipientId: string, ids: readonly string[]): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
|
||||
@@ -562,6 +562,19 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
state: "queued",
|
||||
}),
|
||||
]);
|
||||
|
||||
await store.clearHeld("agent-1");
|
||||
expect(
|
||||
(await store.listByRecipient("agent-1")).map((item) => ({
|
||||
id: item.id,
|
||||
held: item.held,
|
||||
urgency: item.urgency,
|
||||
state: item.state,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "m1", held: false, urgency: null, state: "dispatching" },
|
||||
{ id: "m2", held: false, urgency: null, state: "queued" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("promote promotes FIFO prefix 0..k, clears held, and reports not_found / already_dispatching", async () => {
|
||||
|
||||
@@ -73,6 +73,7 @@ export interface AgentMessageQueueStore {
|
||||
): Promise<PersistedQueuedMessage[]>;
|
||||
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
|
||||
clearHeld(recipientId: string): Promise<void>;
|
||||
clearUrgency(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
promote(
|
||||
recipientId: string,
|
||||
|
||||
@@ -91,9 +91,14 @@ async function steerOrReplaceActiveRun(
|
||||
return null;
|
||||
}
|
||||
const submissionOptions = toSubmissionOptions(options.runOptions, options.uploadedImages);
|
||||
const steerOptions = options.clearPendingPermissions
|
||||
? { ...submissionOptions, clearPendingPermissions: true }
|
||||
: submissionOptions;
|
||||
const steerOptions =
|
||||
submissionOptions || options.clearPendingPermissions || options.replaceRunning === false
|
||||
? {
|
||||
...submissionOptions,
|
||||
...(options.clearPendingPermissions ? { clearPendingPermissions: true } : {}),
|
||||
...(options.replaceRunning === false ? { allowReplace: false } : {}),
|
||||
}
|
||||
: undefined;
|
||||
const result = await agentManager.steerOrReplaceActiveTurn(
|
||||
agentId,
|
||||
prompt,
|
||||
@@ -103,6 +108,9 @@ async function steerOrReplaceActiveRun(
|
||||
if (result.status === "steered") {
|
||||
return { disposition: "steered" };
|
||||
}
|
||||
if (result.status === "busy") {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
if (result.status === "replaced") {
|
||||
return { disposition: "turn_started", iterator: result.iterator };
|
||||
}
|
||||
@@ -325,6 +333,8 @@ export interface SendPromptToAgentParams {
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
/** Override whether an active turn that cannot steer may be interrupted/replaced. */
|
||||
replaceRunning?: boolean;
|
||||
runOptions?: AgentRunOptions;
|
||||
/** Optional mode to set on the agent before the run starts. */
|
||||
sessionMode?: string;
|
||||
@@ -339,7 +349,7 @@ export interface SendPromptToAgentParams {
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
/** A prompt that does not wait its turn. Messages queued for the agent go with it. */
|
||||
/** A prompt that does not wait its turn. */
|
||||
export interface SendDirectPromptParams extends SendPromptToAgentParams {
|
||||
agentMessages: Pick<AgentMessageDelivery, "sendDirect">;
|
||||
/** Raw message text when the caller has it, used if queueing behind a boundary. */
|
||||
@@ -452,8 +462,8 @@ async function resolvePromptSource(
|
||||
* chat mentions, notify-on-finish) MUST go through this so behavior can never
|
||||
* drift between them.
|
||||
*
|
||||
* The prompt does not wait in the agent's message queue, and it does not jump it either:
|
||||
* messages already queued for the agent are delivered ahead of it in the same provider prompt.
|
||||
* The prompt does not wait in the agent's message queue and does not sweep queued messages:
|
||||
* existing queued items stay in the queue until the turn settles or are explicitly promoted.
|
||||
*
|
||||
* When `unarchive` is false and the agent is archived, the call is a silent
|
||||
* no-op (returns the normal turn-start disposition) — the agent is not run.
|
||||
@@ -548,7 +558,7 @@ export async function sendPreparedPromptToAgent(
|
||||
throw new Error("Queued agent message was withdrawn");
|
||||
}
|
||||
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
|
||||
replaceRunning: !params.idleOnly,
|
||||
replaceRunning: params.replaceRunning ?? !params.idleOnly,
|
||||
idleOnly: params.idleOnly,
|
||||
admit: params.admit,
|
||||
onDispatch: params.onDispatch,
|
||||
|
||||
@@ -74,12 +74,14 @@ class Observation implements FinishObservation {
|
||||
}
|
||||
class Delivery implements FinishMessages {
|
||||
prompts: string[] = [];
|
||||
behaviors: Array<string | undefined> = [];
|
||||
/** Prompts as the recipient's provider receives them, inside their envelope. */
|
||||
enqueued: string[] = [];
|
||||
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
|
||||
enqueuedListeners = new Set<Parameters<FinishMessages["onEnqueued"]>[0]>();
|
||||
async enqueue(message: Parameters<FinishMessages["enqueue"]>[0]) {
|
||||
this.prompts.push(message.text);
|
||||
this.behaviors.push(message.activeTurnBehavior);
|
||||
this.enqueued.push(
|
||||
formatAgentMessage({
|
||||
id: "notification",
|
||||
@@ -1067,4 +1069,14 @@ describe("suppressing redundant finished notices after an explicit child report"
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Done after bash");
|
||||
});
|
||||
|
||||
test("finish notifications default to activeTurnBehavior steer", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "All tests passed"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.behaviors).toEqual(["steer"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -337,8 +337,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
title,
|
||||
event: finishNotificationEvents[reason],
|
||||
},
|
||||
// A finish report never enters a running turn.
|
||||
activeTurnBehavior: "queue",
|
||||
// A finish report steers when the provider supports it and queues until turn end otherwise.
|
||||
activeTurnBehavior: "steer",
|
||||
unarchive: false,
|
||||
});
|
||||
const acknowledge = () => {
|
||||
|
||||
@@ -4071,9 +4071,9 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentScoped: true,
|
||||
behavior: undefined,
|
||||
steering: "accepted",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
|
||||
applied: "steer",
|
||||
outcome: "steered",
|
||||
guidance: "Steering the running turn.",
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
@@ -4081,7 +4081,23 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
steering: "none",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also stops the turn',
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "queue",
|
||||
steering: "accepted",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "queue",
|
||||
steering: "none",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
@@ -4095,17 +4111,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentScoped: true,
|
||||
behavior: "steer",
|
||||
steering: "none",
|
||||
applied: "steer",
|
||||
outcome: "replaced",
|
||||
guidance: "This agent's provider cannot steer, so your message interrupts the running turn.",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
// A provider that can steer may refuse one steer; the turn is replaced all the same.
|
||||
// A provider that can steer may refuse one steer mid-turn; keep the message queued instead of
|
||||
// replacing the running turn.
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "steer",
|
||||
steering: "unavailable",
|
||||
applied: "steer",
|
||||
outcome: "replaced",
|
||||
outcome: "queued",
|
||||
guidance: "Steering the running turn.",
|
||||
},
|
||||
{
|
||||
@@ -4306,10 +4323,10 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
);
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
expect(response.structuredContent.guidance).toContain(
|
||||
"Queued. The agent is idle, so your message starts a turn in about 2 seconds.",
|
||||
"The agent is idle, so your message starts a turn now.",
|
||||
);
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(1);
|
||||
} finally {
|
||||
@@ -4361,7 +4378,12 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
|
||||
const response = await mcpClient.callTool({
|
||||
name: "send_agent_prompt",
|
||||
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
|
||||
arguments: {
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
activeTurnBehavior: "queue",
|
||||
notifyOnFinish: true,
|
||||
},
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
@@ -5229,7 +5251,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a person's prompt takes the queued message into its own turn", async () => {
|
||||
it("a person's prompt runs alone without sweeping the queued message, which dispatches after the turn settles", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5237,10 +5259,8 @@ describe("message order for one recipient", () => {
|
||||
|
||||
await recipient.personSends("Pause the release");
|
||||
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts[1]).toBe("Pause the release");
|
||||
const rows = await recipient.agentManager.getTimeline(recipient.recipientId);
|
||||
expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([
|
||||
"Pause the release",
|
||||
@@ -5248,13 +5268,16 @@ describe("message order for one recipient", () => {
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(10 * 60_000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("Stop holds the queued steer for the recipient's next prompt", async () => {
|
||||
it("Stop holds the queued steer until a later prompt reopens the queue without sweeping it", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5268,9 +5291,14 @@ describe("message order for one recipient", () => {
|
||||
expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle");
|
||||
|
||||
await recipient.personSends("Carry on");
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts[1]).toBe("Carry on");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Carry on" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
@@ -5300,7 +5328,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("prompts sent while the provider is still starting a turn reach it in the order sent", async () => {
|
||||
it("a person's direct prompt does not sweep queued prompts while queued agent messages keep their order", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
const acknowledgeStart = recipient.session.holdTurnStart();
|
||||
@@ -5315,15 +5343,15 @@ describe("message order for one recipient", () => {
|
||||
acknowledgeStart();
|
||||
await Promise.all([interrupt, person]);
|
||||
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts[2]).toBe("Pause the release");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(4);
|
||||
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Tests passed" }]);
|
||||
expect(recipient.prompt(3)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: recipient.senderId, text: "Tests passed" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
@@ -5341,14 +5369,16 @@ describe("message order for one recipient", () => {
|
||||
await recipient.stop();
|
||||
await person;
|
||||
|
||||
// The next prompt is sent after the interrupt's dispatch has ended, so a turn the
|
||||
// interrupt started on its own would show up as a prompt between the two.
|
||||
// The next prompt is sent after the interrupt's dispatch has ended, so it runs alone and
|
||||
// reopens the held interrupt to run after this turn finishes.
|
||||
await recipient.personSends("Carry on");
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Skip the backup" },
|
||||
{ from: "person", text: "Carry on" },
|
||||
]);
|
||||
expect(recipient.session.prompts[2]).toBe("Carry on");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(4);
|
||||
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Skip the backup" }]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
@@ -5415,7 +5445,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a queued message returns to the queue when the provider rejects the person's turn", async () => {
|
||||
it("a queued message stays in the queue when the provider rejects the person's turn", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5425,12 +5455,9 @@ describe("message order for one recipient", () => {
|
||||
await expect(recipient.personSends("Pause the release")).rejects.toThrow(
|
||||
"Provider is overloaded",
|
||||
);
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts[1]).toBe("Pause the release");
|
||||
|
||||
// The provider never took that prompt, so the steer is delivered on its own.
|
||||
// The provider rejected the person's prompt; the queued steer still dispatches on its own.
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
|
||||
@@ -2628,7 +2628,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
* dequeues one and resumes the turn we just stopped. SDK user UUIDs are provider-private; never
|
||||
* let them escape the adapter boundary.
|
||||
*/
|
||||
private readonly unstartedMessageUuids = new Set<string>();
|
||||
private readonly unstartedMessages = new Map<string, "prompt" | "steer">();
|
||||
/** Human steers whose text has not reached Claude yet and therefore supersede blocking cards. */
|
||||
private readonly permissionClearingSteerUuids = new Set<string>();
|
||||
private claudeSessionId: string | null;
|
||||
@@ -2898,7 +2898,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.contextUsage.beginTurn();
|
||||
this.transitionTurnState("foreground", "foreground turn started");
|
||||
this.clearRecentStderr();
|
||||
if (sdkUserMessageId) this.unstartedMessageUuids.add(sdkUserMessageId);
|
||||
if (sdkUserMessageId) this.unstartedMessages.set(sdkUserMessageId, "prompt");
|
||||
|
||||
let cancelIssued = false;
|
||||
const requestCancel = () => {
|
||||
@@ -2913,7 +2913,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
// mainTurnInFlight after Claude started it, so the message's own lifecycle counts too.
|
||||
const claudeStartedTurn =
|
||||
this.mainTurnInFlight ||
|
||||
(sdkUserMessageId !== null && !this.unstartedMessageUuids.has(sdkUserMessageId));
|
||||
(sdkUserMessageId !== null && !this.unstartedMessages.has(sdkUserMessageId));
|
||||
this.rejectAllPendingPermissions(new Error("Permission request canceled"));
|
||||
this.finishForegroundTurn({
|
||||
type: "turn_canceled",
|
||||
@@ -2932,7 +2932,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
await this.ensureQuery();
|
||||
if (cancelIssued) {
|
||||
// Stopped while Claude was still starting up: withdrawn by never sending it.
|
||||
if (sdkUserMessageId) this.unstartedMessageUuids.delete(sdkUserMessageId);
|
||||
if (sdkUserMessageId) this.unstartedMessages.delete(sdkUserMessageId);
|
||||
return { turnId };
|
||||
}
|
||||
if (!this.input) {
|
||||
@@ -2952,7 +2952,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
}, 0);
|
||||
} catch (error) {
|
||||
if (sdkUserMessageId) this.unstartedMessageUuids.delete(sdkUserMessageId);
|
||||
if (sdkUserMessageId) this.unstartedMessages.delete(sdkUserMessageId);
|
||||
this.finishForegroundTurn(
|
||||
this.buildTurnFailedEvent(error instanceof Error ? error.message : "Claude stream failed"),
|
||||
);
|
||||
@@ -3004,7 +3004,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
clearPendingPermissions: boolean,
|
||||
): void {
|
||||
const uuid = message.uuid;
|
||||
if (uuid) this.unstartedMessageUuids.add(uuid);
|
||||
if (uuid) this.unstartedMessages.set(uuid, "steer");
|
||||
if (uuid && clearPendingPermissions) {
|
||||
this.permissionClearingSteerUuids.add(uuid);
|
||||
}
|
||||
@@ -3015,7 +3015,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
} catch (error) {
|
||||
if (uuid) {
|
||||
this.unstartedMessageUuids.delete(uuid);
|
||||
this.unstartedMessages.delete(uuid);
|
||||
this.permissionClearingSteerUuids.delete(uuid);
|
||||
}
|
||||
throw error;
|
||||
@@ -3062,12 +3062,13 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
|
||||
// Withdraw queued steers before announcing that the autonomous turn settled.
|
||||
const interrupt = this.interruptActiveTurn();
|
||||
if (this.autonomousTurn) {
|
||||
this.flushPendingToolCalls();
|
||||
this.completeAutonomousTurn();
|
||||
}
|
||||
|
||||
await this.interruptActiveTurn();
|
||||
await interrupt;
|
||||
}
|
||||
|
||||
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
|
||||
@@ -3471,8 +3472,13 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
hasPendingWakeup(): boolean {
|
||||
// A delivered task notification opens its turn only with the next init.
|
||||
return this.notificationTurnId !== null || this.runtimeSafety.hasPendingWakeup();
|
||||
// A steer queued in Claude can open a new turn after this one settles.
|
||||
// A delivered task notification also waits for the next init.
|
||||
return (
|
||||
[...this.unstartedMessages.values()].includes("steer") ||
|
||||
this.notificationTurnId !== null ||
|
||||
this.runtimeSafety.hasPendingWakeup()
|
||||
);
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
@@ -3484,7 +3490,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
!this.activeForegroundTurnId &&
|
||||
!this.autonomousTurn &&
|
||||
!this.mainTurnInFlight &&
|
||||
this.unstartedMessageUuids.size === 0 &&
|
||||
this.unstartedMessages.size === 0 &&
|
||||
this.pendingPermissions.size === 0 &&
|
||||
this.processingSdkMessages === 0 &&
|
||||
this.runtimeSafety.canStopRuntime()
|
||||
@@ -3527,8 +3533,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
// close() already terminates the SDK query. Its control plane is no longer
|
||||
// available; waiting for interrupt/return here delays our process-tree cleanup
|
||||
// beyond the daemon's close deadline when the provider stops answering.
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.detachQuery();
|
||||
// Terminate the entire process tree (claude + MCP children) to prevent
|
||||
// orphan accumulation. The SDK's internal cleanup may only kill the
|
||||
// direct child process.
|
||||
@@ -4009,6 +4014,17 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return { kind: "fresh-session" };
|
||||
}
|
||||
|
||||
private detachQuery(): void {
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
// A steer belongs to the query that accepted it. A foreground prompt can
|
||||
// already be waiting for a replacement query in startTurn().
|
||||
for (const [uuid, kind] of this.unstartedMessages) {
|
||||
if (kind === "steer") this.unstartedMessages.delete(uuid);
|
||||
}
|
||||
this.permissionClearingSteerUuids.clear();
|
||||
}
|
||||
|
||||
private async retireQuery(): Promise<void> {
|
||||
const oldQuery = this.query;
|
||||
if (!oldQuery) return;
|
||||
@@ -4016,8 +4032,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
for (const finish of this.backgroundStops.values()) finish("connection lost");
|
||||
// Null out query/input BEFORE awaiting the old iterator's return so the
|
||||
// old pump sees this.query !== activeQuery and skips failActiveTurns.
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.detachQuery();
|
||||
this.queryRestartNeeded = false;
|
||||
// Ending the input retires the process on purpose. Detach first so its
|
||||
// exit is not reported as a crash.
|
||||
@@ -4728,8 +4743,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
!this.notificationTurnId &&
|
||||
!this.taskProtocolSource.hasRunningTasks()
|
||||
) {
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.detachQuery();
|
||||
this.failRunningRuntimeTasks();
|
||||
this.logger.info(
|
||||
{ agentId: this.agentId, pid: child.pid },
|
||||
@@ -4750,8 +4764,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
// Drop the dead handles so the next write spawns a fresh process instead of
|
||||
// failing against a dead transport forever.
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.detachQuery();
|
||||
// The failure goes first: an idle agent whose background work just ended
|
||||
// otherwise reads as settled to anyone waiting for it to finish.
|
||||
this.dispatchEvents([
|
||||
@@ -4853,8 +4866,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
} finally {
|
||||
if (this.query === activeQuery) {
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.detachQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5122,8 +5134,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
if (this.query === activeQuery) {
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.detachQuery();
|
||||
}
|
||||
this.persistence = null;
|
||||
this.persistedHistory = [];
|
||||
@@ -5175,7 +5186,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
withdrawal.withdrewCount > 0 &&
|
||||
this.query === queryToInterrupt &&
|
||||
!this.mainTurnInFlight &&
|
||||
this.unstartedMessageUuids.size === 0
|
||||
this.unstartedMessages.size === 0
|
||||
) {
|
||||
this.runtimeSafety.notePromptWithdrawn();
|
||||
}
|
||||
@@ -5201,8 +5212,8 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private async withdrawUnstartedMessages(
|
||||
query: Query,
|
||||
): Promise<{ withdrewAll: boolean; withdrewCount: number }> {
|
||||
const uuids = [...this.unstartedMessageUuids];
|
||||
this.unstartedMessageUuids.clear();
|
||||
const uuids = [...this.unstartedMessages.keys()];
|
||||
this.unstartedMessages.clear();
|
||||
this.permissionClearingSteerUuids.clear();
|
||||
if (uuids.length === 0) return { withdrewAll: true, withdrewCount: 0 };
|
||||
// The SDK runtime supports this, but its public Query type has not caught up. Keep the
|
||||
@@ -5318,7 +5329,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private forgetStartedMessage(message: unknown): void {
|
||||
const lifecycle = readClaudeCommandLifecycle(message);
|
||||
if (!lifecycle || lifecycle.state === "queued") return;
|
||||
this.unstartedMessageUuids.delete(lifecycle.commandUuid);
|
||||
this.unstartedMessages.delete(lifecycle.commandUuid);
|
||||
this.permissionClearingSteerUuids.delete(lifecycle.commandUuid);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -1543,6 +1543,44 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("provider history over a $name backend
|
||||
expect(result).toEqual({ kind: "unchanged" });
|
||||
});
|
||||
|
||||
it("reconciles split bundled user rows sharing one providerMessageId and appends new turns", async () => {
|
||||
const bundledRow = (id: string, text: string): TimelineEntry => ({
|
||||
providerMessageId: "provider-bundle-1",
|
||||
providerPromptText: text,
|
||||
item: { type: "user_message", text, messageId: id, clientMessageId: id },
|
||||
});
|
||||
const { timeline } = await owned([
|
||||
bundledRow("u-1", "ping"),
|
||||
bundledRow("u-2", "ping"),
|
||||
reply("Bundled reply"),
|
||||
]);
|
||||
|
||||
expect(
|
||||
await timeline.reconcileProviderHistory(scope, [
|
||||
bundledRow("u-1", "ping"),
|
||||
bundledRow("u-2", "ping"),
|
||||
reply("Bundled reply"),
|
||||
]),
|
||||
).toEqual({ kind: "unchanged" });
|
||||
|
||||
const appended = await timeline.reconcileProviderHistory(scope, [
|
||||
bundledRow("u-1", "ping"),
|
||||
bundledRow("u-2", "ping"),
|
||||
reply("Bundled reply"),
|
||||
prompt("p-2"),
|
||||
reply("Next reply"),
|
||||
]);
|
||||
|
||||
expect(appended).toMatchObject({ kind: "appended" });
|
||||
expect(texts(await timeline.readRows(scope))).toEqual([
|
||||
"ping",
|
||||
"ping",
|
||||
"Bundled reply",
|
||||
"p-2",
|
||||
"Next reply",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the owned history when the provider repeats a prompt id with other text", async () => {
|
||||
const { backend, timeline } = await owned([prompt("a")]);
|
||||
const appendsBefore = backend.appends.length;
|
||||
|
||||
@@ -13,6 +13,7 @@ interface Prompt {
|
||||
|
||||
interface ProviderPrompt extends Prompt {
|
||||
start: number;
|
||||
clientMessageId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -41,7 +42,15 @@ export function planProviderHistory(input: {
|
||||
if (owned.prompts.length > provider.length) {
|
||||
return { kind: "diverged", reason: "The provider history is missing turns Paseo shows" };
|
||||
}
|
||||
if (provider.some((prompt, index) => index > 0 && prompt.id === provider[index - 1].id)) {
|
||||
// Adjacent prompts from one bundled batch share a provider ID across distinct `clientMessageId`s.
|
||||
if (
|
||||
provider.some(
|
||||
(prompt, index) =>
|
||||
index > 0 &&
|
||||
prompt.id === provider[index - 1].id &&
|
||||
prompt.clientMessageId === provider[index - 1].clientMessageId,
|
||||
)
|
||||
) {
|
||||
return { kind: "diverged", reason: "The provider history has two prompts with one id" };
|
||||
}
|
||||
if (owned.prompts.some((prompt, index) => !samePrompt(prompt, provider[index]))) {
|
||||
@@ -80,12 +89,26 @@ function ownedPrompts(
|
||||
|
||||
function providerPrompts(entries: readonly TimelineEntry[]): ProviderPrompt[] {
|
||||
const prompts: ProviderPrompt[] = [];
|
||||
entries.forEach(({ item }, start) => {
|
||||
entries.forEach((entry, start) => {
|
||||
const { item } = entry;
|
||||
if (item.type !== "user_message") return;
|
||||
const prompt = { id: item.messageId, text: item.text, start };
|
||||
const prompt: ProviderPrompt = {
|
||||
id: entry.providerMessageId ?? item.messageId,
|
||||
text: item.text,
|
||||
start,
|
||||
clientMessageId: item.clientMessageId,
|
||||
};
|
||||
const previous = prompts.at(-1);
|
||||
// Some providers replay a prompt twice. Reusing an ID for different text is a mismatch.
|
||||
if (previous && prompt.id !== undefined && samePrompt(prompt, previous)) return;
|
||||
// Some providers replay a prompt twice. Reusing an ID for different text (or a second
|
||||
// bundled row with its own clientMessageId) is kept distinct so validation can judge it.
|
||||
if (
|
||||
previous &&
|
||||
prompt.id !== undefined &&
|
||||
prompt.clientMessageId === previous.clientMessageId &&
|
||||
samePrompt(prompt, previous)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
prompts.push(prompt);
|
||||
});
|
||||
return prompts;
|
||||
|
||||
@@ -1398,7 +1398,7 @@ function createToolCatalog(
|
||||
const agentToAgentSendAgentPromptInputSchema = {
|
||||
...commonSendAgentPromptInputSchema,
|
||||
activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional().describe(
|
||||
'Leave this out unless the message cannot wait. Default "queue": the message waits until the agent\'s running turn ends. "steer": the message joins the running turn; a provider that cannot steer interrupts the turn instead. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries the messages you queued before it, in order.',
|
||||
'Default "steer": the message joins the running turn, or waits until the turn ends if the provider cannot steer. "queue": the message waits until the running turn ends. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries earlier agent-queued messages ahead of it (never human-queued items), in order.',
|
||||
),
|
||||
notifyOnFinish: z
|
||||
.boolean()
|
||||
@@ -2102,7 +2102,7 @@ function createToolCatalog(
|
||||
title: "Send agent prompt",
|
||||
description:
|
||||
scope === "agent"
|
||||
? "Send a message to another agent. The response returns at once. Its guidance says whether the message waits for the running turn to end, joins it, or interrupts it, and how to deliver a waiting message now. Leave activeTurnBehavior out unless the message cannot wait. The recipient reads your messages in the order you sent them. A steer the recipient has not read is lost if its turn stops or is interrupted, along with the messages it carried. Completion reports include the target’s last response by default. Paseo supplies caller identity."
|
||||
? "Send a message to another agent. The response returns at once. Its guidance says whether the message steers the running turn, waits for it to end, or interrupts it, and how to deliver a waiting message now. By default activeTurnBehavior is steer (or queue if the provider cannot steer); pass queue to wait for turn end. The recipient reads your messages in the order you sent them. A steer the recipient has not read is lost if its turn stops or is interrupted, along with the agent-queued messages it carried. Completion reports include the target’s last response by default. Paseo supplies caller identity."
|
||||
: "Send a prompt to an agent. A running turn is interrupted unless activeTurnBehavior is steer.",
|
||||
inputSchema: sendAgentPromptInputSchema,
|
||||
outputSchema: {
|
||||
@@ -2182,7 +2182,7 @@ function createToolCatalog(
|
||||
title: resolveCallerAgent()?.config.title ?? undefined,
|
||||
},
|
||||
sessionMode,
|
||||
activeTurnBehavior,
|
||||
activeTurnBehavior: activeTurnBehavior ?? "steer",
|
||||
onDispatch: confirmDispatch,
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -79,20 +79,31 @@ async function createWorkingRecipient(options: { olderClient?: boolean } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
test("an agent's message without a behavior waits for the running turn and says how to deliver it now", async () => {
|
||||
test("an agent's message without a behavior steers a steering turn and can be overridden to queue", async () => {
|
||||
const { client, runtime, recipient, sender, close } = await createWorkingRecipient();
|
||||
try {
|
||||
const receipt = await client.sendAgentMessage(recipient.id, "Report when done", {
|
||||
const steered = await client.sendAgentMessage(recipient.id, "Adjust approach", {
|
||||
sourceAgentId: sender.id,
|
||||
});
|
||||
expect(receipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
expect(receipt.guidance).toContain("Queued, not delivered yet.");
|
||||
expect(receipt.guidance).toContain('"steer" (it joins the running turn)');
|
||||
expect(runtime.prompts).toHaveLength(1);
|
||||
expect(steered).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "steer" });
|
||||
expect(steered.guidance).toBe(
|
||||
"Steering the running turn. The agent reads your message at its next step and keeps working.",
|
||||
);
|
||||
await expect.poll(() => runtime.prompts.length).toBe(2);
|
||||
expect(runtime.prompts[1]).toContain("Adjust approach");
|
||||
|
||||
const queued = await client.sendAgentMessage(recipient.id, "Report when done", {
|
||||
sourceAgentId: sender.id,
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(queued).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
expect(queued.guidance).toContain("Queued, not delivered yet.");
|
||||
expect(queued.guidance).toContain('"steer" (it joins the running turn)');
|
||||
expect(runtime.prompts).toHaveLength(2);
|
||||
|
||||
runtime.finishExecution();
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
|
||||
expect(runtime.prompts[1]).toContain("Report when done");
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
|
||||
expect(runtime.prompts[2]).toContain("Report when done");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
@@ -229,6 +240,11 @@ async function createModeBoundaryRecipient(input: {
|
||||
onStartTurn: (prompt, config) => {
|
||||
executedTurns.push({ prompt: String(prompt), modeId: config.modeId });
|
||||
},
|
||||
onInterrupt: () => {
|
||||
for (const gate of gates.values()) {
|
||||
gate.release();
|
||||
}
|
||||
},
|
||||
beforeTurnComplete: async (prompt) => {
|
||||
const text = String(prompt);
|
||||
for (const [needle, gate] of gates) {
|
||||
@@ -277,12 +293,12 @@ async function createModeBoundaryRecipient(input: {
|
||||
}
|
||||
}
|
||||
|
||||
test("a direct broader-mode send behind a queued plan-mode message runs as two separate turns in their respective modes", async () => {
|
||||
test("a direct broader-mode send while a plan-mode message is queued runs as two separate turns in their respective modes", async () => {
|
||||
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
|
||||
initialModeId: "default",
|
||||
title: "Mode Boundary Worker",
|
||||
initialPrompt: "Initial work",
|
||||
heldPrompts: ["Inspect files read-only"],
|
||||
heldPrompts: ["Edit production files"],
|
||||
});
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(agent.id, "Inspect files read-only", {
|
||||
@@ -295,34 +311,33 @@ test("a direct broader-mode send behind a queued plan-mode message runs as two s
|
||||
activeTurnBehavior: "interrupt",
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
expect(directReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(directReceipt).toEqual({});
|
||||
|
||||
releaseTurn("Initial work");
|
||||
expect(await waitForTurn(1)).toEqual({
|
||||
prompt: "Inspect files read-only",
|
||||
modeId: "plan",
|
||||
});
|
||||
|
||||
releaseTurn("Inspect files read-only");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Edit production files",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
|
||||
{ text: "Inspect files read-only", state: "queued" },
|
||||
]);
|
||||
|
||||
releaseTurn("Edit production files");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Inspect files read-only",
|
||||
modeId: "plan",
|
||||
});
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a direct bypassPermissions send behind a queued implicit-mode message on a restricted-mode agent runs as two separate turns", async () => {
|
||||
test("a direct bypassPermissions send while an implicit-mode message is queued on a restricted-mode agent runs as two separate turns", async () => {
|
||||
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
|
||||
initialModeId: "always-ask",
|
||||
title: "Implicit Mode Worker",
|
||||
initialPrompt: "Initial restricted turn",
|
||||
heldPrompts: ["Queued in existing mode"],
|
||||
heldPrompts: ["Apply edits in bypass mode"],
|
||||
});
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(agent.id, "Queued in existing mode", {
|
||||
@@ -334,24 +349,156 @@ test("a direct bypassPermissions send behind a queued implicit-mode message on a
|
||||
activeTurnBehavior: "interrupt",
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
expect(directReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(directReceipt).toEqual({});
|
||||
|
||||
releaseTurn("Initial restricted turn");
|
||||
expect(await waitForTurn(1)).toEqual({
|
||||
prompt: "Queued in existing mode",
|
||||
modeId: "always-ask",
|
||||
});
|
||||
|
||||
releaseTurn("Queued in existing mode");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Apply edits in bypass mode",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
|
||||
{ text: "Queued in existing mode", state: "queued" },
|
||||
]);
|
||||
|
||||
releaseTurn("Apply edits in bypass mode");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Queued in existing mode",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["steer", "interrupt"] as const)(
|
||||
"a human direct %s keeps queued user messages in the host queue and dispatches them after the turn ends",
|
||||
async (behavior) => {
|
||||
const { client, runtime, recipient, close } = await createWorkingRecipient();
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(recipient.id, "Queued user follow-up", {
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(queuedReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
const directReceipt = await client.sendAgentMessage(recipient.id, "Human direct prompt", {
|
||||
activeTurnBehavior: behavior,
|
||||
});
|
||||
expect(directReceipt).toEqual({});
|
||||
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 5_000 }).toBe(2);
|
||||
expect(runtime.prompts[1]).toBe("Human direct prompt");
|
||||
expect(runtime.prompts[1]).not.toContain("Queued user follow-up");
|
||||
|
||||
const queueState = await client.listAgentQueue(recipient.id);
|
||||
expect(queueState.items).toHaveLength(1);
|
||||
expect(queueState.items[0]).toMatchObject({
|
||||
text: "Queued user follow-up",
|
||||
state: "queued",
|
||||
});
|
||||
|
||||
runtime.finishExecution();
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
|
||||
expect(runtime.prompts[2]).toBe("Queued user follow-up");
|
||||
await expect
|
||||
.poll(async () => (await client.listAgentQueue(recipient.id)).items.length, {
|
||||
timeout: 5_000,
|
||||
})
|
||||
.toBe(0);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("agent steer falls back to queue on a non-steering provider without interrupting, while explicit interrupt replaces the turn", async () => {
|
||||
const artifacts = path.resolve(".artifacts");
|
||||
await mkdir(artifacts, { recursive: true });
|
||||
const root = await mkdtemp(path.join(artifacts, "agent-non-steering-behavior-"));
|
||||
const runtime = new V2Harness();
|
||||
runtime.autoComplete = false;
|
||||
runtime.api.model.list = async () => ({ location: runtime.info.location, data: [] });
|
||||
runtime.api.provider.list = async () => ({
|
||||
location: runtime.info.location,
|
||||
data: [{ id: "test", name: "Test", activation: "enabled", package: "test" }],
|
||||
});
|
||||
let interrupts = 0;
|
||||
const origInterrupt = runtime.api.session.interrupt;
|
||||
runtime.api.session.interrupt = async (input, options) => {
|
||||
interrupts += 1;
|
||||
return origInterrupt(input, options);
|
||||
};
|
||||
runtime.prompt = async (input) => {
|
||||
runtime.prompts.push(input.text);
|
||||
runtime.startExecution();
|
||||
};
|
||||
const bridge = new OpenCodeBridge({
|
||||
paseoHome: path.join(root, "bridge"),
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
await bridge.start();
|
||||
const opencodeClient = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: runtime.runtime,
|
||||
bridge,
|
||||
});
|
||||
// Disable mid-turn steering to model an ACP provider without steerActiveTurn.
|
||||
const originalCreateSession = opencodeClient.createSession.bind(opencodeClient);
|
||||
opencodeClient.createSession = async (config) => {
|
||||
const session = await originalCreateSession(config);
|
||||
session.steerActiveTurn = undefined;
|
||||
return session;
|
||||
};
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: {
|
||||
...createTestAgentClients(),
|
||||
opencode: opencodeClient,
|
||||
},
|
||||
paseoHomeRoot: path.join(root, "daemon"),
|
||||
staticDir: path.join(root, "static"),
|
||||
cleanup: false,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const recipient = await client.createAgent({
|
||||
provider: "opencode",
|
||||
cwd: root,
|
||||
title: "ACP-like",
|
||||
});
|
||||
const sender = await client.createAgent({ provider: "claude", cwd: root });
|
||||
await client.sendMessage(recipient.id, "Long initial turn");
|
||||
await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running");
|
||||
|
||||
// Default omitted behavior and explicit steer both fall back to queue without interrupting.
|
||||
const defaultSteer = await client.sendAgentMessage(recipient.id, "Default steer note", {
|
||||
sourceAgentId: sender.id,
|
||||
});
|
||||
expect(defaultSteer).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
expect(interrupts).toBe(0);
|
||||
expect(runtime.prompts).toHaveLength(1);
|
||||
|
||||
runtime.finishExecution();
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
|
||||
expect(runtime.prompts[1]).toContain("Default steer note");
|
||||
await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running");
|
||||
|
||||
// Explicit interrupt still interrupts and starts a new turn.
|
||||
const interrupt = await client.sendAgentMessage(recipient.id, "Urgent stop", {
|
||||
sourceAgentId: sender.id,
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(interrupt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "interrupt" });
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
|
||||
expect(interrupts).toBeGreaterThanOrEqual(1);
|
||||
expect(runtime.prompts[2]).toContain("Urgent stop");
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await bridge.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import pino from "pino";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseAgentMessage } from "../agent/agent-messages/index.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { canRunRealProvider, createRealProviderClients } from "./real-provider-test-config.js";
|
||||
|
||||
const CallToolResultSchema = z.object({
|
||||
structuredContent: z.object({ agentId: z.string() }),
|
||||
});
|
||||
|
||||
async function callAgentTool(
|
||||
port: number,
|
||||
callerAgentId: string,
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
) {
|
||||
const url = new URL(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
url.searchParams.set("callerAgentId", callerAgentId);
|
||||
const mcp = new Client({ name: "claude-steer-finish-test", version: "1.0.0" });
|
||||
try {
|
||||
await mcp.connect(new StreamableHTTPClientTransport(url));
|
||||
return await mcp.callTool({ name, arguments: args });
|
||||
} finally {
|
||||
await mcp.close();
|
||||
}
|
||||
}
|
||||
|
||||
test("notifies the parent after a Claude steer runs in its own turn", async ({ skip }) => {
|
||||
if (!(await canRunRealProvider("claude"))) return skip();
|
||||
const logger = pino({ level: "silent" });
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-finish-"));
|
||||
// Send the steer after Claude has written its first reply and entered the Stop hook.
|
||||
// Keep the first turn open until MCP accepts the steer.
|
||||
mkdirSync(path.join(cwd, ".claude"));
|
||||
writeFileSync(
|
||||
path.join(cwd, ".claude/settings.json"),
|
||||
JSON.stringify({
|
||||
hooks: {
|
||||
Stop: [
|
||||
{
|
||||
hooks: [
|
||||
{
|
||||
type: "command",
|
||||
command: "touch .stop-started && while [ ! -f .stop-release ]; do sleep 0.1; done",
|
||||
timeout: 45,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const hookReleasePath = path.join(cwd, ".stop-release");
|
||||
const callerPrompts: string[] = [];
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: {
|
||||
...createTestAgentClients({
|
||||
onStartTurn(prompt, config) {
|
||||
if (config.title === "Finish caller" && typeof prompt === "string")
|
||||
callerPrompts.push(prompt);
|
||||
},
|
||||
}),
|
||||
...createRealProviderClients(["claude"], logger),
|
||||
},
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const token = `FINAL_${Date.now().toString(36)}`;
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
const caller = await client.createAgent({
|
||||
provider: "codex",
|
||||
cwd,
|
||||
title: "Finish caller",
|
||||
modeId: "full-access",
|
||||
});
|
||||
const created = await callAgentTool(daemon.port, caller.id, "create_agent", {
|
||||
relationship: { kind: "subagent" },
|
||||
workspace: { kind: "current" },
|
||||
provider: "claude/haiku",
|
||||
title: "Claude child",
|
||||
settings: { modeId: "bypassPermissions" },
|
||||
initialPrompt: "Reply with exactly FIRST_DONE. Use no tools.",
|
||||
});
|
||||
const childId = CallToolResultSchema.parse(created).structuredContent.agentId;
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(existsSync(path.join(cwd, ".stop-started"))).toBe(true);
|
||||
expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("running");
|
||||
},
|
||||
{ timeout: 45_000, interval: 50 },
|
||||
);
|
||||
|
||||
const steer = await callAgentTool(daemon.port, caller.id, "send_agent_prompt", {
|
||||
agentId: childId,
|
||||
activeTurnBehavior: "steer",
|
||||
prompt: `Reply with exactly ${token}. Use no tools.`,
|
||||
});
|
||||
expect(steer.isError).not.toBe(true);
|
||||
expect(steer.structuredContent).toMatchObject({ deliveryStatus: "queued" });
|
||||
writeFileSync(hookReleasePath, "");
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const timeline = await client.fetchAgentTimeline(childId, { limit: 30 });
|
||||
const firstReply = timeline.entries.find(
|
||||
({ item }) => item.type === "assistant_message" && item.text.includes("FIRST_DONE"),
|
||||
);
|
||||
const steerReply = timeline.entries.find(
|
||||
({ item }) => item.type === "assistant_message" && item.text.includes(token),
|
||||
);
|
||||
expect(firstReply?.turnId).toBeTruthy();
|
||||
expect(steerReply?.turnId).toMatch(/^autonomous/);
|
||||
expect(steerReply?.turnId).not.toBe(firstReply?.turnId);
|
||||
expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("idle");
|
||||
},
|
||||
{ timeout: 50_000, interval: 250 },
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(callerPrompts).toHaveLength(2), {
|
||||
timeout: 5_000,
|
||||
interval: 100,
|
||||
});
|
||||
const [first, second] = callerPrompts.map((prompt) => parseAgentMessage(prompt)!);
|
||||
for (const notice of [first, second]) {
|
||||
expect(notice.source).toMatchObject({
|
||||
kind: "agent-notification",
|
||||
agentId: childId,
|
||||
event: "finished",
|
||||
});
|
||||
}
|
||||
expect(first.text).toContain("FIRST_DONE");
|
||||
expect(first.text).toContain("You will be notified again");
|
||||
expect(second.text).toContain(token);
|
||||
expect(second.text).not.toContain("You will be notified again");
|
||||
} finally {
|
||||
writeFileSync(hookReleasePath, "");
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
@@ -7745,4 +7745,89 @@ describe("session agent_update and agent_stream ordering", () => {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("agent-originated send_agent_message defaults omitted activeTurnBehavior to steer for modern clients and keeps explicit queue", async () => {
|
||||
const receiptDir = mkdtempSync(join(tmpdir(), "paseo-agent-default-steer-"));
|
||||
const dispatched: Array<{ activeTurnBehavior: string; idleOnly: boolean }> = [];
|
||||
const agentMessages = createAgentMessageDelivery({
|
||||
store: createMemoryAgentMessageQueueStore(),
|
||||
paseoHome: receiptDir,
|
||||
isRunning: () => true,
|
||||
canSteer: () => true,
|
||||
dispatch: async (request) => {
|
||||
dispatched.push({
|
||||
activeTurnBehavior: request.activeTurnBehavior,
|
||||
idleOnly: request.idleOnly,
|
||||
});
|
||||
return "steered";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const messages: SessionOutboundMessage[] = [];
|
||||
const session = createSessionForTest({
|
||||
messages,
|
||||
agentMessages,
|
||||
messageReceipts: new MessageReceipts(receiptDir),
|
||||
paseoHome: receiptDir,
|
||||
agentManager: {
|
||||
getAgent: (id: string) =>
|
||||
({
|
||||
id,
|
||||
status: "running",
|
||||
config: { title: id === "sender-1" ? "Sender" : null },
|
||||
}) as never,
|
||||
},
|
||||
agentStorage: {
|
||||
get: async (id: string) =>
|
||||
({ id, title: id === "sender-1" ? "Sender" : null, lastUserMessageAt: null }) as never,
|
||||
},
|
||||
});
|
||||
session.updateClientCapabilities({ agent_active_turn_behaviors: true });
|
||||
|
||||
try {
|
||||
await session.handleMessage({
|
||||
type: "send_agent_message_request",
|
||||
requestId: "req-default",
|
||||
agentId: "agent-1",
|
||||
sourceAgentId: "sender-1",
|
||||
text: "Steer by default",
|
||||
messageId: "msg-steer-default",
|
||||
});
|
||||
expect(findByType(messages, "send_agent_message_response")).toMatchObject({
|
||||
payload: {
|
||||
requestId: "req-default",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "steer",
|
||||
},
|
||||
});
|
||||
await expect.poll(() => dispatched.length).toBe(1);
|
||||
expect(dispatched[0]).toEqual({ activeTurnBehavior: "steer", idleOnly: false });
|
||||
|
||||
messages.length = 0;
|
||||
await session.handleMessage({
|
||||
type: "send_agent_message_request",
|
||||
requestId: "req-explicit-queue",
|
||||
agentId: "agent-1",
|
||||
sourceAgentId: "sender-1",
|
||||
text: "Wait explicitly",
|
||||
messageId: "msg-explicit-queue",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(findByType(messages, "send_agent_message_response")).toMatchObject({
|
||||
payload: {
|
||||
requestId: "req-explicit-queue",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
await agentMessages.close();
|
||||
rmSync(receiptDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9909,7 +9909,7 @@ export class Session {
|
||||
}
|
||||
}
|
||||
|
||||
/** An agent sender's message waits for the running turn to end unless it asks otherwise. */
|
||||
/** An agent sender's message steers by default (or queues if its provider cannot steer). */
|
||||
private agentSenderBehavior(
|
||||
requested: AgentActiveTurnBehavior | undefined,
|
||||
): AgentMessageBehavior {
|
||||
@@ -9918,7 +9918,7 @@ export class Session {
|
||||
// meaning wait for the turn to end, so only their interrupt stays an interrupt.
|
||||
if (!this.supports(CLIENT_CAPS.agentActiveTurnBehaviors))
|
||||
return requested === "interrupt" ? "interrupt" : "queue";
|
||||
return requested ?? "queue";
|
||||
return requested ?? "steer";
|
||||
}
|
||||
|
||||
private async handleAgentProviderSwitchRequest(
|
||||
|
||||
@@ -878,6 +878,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
})
|
||||
: await sendPreparedPromptToAgent({
|
||||
...send,
|
||||
replaceRunning: batch.replaceRunning,
|
||||
sessionMode: batch.sessionMode,
|
||||
runOptions: { clientMessageId: batch.messageIds[0] },
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.19.0-beta.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.19.0-beta.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 });
|
||||
}
|
||||
});
|
||||
@@ -96,13 +96,13 @@ Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false`
|
||||
|
||||
**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Sends a follow-up to an existing agent and returns at once.
|
||||
|
||||
Leave `activeTurnBehavior` out unless the message cannot wait. It decides what happens when the agent is mid-turn:
|
||||
Leave `activeTurnBehavior` out unless you want non-default handling when the agent is mid-turn:
|
||||
|
||||
- `queue` (default): the message waits for the turn to end.
|
||||
- `steer`: the agent reads the message at its next step and keeps working. If its provider cannot steer, the turn is interrupted instead.
|
||||
- `interrupt`: the turn stops, and a new turn starts with the message.
|
||||
- `steer` (default): the agent reads the message at its next step and keeps working. If its provider cannot steer (or refuses steering mid-turn), the message waits until the turn ends instead of interrupting it.
|
||||
- `queue`: wait until the running turn ends.
|
||||
- `interrupt`: stop the running turn and start a new turn with the message.
|
||||
|
||||
Read `guidance` in the response. If it says your message is waiting and the message cannot wait, such as a course correction, send a short follow-up with `steer` or `interrupt`. Do not resend the message: the follow-up carries it, and a resent message is read twice.
|
||||
Read `guidance` in the response. If your message is waiting for turn end and cannot wait, send a short `interrupt` follow-up instead of resending (agent follow-ups carry earlier agent-queued messages ahead of them).
|
||||
|
||||
A steer the agent has not read is lost if its turn stops or is interrupted, along with the messages it carried. For a message that must arrive, use `queue` or `interrupt`.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user