diff --git a/.github/ci-paths.yml b/.github/ci-paths.yml index 87fc924b6b84..baf6de02e7a1 100644 --- a/.github/ci-paths.yml +++ b/.github/ci-paths.yml @@ -50,6 +50,7 @@ desktop: app: - "packages/app/**" - "packages/expo-two-way-audio/**" + - "packages/react-native-enriched-markdown/**" sdk: - "packages/plugin/**" @@ -80,6 +81,7 @@ browser: - "packages/app/index.ts" - "packages/app/*config.{cjs,js,ts}" - "packages/app/package.json" + - "packages/react-native-enriched-markdown/**" relay: - "packages/relay/**" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bdaf833a079c..8b1495c4d93b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ name: CI on: push: - branches: [main] + branches: [main, "release/**"] # Every base branch, so stacked PRs and PRs into any base get the same checks. pull_request: merge_group: @@ -24,6 +24,8 @@ env: # CI does not use the CUDA execution provider, and the onnxruntime-node # postinstall download from NuGet is large enough to make npm ci flaky. ONNXRUNTIME_NODE_INSTALL: skip + NPM_CONFIG_AUDIT: "false" + NPM_CONFIG_FUND: "false" jobs: changes: @@ -60,7 +62,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/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-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 quality: name: quality @@ -169,8 +171,29 @@ jobs: - name: Run website tests run: npx vitest run packages/website/src --bail=1 + # WebKit needs about 180 system packages (125 MB) from the Ubuntu mirror. The mirror + # sometimes serves them at under 100 kB/s, which turns a 1-minute step into 25 minutes. + # Keep the downloaded .deb files in the Actions cache so apt installs them without the mirror. + - name: Restore website browser system packages + uses: actions/cache@v4 + with: + path: ~/website-browser-debs + key: website-browser-debs-${{ runner.os }}-${{ hashFiles('package-lock.json') }} + restore-keys: website-browser-debs-${{ runner.os }}- + - name: Install website test browsers - run: npx playwright install --with-deps chromium webkit + run: | + mkdir -p ~/website-browser-debs + shopt -s nullglob + cached_debs=(~/website-browser-debs/*.deb) + if (( ${#cached_debs[@]} > 0 )); then + sudo cp "${cached_debs[@]}" /var/cache/apt/archives/ + fi + npx playwright install --with-deps chromium webkit + archive_debs=(/var/cache/apt/archives/*.deb) + if (( ${#archive_debs[@]} > 0 )); then + cp "${archive_debs[@]}" ~/website-browser-debs/ + fi - name: Verify website mockups run: npm run test:e2e --workspace=@getpaseo/website @@ -331,10 +354,7 @@ jobs: run: npm run test:integration --workspace=@getpaseo/server env: *server_test_env - # native-recursive.ts serves darwin and win32, but windows-latest above is the only - # runner that exercises it. macOS — the platform the reported watcher bug was on — - # otherwise has no server-test coverage. Scoped to the observer/watcher suites to - # bound runtime. + # Keep this job scoped to regressions reported on macOS. server-tests-macos: name: server-tests (macos-latest, file observation) needs: changes @@ -362,6 +382,24 @@ jobs: src/server/workspace-git-service.observation.integration.test.ts \ --bail=1 + - name: Verify path casing on macOS + run: | + npm run test:unit --workspace=@getpaseo/server -- \ + src/server/agent/agent-storage.test.ts \ + src/utils/directory-suggestions.test.ts \ + --bail=1 + + - name: Verify plugin compiler children are reaped + run: | + npm run test:unit --workspace=@getpaseo/server -- \ + src/server/plugins/index.posix.test.ts \ + -t "reaps compiler children" --bail=1 + + - name: Verify plugin session sockets survive a dead plugin child + run: | + npm run test:unit --workspace=@getpaseo/server -- \ + src/server/plugins/session-socket.posix.test.ts --bail=1 + desktop-tests-ubuntu: name: desktop-tests (ubuntu-latest) needs: changes @@ -515,9 +553,9 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} E2E_WORKERS: "2" # File groups are weighted by observed reporter durations. - # Share of the test list per shard, rebalanced from the Playwright step - # minutes of five eight-shard runs so the slowest and fastest shards meet. - PWTEST_SHARD_WEIGHTS: "85:94:117:128:91:103:127:85" + # Share of the test list per shard, rebalanced from main and PR eight-shard + # durations so the slowest and fastest shards meet. + PWTEST_SHARD_WEIGHTS: "90:114:100:104:108:112:112:90" - name: Upload test artifacts uses: actions/upload-artifact@v4 @@ -631,9 +669,14 @@ jobs: # Source tests do not read PASEO_CLI_TEST_SHARD. Run them once, on the # shortest E2E shard, after its runner has built the server stack. - name: Run CLI source tests - if: ${{ env.PASEO_CLI_TEST_SHARD == '3' }} + if: ${{ env.PASEO_CLI_TEST_SHARD == '2' }} run: npm run test:unit --workspace=@getpaseo/cli + # The dependency watchers write build outputs, so run them after the parallel CLI tests. + - name: Run dev watch shutdown regression + if: ${{ env.PASEO_CLI_TEST_SHARD == '3' }} + run: node --import tsx packages/cli/tests/23-daemon-sigint-supervisor.test.ts --dev-watch + cli-tests-2: name: cli-tests (shard 2/3) needs: changes diff --git a/.github/workflows/desktop-packages.yml b/.github/workflows/desktop-packages.yml index 77e2735c6ae6..08cbf0055b4f 100644 --- a/.github/workflows/desktop-packages.yml +++ b/.github/workflows/desktop-packages.yml @@ -2,7 +2,7 @@ name: Desktop Packages on: push: - branches: [main] + branches: [main, "release/**"] # Packaging leaves ordinary PR CI, but a PR that changes what gets packaged # or how it is smoked still proves the real artifacts before merge. pull_request: @@ -11,10 +11,11 @@ on: - "plugins/**" - "nix/**" - ".github/workflows/desktop-packages.yml" + workflow_dispatch: concurrency: group: desktop-packages-${{ github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + cancel-in-progress: true permissions: contents: read diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 5ac8c9350c63..d169c5f23d4f 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -196,33 +196,11 @@ jobs: run: | set -euo pipefail export PASEO_REAL_XCRUN="$(command -v xcrun)" - stapler_bin="$(mktemp -d)" - trap 'rm -rf "$stapler_bin"' EXIT - cat > "$stapler_bin/xcrun" <<'STAPLER' - #!/bin/bash - if [[ "${1:-}" != stapler || "${2:-}" != staple ]]; then - exec "$PASEO_REAL_XCRUN" "$@" - fi - output="$(mktemp)" - trap 'rm -f "$output"' EXIT - for attempt in 1 2 3 4; do - if "$PASEO_REAL_XCRUN" "$@" >"$output" 2>&1; then - cat "$output" - exit 0 - else - status=$? - fi - cat "$output" - if [[ "$status" != 68 || "$attempt" == 4 ]] || - ! grep -Fq 'NSURLErrorDomain Code=-1005' "$output"; then - exit "$status" - fi - echo "::warning::Apple staple connection lost; retrying the same signed app ($attempt/4)" >&2 - sleep 30 - done - STAPLER - chmod +x "$stapler_bin/xcrun" - export PATH="$stapler_bin:$PATH" + xcrun_bin="$(mktemp -d)" + trap 'rm -rf "$xcrun_bin"' EXIT + cp scripts/macos-xcrun-retry.sh "$xcrun_bin/xcrun" + chmod +x "$xcrun_bin/xcrun" + export PATH="$xcrun_bin:$PATH" build_args=(-- --publish never --mac --${{ matrix.electron_arch }}) build_args+=("-c.publish.releaseType=$RELEASE_TYPE") build_args+=("-c.publish.channel=$RELEASE_CHANNEL") @@ -528,6 +506,7 @@ jobs: shell: bash run: | set -euo pipefail + mkdir -p release-manifests cd release-manifests manifests_dir="$PWD/final" mkdir -p "$manifests_dir" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index aa53f3ec8183..1a243dea7f31 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -29,8 +29,8 @@ on: - "true" concurrency: - group: docker-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: false + group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }} + cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }} env: REGISTRY: ghcr.io diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index b65356479399..72db40e230d1 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -3,6 +3,7 @@ name: Nix on: push: branches: [main] + workflow_dispatch: permissions: contents: read diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 647eabe3e472..c8b79265dab1 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -11,5 +11,11 @@ "arrowParens": "always", "bracketSameLine": false, "bracketSpacing": true, - "ignorePatterns": ["*.lock", "**/*.gen.ts", "**/*.gen.tsx", "fork/**/*.md"] + "ignorePatterns": [ + "*.lock", + "**/*.gen.ts", + "**/*.gen.tsx", + "fork/**/*.md", + "packages/react-native-enriched-markdown/**" + ] } diff --git a/.oxlintrc.json b/.oxlintrc.json index 9ec21e99b05f..a0f0e1b5f33a 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -3,7 +3,7 @@ "options": { "typeAware": false }, - "ignorePatterns": [".dev/**"], + "ignorePatterns": [".dev/**", "packages/react-native-enriched-markdown/**"], "plugins": ["react", "react-perf", "unicorn", "typescript", "oxc", "import", "promise"], "jsPlugins": ["./scripts/oxlint/paseo-plugin.mjs"], "categories": { diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b4b3dce520d..6cd57b74869b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,56 +1,146 @@ # Changelog -## 0.17.0-beta.1 - 2026-11-19 +## 0.17.4 - 2026-11-23 -- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from any branch or pull request. ([#10190](https://github.com/getpaseo/paseo/pull/10190)) -- **Antigravity approvals and history:** Pick a permission mode, answer tool approvals, import CLI sessions and see your history when you reopen a chat. ([#10193](https://github.com/getpaseo/paseo/pull/10193)) -- **Watch pull requests:** Agents can watch a GitHub PR and get notified when checks, reviews or comments change. ([#10148](https://github.com/getpaseo/paseo/pull/10148)) +### Fixed + +- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android ([#10499](https://github.com/getpaseo/paseo/pull/10499)) +- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning ([#10586](https://github.com/getpaseo/paseo/pull/10586)) +- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system ([#10555](https://github.com/getpaseo/paseo/pull/10555) by [@yzim](https://github.com/yzim)) +- Fixed interrupt and steer messages to archived agents being queued without starting a turn ([#10611](https://github.com/getpaseo/paseo/pull/10611) by [@thomasvan](https://github.com/thomasvan)) +- Fixed Hermes Shell rows omitting part of the command ([#10614](https://github.com/getpaseo/paseo/pull/10614)) +- Fixed OpenCode Go usage for logins stored in the OpenCode 2 database, including Console sign-ins and API keys ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612)) +- Fixed existing OpenCode sessions failing to reopen after Paseo tool definitions change ([#10533](https://github.com/getpaseo/paseo/pull/10533) by [@Peanut-HZM](https://github.com/Peanut-HZM)) +- Fixed Paseo tools missing from agents that use MCP protocol version `2026-07-28` ([#10558](https://github.com/getpaseo/paseo/pull/10558) by [@apple-ouyang](https://github.com/apple-ouyang)) +- Fixed Codex MCP startup failures missing from daemon warning logs ([#10566](https://github.com/getpaseo/paseo/pull/10566)) +- Fixed the daemon exiting when it closes a session after the plugin process has stopped ([#10585](https://github.com/getpaseo/paseo/pull/10585)) +- Fixed Git commands selecting the wrong repository when a directory has the layout of a bare repository ([#10587](https://github.com/getpaseo/paseo/pull/10587)) +- Fixed Claude Auto permission mode being unavailable on Bedrock and Vertex ([#6904](https://github.com/getpaseo/paseo/pull/6904)) +- Fixed the sidebar host settings button requiring two clicks to open settings ([#10562](https://github.com/getpaseo/paseo/pull/10562) by [@ShalokShalom](https://github.com/ShalokShalom)) +- Fixed the Changes pane not offering Push for a new branch that was never pushed in a regular checkout ([#10631](https://github.com/getpaseo/paseo/pull/10631)) +- Fixed the daemon using the wrong model catalog when Hub sends a workspace directory for trigger validation ([#10582](https://github.com/getpaseo/paseo/pull/10582)) + +## 0.17.3 - 2026-11-22 + +### Fixed + +- Fixed iPhone sheets such as Workspace tabs ignoring body swipes to expand, scroll, or collapse ([#10525](https://github.com/getpaseo/paseo/pull/10525)) +- Fixed Antigravity applying the default model's thinking levels to every model, which blocked Orchestrator chats from opening ([#10524](https://github.com/getpaseo/paseo/pull/10524)) +- Fixed `/` and `@` pickers disappearing until reload after returning to a workspace through window history ([#8954](https://github.com/getpaseo/paseo/pull/8954) by [@viking1201](https://github.com/viking1201)) + +## 0.17.2 - 2026-11-22 + +- **Turn and session stats:** View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers. ([#10496](https://github.com/getpaseo/paseo/pull/10496), [#10510](https://github.com/getpaseo/paseo/pull/10510)) +- **Automatic model list refresh:** Enabled providers refresh their model lists in the background every 30 minutes. ([#10481](https://github.com/getpaseo/paseo/pull/10481)) +- **Sidebar usage by default:** The sidebar usage summary is enabled by default, sources for inactive providers start hidden, and source toggles move to a Sources list. ([#10491](https://github.com/getpaseo/paseo/pull/10491)) +- **Agents can steer turns:** Agents can steer another agent's running turn alongside queueing or interrupting it, and receive delivery guidance in the response. ([#10483](https://github.com/getpaseo/paseo/pull/10483)) + +### Added + +- Added Archive workspace to the mobile workspace actions menu ([#10507](https://github.com/getpaseo/paseo/pull/10507)) +- Added provider docs links, fuller diagnostic reports, and a scrollable Models list with inline refresh to provider settings ([#10487](https://github.com/getpaseo/paseo/pull/10487)) + +### Changed + +- Removed the "This chat uses OpenCode v2." info row from OpenCode v2 chats ([#10490](https://github.com/getpaseo/paseo/pull/10490)) + +### Fixed + +- Fixed pressing Tab or Enter in the slash menu running a stale `/exit` choice and archiving the agent ([#10484](https://github.com/getpaseo/paseo/pull/10484) by [@3ae3ae](https://github.com/3ae3ae)) +- Fixed busy host connections dropping to reconnect when multiple connections are saved ([#10395](https://github.com/getpaseo/paseo/pull/10395)) +- Fixed retrying an edited New workspace form hitting a conflict error after a failed start, and unified composer error alerts ([#10482](https://github.com/getpaseo/paseo/pull/10482)) +- Fixed Antigravity turns staying running after creating a recurring schedule ([#10469](https://github.com/getpaseo/paseo/pull/10469)) +- Fixed daemon startup and plugin reloads leaving zombie child processes for local directory plugins ([#10470](https://github.com/getpaseo/paseo/pull/10470)) + +## 0.17.1 - 2026-11-21 + +- **Antigravity approvals and history:** Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires [Antigravity CLI 1.5.0 or later](https://paseo.sh/docs/supported-providers/antigravity). ([#10193](https://github.com/getpaseo/paseo/pull/10193)) +- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from a branch or pull request. ([#10190](https://github.com/getpaseo/paseo/pull/10190)) +- **Update providers in Paseo:** See each provider's status and installed version, and update supported CLIs from the app. ([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661)) +- **Provider quota forecasts:** Usage shows when your current pace will use up a quota before it resets. ([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385)) +- **Watch PRs and MRs:** Ask an agent to watch a pull or merge request for new checks, reviews, and comments. ([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280)) - **Heartbeats in Background work:** See and stop an agent's heartbeats next to its background tasks. ([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216)) -- **Agent messages wait their turn:** Reports and notifications from other agents arrive when the current turn ends instead of interrupting it. ([#9757](https://github.com/getpaseo/paseo/pull/9757)) +- **Agent messages wait their turn:** By default, messages from other agents wait for the current turn to end. ([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404)) +- **More goose models:** Select models from every provider configured in goose. ([#9719](https://github.com/getpaseo/paseo/pull/9719) by [@i386](https://github.com/i386)) - **Plugin agent instructions:** Plugins can add their own instructions to agents. ([#9781](https://github.com/getpaseo/paseo/pull/9781)) ### Added +- Added OpenRouter credit balances and API key spending to Usage and `paseo usage` ([#10269](https://github.com/getpaseo/paseo/pull/10269)) +- Added Antigravity account quotas to Usage ([#10232](https://github.com/getpaseo/paseo/pull/10232) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- Added Antigravity skills to `/` suggestions ([#10383](https://github.com/getpaseo/paseo/pull/10383)) +- Added bundled orchestration skills to Antigravity ([#10273](https://github.com/getpaseo/paseo/pull/10273)) - Added shortcuts to open the model picker and cycle thinking levels with Cmd/Ctrl+/ and Cmd/Ctrl+Shift+/ ([#10147](https://github.com/getpaseo/paseo/pull/10147)) - Added agent settings to Command Center search before the first message ([#10182](https://github.com/getpaseo/paseo/pull/10182) by [@cleiter](https://github.com/cleiter)) - Added Rewind to Command Center for the latest turn ([#10144](https://github.com/getpaseo/paseo/pull/10144)) -- Added a separate Ultracode toggle for eligible Claude models ([#10150](https://github.com/getpaseo/paseo/pull/10150) by [@fivetaku](https://github.com/fivetaku)) +- Added a separate Ultracode toggle for Claude ([#10150](https://github.com/getpaseo/paseo/pull/10150) by [@fivetaku](https://github.com/fivetaku)) - Added Flex speed for Codex ([#9809](https://github.com/getpaseo/paseo/pull/9809) by [@qjqqyy](https://github.com/qjqqyy)) - Added syntax highlighting for shell scripts and Dockerfiles ([#10178](https://github.com/getpaseo/paseo/pull/10178)) +- Added project listing on connected daemons for Hub sessions ([#10392](https://github.com/getpaseo/paseo/pull/10392)) - Added labels and workspace IDs to `paseo ls --json` ([#10076](https://github.com/getpaseo/paseo/pull/10076)) ### Changed +- Changed content width to Default, Wide, and Full presets that also resize open chats and Markdown previews ([#10231](https://github.com/getpaseo/paseo/pull/10231)) +- Changed Antigravity tool cards to show shell commands, output, and file diffs ([#10379](https://github.com/getpaseo/paseo/pull/10379)) +- Changed Clone from GitHub to show matching private repositories first ([#10264](https://github.com/getpaseo/paseo/pull/10264)) +- Changed healthy quota bars in Usage to green ([#10397](https://github.com/getpaseo/paseo/pull/10397)) +- Changed worktree teardown to keep the worktree when the command times out ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan)) +- Changed workspace navigation on mobile to acknowledge taps sooner ([#9887](https://github.com/getpaseo/paseo/pull/9887)) +- Changed workspace Git status to skip its reload after a short reconnect with no file changes ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP)) - Changed `browser_new_tab` to ask agents to choose a Desktop when several are connected ([#10189](https://github.com/getpaseo/paseo/pull/10189)) -- Changed workspace Git status to reuse its snapshot after a short reconnect when the checkout has not changed ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP)) -- Changed workspace navigation to acknowledge taps promptly and initially load fewer offscreen chat rows on mobile ([#9887](https://github.com/getpaseo/paseo/pull/9887)) -- Changed worktree teardown to stop after one minute by default and keep the worktree; set `worktree.teardownTimeoutMs` in `paseo.json` for longer commands ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan)) ### Fixed +- Fixed an online host's workspaces going missing ([#10318](https://github.com/getpaseo/paseo/pull/10318)) +- Fixed chat history timing out when many open chats refresh after reconnecting ([#10368](https://github.com/getpaseo/paseo/pull/10368)) +- Fixed slow reopening of long Claude chats while the daemon is busy ([#10369](https://github.com/getpaseo/paseo/pull/10369)) +- Fixed images from a live reply waiting for images in another chat's history to load ([#10371](https://github.com/getpaseo/paseo/pull/10371)) +- Fixed agents failing to recover after stopping a foreground daemon with Ctrl+C ([#10381](https://github.com/getpaseo/paseo/pull/10381)) +- Fixed long Antigravity chats losing the end of their history after a daemon restart ([#10428](https://github.com/getpaseo/paseo/pull/10428)) +- Fixed Antigravity turns ending while a background command is still running ([#10310](https://github.com/getpaseo/paseo/pull/10310)) +- Fixed the Add model sheet staying open after saving a custom model ([#10432](https://github.com/getpaseo/paseo/pull/10432)) +- Fixed slash suggestions failing when a provider reports duplicate command names ([#10275](https://github.com/getpaseo/paseo/pull/10275)) +- Fixed resumed Codex sessions using their previous working directory for configuration and MCP servers ([#10390](https://github.com/getpaseo/paseo/pull/10390) by [@tabulius-ux](https://github.com/tabulius-ux)) +- Fixed stale Codex subagent statuses after reopening or rewinding the parent chat ([#10171](https://github.com/getpaseo/paseo/pull/10171) by [@AnalyticETH](https://github.com/AnalyticETH)) +- Fixed Usage showing the previous Claude account's quota after switching accounts ([#10236](https://github.com/getpaseo/paseo/pull/10236)) +- Fixed the sidebar usage row dropping period labels when several usage windows are pinned ([#10274](https://github.com/getpaseo/paseo/pull/10274)) +- Fixed Changes failing to recognize a checkout immediately after restoring its worktree ([#10224](https://github.com/getpaseo/paseo/pull/10224), [#10304](https://github.com/getpaseo/paseo/pull/10304), [#10406](https://github.com/getpaseo/paseo/pull/10406)) +- Fixed split-pane dividers stopping or lagging during drags ([#5996](https://github.com/getpaseo/paseo/pull/5996)) +- Fixed double-click word selection and triple-click line selection in diffs ([#10252](https://github.com/getpaseo/paseo/pull/10252) by [@pedrovieira](https://github.com/pedrovieira)) +- Fixed the composer and chat column losing alignment when Chat outline is enabled ([#10277](https://github.com/getpaseo/paseo/pull/10277)) +- Fixed the web composer's focus shortcut hint overlapping the placeholder ([#6200](https://github.com/getpaseo/paseo/pull/6200)) +- Fixed the archive shortcut failing when the active workspace's sidebar group is collapsed ([#10356](https://github.com/getpaseo/paseo/pull/10356) by [@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud)) +- Fixed other sessions and plugins seeing a workspace as active while another session is archiving it ([#10391](https://github.com/getpaseo/paseo/pull/10391) by [@tabulius-ux](https://github.com/tabulius-ux)) +- Fixed Android composer buttons requiring a second tap after typing or zooming a chat image ([#10057](https://github.com/getpaseo/paseo/pull/10057), [#10308](https://github.com/getpaseo/paseo/pull/10308)) +- Fixed swiping a terminal in an Android browser opening the keyboard ([#10225](https://github.com/getpaseo/paseo/pull/10225) by [@tonylt](https://github.com/tonylt)) - Fixed Collapse turns hiding a finished OMP or Pi reply when an idle provider notice appears ([#10135](https://github.com/getpaseo/paseo/pull/10135)) -- Fixed repeated finish notifications while an agent responds to background tasks and its earlier finish is unread ([#10200](https://github.com/getpaseo/paseo/pull/10200)) +- Fixed repeated finish notifications while an agent responds to background tasks ([#10200](https://github.com/getpaseo/paseo/pull/10200)) - Fixed an empty chat losing the prompt and start of a reply after reconnecting mid-reply ([#9723](https://github.com/getpaseo/paseo/pull/9723) by [@ragokan](https://github.com/ragokan)) -- Fixed changes between Claude thinking levels stopping its background work ([#10008](https://github.com/getpaseo/paseo/pull/10008) by [@gilad-rubin](https://github.com/gilad-rubin)) +- Fixed changing the Claude thinking level stopping its background work ([#10008](https://github.com/getpaseo/paseo/pull/10008) by [@gilad-rubin](https://github.com/gilad-rubin)) - Fixed OpenCode turns staying running after a shared OpenCode service stops ([#10187](https://github.com/getpaseo/paseo/pull/10187)) - Fixed OMP denying an approved tool call when session or grant choices were offered ([#10126](https://github.com/getpaseo/paseo/pull/10126) by [@dsingal0](https://github.com/dsingal0)) +- Fixed a Codex message stopped before its turn starts showing an error instead of canceled ([#9931](https://github.com/getpaseo/paseo/pull/9931) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed Changes failing to open when Git metadata watching reaches its limit ([#10188](https://github.com/getpaseo/paseo/pull/10188)) - Fixed copying selected reply text into plain-text targets with unwanted Markdown syntax ([#10079](https://github.com/getpaseo/paseo/pull/10079) by [@danberindei](https://github.com/danberindei)) -- Fixed file views losing their scroll position when switching Preview and Source, except HTML previews on iOS ([#10195](https://github.com/getpaseo/paseo/pull/10195) by [@apple-ouyang](https://github.com/apple-ouyang)) +- Fixed Markdown previews and source views losing their scroll position when switching between them ([#10195](https://github.com/getpaseo/paseo/pull/10195) by [@apple-ouyang](https://github.com/apple-ouyang)) - Fixed file tabs in split panes showing or focusing the wrong file ([#9888](https://github.com/getpaseo/paseo/pull/9888) by [@KosmoCHE](https://github.com/KosmoCHE)) - Fixed touch-screen submenus closing as soon as they open ([#10175](https://github.com/getpaseo/paseo/pull/10175) by [@christiantwu](https://github.com/christiantwu)) - Fixed dictation failing after another chat that used the microphone closes ([#10185](https://github.com/getpaseo/paseo/pull/10185) by [@Brandon168](https://github.com/Brandon168)) -- Fixed composer taps being lost on Android after zooming a chat image ([#10057](https://github.com/getpaseo/paseo/pull/10057)) - Fixed clipped text on Samsung DeX ([#9995](https://github.com/getpaseo/paseo/pull/9995) by [@easyhunjune](https://github.com/easyhunjune)) - Fixed workspace images in chat failing to load after a slow host connection ([#10111](https://github.com/getpaseo/paseo/pull/10111) by [@ragokan](https://github.com/ragokan)) - Fixed desktop browser screenshots returning fully transparent images ([#9807](https://github.com/getpaseo/paseo/pull/9807) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) - Fixed Mermaid flowcharts with `@` in labels showing source instead of the diagram ([#10165](https://github.com/getpaseo/paseo/pull/10165) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) - Fixed hidden background workspaces triggering the dock badge and favicon ([#9983](https://github.com/getpaseo/paseo/pull/9983)) - Fixed desktop sidebar navigation crowding out workspaces ([#9903](https://github.com/getpaseo/paseo/pull/9903) by [@pentatonic-alex](https://github.com/pentatonic-alex)) +- Fixed closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053)) - Fixed plugin agents failing to reopen after their provider closes the session ([#10153](https://github.com/getpaseo/paseo/pull/10153)) - Fixed plugin screens and settings failing to use plugin state hooks ([#10049](https://github.com/getpaseo/paseo/pull/10049)) -- Fixed a Codex message stopped before its turn starts showing an error instead of canceled ([#9931](https://github.com/getpaseo/paseo/pull/9931) by [@3ae3ae](https://github.com/3ae3ae)) -- Fixed historical closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053)) + +### Plugins + +- Added plugin control of worktree creation, removal, and restoration ([#10278](https://github.com/getpaseo/paseo/pull/10278)) +- Added a `focusHost` navigation option that selects the destination host in the sidebar ([#5574](https://github.com/getpaseo/paseo/pull/5574) by [@discwl](https://github.com/discwl)) ## 0.16.2 - 2026-11-18 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 4639ea80e5e5..74a27729ad3b 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,56 +1,146 @@ # Changelog -## 0.17.0-beta.1 - 2026-11-19 +## 0.17.4 - 2026-11-23 -- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从任意分支或 PR 创建 worktree。([#10190](https://github.com/getpaseo/paseo/pull/10190)) -- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批、导入 CLI 会话,并在重新打开对话时查看历史记录。([#10193](https://github.com/getpaseo/paseo/pull/10193)) -- **监视 PR**:Agent 可以监视 GitHub PR,在检查、审查或评论有变化时收到通知。([#10148](https://github.com/getpaseo/paseo/pull/10148)) +### 修复 + +- 修复 Android 上嵌套编号列表的编号与正文重叠,以及列表中的引用与后续消息重叠的问题 ([#10499](https://github.com/getpaseo/paseo/pull/10499)) +- 修复 Android 终端输入,要求键盘不将输入内容用于个性化学习 ([#10586](https://github.com/getpaseo/paseo/pull/10586)) +- 修复在不区分大小写的文件系统上,目录路径大小写不一致导致对话消失的问题 ([#10555](https://github.com/getpaseo/paseo/pull/10555),贡献者:[@yzim](https://github.com/yzim)) +- 修复发给已归档 Agent 的中断和引导消息进入队列后未启动新轮次的问题 ([#10611](https://github.com/getpaseo/paseo/pull/10611),贡献者:[@thomasvan](https://github.com/thomasvan)) +- 修复 Hermes 的 Shell 工具行只显示命令摘要的问题,现在会显示完整命令 ([#10614](https://github.com/getpaseo/paseo/pull/10614)) +- 修复使用 OpenCode 2 数据库中保存的登录凭据时的 Go 用量显示,涵盖 Console 登录和 API 密钥 ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612)) +- 修复 Paseo 工具定义变更后无法重新打开已有 OpenCode 会话的问题 ([#10533](https://github.com/getpaseo/paseo/pull/10533),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM)) +- 修复使用 MCP 协议版本 `2026-07-28` 的 Agent 缺少 Paseo 工具的问题 ([#10558](https://github.com/getpaseo/paseo/pull/10558),贡献者:[@apple-ouyang](https://github.com/apple-ouyang)) +- 修复 Codex MCP 启动失败时 daemon 未记录警告的问题 ([#10566](https://github.com/getpaseo/paseo/pull/10566)) +- 修复插件进程停止后 daemon 在关闭会话时退出的问题 ([#10585](https://github.com/getpaseo/paseo/pull/10585)) +- 修复目录结构与裸仓库相同时 Git 命令选错仓库的问题 ([#10587](https://github.com/getpaseo/paseo/pull/10587)) +- 修复在 Bedrock 和 Vertex 上无法选择 Claude Auto 权限模式的问题 ([#6904](https://github.com/getpaseo/paseo/pull/6904)) +- 修复侧边栏的主机设置按钮需要点击两次才能打开设置的问题 ([#10562](https://github.com/getpaseo/paseo/pull/10562),贡献者:[@ShalokShalom](https://github.com/ShalokShalom)) +- 修复普通检出中从未推送过的新分支在“变更”面板中不显示“推送”的问题 ([#10631](https://github.com/getpaseo/paseo/pull/10631)) +- 修复 Hub 在验证触发器时传入工作区目录后,daemon 使用错误模型目录的问题 ([#10582](https://github.com/getpaseo/paseo/pull/10582)) + +## 0.17.3 - 2026-11-22 + +### 修复 + +- 修复 iPhone 上“Workspace 标签”等弹窗忽略主体滑动、无法展开、滚动或收起的问题 ([#10525](https://github.com/getpaseo/paseo/pull/10525)) +- 修复 Antigravity 将默认模型的思考级别套用到所有模型,导致无法打开 Orchestrator 对话的问题 ([#10524](https://github.com/getpaseo/paseo/pull/10524)) +- 修复通过窗口历史记录返回工作区后,`/` 和 `@` 选择器在刷新前一直消失的问题 ([#8954](https://github.com/getpaseo/paseo/pull/8954),贡献者:[@viking1201](https://github.com/viking1201)) + +## 0.17.2 - 2026-11-22 + +- **回合和会话统计**:查看 Claude、OpenCode v2、Pi、Oh My Pi 和插件 Provider 的单轮及会话耗时、token、缓存和费用指标。([#10496](https://github.com/getpaseo/paseo/pull/10496), [#10510](https://github.com/getpaseo/paseo/pull/10510)) +- **自动刷新模型列表**:已启用的 Provider 每 30 分钟在后台刷新一次模型列表。([#10481](https://github.com/getpaseo/paseo/pull/10481)) +- **默认显示侧边栏用量**:侧边栏用量摘要现在默认开启,未启用 Provider 的用量来源默认隐藏,来源开关移至“来源”列表。([#10491](https://github.com/getpaseo/paseo/pull/10491)) +- **Agent 可引导进行中的轮次**:Agent 除了排队或中断外,现在可以引导另一个 Agent 正在运行的轮次,并在响应中收到投递指引。([#10483](https://github.com/getpaseo/paseo/pull/10483)) + +### 新增 + +- 在移动端工作区操作菜单中新增“归档工作区” ([#10507](https://github.com/getpaseo/paseo/pull/10507)) +- 在 Provider 设置中新增文档链接、更完整的诊断报告,以及带内联刷新按钮的可滚动 Models 列表 ([#10487](https://github.com/getpaseo/paseo/pull/10487)) + +### 变更 + +- 移除 OpenCode v2 对话中的“This chat uses OpenCode v2.”提示行 ([#10490](https://github.com/getpaseo/paseo/pull/10490)) + +### 修复 + +- 修复在斜杠菜单中按 Tab 或 Enter 时误触发过期的 `/exit` 选项并归档 Agent 的问题 ([#10484](https://github.com/getpaseo/paseo/pull/10484),贡献者:[@3ae3ae](https://github.com/3ae3ae)) +- 修复保存了多个主机连接时,繁忙的正常连接会断开重连的问题 ([#10395](https://github.com/getpaseo/paseo/pull/10395)) +- 修复新建工作区启动失败后,修改表单再重试时出现冲突错误的问题,并统一了 Composer 错误提示 ([#10482](https://github.com/getpaseo/paseo/pull/10482)) +- 修复 Antigravity 创建循环定时任务后轮次一直停留在运行状态的问题 ([#10469](https://github.com/getpaseo/paseo/pull/10469)) +- 修复启动 daemon 和重载本地目录插件后遗留僵尸子进程的问题 ([#10470](https://github.com/getpaseo/paseo/pull/10470)) + +## 0.17.1 - 2026-11-21 + +- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批,以及导入或重新打开会话。需要 [Antigravity CLI 1.5.0 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity)。([#10193](https://github.com/getpaseo/paseo/pull/10193)) +- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从分支或 PR 创建 worktree。([#10190](https://github.com/getpaseo/paseo/pull/10190)) +- **在 Paseo 中更新 Provider**:查看各 Provider 的状态和已安装版本,并在应用内更新受支持的 CLI。([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661)) +- **Provider 配额预测**:“使用情况”页面会显示配额按当前使用速度将在重置前何时用完。([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385)) +- **监视 PR 和 MR**:让 Agent 监视 PR 或 MR 的检查、审查和评论更新。([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280)) - **在后台任务中查看 heartbeat**:在 Agent 的后台任务旁查看和停止 heartbeat。([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216)) -- **Agent 消息排队等待**:其他 Agent 的报告和通知会在当前轮次结束后到达,不会打断当前轮次。([#9757](https://github.com/getpaseo/paseo/pull/9757)) +- **Agent 消息排队等待**:默认情况下,其他 Agent 的消息会等当前轮次结束后再送达。([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404)) +- **更多 goose 模型**:从 goose 中已配置的所有 Provider 选择模型。([#9719](https://github.com/getpaseo/paseo/pull/9719),贡献者:[@i386](https://github.com/i386)) - **插件 Agent 指令**:插件可以向 Agent 添加自己的指令。([#9781](https://github.com/getpaseo/paseo/pull/9781)) ### 新增 +- 在“使用情况”页面和 `paseo usage` 中新增 OpenRouter 余额和 API 密钥支出 ([#10269](https://github.com/getpaseo/paseo/pull/10269)) +- 在“使用情况”页面新增 Antigravity 账号配额 ([#10232](https://github.com/getpaseo/paseo/pull/10232),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev)) +- 在 `/` 建议中新增 Antigravity 技能 ([#10383](https://github.com/getpaseo/paseo/pull/10383)) +- 为 Antigravity 新增内置编排技能 ([#10273](https://github.com/getpaseo/paseo/pull/10273)) - 新增 Cmd/Ctrl+/ 和 Cmd/Ctrl+Shift+/ 快捷键,用于打开模型选择器和切换思考级别 ([#10147](https://github.com/getpaseo/paseo/pull/10147)) - 新增在发送第一条消息前通过命令中心搜索 Agent 设置 ([#10182](https://github.com/getpaseo/paseo/pull/10182),贡献者:[@cleiter](https://github.com/cleiter)) - 新增在命令中心回退最近轮次的操作 ([#10144](https://github.com/getpaseo/paseo/pull/10144)) -- 新增符合条件的 Claude 模型的独立 Ultracode 开关 ([#10150](https://github.com/getpaseo/paseo/pull/10150),贡献者:[@fivetaku](https://github.com/fivetaku)) +- 新增 Claude 的独立 Ultracode 开关 ([#10150](https://github.com/getpaseo/paseo/pull/10150),贡献者:[@fivetaku](https://github.com/fivetaku)) - 新增 Codex Flex 速度选项 ([#9809](https://github.com/getpaseo/paseo/pull/9809),贡献者:[@qjqqyy](https://github.com/qjqqyy)) - 新增 shell 脚本和 Dockerfile 的语法高亮 ([#10178](https://github.com/getpaseo/paseo/pull/10178)) +- 为 Hub 会话新增列出已连接 daemon 项目的能力 ([#10392](https://github.com/getpaseo/paseo/pull/10392)) - 新增 `paseo ls --json` 输出的标签和工作区 ID ([#10076](https://github.com/getpaseo/paseo/pull/10076)) ### 变更 +- 将内容宽度改为默认、宽版和全宽预设,并同时调整已打开对话和 Markdown 预览的宽度 ([#10231](https://github.com/getpaseo/paseo/pull/10231)) +- Antigravity 工具卡片现在显示 shell 命令、输出和文件 diff ([#10379](https://github.com/getpaseo/paseo/pull/10379)) +- 从 GitHub 克隆时,优先显示匹配的私有仓库 ([#10264](https://github.com/getpaseo/paseo/pull/10264)) +- “使用情况”页面中健康的配额进度条改为绿色 ([#10397](https://github.com/getpaseo/paseo/pull/10397)) +- worktree 清理命令超时时保留 worktree ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan)) +- 手机端工作区导航更快响应点击 ([#9887](https://github.com/getpaseo/paseo/pull/9887)) +- 短暂重连且文件未更改时,工作区 Git 状态不再重新加载 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP)) - 连接多个 Desktop 时,`browser_new_tab` 会让 Agent 选择打开标签页的 Desktop ([#10189](https://github.com/getpaseo/paseo/pull/10189)) -- 工作区 Git 状态在短暂重连且检出的内容未更改时复用之前的快照 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP)) -- 工作区导航会立即响应点击,并在手机端初始加载时减少屏幕外的对话行数 ([#9887](https://github.com/getpaseo/paseo/pull/9887)) -- worktree 清理命令默认在一分钟后停止并保留 worktree;如需更长时间,可在 `paseo.json` 中设置 `worktree.teardownTimeoutMs` ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan)) ### 修复 +- 修复在线主机的工作区不显示的问题 ([#10318](https://github.com/getpaseo/paseo/pull/10318)) +- 修复重新连接后多个已打开的对话同时刷新时,历史记录加载超时的问题 ([#10368](https://github.com/getpaseo/paseo/pull/10368)) +- 修复 daemon 繁忙时,重新打开较长的 Claude 对话速度慢的问题 ([#10369](https://github.com/getpaseo/paseo/pull/10369)) +- 修复当前回复中的图片等待另一个对话的历史图片加载的问题 ([#10371](https://github.com/getpaseo/paseo/pull/10371)) +- 修复用 Ctrl+C 停止前台 daemon 后 Agent 恢复失败的问题 ([#10381](https://github.com/getpaseo/paseo/pull/10381)) +- 修复 daemon 重启后较长的 Antigravity 对话丢失末尾历史记录的问题 ([#10428](https://github.com/getpaseo/paseo/pull/10428)) +- 修复 Antigravity 后台命令仍在运行时轮次就已结束的问题 ([#10310](https://github.com/getpaseo/paseo/pull/10310)) +- 修复保存自定义模型后“添加模型”弹窗一直保持打开的问题 ([#10432](https://github.com/getpaseo/paseo/pull/10432)) +- 修复 Provider 返回重复命令名称时,斜杠建议列表出错的问题 ([#10275](https://github.com/getpaseo/paseo/pull/10275)) +- 修复恢复的 Codex 会话的配置和 MCP 服务器仍沿用旧工作目录的问题 ([#10390](https://github.com/getpaseo/paseo/pull/10390),贡献者:[@tabulius-ux](https://github.com/tabulius-ux)) +- 修复重新打开或回退父对话后,Codex 子 Agent 状态未更新的问题 ([#10171](https://github.com/getpaseo/paseo/pull/10171),贡献者:[@AnalyticETH](https://github.com/AnalyticETH)) +- 修复切换 Claude 账号后,“使用情况”页面仍显示上一个账号配额的问题 ([#10236](https://github.com/getpaseo/paseo/pull/10236)) +- 修复固定多个用量窗口时,侧边栏用量行隐藏周期标签的问题 ([#10274](https://github.com/getpaseo/paseo/pull/10274)) +- 修复恢复 worktree 后,“更改”无法立即识别检出目录的问题 ([#10224](https://github.com/getpaseo/paseo/pull/10224), [#10304](https://github.com/getpaseo/paseo/pull/10304), [#10406](https://github.com/getpaseo/paseo/pull/10406)) +- 修复拖动分屏分隔条时卡住或跟手缓慢的问题 ([#5996](https://github.com/getpaseo/paseo/pull/5996)) +- 修复 diff 中双击选词和三击选行的问题 ([#10252](https://github.com/getpaseo/paseo/pull/10252),贡献者:[@pedrovieira](https://github.com/pedrovieira)) +- 修复启用聊天大纲时,Composer 与对话栏对不齐的问题 ([#10277](https://github.com/getpaseo/paseo/pull/10277)) +- 修复网页版 Composer 的聚焦快捷键提示遮挡占位符文字的问题 ([#6200](https://github.com/getpaseo/paseo/pull/6200)) +- 修复当前工作区所在的侧边栏分组折叠时,归档快捷键失效的问题 ([#10356](https://github.com/getpaseo/paseo/pull/10356),贡献者:[@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud)) +- 修复一个会话正在归档工作区时,其他会话和插件仍将其显示为活跃状态的问题 ([#10391](https://github.com/getpaseo/paseo/pull/10391),贡献者:[@tabulius-ux](https://github.com/tabulius-ux)) +- 修复在 Android 上输入文字或缩放对话图片后,首次点击 Composer 按钮无效的问题 ([#10057](https://github.com/getpaseo/paseo/pull/10057), [#10308](https://github.com/getpaseo/paseo/pull/10308)) +- 修复在 Android 浏览器中滑动终端时弹出键盘的问题 ([#10225](https://github.com/getpaseo/paseo/pull/10225),贡献者:[@tonylt](https://github.com/tonylt)) - 修复启用“折叠轮次”时,空闲的 Provider 通知导致已完成的 OMP 或 Pi 回复被隐藏的问题 ([#10135](https://github.com/getpaseo/paseo/pull/10135)) -- 修复 Agent 响应后台任务时,在之前的完成状态未读的情况下重复发送完成通知的问题 ([#10200](https://github.com/getpaseo/paseo/pull/10200)) +- 修复 Agent 响应后台任务时重复发送完成通知的问题 ([#10200](https://github.com/getpaseo/paseo/pull/10200)) - 修复空对话在回复中途重连后丢失提示词和回复开头的问题 ([#9723](https://github.com/getpaseo/paseo/pull/9723),贡献者:[@ragokan](https://github.com/ragokan)) - 修复切换 Claude 思考级别时停止后台任务的问题 ([#10008](https://github.com/getpaseo/paseo/pull/10008),贡献者:[@gilad-rubin](https://github.com/gilad-rubin)) - 修复共享 OpenCode 服务停止后轮次一直显示为运行中的问题 ([#10187](https://github.com/getpaseo/paseo/pull/10187)) - 修复 OMP 提供会话或授权选项时拒绝已批准工具调用的问题 ([#10126](https://github.com/getpaseo/paseo/pull/10126),贡献者:[@dsingal0](https://github.com/dsingal0)) +- 修复 Codex 消息在轮次开始前停止时显示错误而非已取消的问题 ([#9931](https://github.com/getpaseo/paseo/pull/9931),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复 Git 元数据监听达到上限时无法打开“更改”的问题 ([#10188](https://github.com/getpaseo/paseo/pull/10188)) - 修复将选中的回复复制到纯文本目标时出现多余 Markdown 语法的问题 ([#10079](https://github.com/getpaseo/paseo/pull/10079),贡献者:[@danberindei](https://github.com/danberindei)) -- 修复在预览和源码之间切换时文件视图丢失滚动位置的问题,iOS 的 HTML 预览除外 ([#10195](https://github.com/getpaseo/paseo/pull/10195),贡献者:[@apple-ouyang](https://github.com/apple-ouyang)) +- 修复在预览和源码之间切换时 Markdown 预览和源码视图丢失滚动位置的问题 ([#10195](https://github.com/getpaseo/paseo/pull/10195),贡献者:[@apple-ouyang](https://github.com/apple-ouyang)) - 修复拆分窗格中的文件标签页显示或聚焦错误文件的问题 ([#9888](https://github.com/getpaseo/paseo/pull/9888),贡献者:[@KosmoCHE](https://github.com/KosmoCHE)) - 修复触摸屏上的子菜单打开后立即关闭的问题 ([#10175](https://github.com/getpaseo/paseo/pull/10175),贡献者:[@christiantwu](https://github.com/christiantwu)) - 修复关闭另一个使用过麦克风的对话后无法听写的问题 ([#10185](https://github.com/getpaseo/paseo/pull/10185),贡献者:[@Brandon168](https://github.com/Brandon168)) -- 修复 Android 缩放对话图片后 Composer 点击失效的问题 ([#10057](https://github.com/getpaseo/paseo/pull/10057)) - 修复 Samsung DeX 上的文字被裁剪的问题 ([#9995](https://github.com/getpaseo/paseo/pull/9995),贡献者:[@easyhunjune](https://github.com/easyhunjune)) - 修复主机连接缓慢后对话中的工作区图片无法加载的问题 ([#10111](https://github.com/getpaseo/paseo/pull/10111),贡献者:[@ragokan](https://github.com/ragokan)) - 修复桌面浏览器截图返回全透明图片的问题 ([#9807](https://github.com/getpaseo/paseo/pull/9807),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) - 修复 Mermaid 流程图标签含有 `@` 时显示源码而非图表的问题 ([#10165](https://github.com/getpaseo/paseo/pull/10165),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) - 修复隐藏的后台工作区触发程序坞徽标和网站图标状态的问题 ([#9983](https://github.com/getpaseo/paseo/pull/9983)) - 修复桌面侧边栏导航占满工作区列表空间的问题 ([#9903](https://github.com/getpaseo/paseo/pull/9903),贡献者:[@pentatonic-alex](https://github.com/pentatonic-alex)) +- 修复仓库默认分支显示已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053)) - 修复 Provider 关闭会话后插件 Agent 无法重新打开的问题 ([#10153](https://github.com/getpaseo/paseo/pull/10153)) - 修复插件页面和设置无法使用插件状态钩子的问题 ([#10049](https://github.com/getpaseo/paseo/pull/10049)) -- 修复 Codex 消息在轮次开始前停止时显示错误而非已取消的问题 ([#9931](https://github.com/getpaseo/paseo/pull/9931),贡献者:[@3ae3ae](https://github.com/3ae3ae)) -- 修复仓库默认分支显示历史已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053)) + +### 插件 + +- 新增插件对 worktree 创建、移除和恢复的管理能力 ([#10278](https://github.com/getpaseo/paseo/pull/10278)) +- 新增插件导航 `focusHost` 选项,用于在侧边栏选中目标主机 ([#5574](https://github.com/getpaseo/paseo/pull/5574),贡献者:[@discwl](https://github.com/discwl)) ## 0.16.2 - 2026-11-18 diff --git a/CLAUDE.md b/CLAUDE.md index 365dc1c76314..d553ee1343f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,7 +58,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the | [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression | | [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render | | [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost | -| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, native selection, links, images and library constraints | +| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints | | [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations | | [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison | | [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization | diff --git a/assets/brand/README.md b/assets/brand/README.md new file mode 100644 index 000000000000..805b84a0544a --- /dev/null +++ b/assets/brand/README.md @@ -0,0 +1,63 @@ +# Brand assets + +Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work. + +## Brand architecture + +- **Paseo** (butterfly mark): the local client, daemon, CLI, SDK, and small account features (sign-in, share links, tunnels). +- **Paseo Hub** (flower mark): the software factory, team features, hosted service, and paid plans (`Hub Free`, `Hub Solo`, `Hub Team`). +- **Hub** (flower mark + `Hub`): used only where Paseo is already on screen, such as inside the Hub dashboard header. + +## Specifications + +### Marks + +Both marks are single-line stroked paths on a `700 × 700` viewBox with `stroke-width="50"`, `stroke-linecap="round"`, and `stroke-linejoin="round"`. Both are optically centered to a `527`-unit ink footprint: + +- **Paseo (`marks/paseo-*.svg`)**: refit of the hand-drawn butterfly (redraw B) with smooth curvature on the large wing and lower loop and a uniform `50` stroke width. +- **Paseo Hub (`marks/paseo-hub-*.svg`)**: five-petal looped flower (variant A) with a `12°` clockwise petal lean, sized up to match the butterfly's `527` footprint with the same `50` stroke. + +Colors: + +- `white` (`#FFFFFF`) for dark surfaces (`#101615`, `#101010`, `#000000`) +- `black` (`#000000`) for light surfaces +- `green` (`#20744A`) brand accent + +### Lockups + +All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink height with a `2`-unit margin on all sides) so stacked lockups align cleanly: + +- **Font**: Plus Jakarta Sans SemiBold (`600`), bundled in `fonts/PlusJakartaSans-SemiBold.ttf` under the SIL Open Font License 1.1 (`fonts/OFL.txt`). +- **Outlined text**: lockup SVGs outline the wordmark to `` elements so they render identically everywhere without the font installed. +- **Proportions**: marks are `15%` larger against text and `20%` closer than the original website header baseline (`24 px` box, `12 px` gap, `18 px` text). +- **Optical balance**: in the `paseo` lockup, the butterfly is scaled to `94%` (`stroke-width` proportional) so `Paseo`, `Paseo Hub`, and `Hub` sit at equal visual weight when shown together. + +## Files + +```text +assets/brand/ + build.mjs Regenerates all marks and lockups + fonts/ + PlusJakartaSans-SemiBold.ttf + OFL.txt + marks/ + paseo-white.svg + paseo-black.svg + paseo-green.svg + paseo-hub-white.svg + paseo-hub-black.svg + paseo-hub-green.svg + lockups/ + paseo-white.svg + paseo-black.svg + paseo-hub-white.svg + paseo-hub-black.svg + hub-white.svg + hub-black.svg +``` + +## Regenerate + +```sh +node assets/brand/build.mjs +``` diff --git a/assets/brand/build.mjs b/assets/brand/build.mjs new file mode 100644 index 000000000000..4bc84ca54090 --- /dev/null +++ b/assets/brand/build.mjs @@ -0,0 +1,146 @@ +// Generates the canonical Paseo and Paseo Hub brand marks and lockup SVGs. +// +// node assets/brand/build.mjs +// +// Marks are single-line stroked paths on a 700x700 viewBox (stroke-width 50, +// round caps and joins, centered to a 527-unit ink footprint). Lockups outline +// Plus Jakarta Sans SemiBold to SVG paths so every file is self-contained. + +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { loadSync } from "opentype.js"; + +const root = path.dirname(fileURLToPath(import.meta.url)); +const marksDir = path.join(root, "marks"); +const lockupsDir = path.join(root, "lockups"); +const fontPath = path.join(root, "fonts", "PlusJakartaSans-SemiBold.ttf"); + +const VIEWBOX = 700; +const STROKE = 50; +const FOOTPRINT = 527; + +// Lockup proportions relative to the original website header (24px box, 12px gap, 18px text): +// - marks are 15% larger against text +// - ink-to-text gap is 20% tighter +// - butterfly is undersized by 6% in lockups so Paseo, Paseo Hub, and Hub read as one family +const MARK_SCALE = 1.15; +const GAP_SCALE = 0.8; +const BUTTERFLY_LOCKUP_SCALE = 0.94; + +// Lockup coordinate system: flower ink spans 140 units with a 2-unit margin on all sides (height 144). +const LOCKUP_INK = 140; +const LOCKUP_PAD = 2; +const LOCKUP_HEIGHT = LOCKUP_INK + LOCKUP_PAD * 2; + +const MARK_COLORS = [ + { name: "white", hex: "#FFFFFF" }, + { name: "black", hex: "#000000" }, + { name: "green", hex: "#20744A" }, +]; + +const LOCKUP_COLORS = [ + { name: "white", hex: "#FFFFFF" }, + { name: "black", hex: "#000000" }, +]; + +// Paseo butterfly mark (redraw B): smoothed centreline of the original mark, centered in 700x700. +const PASEO_MARK_PATH = + "M456.84 526.11C462.73 521.72 467.57 517.89 471.79 514.38C476.02 510.88 479.65 507.69 483.14 504.58C486.63 501.46 489.94 498.44 493.24 495.35C496.54 492.27 499.85 489.11 503.26 485.77C506.67 482.44 510.16 478.96 513.7 475.36C517.23 471.76 520.81 468.03 524.4 464.2C527.99 460.37 531.59 456.44 535.18 452.41C538.77 448.39 542.36 444.27 545.89 440.08C549.42 435.9 552.88 431.65 556.23 427.37C559.58 423.08 562.81 418.77 565.83 414.39C568.86 410.01 571.68 405.57 574.2 401.02C576.72 396.48 578.95 391.82 580.73 387C582.5 382.18 583.83 377.16 584.55 371.94C585.27 366.73 585.37 361.37 584.63 356.15C583.9 350.93 582.28 345.83 579.74 341.22C577.21 336.62 573.83 332.53 569.82 329.45C565.81 326.37 561.14 324.38 556.21 323.54C551.28 322.69 546.1 322.94 541.16 324.13C536.22 325.32 531.58 327.49 527.2 330.24C522.82 332.99 518.68 336.32 514.69 339.8C510.7 343.27 506.85 346.9 503.11 350.61C499.36 354.32 495.71 358.12 492.11 361.94C488.51 365.76 484.97 369.62 481.47 373.49C477.98 377.37 474.53 381.27 471.12 385.19C467.71 389.11 464.33 393.05 460.99 397C457.65 400.94 454.33 404.9 451.04 408.87C447.74 412.83 444.47 416.8 441.21 420.78C437.95 424.75 434.7 428.73 431.46 432.71C428.22 436.69 424.98 440.68 421.74 444.67C418.5 448.66 415.27 452.66 412.02 456.67C408.78 460.68 405.52 464.69 402.26 468.72C398.99 472.75 395.71 476.78 392.41 480.83C389.11 484.88 385.78 488.95 382.42 493.02C379.06 497.09 375.66 501.16 372.22 505.23C368.78 509.3 365.28 513.37 361.73 517.41C358.17 521.45 354.55 525.46 350.85 529.41C347.14 533.36 343.36 537.24 339.47 541.02C335.59 544.8 331.62 548.47 327.54 551.97C323.45 555.47 319.27 558.81 314.98 561.93C310.68 565.05 306.29 567.97 301.8 570.62C297.31 573.28 292.72 575.68 288.04 577.8C283.37 579.92 278.61 581.75 273.79 583.28C268.96 584.81 264.07 586.03 259.14 586.93C254.2 587.83 249.23 588.4 244.24 588.64C239.25 588.88 234.24 588.79 229.26 588.36C224.28 587.93 219.32 587.16 214.42 586.06C209.51 584.95 204.67 583.52 199.91 581.77C195.16 580.01 190.5 577.94 185.97 575.56C181.45 573.19 177.05 570.51 172.82 567.55C168.58 564.59 164.52 561.36 160.64 557.87C156.77 554.39 153.09 550.65 149.64 546.7C146.19 542.75 142.95 538.58 139.97 534.23C136.98 529.88 134.23 525.34 131.75 520.67C129.27 515.99 127.04 511.16 125.09 506.23C123.15 501.3 121.47 496.26 120.08 491.16C118.69 486.05 117.57 480.88 116.75 475.67C115.93 470.47 115.39 465.24 115.14 460.02C114.89 454.79 114.93 449.58 115.26 444.41C115.58 439.24 116.2 434.12 117.1 429.08C117.99 424.04 119.18 419.08 120.64 414.24C122.11 409.4 123.86 404.67 125.88 400.08C127.91 395.49 130.21 391.05 132.78 386.77C135.36 382.5 138.21 378.39 141.32 374.47C144.44 370.55 147.83 366.82 151.47 363.3C155.12 359.77 159.03 356.47 163.19 353.41C167.35 350.36 171.76 347.55 176.39 345.05C181.03 342.55 185.88 340.35 190.91 338.52C195.94 336.7 201.17 335.24 206.49 334.19C211.82 333.15 217.24 332.51 222.68 332.31C228.11 332.12 233.55 332.37 238.92 333.01C244.29 333.66 249.59 334.71 254.75 336.09C259.91 337.48 264.92 339.21 269.75 341.29C274.58 343.36 279.23 345.78 283.63 348.53C288.04 351.29 292.18 354.4 295.95 357.9C299.71 361.39 303.1 365.29 305.97 369.58C308.84 373.86 311.2 378.51 312.91 383.42C314.62 388.32 315.66 393.52 315.96 398.78C316.25 404.03 315.8 409.35 314.55 414.46C313.3 419.57 311.22 424.48 308.43 428.88C305.64 433.29 302.15 437.19 298.08 440.28C294.02 443.37 289.39 445.66 284.5 447.04C279.61 448.43 274.47 448.92 269.39 448.45C264.3 447.98 259.26 446.59 254.46 444.51C249.67 442.43 245.14 439.66 241.03 436.43C236.91 433.2 233.16 429.52 229.72 425.64C226.28 421.76 223.16 417.73 220.26 413.65C217.37 409.57 214.68 405.42 212.07 401.22C209.46 397.01 206.9 392.76 204.38 388.43C201.85 384.1 199.36 379.71 196.91 375.21C194.46 370.72 192.05 366.13 189.7 361.45C187.35 356.76 185.06 351.99 182.86 347.13C180.67 342.28 178.57 337.34 176.57 332.32C174.57 327.31 172.68 322.22 170.91 317.07C169.13 311.91 167.48 306.69 165.96 301.42C164.44 296.14 163.05 290.8 161.8 285.42C160.55 280.03 159.45 274.6 158.51 269.13C157.57 263.67 156.78 258.17 156.18 252.66C155.58 247.15 155.16 241.62 154.94 236.11C154.72 230.6 154.7 225.1 154.91 219.65C155.11 214.2 155.54 208.8 156.21 203.47C156.89 198.15 157.8 192.91 158.98 187.8C160.16 182.69 161.59 177.71 163.3 172.9C165.01 168.09 166.99 163.45 169.24 159.04C171.49 154.63 174.02 150.44 176.81 146.52C179.61 142.61 182.67 138.96 185.98 135.62C189.29 132.28 192.85 129.25 196.64 126.57C200.42 123.89 204.43 121.55 208.62 119.57C212.82 117.59 217.2 115.98 221.73 114.74C226.26 113.5 230.93 112.62 235.71 112.12C240.49 111.61 245.36 111.47 250.3 111.67C255.24 111.87 260.23 112.42 265.24 113.28C270.25 114.15 275.28 115.34 280.29 116.8C285.31 118.27 290.3 120.03 295.25 122.03C300.2 124.03 305.1 126.28 309.94 128.74C314.77 131.2 319.54 133.87 324.23 136.72C328.91 139.56 333.51 142.59 338.01 145.76C342.52 148.93 346.93 152.24 351.24 155.68C355.54 159.11 359.75 162.67 363.85 166.33C367.95 169.99 371.94 173.74 375.82 177.59C379.7 181.43 383.47 185.36 387.13 189.37C390.78 193.37 394.32 197.46 397.74 201.61C401.16 205.76 404.46 209.99 407.63 214.28C410.8 218.57 413.84 222.93 416.75 227.36C419.66 231.79 422.42 236.28 425.04 240.84C427.66 245.4 430.14 250.03 432.45 254.72C434.76 259.41 436.91 264.16 438.88 268.98C440.86 273.79 442.66 278.66 444.27 283.59C445.89 288.51 447.31 293.49 448.54 298.51C449.77 303.53 450.8 308.59 451.62 313.68C452.45 318.77 453.06 323.89 453.46 329.02C453.86 334.15 454.05 339.29 454.02 344.42C454 349.55 453.75 354.67 453.29 359.76C452.83 364.85 452.16 369.91 451.27 374.92C450.39 379.92 449.29 384.88 447.98 389.76C446.68 394.64 445.17 399.44 443.46 404.15C441.75 408.87 439.85 413.49 437.75 418C435.65 422.51 433.38 426.88 430.83 431.24C428.27 435.6 425.41 439.96 422.06 444.51C418.7 449.06 414.7 453.93 410.99 458.32C407.29 462.71 403.92 466.59 401.91 469.1"; + +// Paseo Hub flower mark (5-petal A, 12 deg clockwise lean): scaled to the butterfly's 527 footprint. +const PASEO_HUB_MARK_PATH = + "M389.47 112.65C383.85 111.46 377.9 111.12 371.85 111.7C365.8 112.28 359.66 113.78 353.67 116.15C347.7 118.52 341.89 121.77 336.47 125.79C331.07 129.81 326.07 134.6 321.7 139.98C317.32 145.37 313.55 151.35 310.53 157.69C307.52 164.02 305.25 170.72 303.79 177.54C302.32 184.35 301.67 191.27 301.77 198.07C301.87 204.87 302.75 211.54 304.28 217.89C305.8 224.25 307.98 230.28 310.66 235.86C313.33 241.46 316.5 246.6 319.96 251.26C323.43 255.92 327.19 260.09 331.07 263.82C334.95 267.53 338.95 270.81 342.89 273.74C346.84 276.67 350.75 279.26 354.51 281.62C358.27 283.98 361.88 286.13 365.3 288.2C368.7 290.29 371.92 292.29 374.95 294.34C377.98 296.38 380.81 298.49 383.54 300.73C386.26 302.97 388.87 305.36 391.48 307.96C394.08 310.55 396.69 313.35 399.42 316.37C402.14 319.4 404.99 322.65 408.09 326.09C411.18 329.51 414.51 333.14 418.18 336.89C421.83 340.63 425.82 344.49 430.16 348.36C434.5 352.22 439.2 356.09 444.25 359.82C449.31 363.56 454.71 367.15 460.41 370.46C466.11 373.77 472.11 376.79 478.3 379.39C484.49 381.98 490.9 384.15 497.37 385.76C503.83 387.38 510.38 388.43 516.83 388.85C523.28 389.26 529.64 389.03 535.73 388.12C541.83 387.2 547.65 385.6 553.03 383.33C558.4 381.05 563.31 378.09 567.59 374.55C571.88 370.99 575.53 366.83 578.41 362.22C581.28 357.6 583.38 352.5 584.59 347.13C585.79 341.76 586.13 336.1 585.52 330.39C584.92 324.69 583.4 318.92 580.98 313.34C578.55 307.78 575.24 302.4 571.14 297.43C567.03 292.48 562.15 287.96 556.66 284.06C551.16 280.16 545.05 276.89 538.59 274.39C532.11 271.89 525.27 270.15 518.3 269.24C511.34 268.33 504.27 268.24 497.34 268.96C490.4 269.67 483.61 271.19 477.18 273.38C470.75 275.58 464.67 278.47 459.11 281.9C453.53 285.31 448.47 289.25 443.98 293.52C439.49 297.79 435.58 302.39 432.22 307.12C428.86 311.86 426.05 316.73 423.71 321.56C421.37 326.41 419.49 331.22 417.92 335.88C416.36 340.55 415.11 345.06 414.03 349.37C412.93 353.67 412.01 357.78 411.09 361.66C410.16 365.55 409.26 369.22 408.24 372.73C407.23 376.24 406.11 379.59 404.82 382.87C403.52 386.16 402.06 389.38 400.4 392.66C398.73 395.94 396.87 399.28 394.84 402.81C392.81 406.34 390.6 410.05 388.29 414.05C385.98 418.06 383.56 422.36 381.13 426.99C378.7 431.63 376.26 436.6 373.93 441.93C371.59 447.26 369.37 452.92 367.38 458.88C365.4 464.83 363.64 471.09 362.26 477.53C360.86 483.98 359.84 490.61 359.29 497.31C358.73 504 358.66 510.76 359.12 517.41C359.58 524.06 360.6 530.6 362.2 536.87C363.81 543.13 365.99 549.12 368.74 554.63C371.49 560.14 374.82 565.19 378.64 569.59C382.47 574 386.78 577.76 391.49 580.73C396.2 583.71 401.28 585.9 406.55 587.21C411.84 588.51 417.33 588.93 422.82 588.42C428.3 587.91 433.78 586.48 439.02 584.14C444.26 581.81 449.28 578.57 453.82 574.54C458.38 570.53 462.47 565.7 465.92 560.28C469.36 554.84 472.16 548.79 474.17 542.37C476.18 535.93 477.4 529.12 477.78 522.19C478.16 515.26 477.69 508.22 476.41 501.32C475.13 494.41 473.02 487.66 470.2 481.29C467.38 474.91 463.85 468.93 459.76 463.49C455.68 458.04 451.05 453.17 446.08 448.92C441.11 444.68 435.8 441.08 430.35 438.14C424.9 435.18 419.32 432.88 413.78 431.15C408.24 429.41 402.74 428.25 397.41 427.52C392.08 426.79 386.92 426.48 382.01 426.44C377.09 426.4 372.41 426.6 367.98 426.9C363.55 427.2 359.36 427.58 355.38 427.9C351.41 428.23 347.63 428.5 343.97 428.62C340.32 428.74 336.8 428.72 333.27 428.5C329.75 428.29 326.23 427.89 322.59 427.32C318.96 426.75 315.2 426.01 311.23 425.17C307.24 424.32 303.03 423.38 298.51 422.42C293.98 421.45 289.15 420.48 283.99 419.61C278.84 418.72 273.35 417.94 267.56 417.37C261.78 416.79 255.7 416.43 249.41 416.38C243.14 416.33 236.65 416.6 230.09 417.26C223.53 417.94 216.9 419.01 210.37 420.56C203.83 422.1 197.38 424.11 191.19 426.61C185.02 429.11 179.11 432.1 173.64 435.56C168.18 439.01 163.16 442.94 158.77 447.26C154.38 451.58 150.61 456.29 147.61 461.3C144.6 466.3 142.35 471.57 140.98 476.96C139.59 482.36 139.08 487.87 139.48 493.29C139.86 498.73 141.16 504.07 143.34 509.13C145.52 514.19 148.57 518.96 152.42 523.22C156.27 527.49 160.89 531.25 166.12 534.34C171.35 537.43 177.19 539.83 183.43 541.42C189.66 543.02 196.27 543.81 203.01 543.73C209.75 543.66 216.6 542.72 223.32 540.94C230.02 539.16 236.58 536.53 242.75 533.18C248.92 529.83 254.69 525.74 259.87 521.09C265.06 516.43 269.67 511.22 273.58 505.66C277.49 500.1 280.71 494.19 283.2 488.15C285.7 482.11 287.49 475.95 288.6 469.85C289.72 463.76 290.19 457.74 290.13 451.93C290.06 446.13 289.47 440.54 288.52 435.25C287.57 429.96 286.26 424.96 284.79 420.27C283.32 415.58 281.66 411.19 280.02 407.07C278.36 402.94 276.71 399.09 275.16 395.4C273.63 391.72 272.21 388.2 270.96 384.77C269.72 381.34 268.65 377.96 267.77 374.55C266.88 371.13 266.17 367.66 265.59 364.03C265.01 360.4 264.55 356.61 264.12 352.56C263.69 348.51 263.29 344.21 262.81 339.61C262.32 335.01 261.77 330.11 261 324.94C260.24 319.76 259.28 314.29 258.05 308.62C256.8 302.93 255.28 297.05 253.38 291.05C251.48 285.07 249.23 278.98 246.56 272.95C243.9 266.92 240.83 260.95 237.34 255.21C233.85 249.46 229.94 243.95 225.66 238.85C221.37 233.74 216.7 229.04 211.72 224.92C206.75 220.79 201.47 217.23 196.01 214.39C190.54 211.55 184.89 209.42 179.2 208.1C173.52 206.79 167.81 206.29 162.25 206.64C156.7 207 151.3 208.21 146.25 210.26C141.22 212.31 136.52 215.19 132.38 218.84C128.25 222.47 124.66 226.85 121.79 231.82C118.92 236.8 116.77 242.35 115.45 248.28C114.13 254.22 113.66 260.52 114.07 266.94C114.47 273.36 115.77 279.9 117.91 286.28C120.07 292.66 123.08 298.89 126.85 304.73C130.61 310.55 135.14 315.98 140.23 320.81C145.33 325.63 151 329.86 157.03 333.36C163.06 336.86 169.44 339.62 175.94 341.63C182.44 343.63 189.04 344.85 195.57 345.37C202.08 345.87 208.49 345.67 214.62 344.85C220.77 344.04 226.65 342.61 232.15 340.76C237.65 338.9 242.77 336.61 247.52 334.08C252.26 331.53 256.61 328.75 260.62 325.9C264.61 323.05 268.28 320.12 271.69 317.28C275.11 314.43 278.27 311.67 281.3 309.06C284.33 306.46 287.22 304.02 290.1 301.77C292.99 299.53 295.85 297.48 298.83 295.59C301.81 293.68 304.89 291.94 308.17 290.27C311.44 288.59 314.91 286.98 318.63 285.31C322.35 283.66 326.31 281.95 330.53 280.07C334.76 278.19 339.24 276.14 343.93 273.82C348.62 271.49 353.52 268.9 358.54 265.97C363.56 263.02 368.68 259.75 373.8 256.09C378.91 252.44 384 248.42 388.91 244.02C393.82 239.62 398.55 234.85 402.93 229.76C407.32 224.67 411.35 219.25 414.88 213.6C418.41 207.94 421.44 202.05 423.83 196.05C426.21 190.03 427.96 183.92 428.97 177.84C429.99 171.76 430.26 165.73 429.76 159.92C429.25 154.11 427.97 148.52 425.91 143.34C423.86 138.18 421.05 133.42 417.53 129.25C414.03 125.09 409.83 121.52 405.09 118.71C400.35 115.9 395.08 113.84 389.47 112.65Z"; + +const round = (value) => Number(value.toFixed(2)); + +function transformPath(d, scale, offsetX, offsetY) { + let index = 0; + return d.replace(/-?\d+(?:\.\d+)?/g, (token) => { + const value = Number.parseFloat(token); + const out = index % 2 === 0 ? offsetX + value * scale : offsetY + value * scale; + index += 1; + return String(round(out)); + }); +} + +function renderMarkSvg(d, color) { + return [ + ``, + ` `, + "", + "", + ].join("\n"); +} + +function renderLockupSvg({ font, markPath, markFactor, label, color }) { + const emptyShare = (VIEWBOX - FOOTPRINT) / 2 / VIEWBOX; + const headerBoxEm = (24 / 18) * MARK_SCALE; + const flowerInkEm = headerBoxEm * (FOOTPRINT / VIEWBOX); + const visibleGapEm = GAP_SCALE * (12 / 18 + (24 / 18) * emptyShare); + + const fontSize = LOCKUP_INK / flowerInkEm; + const markCenter = LOCKUP_PAD + LOCKUP_INK / 2; + const unitScale = (LOCKUP_INK / FOOTPRINT) * markFactor; + const markOffset = markCenter - (VIEWBOX / 2) * unitScale; + const bakedMark = transformPath(markPath, unitScale, markOffset, markOffset); + const strokeWidth = round(STROKE * unitScale); + + // Baseline matches CSS display:flex; align-items:center; line-height:1 for Plus Jakarta Sans. + const ascender = (font.ascender / font.unitsPerEm) * fontSize; + const descender = (font.descender / font.unitsPerEm) * fontSize; + const halfLeading = (fontSize - (ascender - descender)) / 2; + const baselineY = markCenter - fontSize / 2 + halfLeading + ascender; + + const textOriginX = LOCKUP_PAD + LOCKUP_INK + visibleGapEm * fontSize; + const textPath = font.getPath(label, textOriginX, baselineY, fontSize); + const bounds = textPath.getBoundingBox(); + const width = Math.ceil(bounds.x2 + LOCKUP_PAD); + + return [ + ``, + ` `, + ` `, + "", + "", + ].join("\n"); +} + +function build() { + mkdirSync(marksDir, { recursive: true }); + mkdirSync(lockupsDir, { recursive: true }); + + const font = loadSync(fontPath); + + const marks = [ + { slug: "paseo", d: PASEO_MARK_PATH }, + { slug: "paseo-hub", d: PASEO_HUB_MARK_PATH }, + ]; + + for (const mark of marks) { + for (const color of MARK_COLORS) { + const file = path.join(marksDir, `${mark.slug}-${color.name}.svg`); + writeFileSync(file, renderMarkSvg(mark.d, color.hex)); + } + } + + const lockups = [ + { + slug: "paseo", + markPath: PASEO_MARK_PATH, + markFactor: BUTTERFLY_LOCKUP_SCALE, + label: "Paseo", + }, + { slug: "paseo-hub", markPath: PASEO_HUB_MARK_PATH, markFactor: 1, label: "Paseo Hub" }, + { slug: "hub", markPath: PASEO_HUB_MARK_PATH, markFactor: 1, label: "Hub" }, + ]; + + for (const lockup of lockups) { + for (const color of LOCKUP_COLORS) { + const file = path.join(lockupsDir, `${lockup.slug}-${color.name}.svg`); + writeFileSync(file, renderLockupSvg({ font, ...lockup, color: color.hex })); + } + } +} + +build(); diff --git a/assets/brand/fonts/OFL.txt b/assets/brand/fonts/OFL.txt new file mode 100644 index 000000000000..ea69b0ca12a0 --- /dev/null +++ b/assets/brand/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/brand/fonts/PlusJakartaSans-SemiBold.ttf b/assets/brand/fonts/PlusJakartaSans-SemiBold.ttf new file mode 100644 index 000000000000..c12d4b0e72bd Binary files /dev/null and b/assets/brand/fonts/PlusJakartaSans-SemiBold.ttf differ diff --git a/assets/brand/lockups/hub-black.svg b/assets/brand/lockups/hub-black.svg new file mode 100644 index 000000000000..41adbc902041 --- /dev/null +++ b/assets/brand/lockups/hub-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/hub-white.svg b/assets/brand/lockups/hub-white.svg new file mode 100644 index 000000000000..3fb1c659282a --- /dev/null +++ b/assets/brand/lockups/hub-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-black.svg b/assets/brand/lockups/paseo-black.svg new file mode 100644 index 000000000000..104dfefa4496 --- /dev/null +++ b/assets/brand/lockups/paseo-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-hub-black.svg b/assets/brand/lockups/paseo-hub-black.svg new file mode 100644 index 000000000000..849f5fae2440 --- /dev/null +++ b/assets/brand/lockups/paseo-hub-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-hub-white.svg b/assets/brand/lockups/paseo-hub-white.svg new file mode 100644 index 000000000000..0174e895bb86 --- /dev/null +++ b/assets/brand/lockups/paseo-hub-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-white.svg b/assets/brand/lockups/paseo-white.svg new file mode 100644 index 000000000000..a14ccab72d02 --- /dev/null +++ b/assets/brand/lockups/paseo-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/marks/paseo-black.svg b/assets/brand/marks/paseo-black.svg new file mode 100644 index 000000000000..b6f1db1f3e57 --- /dev/null +++ b/assets/brand/marks/paseo-black.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-green.svg b/assets/brand/marks/paseo-green.svg new file mode 100644 index 000000000000..51d22edb5b39 --- /dev/null +++ b/assets/brand/marks/paseo-green.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-hub-black.svg b/assets/brand/marks/paseo-hub-black.svg new file mode 100644 index 000000000000..882db41661b5 --- /dev/null +++ b/assets/brand/marks/paseo-hub-black.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-hub-green.svg b/assets/brand/marks/paseo-hub-green.svg new file mode 100644 index 000000000000..6fb1dac7ed2a --- /dev/null +++ b/assets/brand/marks/paseo-hub-green.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-hub-white.svg b/assets/brand/marks/paseo-hub-white.svg new file mode 100644 index 000000000000..1a15ec539c5a --- /dev/null +++ b/assets/brand/marks/paseo-hub-white.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-white.svg b/assets/brand/marks/paseo-white.svg new file mode 100644 index 000000000000..152c280e8c3d --- /dev/null +++ b/assets/brand/marks/paseo-white.svg @@ -0,0 +1,3 @@ + + + diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 17d25ef6b9e5..d6230815c72f 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -162,13 +162,29 @@ Users can also detach an existing subagent from the subagents track. Detach is d `notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback. -Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches. +Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission 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. -The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt -crash can lose queued prompts. A durable send receipt remains pending until actual dispatch +An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way: + +- **`queue`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. 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 prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior 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. + +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. + +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 command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text. + +One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches. + +The pending message window is in memory. Clean shutdown flushes it, held messages included, before +closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued -admission within their original timeout and cancellation scope, and return permission checkpoints -while messages are waiting. +admission within their original timeout and cancellation scope, and return at permission +checkpoints and when a Stop holds the queue. Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses diff --git a/docs/android.md b/docs/android.md index c8ac59e4c793..6d19fb72923a 100644 --- a/docs/android.md +++ b/docs/android.md @@ -156,6 +156,12 @@ from `packages/app/android`: These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing. +Run the terminal module's tests the same way with `:paseo-terminal:connectedDebugAndroidTest`. Besides +row layout, they check that the terminal input asks the keyboard not to learn what is typed +(`IME_FLAG_NO_PERSONALIZED_LEARNING`), so passwords typed at a prompt stay out of Gboard's +suggestions in other apps. React Native's TextInput has no prop for that flag, and it replaces +`imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the terminal input sets neither. + Run the display density regression tests the same way: ```bash diff --git a/docs/custom-providers.md b/docs/custom-providers.md index 384f4ae8c676..76f0e8eb09c3 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -530,7 +530,7 @@ The [Agent Client Protocol (ACP)](https://agentclientprotocol.com) is an open st ACP agents communicate over JSON-RPC 2.0 on stdio. Paseo spawns the agent process and talks to it through stdin/stdout. -Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead. +Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Goose, Hermes, and Hoplite activate their [bundled providers](plugins.md#built-in-plugins) instead. An existing `extends: "acp"` entry for goose or Hermes migrates to the bundled provider on load and keeps a custom command. Hermes agents saved with the old adapter resume with their mode translated (`plugins/hermes-provider/server/legacy-modes.ts`). ### Adding a generic ACP provider @@ -643,32 +643,6 @@ ACP probes use short timeouts and browser-suppression environment variables so a Ref: [Gemini CLI ACP mode docs](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/acp-mode.md) -### Example: Hermes (Nous Research) - -[Hermes](https://github.com/NousResearch/hermes-agent) is an open-source coding agent by Nous Research with persistent memory and multi-provider LLM support. It supports ACP via the `acp` subcommand. - -1. Install: `curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash` -2. Install ACP support: `pip install -e '.[acp]'` -3. Configure Hermes credentials in `~/.hermes/` -4. Add to config.json: - -```json -{ - "agents": { - "providers": { - "hermes": { - "extends": "acp", - "label": "Hermes", - "description": "Nous Research self-improving AI agent", - "command": ["hermes", "acp"] - } - } - } -} -``` - -Ref: [Hermes ACP docs](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp) - ### How ACP providers work in Paseo When you launch an agent with an ACP provider: @@ -869,12 +843,6 @@ A config.json with multiple custom providers: "extends": "acp", "label": "Google Gemini", "command": ["gemini", "--acp"] - }, - - "hermes": { - "extends": "acp", - "label": "Hermes", - "command": ["hermes", "acp"] } } } diff --git a/docs/data-model.md b/docs/data-model.md index ff77593e5da7..5102eb033cd7 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -102,6 +102,7 @@ Each agent is stored as a separate JSON file, grouped by project directory. | `config` | `SerializableConfig?` | Agent session configuration (see below) | | `runtimeInfo` | `RuntimeInfo?` | Live runtime state (see below) | | `features` | `AgentFeature[]?` | Provider-reported features (toggles/selects) | +| `sessionMetrics` | `AgentMetric[]?` | Provider-reported session metrics, already formatted for display; the latest report replaces the list | | `persistence` | `PersistenceHandle?` | Handle for resuming sessions | | `lastError` | `string?` (nullable) | Last error message, if any | | `requiresAttention` | `boolean?` | Whether the agent needs user attention | @@ -186,11 +187,13 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId` Single file, validated with `PersistedConfigSchema`. -`agents.skills.selection` is the daemon host's orchestration-skill preference. Missing means -`{ mode: "all" }`. Installed state is not persisted; the daemon derives it from the shared -`~/.agents/skills` and Claude skill directories and keeps config plus filesystem convergence behind -one serialized owner. Codex discovers the shared directory. Updates retire unchanged files from -Paseo-managed copies in `~/.codex/skills`, preserving user edits and untracked files. +`agents.skills.selection` stores the orchestration-skill preference for the daemon host, and a +missing value defaults to `{ mode: "all" }`. The daemon does not persist installed state. It +derives installed state from `~/.agents/skills`, `~/.claude/skills`, and `~/.gemini/config/skills`, +and serializes configuration and filesystem convergence through one owner. Codex and Gemini CLI +discover `~/.agents/skills`, while Antigravity discovers `~/.gemini/config/skills`. Updates retire +unchanged files from Paseo-managed copies in `~/.codex/skills` and preserve user edits and +untracked files. `paseo reload` reads and validates this file once inside the daemon. That snapshot drives resolution, classification, application, and reload bookkeeping. `DaemonConfigStore` owns applying runtime-safe @@ -580,12 +583,17 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec directory scan. One invalid row is deleted and returned as a miss without affecting other rows. An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a later launch cannot accept a checkpoint for a partial baseline. Directory changes and their -checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage, +checkpoint are also applied in one transaction. A stored checkpoint carries a version. When a writer +bug could have stored a checkpoint without its directory, bump the version: older checkpoints are +rejected on read, cached rows still paint, and each host re-syncs its directory once. Reads wait for +accepted changes to reach storage, then retry only when a requested row changes during the read. Unrelated agent streams do not invalidate the read. Directory baseline replacements and host removal or renaming still invalidate the affected reads. -The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget +The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an +eviction, only a baseline replacement stores that host's directory again. Mutations queued around +the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision. diff --git a/docs/design.md b/docs/design.md index 16d4fdb0eaed..fdb147c84115 100644 --- a/docs/design.md +++ b/docs/design.md @@ -80,7 +80,7 @@ In the composer, the first glyph's ink starts on the text column's edge, and the One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size. -Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use. +Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use. A `` wrapping a `` is a sixth variant. It is wrong. `; } +const searchQuery = "IANA example domains"; +const queryOnlySearch = { type: "search", query: searchQuery, toolName: "web_search" } as const; + +function renderSearchDetails() { + return ; +} + +function SearchBadge() { + const [expanded, setExpanded] = React.useState(false); + const toggle = React.useCallback(() => setExpanded((current) => !current), []); + return ( + + ); +} + describe("tool detail interaction", () => { + it("shows the query when an expanded search has no results", async () => { + act(() => root.render()); + await page.getByRole("button", { name: "Search" }).click(); + await expect.element(page.getByText(searchQuery, { exact: true })).toBeVisible(); + }); + it("keeps detail controls in the tab order", async () => { function Badge() { const [expanded, setExpanded] = React.useState(true); diff --git a/packages/app/src/agent-stream/layout.test.ts b/packages/app/src/agent-stream/layout.test.ts index fde9a3a342fa..e41c05dec90b 100644 --- a/packages/app/src/agent-stream/layout.test.ts +++ b/packages/app/src/agent-stream/layout.test.ts @@ -393,6 +393,39 @@ describe("layoutStream", () => { expect(findLayoutItem(layout, thinking.id).toolSequence).toBe("last"); }); + it.each(["web", "android"] as const)( + "carries turn metrics from the footer's source row on %s", + (platform) => { + const metrics = [{ label: "Model", value: "opus" }]; + const earlier = { ...assistantMessage("a1", 2), turnMetrics: metrics }; + const latest = { ...toolCall("tool-2", 5), turnMetrics: [{ label: "Steps", value: "2" }] }; + const layout = layoutFor({ + platform, + tail: [userMessage("u1", 1), earlier, toolCall("tool-1", 3), userMessage("u2", 4), latest], + }); + + expect(findLayoutItem(layout, "tool-1").completedFooter?.turnMetrics).toBe(metrics); + expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(latest.turnMetrics); + }, + ); + + it("lays out the footer again when its source row gains turn metrics", () => { + const assistant = assistantMessage("a1", 2); + const trailing = toolCall("tool-2", 4); + const tail = [userMessage("u1", 1), assistant, toolCall("tool-1", 3), trailing]; + const next = userMessage("u2", 5); + const before = layoutFor({ platform: "android", tail: [...tail, next] }); + + const metrics = [{ label: "Model", value: "opus" }]; + const stamped = [...tail]; + stamped[1] = { ...assistant, turnMetrics: metrics }; + const after = layoutFor({ platform: "android", tail: [...stamped, next] }); + + expect(findLayoutItem(before, trailing.id).completedFooter?.turnMetrics).toBeUndefined(); + expect(findLayoutItem(after, trailing.id).completedFooter?.turnMetrics).toBe(metrics); + expect(findLayoutItem(after, next.id)).toBe(findLayoutItem(before, next.id)); + }); + it("keeps bottom and inline footer ownership mutually exclusive", () => { const assistant = assistantMessage("a1", 2); const layout = layoutFor({ diff --git a/packages/app/src/agent-stream/layout.ts b/packages/app/src/agent-stream/layout.ts index 924d9d75ec85..e1918ddc4ff4 100644 --- a/packages/app/src/agent-stream/layout.ts +++ b/packages/app/src/agent-stream/layout.ts @@ -1,3 +1,4 @@ +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; import type { TurnTiming } from "@/timeline/turn-time"; import type { StreamItem } from "@/types/stream"; import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing"; @@ -10,6 +11,7 @@ export interface TurnFooterHost { itemId: string; items: StreamItem[]; timing?: TurnTiming; + turnMetrics?: AgentMetric[]; startIndex: number; } @@ -69,10 +71,15 @@ function createTurnFooterHost(input: { index: number; timingByItemId: Map; }): TurnFooterHost { + const turnMetrics = + input.item.kind === "assistant_message" || input.item.kind === "tool_call" + ? input.item.turnMetrics + : undefined; return { itemId: input.item.id, items: input.items, timing: input.timingByItemId.get(input.item.id), + ...(turnMetrics ? { turnMetrics } : {}), startIndex: input.index, }; } @@ -247,6 +254,7 @@ function areTurnFooterHostsEqual( return ( left.itemId === right.itemId && left.timing === right.timing && + left.turnMetrics === right.turnMetrics && left.startIndex === right.startIndex && left.items === right.items ); diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index 363a4d92a1cc..ace91d4a51f3 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -40,6 +40,7 @@ import { type HistoryStartSettleScheduler, } from "./history-start-settle-scheduler"; import { useChatFindSelectedMessageId } from "@/agent-stream/chat-find"; +import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "@/chat-rail/gutters"; import { useScrollToMessage } from "./use-scroll-to-message.web"; interface CreateWebStreamStrategyInput { @@ -314,6 +315,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool olderHistoryProgressKey, scrollEnabled, contentMaxWidth, + outlineInset = 0, isMobileBreakpoint, } = props; const historyVirtualized = useRevisedHistoryRows( @@ -453,7 +455,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool unsubscribe?.(); }; }, []); - const contentWidth = contentRef.current?.getBoundingClientRect().width; + // The scroll viewport keeps its width when the reading column changes. + // Track the effective column width for cached measurements and estimates. + const readContentWidth = () => { + const available = rowsHostRef.current?.getBoundingClientRect().width; + return available ? Math.min(available, contentMaxWidth ?? available) : contentMaxWidth; + }; + const contentWidth = readContentWidth(); const rowVirtualizer = useVirtualizer({ count: segments.historyVirtualized.length, enabled: shouldUseVirtualizer, @@ -469,7 +477,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const row = segments.historyVirtualized[index]; const measured = row && measuredRowHeights.current.get(row.id); if (measured && measured.width === contentWidth) return measured.height; - return row ? estimateStreamItemHeight({ item: row, contentMaxWidth }) : 120; + return row + ? estimateStreamItemHeight({ item: row, contentMaxWidth: contentWidth ?? 0 }) + : 120; }, observeElementOffset: observeVirtualOffset, rangeExtractor, @@ -477,6 +487,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool overscan: 8, }); rowVirtualizerRef.current = rowVirtualizer; + useLayoutEffect(() => { + // Discard offscreen sizes measured with the previous text wrapping. + rowVirtualizer.measure(); + }, [contentMaxWidth, outlineInset, rowVirtualizer]); // Scroll correction belongs to the viewport's committed layout. The virtualizer // otherwise writes scrollTop before React applies its new row positions. rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false; @@ -722,7 +736,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool if (!container || !content) return null; const viewportTop = container.getBoundingClientRect().top; const scrollTop = container.scrollTop; - const width = content.getBoundingClientRect().width; + const width = readContentWidth() ?? 0; return Array.from(content.querySelectorAll("[data-history-row-id]"), (element) => { const bounds = element.getBoundingClientRect(); const id = element.dataset.historyRowId!; @@ -1222,17 +1236,23 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool ]); const contentContainerStyle = useMemo((): CSSProperties => { + const gutter = isMobileBreakpoint ? 8 : CHAT_COLUMN_BASE_GUTTER; + const { paddingLeft, paddingRight } = resolveChatColumnGutters({ + gutter, + outlineInset, + contentMaxWidth, + }); return { display: "flex", flexDirection: "column", minHeight: "100%", paddingTop: CONTENT_PADDING_TOP_PX, paddingBottom: 16, - paddingLeft: isMobileBreakpoint ? 8 : 16, - paddingRight: isMobileBreakpoint ? 8 : 16, + paddingLeft, + paddingRight, boxSizing: "border-box", }; - }, [isMobileBreakpoint]); + }, [contentMaxWidth, isMobileBreakpoint, outlineInset]); const scrollContainerStyle = useMemo((): CSSProperties => { const overlayScrollbarEnabled = scrollEnabled && !isMobileBreakpoint; return { diff --git a/packages/app/src/agent-stream/strategy.ts b/packages/app/src/agent-stream/strategy.ts index aab5b0413e60..7507f3442bee 100644 --- a/packages/app/src/agent-stream/strategy.ts +++ b/packages/app/src/agent-stream/strategy.ts @@ -107,7 +107,8 @@ export interface StreamRenderInput { baseListContentContainerStyle: StyleProp; forwardListContentContainerStyle: StyleProp; // The chat column's max width. The web viewport estimates unmeasured row heights with it. - contentMaxWidth: number; + contentMaxWidth: number | undefined; + outlineInset?: number; } export interface ResolveStreamRenderStrategyInput { diff --git a/packages/app/src/agent-stream/turn-footer.browser.test.tsx b/packages/app/src/agent-stream/turn-footer.browser.test.tsx index 702a7e3c20c1..185846f0a95a 100644 --- a/packages/app/src/agent-stream/turn-footer.browser.test.tsx +++ b/packages/app/src/agent-stream/turn-footer.browser.test.tsx @@ -1,6 +1,10 @@ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { PortalProvider } from "@gorhom/portal"; +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { page } from "vitest/browser"; +import { FloatingPanelPortalHost } from "@/components/ui/floating-panel-portal"; import { i18n } from "@/i18n/i18next"; import type { TurnTiming } from "@/timeline/turn-time"; import type { StreamItem } from "@/types/stream"; @@ -93,3 +97,57 @@ it.each([ [formatMessageTimestamp(FRIDAY_NIGHT, NOW)]: 1, }); }); + +const COMPLETED_TIMING: TurnTiming = { completedAt: FRIDAY_NIGHT, durationMs: 26_000 }; + +describe("turn stats", () => { + const metrics: AgentMetric[] = [ + { label: "Model", value: "opus" }, + { label: "Cost", value: "$0.42", tone: "warning" }, + ]; + + function renderFooterWithMetrics(turnMetrics?: AgentMetric[]): void { + act(() => + root.render( + + + + , + ), + ); + } + + it("has no trigger when the provider reported nothing for the turn", () => { + renderFooterWithMetrics(undefined); + + expect(page.getByRole("button", { name: "Turn stats" }).elements()).toHaveLength(0); + }); + + it("shows the turn's metrics while the pointer is on the trigger", async () => { + renderFooterWithMetrics(metrics); + + await page.getByRole("button", { name: "Turn stats" }).hover(); + + const card = page.getByRole("dialog", { name: "Turn stats" }); + await expect.element(card).toBeVisible(); + await expect.element(card.getByText("Model")).toBeVisible(); + await expect.element(card.getByText("opus")).toBeVisible(); + await expect.element(card.getByText("$0.42")).toBeVisible(); + }); + + it("keeps the footer's height when the trigger appears", () => { + renderFooterWithMetrics(undefined); + const without = host.getBoundingClientRect().height; + + renderFooterWithMetrics(metrics); + + expect(host.getBoundingClientRect().height).toBe(without); + }); +}); diff --git a/packages/app/src/agent-stream/turn-footer.tsx b/packages/app/src/agent-stream/turn-footer.tsx index fcdc4437e1dd..2e6c70c408d7 100644 --- a/packages/app/src/agent-stream/turn-footer.tsx +++ b/packages/app/src/agent-stream/turn-footer.tsx @@ -1,3 +1,4 @@ +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; import React, { memo, useCallback, useMemo, type ReactNode } from "react"; import { View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; @@ -83,6 +84,7 @@ export const TurnFooter = memo(function TurnFooter({ items={host.items} timing={host.timing} startIndex={host.startIndex} + turnMetrics={host.turnMetrics} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} onPin={onPin} @@ -95,6 +97,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ items, timing, startIndex, + turnMetrics, supportsTimelineCursor, onForkAssistantTurn, onPin, @@ -103,6 +106,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ items: StreamItem[]; timing?: TurnTiming; startIndex: number; + turnMetrics?: AgentMetric[]; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; onPin?: (text: string) => void; @@ -114,6 +118,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ items={items} timing={timing} startIndex={startIndex} + turnMetrics={turnMetrics} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} onPin={onPin} @@ -171,6 +176,7 @@ function CompletedTurnFooter({ items, timing, startIndex, + turnMetrics, supportsTimelineCursor, onForkAssistantTurn, onPin, @@ -179,6 +185,7 @@ function CompletedTurnFooter({ items: StreamItem[]; timing?: TurnTiming; startIndex: number; + turnMetrics?: AgentMetric[]; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; onPin?: (text: string) => void; @@ -214,6 +221,7 @@ function CompletedTurnFooter({ durationMs={timing?.durationMs} onFork={boundary && onForkAssistantTurn ? handleFork : undefined} onPin={onPin} + metrics={turnMetrics} /> ); diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 851693b07f5d..760c65aaab63 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -88,6 +88,7 @@ import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail"; import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline"; import { PinnedPrompt } from "@/agent-stream/pinned-prompt/pinned-prompt"; import { usePinnedPrompt } from "@/agent-stream/pinned-prompt/use-pinned-prompt"; +import { CHAT_COLUMN_RAIL_DATASET, useChatOutlineRail } from "@/chat-rail"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; import { @@ -224,6 +225,7 @@ function renderStreamItemWithTurnFooter(input: { items={footerHost.items} timing={footerHost.timing} startIndex={footerHost.startIndex} + turnMetrics={footerHost.turnMetrics} supportsTimelineCursor={input.supportsTimelineCursor} onForkAssistantTurn={input.onForkAssistantTurn} onPin={input.onPin} @@ -360,7 +362,7 @@ function ScrollToBottomButton({ ); if (isNearBottom && !isTimelineDetached) return null; return ( - + settings.autoExpandReasoning); const chatDisplay = useSettings((settings) => settings.chatDisplay); - const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled); const contentMaxWidth = useSettings(resolveContentMaxWidth); const viewportRef = useRef(null); const pendingClientMessageIds = useMemo( @@ -444,10 +445,6 @@ const AgentStreamViewComponent = forwardRef state.sessions[resolvedServerId]?.serverInfo?.features?.agentForkContextCursor === true, ); - const supportsChatOutline = useSessionStore( - (state) => - state.sessions[resolvedServerId]?.serverInfo?.features?.agentTimelinePromptIndex === true, - ); const timelineEpoch = useSessionStore( (state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null, ); @@ -676,13 +673,15 @@ const AgentStreamViewComponent = forwardRef - + {outlineInset > 0 && chatOutline.prompts.length >= 2 ? ( + + ) : null} {workspaceChrome} + {!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? ( @@ -938,6 +940,7 @@ function RootStack() { + ); } diff --git a/packages/app/src/app/settings/hosts/[serverId]/providers/[providerId].tsx b/packages/app/src/app/settings/hosts/[serverId]/providers/[providerId].tsx new file mode 100644 index 000000000000..adad9c6f6a03 --- /dev/null +++ b/packages/app/src/app/settings/hosts/[serverId]/providers/[providerId].tsx @@ -0,0 +1,24 @@ +import { useLocalSearchParams } from "expo-router"; +import { useMemo } from "react"; +import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; +import SettingsScreen from "@/screens/settings-screen"; +import { normalizeProjectSettingsRouteId } from "@/utils/host-routes"; + +export default function SettingsHostProviderDetailRoute() { + const params = useLocalSearchParams<{ + serverId?: string | string[]; + providerId?: string | string[]; + }>(); + const serverId = normalizeProjectSettingsRouteId(params.serverId); + const providerId = normalizeProjectSettingsRouteId(params.providerId); + const view = useMemo( + () => ({ kind: "provider" as const, serverId, providerId }), + [providerId, serverId], + ); + + return ( + + + + ); +} diff --git a/packages/app/src/appearance/apply.test.ts b/packages/app/src/appearance/apply.test.ts index e18eaa65551f..2b7ab833f8a7 100644 --- a/packages/app/src/appearance/apply.test.ts +++ b/packages/app/src/appearance/apply.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { darkHighlightColors, resolveSyntaxColors } from "@getpaseo/highlight"; -import { DEFAULT_UI_FONT_STACK, REGISTERED_THEMES } from "@/styles/theme"; +import { DEFAULT_UI_FONT_STACK, REGISTERED_THEMES, type Theme } from "@/styles/theme"; import { applyAppearance, type AppearanceInput } from "./apply"; // Override the global react-native-unistyles mock (vitest.setup.ts) so that @@ -37,7 +37,7 @@ interface FakeTheme { "4xl": number; }; lineHeight: { diff: number }; - contentMaxWidth: number; + contentMaxWidth: Theme["contentMaxWidth"]; colors: { foreground: string; syntax: Record }; } @@ -105,10 +105,13 @@ describe("applyAppearance", () => { ]); }); - it("patches the content max width into the theme", () => { - applyAppearance(makeInput({ contentMaxWidth: 1600 })); + it.each([ + [1600, "1600px"], + [undefined, "100%"], + ])("uses a CSS variable-compatible width on web for %s", (contentMaxWidth, cssWidth) => { + applyAppearance(makeInput({ contentMaxWidth })); - expect(runCapturedUpdater().contentMaxWidth).toBe(1600); + expect(runCapturedUpdater().contentMaxWidth).toBe(cssWidth); }); it("resolves an empty UI font family to the default stack", () => { diff --git a/packages/app/src/appearance/apply.ts b/packages/app/src/appearance/apply.ts index 04032a00b049..ea4486fe6323 100644 --- a/packages/app/src/appearance/apply.ts +++ b/packages/app/src/appearance/apply.ts @@ -5,6 +5,7 @@ import { DEFAULT_MONO_FONT_STACK, FONT_SIZE, REGISTERED_THEMES, + themeContentMaxWidth, type Theme, } from "@/styles/theme"; import { applyRootUiFont } from "./apply-root-font"; @@ -17,7 +18,7 @@ export interface AppearanceInput { uiBaseFontSize: number; // already clamped contentFontSize: number; // already clamped codeFontSize: number; // already clamped - contentMaxWidth: number; // already clamped, default resolved + contentMaxWidth: number | undefined; // undefined fills the available width syntaxTheme: SyntaxThemeId; } @@ -64,6 +65,7 @@ export function applyAppearance(input: AppearanceInput): void { const ui = input.uiFontFamily.trim() || DEFAULT_UI_FONT_STACK; const mono = input.monoFontFamily.trim() || DEFAULT_MONO_FONT_STACK; const diffLineHeight = Math.round(input.codeFontSize * 1.5); // couple to code size + const contentMaxWidth = themeContentMaxWidth(input.contentMaxWidth); const activeTheme = UnistylesRuntime.themeName; // Unistyles web emits after each registry patch. Updating the mounted theme // first ensures subscribers receive its new numeric tokens in this render; @@ -87,7 +89,7 @@ export function applyAppearance(input: AppearanceInput): void { fontFamily, fontSize, lineHeight, - contentMaxWidth: input.contentMaxWidth, + contentMaxWidth, colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) }, }; } @@ -96,7 +98,7 @@ export function applyAppearance(input: AppearanceInput): void { fontFamily, fontSize, lineHeight, - contentMaxWidth: input.contentMaxWidth, + contentMaxWidth, colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) }, }; }); diff --git a/packages/app/src/appearance/provider.tsx b/packages/app/src/appearance/provider.tsx index 77addad9a319..6466221197b7 100644 --- a/packages/app/src/appearance/provider.tsx +++ b/packages/app/src/appearance/provider.tsx @@ -65,6 +65,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { return options.find((option) => option.id === settings.pluginThemeId) ?? null; }, [options, settings.pluginThemeId, settings.theme]); + const contentMaxWidth = resolveContentMaxWidth(settings); useEffect(() => { if (isLoading) return; applyTheme({ preference: settings.theme, contributedTheme: selected }); @@ -74,7 +75,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { uiBaseFontSize: settings.uiBaseFontSize, contentFontSize: settings.contentFontSize, codeFontSize: settings.codeFontSize, - contentMaxWidth: resolveContentMaxWidth({ contentMaxWidth: settings.contentMaxWidth }), + contentMaxWidth, syntaxTheme: settings.syntaxTheme, }); setHasAppliedAppearance(true); @@ -87,7 +88,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { settings.uiBaseFontSize, settings.contentFontSize, settings.codeFontSize, - settings.contentMaxWidth, + contentMaxWidth, settings.syntaxTheme, ]); diff --git a/packages/app/src/chat-rail/gutters.test.ts b/packages/app/src/chat-rail/gutters.test.ts new file mode 100644 index 000000000000..245fdc0374ca --- /dev/null +++ b/packages/app/src/chat-rail/gutters.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; +import { CHAT_OUTLINE_GUTTER_INSET } from "@/agent-stream/chat-outline/geometry"; +import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters"; +import { + CHAT_COLUMN_RAIL_DATASET as NATIVE_CHAT_COLUMN_RAIL_DATASET, + ChatColumnRailSurface as NativeChatColumnRailSurface, + useChatOutlineRail as useNativeChatOutlineRail, +} from "./index.native"; +import { CHAT_COLUMN_RAIL_DATASET as WEB_CHAT_COLUMN_RAIL_DATASET } from "./index.web"; + +describe("resolveChatColumnGutters", () => { + it("uses symmetric base gutters when no outline inset is reserved", () => { + expect( + resolveChatColumnGutters({ + gutter: CHAT_COLUMN_BASE_GUTTER, + outlineInset: 0, + contentMaxWidth: 820, + }), + ).toEqual({ paddingLeft: 16, paddingRight: 16 }); + + expect( + resolveChatColumnGutters({ + gutter: CHAT_COLUMN_BASE_GUTTER, + outlineInset: 0, + contentMaxWidth: undefined, + }), + ).toEqual({ paddingLeft: 16, paddingRight: 16 }); + }); + + it("reserves only the left outline gutter when content width is Full", () => { + expect( + resolveChatColumnGutters({ + gutter: CHAT_COLUMN_BASE_GUTTER, + outlineInset: CHAT_OUTLINE_GUTTER_INSET, + contentMaxWidth: undefined, + }), + ).toEqual({ paddingLeft: 60, paddingRight: 16 }); + }); + + it("balances capped columns with a clamped right gutter from the remaining width", () => { + expect( + resolveChatColumnGutters({ + gutter: CHAT_COLUMN_BASE_GUTTER, + outlineInset: CHAT_OUTLINE_GUTTER_INSET, + contentMaxWidth: 820, + }), + ).toEqual({ + paddingLeft: 60, + paddingRight: "clamp(16px, calc(100% - 880px), 60px)", + }); + + expect( + resolveChatColumnGutters({ + gutter: CHAT_COLUMN_BASE_GUTTER, + outlineInset: CHAT_OUTLINE_GUTTER_INSET, + contentMaxWidth: 1200, + }), + ).toEqual({ + paddingLeft: 60, + paddingRight: "clamp(16px, calc(100% - 1260px), 60px)", + }); + }); +}); + +describe("native and web chat-rail boundaries", () => { + it("keeps native as a zero-overhead pass-through with no dataset or outline inset", () => { + const sentinel = "child"; + expect(NATIVE_CHAT_COLUMN_RAIL_DATASET).toBeUndefined(); + expect(useNativeChatOutlineRail()).toEqual({ enabled: false, inset: 0 }); + expect(NativeChatColumnRailSurface({ serverId: "srv-1", children: sentinel })).toBe(sentinel); + }); + + it("tags web rail lanes with a frozen dataset reference", () => { + expect(WEB_CHAT_COLUMN_RAIL_DATASET).toEqual({ chatRailLane: "true" }); + expect(Object.isFrozen(WEB_CHAT_COLUMN_RAIL_DATASET)).toBe(true); + }); +}); diff --git a/packages/app/src/chat-rail/gutters.ts b/packages/app/src/chat-rail/gutters.ts new file mode 100644 index 000000000000..9db1ad9b11fc --- /dev/null +++ b/packages/app/src/chat-rail/gutters.ts @@ -0,0 +1,30 @@ +import { SPACING } from "@/styles/theme"; + +export const CHAT_COLUMN_BASE_GUTTER = SPACING[4]; + +export interface ChatColumnGutters { + paddingLeft: number; + paddingRight: number | string; +} + +/** + * Horizontal padding for a chat column on web. + * + * When the chat outline reserves `outlineInset` on the left, a capped column matches + * that inset on the right using only the horizontal slack left over after fitting + * `contentMaxWidth`. Default and Wide stay centered while the pane has room, shift + * smoothly away from the outline as the pane narrows, and fall back to the base gutter + * on the right when uncapped (`Full`) or tight. + */ +export function resolveChatColumnGutters(input: { + gutter: number; + outlineInset: number; + contentMaxWidth: number | undefined; +}): ChatColumnGutters { + const paddingLeft = input.gutter + input.outlineInset; + const paddingRight = + input.outlineInset > 0 && input.contentMaxWidth !== undefined + ? `clamp(${input.gutter}px, calc(100% - ${paddingLeft + input.contentMaxWidth}px), ${paddingLeft}px)` + : input.gutter; + return { paddingLeft, paddingRight }; +} diff --git a/packages/app/src/chat-rail/index.native.tsx b/packages/app/src/chat-rail/index.native.tsx new file mode 100644 index 000000000000..89f50dade66b --- /dev/null +++ b/packages/app/src/chat-rail/index.native.tsx @@ -0,0 +1,39 @@ +import type { ReactNode } from "react"; + +export interface ChatColumnRailSurfaceProps { + serverId: string; + children: ReactNode; +} + +export interface ChatOutlineRailState { + /** Whether the chat outline feature is enabled for this pane (independent of pane width). */ + readonly enabled: boolean; + /** Left gutter inset currently reserved for the outline rail (`0` or `44` on web). */ + readonly inset: number; +} + +const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({ + enabled: false, + inset: 0, +}); + +/** + * Marker for chat surfaces (composer, track bar, callouts) that share the pane's + * horizontal column rail. On web, an active `ChatColumnRailSurface` applies the + * pane's outline-aware gutters via CSS custom properties without re-rendering + * children. Native never reserves an outline gutter, so this is undefined. + */ +export const CHAT_COLUMN_RAIL_DATASET: Record | undefined = undefined; + +/** + * Native pass-through: the chat outline is a wide-layout web affordance, so native + * renders no wrapper view, registers no subscriptions, and reserves no outline inset. + */ +export function ChatColumnRailSurface({ children }: ChatColumnRailSurfaceProps) { + return children; +} + +/** Chat outline state for this pane (always disabled with 0 inset on native). */ +export function useChatOutlineRail(): ChatOutlineRailState { + return DISABLED_CHAT_OUTLINE_RAIL; +} diff --git a/packages/app/src/chat-rail/index.tsx b/packages/app/src/chat-rail/index.tsx new file mode 100644 index 000000000000..3669dcf1fc4b --- /dev/null +++ b/packages/app/src/chat-rail/index.tsx @@ -0,0 +1,7 @@ +export { + CHAT_COLUMN_RAIL_DATASET, + ChatColumnRailSurface, + useChatOutlineRail, + type ChatColumnRailSurfaceProps, + type ChatOutlineRailState, +} from "./index.native"; diff --git a/packages/app/src/chat-rail/index.web.tsx b/packages/app/src/chat-rail/index.web.tsx new file mode 100644 index 000000000000..51a5483f22e5 --- /dev/null +++ b/packages/app/src/chat-rail/index.web.tsx @@ -0,0 +1,143 @@ +import { + createContext, + useContext, + useLayoutEffect, + useMemo, + useRef, + useState, + type CSSProperties, +} from "react"; +import { + CHAT_OUTLINE_GUTTER_INSET, + CHAT_OUTLINE_MIN_PANEL_WIDTH, +} from "@/agent-stream/chat-outline/geometry"; +import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings"; +import { useSessionStore } from "@/stores/session-store"; +import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters"; +import type { ChatColumnRailSurfaceProps, ChatOutlineRailState } from "./index"; + +export type { ChatColumnRailSurfaceProps, ChatOutlineRailState }; + +const STYLE_ID = "paseo-chat-column-rail"; +// React Native Web turns `dataSet={{ chatRailLane: "true" }}` into `data-chat-rail-lane="true"`. +// When the enclosing pane reserves an outline gutter, every tagged rail consumer receives +// the same horizontal gutters in the browser's layout pass without re-rendering React subtrees +// or growing Unistyles' CSS registry. +const RAIL_RULE = + '[data-chat-rail-active="true"] [data-chat-rail-lane="true"]{padding-left:var(--paseo-chat-rail-left)!important;padding-right:var(--paseo-chat-rail-right)!important;}'; + +const BASE_SURFACE_STYLE: CSSProperties = { + display: "flex", + flexDirection: "column", + flex: 1, + minWidth: 0, + minHeight: 0, +}; + +const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({ + enabled: false, + inset: 0, +}); + +const ChatOutlineRailContext = createContext(DISABLED_CHAT_OUTLINE_RAIL); + +export const CHAT_COLUMN_RAIL_DATASET: Record | undefined = Object.freeze({ + chatRailLane: "true", +}); + +function ensureChatColumnRailStyle(): void { + if (typeof document === "undefined") return; + if (document.getElementById(STYLE_ID)) return; + const style = document.createElement("style"); + style.id = STYLE_ID; + style.textContent = RAIL_RULE; + document.head.appendChild(style); +} + +function cssLength(value: number | string): string { + return typeof value === "number" ? `${value}px` : value; +} + +/** + * Pane-level owner of the chat column rail on web. + * + * Measures the pane width once against `CHAT_OUTLINE_MIN_PANEL_WIDTH` (ignoring 0px + * measurements from hidden retained tabs) and publishes the resolved horizontal gutters + * via CSS custom properties to the composer, track bar, and callouts. Only the outline + * enabled flag and reserved inset (`0` or `44`) enter React context for `AgentStreamView`. + */ +export function ChatColumnRailSurface({ serverId, children }: ChatColumnRailSurfaceProps) { + const surfaceRef = useRef(null); + const [isBelow, setIsBelow] = useState(true); + const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled); + const contentMaxWidth = useSettings(resolveContentMaxWidth); + const supportsChatOutline = useSessionStore( + (state) => state.sessions[serverId]?.serverInfo?.features?.agentTimelinePromptIndex === true, + ); + + useLayoutEffect(() => { + const node = surfaceRef.current; + if (!node) return; + const update = (width: number) => { + // Retained inactive tabs sit under `display: none` and report 0; ignore them. + if (width <= 0) return; + const next = width < CHAT_OUTLINE_MIN_PANEL_WIDTH; + setIsBelow((current) => (current === next ? current : next)); + }; + update(node.getBoundingClientRect().width); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver((entries) => { + const width = + entries[entries.length - 1]?.contentRect.width ?? node.getBoundingClientRect().width; + update(width); + }); + observer.observe(node); + return () => observer.disconnect(); + }, []); + + const enabled = supportsChatOutline && chatOutlineEnabled; + const inset = enabled && !isBelow ? CHAT_OUTLINE_GUTTER_INSET : 0; + + useLayoutEffect(() => { + if (inset > 0) { + ensureChatColumnRailStyle(); + } + }, [inset]); + + const outlineRail = useMemo( + () => (enabled ? { enabled, inset } : DISABLED_CHAT_OUTLINE_RAIL), + [enabled, inset], + ); + + const surfaceStyle = useMemo((): CSSProperties => { + if (inset === 0) { + return BASE_SURFACE_STYLE; + } + const gutters = resolveChatColumnGutters({ + gutter: CHAT_COLUMN_BASE_GUTTER, + outlineInset: inset, + contentMaxWidth, + }); + return { + ...BASE_SURFACE_STYLE, + "--paseo-chat-rail-left": cssLength(gutters.paddingLeft), + "--paseo-chat-rail-right": cssLength(gutters.paddingRight), + } as CSSProperties; + }, [contentMaxWidth, inset]); + + return ( + +
0 ? "true" : undefined} + > + {children} +
+
+ ); +} + +export function useChatOutlineRail(): ChatOutlineRailState { + return useContext(ChatOutlineRailContext); +} diff --git a/packages/app/src/components/adaptive-modal-sheet.tsx b/packages/app/src/components/adaptive-modal-sheet.tsx index a20c4a1a479f..193ef7ad3106 100644 --- a/packages/app/src/components/adaptive-modal-sheet.tsx +++ b/packages/app/src/components/adaptive-modal-sheet.tsx @@ -437,11 +437,13 @@ export function SheetHeaderSubtitle({ text, testID }: { text: string; testID?: s export function SheetHeaderView({ header, onClose, + showCloseButton = true, testID, closeTestID, }: { header: SheetHeader; onClose: () => void; + showCloseButton?: boolean; testID?: string; closeTestID?: string; }) { @@ -473,12 +475,14 @@ export function SheetHeaderView({
{header.actions} - + {showCloseButton ? ( + + ) : null}
@@ -566,6 +570,11 @@ export interface AdaptiveModalSheetProps { * corner, and the compact sheet closes from its handle. */ header?: SheetHeader; + /** + * Leave out the header's close button when `header.back` is the only way out, as for a sheet + * that stands in for a page of the surface beneath it. Escape still closes the sheet. + */ + showCloseButton?: boolean; visible: boolean; onClose: () => void; onDismiss?: () => void; @@ -596,6 +605,7 @@ export interface AdaptiveModalSheetProps { */ function CompactSheetBody({ header, + showCloseButton, onClose, testID, footer, @@ -606,6 +616,7 @@ function CompactSheetBody({ children, }: { header?: SheetHeader; + showCloseButton: boolean; onClose: () => void; testID?: string; footer: ReactNode; @@ -635,7 +646,14 @@ function CompactSheetBody({ ); return ( - {header ? : null} + {header ? ( + + ) : null} {scrollable ? ( - {header ? : null} + {header ? ( + + ) : null} {scrollable ? ( - + diff --git a/packages/app/src/components/context-window-details.browser.test.tsx b/packages/app/src/components/context-window-details.browser.test.tsx new file mode 100644 index 000000000000..30867283c683 --- /dev/null +++ b/packages/app/src/components/context-window-details.browser.test.tsx @@ -0,0 +1,65 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { page } from "vitest/browser"; +import { i18n } from "@/i18n/i18next"; +import { ContextWindowDetails } from "./context-window-details"; + +const CONTEXT = { percentage: 40, usedTokens: 80_000, maxTokens: 200_000 }; + +let root: Root; +let host: HTMLDivElement; + +beforeEach(async () => { + await i18n.changeLanguage("en"); + vi.stubGlobal("React", React); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + host = document.createElement("div"); + document.body.appendChild(host); + root = createRoot(host); +}); + +afterEach(() => { + act(() => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +function renderDetails(sessionMetrics: AgentMetric[]): void { + act(() => + root.render( + + + , + ), + ); +} + +it("shows what the provider reports about the session", async () => { + renderDetails([ + { label: "Model", value: "opus" }, + { label: "Requests", value: "12" }, + ]); + + await expect.element(page.getByText("Model")).toBeVisible(); + await expect.element(page.getByText("opus")).toBeVisible(); + await expect.element(page.getByText("Requests")).toBeVisible(); + await expect.element(page.getByText("Session cost $1.20")).toBeVisible(); +}); + +it("leaves the cost to the provider when it reports one", async () => { + renderDetails([{ label: "Cost", value: "$1.25" }]); + + await expect.element(page.getByText("$1.25")).toBeVisible(); + expect(page.getByText("Session cost $1.20").elements()).toHaveLength(0); +}); diff --git a/packages/app/src/components/context-window-details.tsx b/packages/app/src/components/context-window-details.tsx index 3221539cec14..dba07eb245c4 100644 --- a/packages/app/src/components/context-window-details.tsx +++ b/packages/app/src/components/context-window-details.tsx @@ -1,8 +1,10 @@ import { Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; import { AgentUsage } from "@/usage"; import { formatTokenCount } from "./context-window-meter.utils"; +import { MetricsList } from "./metrics-list"; interface ContextWindowDetailsProps { serverId: string; @@ -13,6 +15,8 @@ interface ContextWindowDetailsProps { maxTokens: number; } | null; sessionCost: string | null; + /** What the provider reports about the session. A reported cost replaces `sessionCost`. */ + sessionMetrics: AgentMetric[]; /** The hover card and tooltip title themselves; the sheet's header carries the title instead. */ showTitle: boolean; /** Whether the usage cards have a Refresh button; without one they show their freshness. */ @@ -20,18 +24,22 @@ interface ContextWindowDetailsProps { } /** - * What the context window meter opens: how full the window is, then the usage of the agent's - * account. The desktop hover card, the native wide tooltip, and the compact sheet all render it. + * What the context window meter opens: how full the window is, what the provider reports about the + * session, then the usage of the agent's account. The desktop hover card, the native wide tooltip, and the compact sheet all render it. */ export function ContextWindowDetails({ serverId, agentId, context, sessionCost, + sessionMetrics, showTitle, refreshable, }: ContextWindowDetailsProps) { const { t } = useTranslation(); + const providerReportsCost = sessionMetrics.some( + (metric) => metric.label.toLowerCase() === "cost", + ); return ( <> @@ -51,10 +59,11 @@ export function ContextWindowDetails({ ) : ( {t("contextWindow.noData")} )} - {sessionCost ? ( + {sessionCost && !providerReportsCost ? ( {t("contextWindow.sessionCost", { cost: sessionCost })} ) : null} + {sessionMetrics.length > 0 ? : null} ); diff --git a/packages/app/src/components/context-window-meter.tsx b/packages/app/src/components/context-window-meter.tsx index e0ed5b22a815..a1bd689517f1 100644 --- a/packages/app/src/components/context-window-meter.tsx +++ b/packages/app/src/components/context-window-meter.tsx @@ -13,11 +13,12 @@ import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/h import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isNative } from "@/constants/platform"; +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; import { useHostReportsUsage } from "@/usage"; import type { Theme } from "@/styles/theme"; import { TOOLBAR_DISC_SIZE, type ToolbarRing } from "@/components/ui/control-geometry"; import { ContextWindowDetails } from "./context-window-details"; -import { ContextWindowSheet } from "./context-window-sheet"; +import { DetailsSheet } from "./details-sheet"; import { formatContextPercentage } from "./context-window-meter.utils"; interface ContextWindowMeterProps { @@ -26,11 +27,14 @@ interface ContextWindowMeterProps { maxTokens: number | null; usedTokens: number | null; totalCostUsd?: number | null; + /** What the provider reports about the session, shown in the details. */ + sessionMetrics?: AgentMetric[]; showPercentage?: boolean; /** The ring's box and stroke when it sits in an icon toolbar. */ toolbarRing?: ToolbarRing; } +const EMPTY_METRICS: AgentMetric[] = []; const SVG_SIZE = 14; const USAGE_POPOVER_WIDTH = 300; const COMPACT_SVG_SIZE = 12; @@ -156,13 +160,16 @@ export function ContextWindowMeter({ maxTokens, usedTokens, totalCostUsd, + sessionMetrics = EMPTY_METRICS, showPercentage = false, toolbarRing, }: ContextWindowMeterProps) { const { t, i18n } = useTranslation(); const { width } = useWindowDimensions(); - // Usage cards need a wider popover; without them it keeps the plain tooltip shape. + // Usage cards and session metrics need a wider popover; without them it keeps the plain tooltip + // shape. const showsUsage = useHostReportsUsage(serverId); + const isWide = showsUsage || sessionMetrics.length > 0; const popoverWidth = Math.min(USAGE_POPOVER_WIDTH, width - 24); // Compact screens open the details in a sheet, which can hold a pressable Refresh. const isCompact = useIsCompactFormFactor(); @@ -226,21 +233,22 @@ export function ContextWindowMeter({ {ring} {percentageLabel}
- + - + ); } - const popoverStyle = showsUsage + const popoverStyle = isWide ? [styles.usagePopover, { width: popoverWidth }] : styles.plainPopover; @@ -264,7 +272,7 @@ export function ContextWindowMeter({ side="top" align="center" offset={8} - maxWidth={showsUsage ? popoverWidth : undefined} + maxWidth={isWide ? popoverWidth : undefined} style={popoverStyle} testID="context-window-meter-tooltip" > @@ -273,6 +281,7 @@ export function ContextWindowMeter({ agentId={agentId} context={context} sessionCost={formattedSessionCost} + sessionMetrics={sessionMetrics} showTitle refreshable={false} /> @@ -307,6 +316,7 @@ export function ContextWindowMeter({ agentId={agentId} context={context} sessionCost={formattedSessionCost} + sessionMetrics={sessionMetrics} showTitle refreshable /> diff --git a/packages/app/src/components/desktop/titlebar-drag-region.tsx b/packages/app/src/components/desktop/titlebar-drag-region.tsx index e39e211bf1d8..aa35181a7128 100644 --- a/packages/app/src/components/desktop/titlebar-drag-region.tsx +++ b/packages/app/src/components/desktop/titlebar-drag-region.tsx @@ -24,6 +24,9 @@ import { isNative } from "@/constants/platform"; */ export const WINDOW_CONTENT_DATASET = { "window-content": "" }; +/** Reserves a clickable area for a control mounted outside the titlebar rail. */ +export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" }; + export const titlebarDragSurfaceStyle: React.CSSProperties = { cursor: "default", // @ts-expect-error — WebkitAppRegion is not in CSSProperties diff --git a/packages/app/src/components/context-window-sheet.tsx b/packages/app/src/components/details-sheet.tsx similarity index 82% rename from packages/app/src/components/context-window-sheet.tsx rename to packages/app/src/components/details-sheet.tsx index 5dd454e048ec..56cb66b0ba90 100644 --- a/packages/app/src/components/context-window-sheet.tsx +++ b/packages/app/src/components/details-sheet.tsx @@ -1,7 +1,6 @@ import { useMemo, type ReactNode } from "react"; import { View, useWindowDimensions } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { useTranslation } from "react-i18next"; import { BottomSheetScrollView } from "@gorhom/bottom-sheet"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SheetHeaderView, SHEET_HORIZONTAL_PADDING_SCALE } from "@/components/adaptive-modal-sheet"; @@ -23,23 +22,24 @@ const ThemedBottomSheetModal = withUnistyles(IsolatedBottomSheetModal, (theme) = })); /** - * The context window meter's details on compact screens, in a sheet as tall as its content. - * Gorhom mounts the content only while the sheet is presented, so whatever it fetches stops once - * the sheet closes. + * What a hover card or tooltip shows on wide screens, shown on compact screens in a sheet as tall + * as its content. Gorhom mounts the content only while the sheet is presented, so whatever it + * fetches stops once the sheet closes. */ -export function ContextWindowSheet({ +export function DetailsSheet({ open, onClose, + title, children, }: { open: boolean; onClose: () => void; + title: string; children: ReactNode; }) { - const { t } = useTranslation(); const { height } = useWindowDimensions(); const insets = useSafeAreaInsets(); - const header = useMemo(() => ({ title: t("contextWindow.title") }), [t]); + const header = useMemo(() => ({ title }), [title]); const scrollContentStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]); const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({ visible: open, @@ -50,7 +50,8 @@ export function ContextWindowSheet({ void; title?: string; @@ -49,6 +50,7 @@ interface CompactHeaderProps { */ export function CompactHeader({ navigation, + inDesktopTitlebar = false, onBack, title, titleTestID, @@ -58,22 +60,28 @@ export function CompactHeader({ }: CompactHeaderProps) { const insets = useSafeAreaInsets(); const inTopBand = useTopBand() !== null; + const usesTitlebarHeight = inTopBand || inDesktopTitlebar; const rootStyle = useMemo( () => [ styles.root, { - paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE), + paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE), marginLeft: insets.left, marginRight: insets.right, }, ], - [inTopBand, insets.top, insets.left, insets.right], + [usesTitlebarHeight, insets.top, insets.left, insets.right], ); return ( - + {navigation === "menu" ? : } @@ -155,12 +163,16 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", gap: theme.spacing[2], }, - topBandRow: { + titlebarRow: { height: HEADER_INNER_HEIGHT, flexDirection: "row", alignItems: "center", gap: theme.spacing[2], }, + desktopTitlebarDividerSpace: { + borderBottomWidth: theme.borderWidth[1], + borderBottomColor: "transparent", + }, titleGroup: { flex: 1, minWidth: 0, diff --git a/packages/app/src/components/hosts/host-picker.tsx b/packages/app/src/components/hosts/host-picker.tsx index ced0be3d55d5..c8a7c0060c05 100644 --- a/packages/app/src/components/hosts/host-picker.tsx +++ b/packages/app/src/components/hosts/host-picker.tsx @@ -1,6 +1,5 @@ import { useCallback, useMemo, type ReactElement, type ReactNode } from "react"; import { Pressable, View } from "react-native"; -import type { GestureResponderEvent } from "react-native"; import { Plus, Server, Settings } from "lucide-react-native"; import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { HostStatusDot } from "@/components/host-status-dot"; @@ -80,19 +79,15 @@ export function HostPickerOption({ ? formatActiveConnectionLabel(activeConnection) : undefined; const leadingSlot = useMemo(() => , [serverId]); - const handleSettingsPress = useCallback( - (event: GestureResponderEvent) => { - event.stopPropagation(); - onOpenHostSettings?.(serverId); - }, - [onOpenHostSettings, serverId], - ); - const trailingSlot = useMemo(() => { + const handleSettingsPress = useCallback(() => { + onOpenHostSettings?.(serverId); + }, [onOpenHostSettings, serverId]); + const trailingAction = useMemo(() => { if (!onOpenHostSettings) return undefined; return ( @@ -112,7 +107,7 @@ export function HostPickerOption({ label={label} description={connectionLabel} leadingSlot={leadingSlot} - trailingSlot={trailingSlot} + trailingAction={trailingAction} selected={selected} active={active} onPress={onPress} @@ -319,6 +314,12 @@ export function HostPicker({ } const styles = StyleSheet.create((theme) => ({ + settingsAction: { + flex: 1, + justifyContent: "center", + paddingLeft: theme.spacing[1], + paddingRight: theme.spacing[3], + }, statusDotSlot: { width: theme.iconSize.sm, height: theme.iconSize.sm, diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index 41470f931e9c..d15c08f7fe71 100644 --- a/packages/app/src/components/message.tsx +++ b/packages/app/src/components/message.tsx @@ -3,6 +3,7 @@ import { MessagePreview, MessageSender } from "@/components/user-message"; import { useStableEvent } from "@/hooks/use-stable-event"; import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content"; import { AssistantForkMenu, type AssistantForkTarget } from "@/components/assistant-fork-menu"; +import { TurnMetricsButton } from "@/components/turn-metrics"; import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox"; import { AttachmentFrame, @@ -36,7 +37,11 @@ import { useToolCallExpanded } from "@/tool-calls/expansion-context"; import { useTargetAgentTitle } from "@/tool-calls/use-target-agent-title"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import type { AgentMessage } from "@getpaseo/protocol/agent-message"; -import type { AgentCapabilityFlags, ToolCallDetail } from "@getpaseo/protocol/agent-types"; +import type { + AgentCapabilityFlags, + AgentMetric, + ToolCallDetail, +} from "@getpaseo/protocol/agent-types"; import type { AgentAttachment } from "@getpaseo/protocol/messages"; import MaskedView from "@react-native-masked-view/masked-view"; import { @@ -582,6 +587,8 @@ interface AssistantTurnFooterProps { durationMs?: number | null; onFork?: (target: AssistantForkTarget) => Promise | void; onPin?: (text: string) => void; + /** What the provider reported about the turn. Without any, the footer has no stats button. */ + metrics?: AgentMetric[]; } const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ @@ -619,6 +626,8 @@ const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ flexShrink: 0, color: theme.colors.foregroundMuted, fontSize: STREAM_METADATA_FONT_SIZE, + // React Native Web preserves trailing spaces at line wraps by default. + ...(isWeb ? { whiteSpace: "normal" } : {}), }, overlappingLabel: { marginLeft: "-100%", @@ -641,6 +650,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ durationMs, onFork, onPin, + metrics, }: AssistantTurnFooterProps) { const { t } = useTranslation(); const [hovered, setHovered] = useState(false); @@ -683,38 +693,14 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ revealTimerRef.current = null; }, TIMESTAMP_REVEAL_MS); }, [canSwap]); - const handleFork = useCallback( - (target: AssistantForkTarget) => { - return onFork?.(target); - }, - [onFork], - ); - const handlePin = useCallback(() => { - if (onPin && getContent) { - onPin(getContent()); - } - }, [onPin, getContent]); - const canFork = Boolean(onFork); - return ( - {onPin || getContent || canFork ? ( - - {onPin ? ( - - ) : null} - {getContent ? ( - - ) : null} - {canFork ? : null} - - ) : null} + {primaryLabel ? ( ) { + const handleFork = useCallback( + (target: AssistantForkTarget) => { + return onFork?.(target); + }, + [onFork], + ); + const handlePin = useCallback(() => { + if (onPin && getContent) { + onPin(getContent()); + } + }, [onPin, getContent]); + const hasMetrics = metrics !== undefined && metrics.length > 0; + if (!onPin && !getContent && !onFork && !hasMetrics) return null; + return ( + + {onPin ? ( + + ) : null} + {getContent ? ( + + ) : null} + {onFork ? : null} + {hasMetrics ? : null} + + ); +} + interface LiveElapsedProps { startedAt: Date; active?: boolean; diff --git a/packages/app/src/components/metrics-list.tsx b/packages/app/src/components/metrics-list.tsx new file mode 100644 index 000000000000..90d0a40f4bf6 --- /dev/null +++ b/packages/app/src/components/metrics-list.tsx @@ -0,0 +1,72 @@ +import { memo } from "react"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; + +/** + * Label and value rows a provider reports for a session or a turn. The provider owns the words and + * the tone; the list only lines them up. + */ +export const MetricsList = memo(function MetricsList({ + metrics, + testID, +}: { + metrics: AgentMetric[]; + testID?: string; +}) { + return ( + + {metrics.map((metric) => ( + + + {metric.label} + + + {metric.value} + + + ))} + + ); +}); + +function toneStyle(tone: AgentMetric["tone"]) { + switch (tone) { + case "ok": + return styles.ok; + case "warning": + return styles.warning; + case "danger": + return styles.danger; + default: + return null; + } +} + +const styles = StyleSheet.create((theme) => ({ + list: { + gap: theme.spacing[1.5], + }, + row: { + flexDirection: "row", + alignItems: "baseline", + gap: theme.spacing[6], + }, + label: { + flexShrink: 1, + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + lineHeight: theme.fontSize.sm * 1.4, + }, + value: { + flex: 1, + textAlign: "right", + color: theme.colors.foreground, + fontSize: theme.fontSize.sm, + lineHeight: theme.fontSize.sm * 1.4, + fontVariant: ["tabular-nums"], + }, + ok: { color: theme.colors.statusSuccess }, + warning: { color: theme.colors.statusWarning }, + danger: { color: theme.colors.statusDanger }, +})); diff --git a/packages/app/src/components/page-layout/index.tsx b/packages/app/src/components/page-layout/index.tsx index cf70d5c31d98..3498e3e50c05 100644 --- a/packages/app/src/components/page-layout/index.tsx +++ b/packages/app/src/components/page-layout/index.tsx @@ -1,13 +1,15 @@ import { AppearanceText as Text } from "@/appearance/text"; +import { ChevronRight } from "lucide-react-native"; import { useMemo, type ReactNode } from "react"; -import { Platform, ScrollView, View } from "react-native"; +import { Platform, ScrollView, View, type PressableStateCallbackType } from "react-native"; import { KeyboardAwareScrollView } from "react-native-keyboard-controller"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { StyleSheet } from "react-native-unistyles"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { BackHeader } from "@/components/headers/back-header"; import { MenuHeader } from "@/components/headers/menu-header"; +import { PressHighlight } from "@/components/ui/press-highlight"; import { useIsCompactFormFactor } from "@/constants/layout"; -import { SPACING } from "@/styles/theme"; +import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme"; const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView; @@ -58,14 +60,7 @@ export function PageLayout({ testID={testID} > - {showTitle ? ( - - - {title} - - {actions} - - ) : null} + {showTitle ? : null} {children} @@ -73,6 +68,77 @@ export function PageLayout({ ); } +/** The page that holds this one. Its name is the first part of the title and goes back to it. */ +export interface PageTitleParent { + label: string; + /** What the press does, such as "Back to providers". */ + accessibilityLabel: string; + onPress: () => void; + testID?: string; +} + +interface PageTitleProps { + parent?: PageTitleParent; + /** Drawn before the title, such as the icon of the thing the page is about. */ + icon?: ReactNode; + title?: string; + /** A control that belongs to the title, drawn right after it. */ + adornment?: ReactNode; + /** Controls for the whole page, drawn at the trailing edge. */ + actions?: ReactNode; + testID?: string; + titleTestID?: string; +} + +/** + * The heading of a desktop page. A page that opens from another page, such as one provider from + * Providers, names that page first: "Providers > Antigravity". + */ +export function PageTitle({ + parent, + icon, + title, + adornment, + actions, + testID, + titleTestID = "page-title", +}: PageTitleProps) { + return ( + + + {parent ? ( + + {({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => ( + + {parent.label} + + )} + + ) : null} + {parent && title !== undefined ? ( + + ) : null} + {icon} + {title !== undefined ? ( + + {title} + + ) : null} + {adornment} + + {actions} + + ); +} + +const ThemedChevronRight = withUnistyles(ChevronRight); +const separatorColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + const styles = StyleSheet.create((theme) => ({ container: { flex: 1, @@ -102,11 +168,27 @@ const styles = StyleSheet.create((theme) => ({ gap: theme.spacing[4], marginBottom: theme.spacing[6], }, - title: { + titleParts: { // Line up with the section titles, which sit inset from their cards. marginLeft: theme.spacing[1], + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + flexShrink: 1, + minWidth: 0, + }, + title: { fontSize: theme.fontSize["4xl"], fontWeight: theme.fontWeight.medium, color: theme.colors.foreground, }, + titleLeaf: { + flexShrink: 1, + }, + parent: { + color: theme.colors.foregroundMuted, + }, + parentHovered: { + color: theme.colors.foreground, + }, })); diff --git a/packages/app/src/components/provider-catalog-list.tsx b/packages/app/src/components/provider-catalog-list.tsx deleted file mode 100644 index b911f10553ed..000000000000 --- a/packages/app/src/components/provider-catalog-list.tsx +++ /dev/null @@ -1,234 +0,0 @@ -import { useCallback, useMemo, useState } from "react"; -import { useTranslation } from "react-i18next"; -import { Text, View, type LayoutChangeEvent } from "react-native"; -import { SvgXml } from "react-native-svg"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { PackagePlus } from "lucide-react-native"; -import { Button } from "@/components/ui/button"; -import { ExternalLink } from "@/components/ui/external-link"; -import { SearchField } from "@/components/ui/search-field"; -import { StatusBadge } from "@/components/ui/status-badge"; -import { rankProviderCatalog } from "@/components/provider-catalog-search"; -import { - useAcpProviderCatalog, - type AcpProviderCatalogItem, -} from "@/hooks/use-acp-provider-catalog"; -import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; -import { SPACING, type Theme } from "@/styles/theme"; -import { settingsStyles } from "@/styles/settings"; - -interface ProviderCatalogListProps { - serverId: string; - installingProviderId: string | null; - onInstall: (entry: AcpProviderCatalogItem) => Promise | void; -} - -const PROVIDER_FALLBACK_ICON_SIZE = 20; -const PROVIDER_REMOTE_ICON_SIZE = 24; -const TILE_GAP = SPACING[3]; -/** Narrowest tile that keeps the icon, type badge, install link, and Add on one row. */ -const MIN_TILE_WIDTH = 300; -const MAX_COLUMNS = 4; - -const ThemedPackagePlus = withUnistyles(PackagePlus); -const ThemedSvgXml = withUnistyles(SvgXml); - -const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); - -function columnCountForWidth(width: number): number { - const fits = Math.floor((width + TILE_GAP) / (MIN_TILE_WIDTH + TILE_GAP)); - return Math.min(MAX_COLUMNS, Math.max(1, fits)); -} - -interface CatalogTileProps { - entry: AcpProviderCatalogItem; - /** `undefined` until the grid is measured, or in a single column; the tile fills the row. */ - width: number | undefined; - installing: boolean; - onInstall: (entry: AcpProviderCatalogItem) => void; -} - -function CatalogTile({ entry, width, installing, onInstall }: CatalogTileProps) { - const { t } = useTranslation(); - const handleInstall = useCallback(() => { - onInstall(entry); - }, [entry, onInstall]); - const tileStyle = useMemo( - () => [settingsStyles.card, styles.tile, width === undefined ? styles.tileFull : { width }], - [width], - ); - - return ( - - - {entry.iconSvg ? ( - - ) : ( - - )} - - - - {entry.title} - - - {/* The catalog is the ACP registry, so every entry it offers is an ACP provider. */} - - - - - - - ); -} - -export function ProviderCatalogList({ - serverId, - installingProviderId, - onInstall, -}: ProviderCatalogListProps) { - const { t } = useTranslation(); - const { entries: catalogEntries } = useAcpProviderCatalog(); - const { entries: providerEntries } = useProvidersSnapshot(serverId); - const [search, setSearch] = useState(""); - const [gridWidth, setGridWidth] = useState(null); - - const installedIds = useMemo( - () => new Set(providerEntries?.map((entry) => entry.provider) ?? []), - [providerEntries], - ); - - const availableEntries = useMemo( - () => - rankProviderCatalog( - catalogEntries.filter((entry) => !installedIds.has(entry.id)), - search, - ), - [catalogEntries, installedIds, search], - ); - - const handleGridLayout = useCallback((event: LayoutChangeEvent) => { - setGridWidth(event.nativeEvent.layout.width); - }, []); - - const tileWidth = useMemo(() => { - if (gridWidth === null) return undefined; - const columns = columnCountForWidth(gridWidth); - if (columns === 1) return undefined; - return Math.floor((gridWidth - TILE_GAP * (columns - 1)) / columns); - }, [gridWidth]); - - return ( - - - - - - {availableEntries.length === 0 ? ( - - {t("providerCatalog.noProviders")} - - ) : ( - - {availableEntries.map((entry) => ( - - ))} - - )} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - searchRail: { - flexDirection: "row", - marginBottom: theme.spacing[3], - }, - grid: { - flexDirection: "row", - flexWrap: "wrap", - gap: TILE_GAP, - }, - tile: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[3], - padding: theme.spacing[3], - }, - tileFull: { - width: "100%", - }, - details: { - flex: 1, - minWidth: 0, - gap: theme.spacing[1], - }, - iconFrame: { - flexShrink: 0, - width: 36, - height: 36, - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - alignItems: "center", - justifyContent: "center", - }, - addButton: { - flexShrink: 0, - }, - name: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.normal, - }, - metaRow: { - flexDirection: "row", - flexWrap: "wrap", - alignItems: "center", - gap: theme.spacing[2], - }, - stateBox: { - minHeight: 96, - alignItems: "center", - justifyContent: "center", - padding: theme.spacing[4], - }, - stateText: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, -})); diff --git a/packages/app/src/components/provider-diagnostic-sheet.tsx b/packages/app/src/components/provider-diagnostic-sheet.tsx deleted file mode 100644 index 904ba17e8bf8..000000000000 --- a/packages/app/src/components/provider-diagnostic-sheet.tsx +++ /dev/null @@ -1,825 +0,0 @@ -import * as Clipboard from "expo-clipboard"; -import { AlertTriangle, Copy, FileText, Plus, RotateCw, Trash2 } from "lucide-react-native"; -import type { TFunction } from "i18next"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { useTranslation } from "react-i18next"; -import { Pressable, type PressableStateCallbackType, Text, View } from "react-native"; -import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { - AdaptiveModalSheet, - AdaptiveTextInput, - SheetHeaderIconButton, - type SheetHeader, -} from "@/components/adaptive-modal-sheet"; -import { Button } from "@/components/ui/button"; -import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface"; -import { useIsCompactFormFactor } from "@/constants/layout"; -import { isWeb } from "@/constants/platform"; -import { useToast } from "@/contexts/toast-context"; -import { CODE_SURFACE_DATASET } from "@/styles/code-surface"; -import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; -import { useTimeAgo } from "@/hooks/use-time-ago"; -import { useHostRuntimeClient } from "@/runtime/host-runtime"; -import { settingsStyles } from "@/styles/settings"; -import { resolveProviderLabel } from "@/utils/provider-definitions"; -import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; -import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types"; -import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config"; -import { - resolveProviderDiscoveredModels, - type ProviderDiscoveredModelsCache, -} from "./provider-diagnostic-models"; - -interface ProviderDiagnosticSheetProps { - provider: string; - visible: boolean; - onClose: () => void; - serverId: string; -} - -function rankModels(items: T[], query: string, fields: (item: T) => string[]): T[] { - if (!query.trim()) return items; - const scored = items - .map((item) => ({ item, score: scoreTextFields(query, fields(item)) })) - .filter( - (entry): entry is { item: T; score: NonNullable } => entry.score !== null, - ); - scored.sort((a, b) => compareMatchScores(a.score, b.score)); - return scored.map((entry) => entry.item); -} - -function DiscoveredModelRow({ model }: { model: AgentModelDefinition }) { - return ( - - - {model.label} - - - {model.id} - - {model.description ? ( - - {model.description} - - ) : null} - - ); -} - -function CustomModelRow({ - model, - deleting, - onDelete, -}: { - model: ProviderProfileModel; - deleting: boolean; - onDelete: (modelId: string) => void; -}) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const handleDelete = useCallback(() => onDelete(model.id), [model.id, onDelete]); - const deleteButtonStyle = useCallback( - ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ - sheetStyles.iconButton, - (Boolean(hovered) || pressed) && sheetStyles.iconButtonHovered, - deleting ? sheetStyles.disabled : null, - ], - [deleting], - ); - - return ( - - - {model.label} - - - {model.id} - - - - - - - ); -} - -function SectionHeader({ title, count, hint }: { title: string; count?: number; hint?: string }) { - return ( - - {title} - - {count !== undefined ? ( - {count} - ) : null} - {count !== undefined && hint ? ( - · - ) : null} - {hint ? {hint} : null} - - - ); -} - -function AddCustomModelSubSheet({ - provider, - serverId, - visible, - onClose, - refresh, -}: { - provider: string; - serverId: string; - visible: boolean; - onClose: () => void; - refresh: (providers?: AgentProvider[]) => Promise; -}) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const { config, patchConfig } = useDaemonConfig(serverId); - const [input, setInput] = useState(""); - const [error, setError] = useState(null); - const [saving, setSaving] = useState(false); - - const additionalModels = useMemo( - () => config?.providers?.[provider]?.additionalModels ?? [], - [config?.providers, provider], - ); - const trimmed = input.trim(); - const canAdd = trimmed.length > 0 && !additionalModels.some((model) => model.id === trimmed); - - useEffect(() => { - if (!visible) { - setInput(""); - setError(null); - } - }, [visible]); - - const handleAdd = useCallback(() => { - if (!canAdd) return; - setError(null); - setSaving(true); - void patchConfig({ - providers: { - [provider]: { - additionalModels: [...additionalModels, { id: trimmed, label: trimmed }], - }, - }, - }) - .then(() => refresh([provider])) - .then(() => onClose()) - .catch((err) => { - setError(err instanceof Error ? err.message : t("settings.providers.models.failedToSave")); - }) - .finally(() => setSaving(false)); - }, [additionalModels, canAdd, onClose, patchConfig, provider, refresh, t, trimmed]); - - const header = useMemo( - () => ({ title: t("settings.providers.models.addCustomTitle") }), - [t], - ); - - return ( - - - {t("settings.providers.models.modelId")} - - {error ? {error} : null} - - - - - - - ); -} - -function DiagnosticSubSheet({ - provider, - serverId, - visible, - onClose, -}: { - provider: string; - serverId: string; - visible: boolean; - onClose: () => void; -}) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const toast = useToast(); - const client = useHostRuntimeClient(serverId); - const [diagnostic, setDiagnostic] = useState(null); - const [loading, setLoading] = useState(false); - - const fetchDiagnostic = useCallback(async () => { - if (!client) return; - setLoading(true); - try { - const result = await client.getProviderDiagnostic(provider); - setDiagnostic(result.diagnostic); - } catch (err) { - setDiagnostic( - err instanceof Error ? err.message : t("settings.providers.diagnostic.failedToFetch"), - ); - } finally { - setLoading(false); - } - }, [client, provider, t]); - - useEffect(() => { - if (visible) { - void fetchDiagnostic(); - } else { - setDiagnostic(null); - } - }, [visible, fetchDiagnostic]); - - const handleRefreshPress = useCallback(() => { - void fetchDiagnostic(); - }, [fetchDiagnostic]); - - const handleCopyPress = useCallback(() => { - if (!diagnostic) return; - void Clipboard.setStringAsync(diagnostic) - .then(() => toast.copied(t("settings.providers.diagnostic.copyLabel"))) - .catch(() => toast.error(t("settings.providers.diagnostic.copyFailed"))); - }, [diagnostic, t, toast]); - - const header = useMemo( - () => ({ - title: t("settings.providers.diagnostic.title"), - actions: ( - <> - - - - ), - }), - [diagnostic, handleCopyPress, handleRefreshPress, loading, t], - ); - - let body: React.ReactNode; - if (loading && !diagnostic) { - body = ( - - - - {t("settings.providers.diagnostic.running")} - - - ); - } else if (diagnostic) { - body = ( - - {diagnostic} - - ); - } else { - body = ( - - - {t("settings.providers.diagnostic.none")} - - - ); - } - - return ( - - {body} - - ); -} - -interface ProviderModalBodyProps { - discoveredCount: number; - additionalCount: number; - providerSnapshotRefreshing: boolean; - providerErrorMessage: string | null; - modelsRefreshing: boolean; - searchActive: boolean; - filteredDiscovered: AgentModelDefinition[]; - filteredCustom: ProviderProfileModel[]; - deletingModelId: string | null; - onRefresh: () => void; - onDeleteCustom: (modelId: string) => void; - theme: { iconSize: { md: number }; colors: { foregroundMuted: string } }; -} - -interface ProviderSheetFooterInput { - fetchedAt: string | null; - isCompact: boolean; - modelsRefreshing: boolean; - t: TFunction; - onOpenAddSheet: () => void; - onOpenDiagSheet: () => void; - onRefreshModels: () => void; -} - -function renderProviderSheetFooter({ - fetchedAt, - isCompact, - modelsRefreshing, - t, - onOpenAddSheet, - onOpenDiagSheet, - onRefreshModels, -}: ProviderSheetFooterInput) { - const contentStyle = isCompact ? sheetStyles.compactFooterContent : sheetStyles.footerContent; - const actionsStyle = isCompact ? sheetStyles.compactFooterActions : sheetStyles.footerActions; - const buttonStyle = isCompact ? sheetStyles.compactFooterButton : null; - return ( - - {fetchedAt || !isCompact ? ( - - ) : null} - - - - - - - ); -} - -function ProviderUpdatedLabel({ - fetchedAt, - isCompact, -}: { - fetchedAt: string | null; - isCompact: boolean; -}) { - const { t } = useTranslation(); - const label = useTimeAgo(fetchedAt ? new Date(fetchedAt) : null); - const style = isCompact - ? [sheetStyles.footerMeta, sheetStyles.compactFooterMeta] - : sheetStyles.footerMeta; - return ( - - {fetchedAt ? t("settings.providers.models.updated", { time: label }) : ""} - - ); -} - -function ProviderModalBody(props: ProviderModalBodyProps) { - const { t } = useTranslation(); - const { - discoveredCount, - additionalCount, - providerSnapshotRefreshing, - providerErrorMessage, - modelsRefreshing, - searchActive, - filteredDiscovered, - filteredCustom, - deletingModelId, - onRefresh, - onDeleteCustom, - theme, - } = props; - - if (discoveredCount === 0 && additionalCount === 0 && providerSnapshotRefreshing) { - return ( - - - {t("settings.providers.models.loading")} - - ); - } - if (discoveredCount === 0 && additionalCount === 0 && providerErrorMessage) { - return ( - - - {providerErrorMessage} - - - ); - } - if (filteredDiscovered.length === 0 && filteredCustom.length === 0 && searchActive) { - return ( - - {t("settings.providers.models.noSearchMatches")} - - ); - } - if (discoveredCount === 0 && additionalCount === 0) { - return ( - - {t("settings.providers.models.noneDetected")} - - ); - } - return ( - <> - {filteredDiscovered.length > 0 ? ( - - - - {filteredDiscovered.map((model) => ( - - ))} - - - ) : null} - {filteredCustom.length > 0 ? ( - - - - {filteredCustom.map((model) => ( - - ))} - - - ) : null} - - ); -} - -export function ProviderDiagnosticSheet({ - provider, - visible, - onClose, - serverId, -}: ProviderDiagnosticSheetProps) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const isCompact = useIsCompactFormFactor(); - const { entries: snapshotEntries, refresh, isRefreshing } = useProvidersSnapshot(serverId); - const { config, patchConfig } = useDaemonConfig(serverId); - const [query, setQuery] = useState(""); - const [addSheetOpen, setAddSheetOpen] = useState(false); - const [diagSheetOpen, setDiagSheetOpen] = useState(false); - const [deletingModelId, setDeletingModelId] = useState(null); - - const providerLabel = resolveProviderLabel(provider, snapshotEntries); - const providerEntry = useMemo( - () => snapshotEntries?.find((entry) => entry.provider === provider), - [snapshotEntries, provider], - ); - const additionalModels = useMemo( - () => config?.providers?.[provider]?.additionalModels ?? [], - [config?.providers, provider], - ); - const providerSnapshotRefreshing = providerEntry?.status === "loading"; - const providerErrorMessage = - providerEntry?.status === "error" - ? (providerEntry.error ?? t("settings.providers.diagnostic.unknownError")) - : null; - const modelsRefreshing = isRefreshing || providerSnapshotRefreshing; - - const stableDiscoveredRef = useRef(null); - const currentModels = providerEntry?.models; - const { models: discoveredModels, cache: nextDiscoveredCache } = resolveProviderDiscoveredModels({ - serverId, - provider, - currentModels, - providerSnapshotRefreshing, - previousCache: stableDiscoveredRef.current, - }); - stableDiscoveredRef.current = nextDiscoveredCache; - - useEffect(() => { - if (!visible) { - setQuery(""); - setAddSheetOpen(false); - setDiagSheetOpen(false); - } - }, [visible]); - - const q = query.trim(); - const filteredDiscovered = useMemo( - () => rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]), - [discoveredModels, q], - ); - const filteredCustom = useMemo( - () => rankModels(additionalModels, q, (m) => [m.label, m.id]), - [additionalModels, q], - ); - - const handleRefreshModels = useCallback(() => { - void refresh([provider]); - }, [provider, refresh]); - - const handleOpenAddSheet = useCallback(() => setAddSheetOpen(true), []); - const handleCloseAddSheet = useCallback(() => setAddSheetOpen(false), []); - const handleOpenDiagSheet = useCallback(() => setDiagSheetOpen(true), []); - const handleCloseDiagSheet = useCallback(() => setDiagSheetOpen(false), []); - - const handleDeleteCustom = useCallback( - (modelId: string) => { - setDeletingModelId(modelId); - void patchConfig({ - providers: { - [provider]: { - additionalModels: additionalModels.filter((model) => model.id !== modelId), - }, - }, - }) - .then(() => refresh([provider])) - .finally(() => { - setDeletingModelId((current) => (current === modelId ? null : current)); - }); - }, - [additionalModels, patchConfig, provider, refresh], - ); - - const sheetHeader = useMemo( - () => ({ - title: providerLabel, - search: { - onChange: setQuery, - placeholder: t("settings.providers.models.searchPlaceholder"), - testID: "provider-settings-search", - }, - }), - [providerLabel, t], - ); - - return ( - <> - - - - - - - ); -} - -const sheetStyles = StyleSheet.create((theme) => ({ - mutedText: { - fontSize: theme.fontSize.base, - color: theme.colors.foregroundMuted, - }, - monoHint: { - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.code, - color: theme.colors.foregroundMuted, - flexShrink: 0, - }, - descriptionInline: { - flex: 1, - fontSize: theme.fontSize.sm, - color: theme.colors.foregroundMuted, - }, - errorText: { - fontSize: theme.fontSize.sm, - color: theme.colors.destructive, - }, - formInput: { - backgroundColor: theme.colors.surface2, - borderRadius: theme.borderRadius.lg, - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[3], - color: theme.colors.foreground, - borderWidth: 1, - borderColor: theme.colors.border, - fontSize: theme.fontSize.base, - }, - iconButton: { - width: 28, - height: 28, - flexShrink: 0, - borderRadius: theme.borderRadius.full, - alignItems: "center", - justifyContent: "center", - }, - iconButtonHovered: { - backgroundColor: theme.colors.surface2, - }, - disabled: { - opacity: 0.5, - }, - section: { - marginBottom: theme.spacing[4], - }, - sectionHeader: { - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - gap: theme.spacing[2], - marginBottom: theme.spacing[2], - marginLeft: theme.spacing[1], - }, - sectionHeaderMeta: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1], - }, - modelRow: { - flexDirection: "row", - alignItems: "center", - paddingVertical: theme.spacing[2], - paddingHorizontal: theme.spacing[4], - gap: theme.spacing[3], - borderTopWidth: 1, - borderTopColor: theme.colors.border, - }, - modelTitle: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - flexShrink: 0, - }, - customModelText: { - flexShrink: 1, - minWidth: 0, - }, - modelRowFiller: { - flex: 1, - }, - emptyState: { - paddingVertical: theme.spacing[8], - alignItems: "center", - gap: theme.spacing[3], - }, - footerContent: { - flex: 1, - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - gap: theme.spacing[2], - }, - compactFooterContent: { - flex: 1, - gap: theme.spacing[2], - }, - footerMeta: { - flex: 1, - fontSize: theme.fontSize.sm, - color: theme.colors.foregroundMuted, - }, - compactFooterMeta: { - flex: 0, - }, - footerActions: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - compactFooterActions: { - gap: theme.spacing[2], - }, - compactFooterButton: { - alignSelf: "stretch", - }, - formGroup: { - gap: theme.spacing[3], - }, - formLabel: { - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - color: theme.colors.foreground, - }, - formActions: { - flexDirection: "row", - justifyContent: "flex-end", - gap: theme.spacing[2], - }, - codeBlockLoading: { - paddingVertical: theme.spacing[4], - paddingHorizontal: theme.spacing[4], - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, -})); - -const MAIN_SNAP_POINTS = ["65%", "92%"]; -const ADD_SNAP_POINTS = ["40%"]; -const DIAGNOSTIC_SNAP_POINTS = ["50%", "85%"]; diff --git a/packages/app/src/components/provider-installation-section.browser.test.tsx b/packages/app/src/components/provider-installation-section.browser.test.tsx new file mode 100644 index 000000000000..facb39b2a740 --- /dev/null +++ b/packages/app/src/components/provider-installation-section.browser.test.tsx @@ -0,0 +1,480 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { within } from "@testing-library/dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { i18n as testI18n } from "@/i18n/i18next"; +import { + ProviderInstallationSection, + type ProviderInstallationState, + type ProviderUpdateAction, + type ProviderUpdatesState, +} from "./provider-installation-section"; + +// Load translations so controls expose their real accessible names. +void testI18n; + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +const mounted: { root: Root; container: HTMLDivElement }[] = []; +afterEach(() => { + for (const entry of mounted.splice(0)) { + act(() => entry.root.unmount()); + entry.container.remove(); + } +}); + +const INSTALL_URL = "https://example.com/install"; +const UPDATE_URL = "https://example.com/update"; + +function mount( + state: ProviderInstallationState, + updates: ProviderUpdatesState = { status: "hidden" }, + action?: ProviderUpdateAction, +) { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + act(() => + root.render(), + ); + mounted.push({ root, container }); + const view = within(container); + return { + view, + rerender: (nextUpdates: ProviderUpdatesState, nextAction?: ProviderUpdateAction) => + act(() => + root.render( + , + ), + ), + installButton: () => view.queryByRole("button", { name: "Install" }), + installLink: () => view.queryByRole("link", { name: "Install instructions" }), + }; +} + +function ready(installation: ProviderInstallationState & { status: "ready" }) { + return installation; +} + +describe("install link visibility", () => { + it("offers the Install button when the provider reports it is not installed", () => { + const section = mount( + ready({ + status: "ready", + installation: { installUrl: INSTALL_URL, inspection: { status: "not_installed" } }, + }), + ); + expect(section.installButton()).not.toBeNull(); + expect(section.installLink()).toBeNull(); + }); + + it("offers a quiet install link when the installation check failed", async () => { + const section = mount( + ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + inspection: { status: "error", message: "version probe exploded" }, + }, + }), + ); + await expect.element(section.view.getByText("version probe exploded")).toBeVisible(); + expect(section.installLink()).not.toBeNull(); + expect(section.installButton()).toBeNull(); + }); + + it("offers a quiet install link for a provider that only declares where to install it", () => { + const section = mount(ready({ status: "ready", installation: { installUrl: INSTALL_URL } })); + expect(section.installLink()).not.toBeNull(); + expect(section.installButton()).toBeNull(); + }); + + it("offers no install link once the provider reports it is installed", () => { + const section = mount( + ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + inspection: { status: "installed", version: "1" }, + }, + }), + ); + expect(section.installLink()).toBeNull(); + expect(section.installButton()).toBeNull(); + }); +}); + +describe("update check", () => { + const installed = ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + updateUrl: UPDATE_URL, + inspection: { status: "installed", version: "0.165.0" }, + }, + }); + + it("shows the reported versions and message as written, with Update instructions", async () => { + const section = mount(installed, { + status: "ready", + updateCheck: { + status: "available", + versions: ["0.168.0", "nightly (unstable)"], + message: "Restart to finish", + }, + }); + await expect.element(section.view.getByText("Update available")).toBeVisible(); + expect( + section.view.getAllByTestId("provider-updates-version").map((node) => node.textContent), + ).toEqual(["0.168.0", "nightly (unstable)"]); + await expect.element(section.view.getByText("Restart to finish")).toBeVisible(); + await expect + .element(section.view.getByRole("button", { name: "Update instructions" })) + .toBeVisible(); + }); + + const inconclusive = [ + { + name: "unknown", + updates: { status: "ready", updateCheck: { status: "unknown", message: "Offline" } }, + }, + { + name: "a thrown or timed-out check", + updates: { status: "ready", updateCheck: { status: "error", message: "Offline" } }, + }, + { name: "a failed request", updates: { status: "error", message: "Offline" } }, + ] as const; + + it.each(inconclusive)("shows $name as inconclusive, never up to date", async ({ updates }) => { + const section = mount(installed, updates); + await expect.element(section.view.getByText("Couldn't check for updates")).toBeVisible(); + await expect.element(section.view.getByText("Offline")).toBeVisible(); + expect(section.view.queryByText("Up to date")).toBeNull(); + await expect + .element(section.view.getByRole("button", { name: "Update instructions" })) + .toBeVisible(); + }); + + it.each(inconclusive)( + "still says $name when the provider offers no update", + async ({ updates }) => { + const section = mount( + ready({ + status: "ready", + installation: { inspection: { status: "installed", version: "0.165.0" } }, + }), + updates, + ); + await expect.element(section.view.getByText("Couldn't check for updates")).toBeVisible(); + expect(section.view.queryByRole("button")).toBeNull(); + }, + ); + + it("shows up to date only when the provider says so", async () => { + const section = mount(installed, { status: "ready", updateCheck: { status: "current" } }); + await expect.element(section.view.getByText("Up to date")).toBeVisible(); + }); + + it("shows the check's answer for a provider that offers no update", async () => { + const section = mount( + ready({ + status: "ready", + installation: { inspection: { status: "installed", version: "1.4.18" } }, + }), + { status: "ready", updateCheck: { status: "current" } }, + ); + await expect.element(section.view.getByText("Up to date")).toBeVisible(); + expect(section.view.queryByRole("button")).toBeNull(); + }); + + it.each([ + { name: "cannot check", updates: { status: "ready", updateCheck: null } }, + { name: "is still checking", updates: { status: "loading" } }, + ] as const)( + "shows no Updates row while a provider that offers no update $name", + ({ updates }) => { + const section = mount( + ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + inspection: { status: "installed", version: "1.0.0" }, + }, + }), + updates, + ); + expect(section.view.queryByTestId("provider-updates")).toBeNull(); + expect(section.view.getByTestId("provider-installation-version").textContent).toBe("1.0.0"); + }, + ); +}); + +describe("update action", () => { + const installed = (canUpdate: boolean) => + ready({ + status: "ready", + installation: { + updateUrl: UPDATE_URL, + inspection: { status: "installed", version: "1.0.0" }, + ...(canUpdate ? { canUpdate: true } : {}), + }, + }); + const available: ProviderUpdatesState = { + status: "ready", + updateCheck: { status: "available", versions: ["2.0.0"] }, + }; + function action(overrides: Partial = {}) { + let starts = 0; + const value: ProviderUpdateAction = { + current: null, + starting: false, + startError: null, + start: () => { + starts += 1; + }, + ...overrides, + }; + return { value, starts: () => starts }; + } + const operation = { id: "op", startedAt: "2026-11-13T00:00:00.000Z" }; + const finishedAt = "2026-11-13T00:01:00.000Z"; + + // The check only informs: Update and the update instructions never wait on it. + const checkStates = [ + { name: "an update is available", updates: available, says: "Update available" }, + // No check answer: the row shows only its title (asserted whole below). + { + name: "the provider cannot check", + updates: { status: "ready", updateCheck: null }, + says: "Updates", + }, + { name: "the check is running", updates: { status: "loading" }, says: "Checking..." }, + { + name: "the check could not tell", + updates: { status: "ready", updateCheck: { status: "unknown" } }, + says: "Couldn't check for updates", + }, + { + name: "the check failed", + updates: { status: "error", message: "Offline" }, + says: "Couldn't check for updates", + }, + { + name: "the provider is up to date", + updates: { status: "ready", updateCheck: { status: "current" } }, + says: "Up to date", + }, + ] satisfies { name: string; updates: ProviderUpdatesState; says: string }[]; + + it.each(checkStates)( + "offers Update when $name and the provider runs its own", + async ({ updates, says }) => { + const control = action(); + const section = mount(installed(true), updates, control.value); + const button = section.view.getByRole("button", { name: "Update" }); + act(() => button.click()); + expect(control.starts()).toBe(1); + expect(section.view.queryByRole("button", { name: "Update instructions" })).toBeNull(); + await expect.element(section.view.getByText(says, { exact: true })).toBeVisible(); + }, + ); + + it.each(checkStates)( + "offers Update instructions when $name and the provider only links its guide", + async ({ updates }) => { + const section = mount(installed(false), updates, action().value); + expect(section.view.queryByRole("button", { name: "Update" })).toBeNull(); + await expect + .element(section.view.getByRole("button", { name: "Update instructions" })) + .toBeVisible(); + }, + ); + + it("shows no update status beside Update when the provider cannot check", () => { + const section = mount(installed(true), { status: "ready", updateCheck: null }, action().value); + expect(section.view.getByTestId("provider-updates").textContent).toBe("UpdatesUpdate"); + }); + + it("shows a running update with its output so far", () => { + const section = mount( + installed(true), + available, + action({ + current: { + operation: { ...operation, status: "running" }, + output: [ + { type: "message", text: "Running codex update\n" }, + { type: "stdout", text: "added 1 package\n" }, + ], + }, + }).value, + ); + expect(section.view.queryByTestId("provider-update-status")).toBeNull(); + expect(section.view.getByTestId("provider-update-output").textContent).toBe( + "Running codex update\nadded 1 package\n", + ); + }); + + it("shows the provider's success message as written", () => { + const section = mount( + installed(true), + { status: "ready", updateCheck: { status: "current" } }, + action({ + current: { + operation: { + ...operation, + status: "succeeded", + finishedAt, + message: " Restart agents \n", + }, + output: [], + }, + }).value, + ); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Updated"); + expect(section.view.getByTestId("provider-update-message").textContent).toBe( + " Restart agents \n", + ); + expect(section.view.queryByTestId("provider-update-output")).toBeNull(); + }); + + it("shows a failure with its message, its output and the update instructions", async () => { + const section = mount( + installed(true), + available, + action({ + current: { + operation: { ...operation, status: "failed", finishedAt, message: "exited with code 1" }, + output: [{ type: "stderr", text: "npm error EACCES\n" }], + truncated: true, + }, + }).value, + ); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed"); + await expect.element(section.view.getByText("exited with code 1")).toBeVisible(); + expect(section.view.getByTestId("provider-update-output").textContent).toBe( + "npm error EACCES\n", + ); + await expect.element(section.view.getByText("Earlier output was dropped.")).toBeVisible(); + await expect + .element(section.view.getByRole("link", { name: "Update instructions" })) + .toBeVisible(); + await expect.element(section.view.getByRole("button", { name: "Update" })).toBeVisible(); + }); + + // Update carries the update's progress from the tap until it settles, like every in-flight + // button in Settings. The update's row shows only its output meanwhile. + describe("progress", () => { + const runningUpdate = (output: string[] = []) => ({ + operation: { ...operation, status: "running" as const }, + output: output.map((text) => ({ type: "stdout" as const, text })), + }); + function progress(section: ReturnType) { + const indicators = section.view.queryAllByRole("progressbar"); + const button = section.view.queryByTestId("provider-update-start"); + return { + count: indicators.length, + inButton: indicators.every((indicator) => button?.contains(indicator) ?? false), + label: button?.textContent, + pressable: button?.getAttribute("aria-disabled") !== "true", + }; + } + const updating = { count: 1, inButton: true, label: "Updating...", pressable: false }; + const idle = { count: 0, inButton: true, label: "Update", pressable: true }; + + it("shows progress on Update alone from tap to settle", () => { + const previous = { + operation: { ...operation, status: "failed" as const, finishedAt, message: "exit 1" }, + output: [{ type: "stderr" as const, text: "old failure\n" }], + }; + const section = mount(installed(true), available, action({ current: previous }).value); + expect(progress(section)).toEqual(idle); + + // Tapped, the host has not answered yet: the previous result gives way to the new update. + section.rerender(available, action({ current: previous, starting: true }).value); + expect(progress(section)).toEqual(updating); + expect(section.view.queryByTestId("provider-update-run")).toBeNull(); + + // Running before any output arrives. + section.rerender(available, action({ current: runningUpdate() }).value); + expect(progress(section)).toEqual(updating); + expect(section.view.queryByTestId("provider-update-run")).toBeNull(); + + section.rerender(available, action({ current: runningUpdate(["downloading\n"]) }).value); + expect(progress(section)).toEqual(updating); + expect(section.view.getByTestId("provider-update-run").textContent).toBe("downloading\n"); + + section.rerender( + { status: "ready", updateCheck: { status: "current" } }, + action({ + current: { + ...runningUpdate(["downloading\n"]), + operation: { ...operation, status: "succeeded", finishedAt }, + }, + }).value, + ); + expect(progress(section)).toEqual(idle); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Updated"); + }); + + it("shows progress on Update when the sheet reopens mid-update", () => { + const section = mount( + installed(true), + available, + action({ current: runningUpdate(["downloading\n"]) }).value, + ); + expect(progress(section)).toEqual(updating); + expect(section.view.queryByTestId("provider-update-status")).toBeNull(); + }); + + it.each([ + { name: "still loading", state: { status: "loading" } }, + { + name: "not installed", + state: { status: "ready", installation: { inspection: { status: "not_installed" } } }, + }, + { + name: "failing", + state: { + status: "ready", + installation: { inspection: { status: "error", message: "--version timed out" } }, + }, + }, + { name: "unreachable", state: { status: "error", message: "Host disconnected" } }, + ] satisfies { name: string; state: ProviderInstallationState }[])( + "shows progress on Update while the installation reads as $name", + ({ state }) => { + const section = mount( + state, + { status: "hidden" }, + action({ current: runningUpdate() }).value, + ); + // The inspection may show its own progress beside the Version row. + const button = section.view.getByRole("button", { name: "Updating..." }); + expect(button.getAttribute("aria-disabled")).toBe("true"); + expect(within(button).queryAllByRole("progressbar")).toHaveLength(1); + }, + ); + + it("returns Update to rest when the host refuses the start", () => { + const section = mount(installed(true), available, action({ starting: true }).value); + expect(progress(section)).toEqual(updating); + section.rerender(available, action({ startError: "Busy" }).value); + expect(progress(section)).toEqual(idle); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed"); + }); + }); + + it("shows why the host refused to start the update", async () => { + const section = mount( + installed(true), + available, + action({ startError: "Provider codex cannot update itself" }).value, + ); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed"); + await expect + .element(section.view.getByText("Provider codex cannot update itself")) + .toBeVisible(); + }); +}); diff --git a/packages/app/src/components/provider-installation-section.tsx b/packages/app/src/components/provider-installation-section.tsx new file mode 100644 index 000000000000..59373d9af5a1 --- /dev/null +++ b/packages/app/src/components/provider-installation-section.tsx @@ -0,0 +1,448 @@ +import { useCallback, useRef } from "react"; +import { useTranslation } from "react-i18next"; +import { ScrollView, Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import type { + ProviderInstallation, + ProviderInstallationUpdate, + ProviderInstallationUpdateCheck, +} from "@getpaseo/protocol/messages"; +import { Button } from "@/components/ui/button"; +import { ExternalLink } from "@/components/ui/external-link"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { CODE_SURFACE_DATASET } from "@/styles/code-surface"; +import { settingsStyles } from "@/styles/settings"; +import type { Theme } from "@/styles/theme"; +import { openExternalUrl } from "@/utils/open-external-url"; + +const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); +const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + +export type ProviderInstallationState = + | { status: "unsupported" } + | { status: "loading" } + | { status: "ready"; installation: ProviderInstallation | null } + | { status: "error"; message: string }; + +/** + * What the provider's update check knows. `hidden` until the provider is installed. A null + * `updateCheck` means the provider cannot check; the check only informs, and never gates Update. + */ +export type ProviderUpdatesState = + | { status: "hidden" } + | { status: "loading" } + | { status: "ready"; updateCheck: ProviderInstallationUpdateCheck | null } + | { status: "error"; message: string }; + +/** Running the provider's own update. Absent when the host cannot report updates. */ +export interface ProviderUpdateAction { + /** The provider's latest update since the host started, or null. */ + current: ProviderInstallationUpdate | null; + /** The request to start an update is in flight. */ + starting: boolean; + /** Why the host did not start the update. */ + startError: string | null; + start(): void; +} + +export function ProviderInstallationSection({ + state, + updates, + action, +}: { + state: ProviderInstallationState; + updates: ProviderUpdatesState; + action?: ProviderUpdateAction; +}) { + const { t } = useTranslation(); + if (state.status === "unsupported") return null; + if ( + state.status === "ready" && + !state.installation?.inspection && + !state.installation?.installUrl + ) + return null; + const installation = state.status === "ready" ? state.installation : null; + const run = action ? readUpdateRun(action) : null; + // A running update keeps its row, so Update shows its progress whatever the inspection reads + // meanwhile; the binary may be mid-replacement. + const updating = action ? isUpdating(action) : false; + + return ( + + + + {t("settings.providers.installation.title")} + + + + + {installation?.inspection?.status === "installed" || updating ? ( + + ) : null} + {run ? : null} + + + ); +} + +function InstallInstructionsLink({ installUrl }: { installUrl: string }) { + const { t } = useTranslation(); + return ( + + ); +} + +function InstallationRow({ state }: { state: ProviderInstallationState }) { + const { t } = useTranslation(); + const installation = state.status === "ready" ? state.installation : null; + const installUrl = installation?.installUrl; + const handleInstall = useCallback(() => { + if (installUrl) void openExternalUrl(installUrl); + }, [installUrl]); + + if (state.status === "loading") { + return ( + + {t("settings.providers.installation.version")} + + + {t("settings.providers.installation.checking")} + + + ); + } + const inspection = installation?.inspection; + if (inspection?.status === "not_installed") { + return ( + + + {t("settings.providers.installation.notInstalled")} + + {installUrl ? ( + + ) : null} + + ); + } + if (inspection?.status === "installed") { + return ( + + {t("settings.providers.installation.version")} + {inspection.version ? ( + + {inspection.version} + + ) : ( + {t("settings.providers.installation.installed")} + )} + + ); + } + // The installed state is unknown: the check failed, or the provider only links to a guide. + let message: string | null = null; + if (state.status === "error") message = state.message; + else if (inspection?.status === "error") message = inspection.message; + if (!message) { + return installUrl ? ( + + + + ) : null; + } + return ( + + + {t("settings.providers.installation.failed")} + {message} + {installUrl ? ( + + + + ) : null} + + + ); +} + +/** + * The update the provider offers, with what its check knows beside it. Update, or the update + * instructions, stay in place whatever the check says: an answer can be an hour old, and the + * provider's own updater reports when there is nothing newer. + */ +function UpdatesRow({ + updates, + updateUrl, + action, +}: { + updates: ProviderUpdatesState; + updateUrl: string | undefined; + /** Present when the provider runs its own update. */ + action: ProviderUpdateAction | undefined; +}) { + const { t } = useTranslation(); + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + const offersUpdate = Boolean(action || updateUrl); + // With nothing to offer, the row waits until the check has something to say. + if (!offersUpdate && !updateCheck && updates.status !== "error") return null; + + return ( + + + + {updateCheck?.status === "available" + ? t("settings.providers.installation.updateAvailable") + : t("settings.providers.installation.updates")} + + + + + + ); +} + +function UpdateCheckSummary({ updates }: { updates: ProviderUpdatesState }) { + const { t } = useTranslation(); + if (updates.status === "loading") { + return ( + + + {t("settings.providers.installation.checking")} + + ); + } + if (updates.status === "hidden") return null; + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + if (updates.status === "ready" && !updateCheck) return null; + if (updateCheck?.status === "current") { + return ( + + {t("settings.providers.installation.upToDate")} + + ); + } + if (updateCheck?.status === "available") { + // Versions are opaque; drop repeats so each one keys its own line. + const versions = [...new Set(updateCheck.versions ?? [])]; + return ( + <> + {versions.map((version) => ( + + {version} + + ))} + {updateCheck.message ? ( + {updateCheck.message} + ) : null} + + ); + } + // A check that threw, timed out or could not tell is never shown as up to date. + const message = updates.status === "error" ? updates.message : updateCheck?.message; + return ( + <> + + {t("settings.providers.installation.updatesFailed")} + + {message ? {message} : null} + + ); +} + +function isUpdating(action: ProviderUpdateAction): boolean { + return action.starting || action.current?.operation.status === "running"; +} + +/** + * Update runs the provider's updater; without one, the provider's update guide opens. The button + * carries the update's progress from the tap until it settles. + */ +function UpdateButton({ + action, + updateUrl, +}: { + action: ProviderUpdateAction | undefined; + updateUrl: string | undefined; +}) { + const { t } = useTranslation(); + const handleOpenInstructions = useCallback(() => { + if (updateUrl) void openExternalUrl(updateUrl); + }, [updateUrl]); + if (action) + return ( + + ); + if (!updateUrl) return null; + return ( + + ); +} + +type UpdateRun = + | { status: "running"; update: ProviderInstallationUpdate } + | { status: "succeeded" | "failed"; update: ProviderInstallationUpdate } + | { status: "refused"; message: string }; + +/** + * What the update's row shows, or null for nothing. While the update starts or runs, Update shows + * its progress and the row holds only the output so far. A new start clears the previous result. + */ +function readUpdateRun(action: ProviderUpdateAction): UpdateRun | null { + const update = action.current; + if (isUpdating(action)) { + return update?.operation.status === "running" && update.output.length > 0 + ? { status: "running", update } + : null; + } + if (action.startError) return { status: "refused", message: action.startError }; + if (!update || update.operation.status === "running") return null; + return { status: update.operation.status, update }; +} + +function UpdateRunRow({ run, updateUrl }: { run: UpdateRun; updateUrl: string | undefined }) { + const { t } = useTranslation(); + const scroll = useRef(null); + const followOutput = useCallback(() => scroll.current?.scrollToEnd({ animated: false }), []); + const update = run.status === "refused" ? null : run.update; + const output = update?.output.map((entry) => entry.text).join("") ?? ""; + let message: string | undefined; + if (run.status === "refused") message = run.message; + else if (run.update.operation.status !== "running") message = run.update.operation.message; + + return ( + + + {run.status === "running" ? null : ( + + {run.status === "succeeded" + ? t("settings.providers.installation.updated") + : t("settings.providers.installation.updateFailed")} + + )} + {message ? ( + + {message} + + ) : null} + {output ? ( + + {update?.truncated ? ( + + {t("settings.providers.installation.outputTruncated")} + + ) : null} + + {output} + + + ) : null} + {(run.status === "failed" || run.status === "refused") && updateUrl ? ( + + + + ) : null} + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + output: { + maxHeight: 240, + borderRadius: theme.borderRadius.md, + backgroundColor: theme.colors.surface0, + }, + outputAfterResult: { + marginTop: theme.spacing[2], + }, + outputContent: { + padding: theme.spacing[3], + }, + outputText: { + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + lineHeight: 20, + color: theme.colors.foreground, + }, + outputNote: { + marginBottom: theme.spacing[1], + fontSize: theme.fontSize.sm, + color: theme.colors.foregroundMuted, + }, + trailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + value: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, + version: { + flexShrink: 1, + marginLeft: theme.spacing[3], + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + color: theme.colors.foregroundMuted, + }, + availableVersion: { + marginTop: theme.spacing[1], + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + color: theme.colors.foregroundMuted, + }, + link: { + flexDirection: "row", + marginTop: theme.spacing[1], + }, +})); diff --git a/packages/app/src/components/provider-installation.tsx b/packages/app/src/components/provider-installation.tsx new file mode 100644 index 000000000000..957301a7d24d --- /dev/null +++ b/packages/app/src/components/provider-installation.tsx @@ -0,0 +1,195 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useCallback, useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import type { ProviderInstallationUpdate } from "@getpaseo/protocol/messages"; +import { useFetchQuery } from "@/data/query"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import type { + ProviderInstallationState, + ProviderUpdateAction, + ProviderUpdatesState, +} from "./provider-installation-section"; +import { applyProviderUpdateProgress } from "./provider-update-progress"; + +export interface ProviderInstallationRead { + state: ProviderInstallationState; + updates: ProviderUpdatesState; + /** Absent when the host cannot report provider installations. */ + action: ProviderUpdateAction | undefined; + /** Ask the provider again, skipping the host's caches. */ + refresh: () => void; + /** A refresh is in flight. The last answers stay on screen until the new ones arrive. */ + refreshing: boolean; +} + +/** + * Reads a provider's installation from hosts that advertise `providerInstallation`. The update + * check is a separate request that starts once the provider reports itself installed, so the + * installed version never waits on it. + */ +export function useProviderInstallation(input: { + serverId: string; + provider: string; + visible: boolean; +}): ProviderInstallationRead { + const { serverId, provider, visible } = input; + const supported = useHostFeature(serverId, "providerInstallation"); + const client = useHostRuntimeClient(serverId); + const queryClient = useQueryClient(); + const { t } = useTranslation(); + const enabled = supported && visible && Boolean(client); + const installationKey = ["provider-installation", serverId, provider] as const; + const updatesKey = ["provider-updates", serverId, provider] as const; + + const inspect = useCallback( + async (refresh: boolean) => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + const result = await client.inspectProviderInstallation(provider, { refresh }); + if (result.error) throw new Error(result.error); + return result.installation; + }, + [client, provider, t], + ); + const checkForUpdates = useCallback( + async (refresh: boolean) => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + const result = await client.checkProviderUpdates(provider, { refresh }); + if (result.error) throw new Error(result.error); + return result.updateCheck; + }, + [client, provider, t], + ); + + // The host caches both answers, so reading on every open is cheap. + const installationQuery = useFetchQuery({ + queryKey: installationKey, + queryFn: () => inspect(false), + enabled, + dataShape: "value", + staleTimeMs: 0, + }); + const installed = installationQuery.data?.inspection?.status === "installed"; + const updatesQuery = useFetchQuery({ + queryKey: updatesKey, + queryFn: () => checkForUpdates(false), + enabled: enabled && installed, + dataShape: "value", + staleTimeMs: 0, + }); + + // A refresh runs through the queries so its answer or its failure is what the screen shows. + // `staleTime: 0` overrides the app default so the request always goes out. + const refreshInstallation = useMutation({ + mutationFn: () => + queryClient.fetchQuery({ + queryKey: installationKey, + queryFn: () => inspect(true), + staleTime: 0, + }), + }); + const refreshUpdates = useMutation({ + mutationFn: () => + queryClient.fetchQuery({ + queryKey: updatesKey, + queryFn: () => checkForUpdates(true), + staleTime: 0, + }), + }); + // The host owns the update; this view follows it while open and catches up on reopen. + const [currentUpdate, setCurrentUpdate] = useState(null); + useEffect(() => { + if (!enabled || !client) return; + const subscription = client.observeProviderUpdates(provider); + // The update this view saw running. Its success arrives as live progress, or as the snapshot + // a reconnect delivers when the progress was missed; either way the host dropped its cached + // answers, so read the new version and update state. + let runningId: string | null = null; + const follow = (operation: ProviderInstallationUpdate["operation"] | undefined) => { + if (!operation) return; + if (operation.status === "running") { + runningId = operation.id; + return; + } + if (operation.id !== runningId) return; + runningId = null; + if (operation.status !== "succeeded") return; + void queryClient.invalidateQueries({ + queryKey: ["provider-installation", serverId, provider], + }); + void queryClient.invalidateQueries({ queryKey: ["provider-updates", serverId, provider] }); + }; + const detach = subscription.subscribe({ + snapshot: (response) => { + setCurrentUpdate(response.update); + follow(response.update?.operation); + }, + update: (message) => { + if (message.type === "provider.installation.update.cleared") { + const { operationId } = message.payload; + setCurrentUpdate((current) => (current?.operation.id === operationId ? null : current)); + return; + } + if (message.type !== "provider.installation.update.progress") return; + setCurrentUpdate((current) => applyProviderUpdateProgress(current, message.payload)); + follow(message.payload.operation); + }, + error: (failure) => console.warn("Failed to observe provider updates", failure), + }); + return () => { + detach(); + void subscription + .release() + .catch((failure) => console.warn("Failed to release provider update observation", failure)); + }; + }, [client, enabled, provider, queryClient, serverId]); + const startUpdate = useMutation({ + mutationFn: async () => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + const result = await client.updateProvider(provider); + if (result.error) throw new Error(result.error); + return result.update; + }, + onSuccess: (update) => { + if (!update) return; + // Progress for this operation may already have arrived; keep the further-along copy. + setCurrentUpdate((current) => + current?.operation.id === update.operation.id ? current : update, + ); + }, + }); + const { mutate: mutateStartUpdate } = startUpdate; + const start = useCallback(() => mutateStartUpdate(), [mutateStartUpdate]); + const action: ProviderUpdateAction | undefined = supported + ? { + current: currentUpdate, + starting: startUpdate.isPending, + startError: startUpdate.error?.message ?? null, + start, + } + : undefined; + + const { mutate: mutateInstallation } = refreshInstallation; + const { mutate: mutateUpdates } = refreshUpdates; + const refresh = useCallback(() => { + if (!supported || !client) return; + mutateInstallation(); + if (installed) mutateUpdates(); + }, [client, installed, mutateInstallation, mutateUpdates, supported]); + + let state: ProviderInstallationState; + if (!supported) state = { status: "unsupported" }; + else if (installationQuery.isPending) state = { status: "loading" }; + else if (installationQuery.isError) + state = { status: "error", message: installationQuery.error.message }; + else state = { status: "ready", installation: installationQuery.data ?? null }; + + let updates: ProviderUpdatesState; + if (!supported || !installed) updates = { status: "hidden" }; + else if (updatesQuery.isPending) updates = { status: "loading" }; + else if (updatesQuery.isError) updates = { status: "error", message: updatesQuery.error.message }; + else updates = { status: "ready", updateCheck: updatesQuery.data ?? null }; + + const refreshing = refreshInstallation.isPending || refreshUpdates.isPending; + return { state, updates, action, refresh, refreshing }; +} diff --git a/packages/app/src/components/provider-settings-host.tsx b/packages/app/src/components/provider-settings-host.tsx index f6ff75c74e0a..c717a2705cd5 100644 --- a/packages/app/src/components/provider-settings-host.tsx +++ b/packages/app/src/components/provider-settings-host.tsx @@ -1,5 +1,5 @@ import { useCallback } from "react"; -import { ProviderDiagnosticSheet } from "@/components/provider-diagnostic-sheet"; +import { ProviderDetailSheet } from "@/provider-settings"; import { OverlayLayerProvider } from "@/lib/overlay-root"; import { useProviderSettingsStore } from "@/stores/provider-settings-store"; @@ -20,7 +20,7 @@ export function ProviderSettingsHost() { return ( - ({ type: "stdout", text })), + }; +} + +describe("applyProviderUpdateProgress", () => { + it("appends output for the same update", () => { + const first = applyProviderUpdateProgress(null, progress("a"), { outputLimit: 10 }); + const second = applyProviderUpdateProgress(first, progress("b"), { outputLimit: 10 }); + expect(second.output.map((entry) => entry.text)).toEqual(["a", "b"]); + expect(second.truncated).toBeUndefined(); + }); + + it("drops the oldest output beyond the limit and marks the update truncated", () => { + let update = applyProviderUpdateProgress(null, progress("12345"), { outputLimit: 8 }); + update = applyProviderUpdateProgress(update, progress("6789"), { outputLimit: 8 }); + expect(update.output.map((entry) => entry.text)).toEqual(["6789"]); + expect(update.truncated).toBe(true); + + update = applyProviderUpdateProgress(update, progress("abcdefghij"), { outputLimit: 8 }); + expect(update.output.map((entry) => entry.text)).toEqual(["cdefghij"]); + expect(update.truncated).toBe(true); + }); + + it("starts a new update empty", () => { + const first = applyProviderUpdateProgress(null, progress("123456789"), { outputLimit: 4 }); + const next = applyProviderUpdateProgress( + first, + { ...progress("x"), operation: { ...running, id: "update-2" } }, + { outputLimit: 4 }, + ); + expect(next.output.map((entry) => entry.text)).toEqual(["x"]); + expect(next.truncated).toBeUndefined(); + }); +}); diff --git a/packages/app/src/components/provider-update-progress.ts b/packages/app/src/components/provider-update-progress.ts new file mode 100644 index 000000000000..ad72471d4ccc --- /dev/null +++ b/packages/app/src/components/provider-update-progress.ts @@ -0,0 +1,38 @@ +import type { + ProviderInstallationUpdate, + ProviderInstallationUpdateOutput, + ProviderInstallationUpdateProgress, +} from "@getpaseo/protocol/messages"; + +/** Characters of update output the app keeps, matching what the daemon retains. */ +export const PROVIDER_UPDATE_OUTPUT_LIMIT = 64 * 1024; + +/** + * Folds a progress message into the update it belongs to; a new operation starts empty. Output + * beyond `outputLimit` characters drops oldest first and marks the update truncated, so a noisy + * updater cannot grow the screen's memory while it stays open. + */ +export function applyProviderUpdateProgress( + current: ProviderInstallationUpdate | null, + progress: ProviderInstallationUpdateProgress, + options: { outputLimit: number } = { outputLimit: PROVIDER_UPDATE_OUTPUT_LIMIT }, +): ProviderInstallationUpdate { + const previous = current?.operation.id === progress.operation.id ? current : null; + const limit = options.outputLimit; + const output: ProviderInstallationUpdateOutput[] = [ + ...(previous?.output ?? []), + ...progress.output, + ]; + let length = output.reduce((total, entry) => total + entry.text.length, 0); + let truncated = previous?.truncated ?? false; + while (length > limit && output.length > 1) { + length -= output.shift()!.text.length; + truncated = true; + } + const last = output.at(-1); + if (last && last.text.length > limit) { + output[output.length - 1] = { type: last.type, text: last.text.slice(-limit) }; + truncated = true; + } + return { operation: progress.operation, output, ...(truncated ? { truncated: true } : {}) }; +} diff --git a/packages/app/src/components/settings/add-row.tsx b/packages/app/src/components/settings/add-row.tsx new file mode 100644 index 000000000000..41bf0d11b934 --- /dev/null +++ b/packages/app/src/components/settings/add-row.tsx @@ -0,0 +1,60 @@ +import { Plus } from "lucide-react-native"; +import { useCallback } from "react"; +import { Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { mutedIconColorMapping } from "@/components/ui/icon-color"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { ICON_SIZE } from "@/styles/theme"; +import { useSettingsRowLayout } from "./row-density"; + +const ThemedPlus = withUnistyles(Plus); + +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +/** + * The last row of a card that lists things, adding one more. Quiet, so the list reads first: a + * muted plus in the rows' leading slot and a muted label on the labels' rail. + */ +export function SettingsAddRow({ + label, + onPress, + testID, +}: { + label: string; + onPress: () => void; + testID?: string; +}) { + const layout = useSettingsRowLayout(); + const rowStyle = useCallback( + ({ hovered, pressed }: HoverState) => [ + layout.row, + styles.row, + hovered && styles.hovered, + pressed && styles.pressed, + ], + [layout], + ); + return ( + + + + + {label} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + row: { justifyContent: "flex-start" }, + leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" }, + label: { color: theme.colors.foregroundMuted }, + hovered: { backgroundColor: theme.colors.surface2 }, + pressed: { backgroundColor: theme.colors.surface3 }, +})); diff --git a/packages/app/src/components/settings/detail-header.tsx b/packages/app/src/components/settings/detail-header.tsx new file mode 100644 index 000000000000..47508ad77f8d --- /dev/null +++ b/packages/app/src/components/settings/detail-header.tsx @@ -0,0 +1,97 @@ +import { ArrowLeft } from "lucide-react-native"; +import type { ReactNode } from "react"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { PageTitle, type PageTitleParent } from "@/components/page-layout"; +import { Button } from "@/components/ui/button"; +import { useIsCompactFormFactor } from "@/constants/layout"; + +/** + * "Back to …" above a settings detail page on wide layouts, where the page has no header of its + * own. The ghost button drops its padding so the arrow sits on the content's leading rail. + */ +export function SettingsBackLink({ + label, + onPress, + testID, +}: { + label: string; + onPress: () => void; + testID?: string; +}) { + return ( + + ); +} + +/** + * The top of a settings detail page: the icon and name of the thing the page is about, with an + * optional action after the name. On wide layouts it is the page's title and names the parent page + * first, which goes back to it. On compact layouts the back header already names the parent. + */ +export function SettingsDetailHeader({ + parent, + icon, + title, + trailing, + titleTestID, +}: { + parent: PageTitleParent; + icon?: ReactNode; + /** Absent while the page has nothing to name, such as a project that no longer exists. */ + title?: string; + trailing?: ReactNode; + titleTestID?: string; +}) { + const isCompact = useIsCompactFormFactor(); + if (!isCompact) + return ( + + ); + if (title === undefined) return null; + return ( + + {icon} + + {title} + + {trailing} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + backLink: { + alignSelf: "flex-start", + paddingHorizontal: 0, + }, + titleRow: { + // Line up with the section titles, which sit inset from their cards. + marginLeft: theme.spacing[1], + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[4], + }, + title: { + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + fontWeight: theme.fontWeight.medium, + flexShrink: 1, + }, +})); diff --git a/packages/app/src/components/settings/detail-row.tsx b/packages/app/src/components/settings/detail-row.tsx index 0838d06ca4f5..a1d96c79b630 100644 --- a/packages/app/src/components/settings/detail-row.tsx +++ b/packages/app/src/components/settings/detail-row.tsx @@ -1,12 +1,16 @@ import type { ReactNode } from "react"; -import { SettingsRowHeader } from "./row-header"; +import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header"; interface SettingsDetailRowProps { label: string; + /** An icon before the label, such as the thing the row opens. */ + leading?: ReactNode; /** Shown beside the label, such as a badge. */ labelAccessory?: ReactNode; /** A line under the label saying what the row leads to. */ hint?: string; + /** Marks the hint as work under way, a fault, or a value still loading. */ + hintStatus?: SettingsRowHintStatus; /** What the detail is set to, so the row says it without being opened. */ summary?: string; onPress: () => void; @@ -14,6 +18,10 @@ interface SettingsDetailRowProps { disabled?: boolean; /** Opens a page outside the app; an outward arrow replaces the chevron. */ external?: boolean; + /** A control acting on the row's subject in place, such as a switch, before the chevron. */ + control?: ReactNode; + /** Names the row for assistive tech when the label alone does not say where it leads. */ + accessibilityLabel?: string; testID?: string; } diff --git a/packages/app/src/components/settings/headings/heading-trailing.tsx b/packages/app/src/components/settings/headings/heading-trailing.tsx new file mode 100644 index 000000000000..20654b750b51 --- /dev/null +++ b/packages/app/src/components/settings/headings/heading-trailing.tsx @@ -0,0 +1,22 @@ +import type { ReactNode } from "react"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; + +/** + * The action at a heading's end. It adds no height, so a heading with a button is as tall as one + * without and both sit the same distance from their cards. The button stays centered on the title + * and its hit area grows past the heading. + */ +export function HeadingTrailing({ children }: { children: ReactNode }) { + if (children === null || children === undefined || children === false) return null; + return {children}; +} + +const styles = StyleSheet.create({ + trailing: { + height: 0, + justifyContent: "center", + // A long trailing gives way to the title. + flexShrink: 1, + }, +}); diff --git a/packages/app/src/components/settings/headings/settings-group.tsx b/packages/app/src/components/settings/headings/settings-group.tsx index e13bc6017ab5..a9018d23684e 100644 --- a/packages/app/src/components/settings/headings/settings-group.tsx +++ b/packages/app/src/components/settings/headings/settings-group.tsx @@ -1,6 +1,7 @@ import { useMemo, type ReactNode } from "react"; import { Text, View, type StyleProp, type ViewStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; +import { HeadingTrailing } from "./heading-trailing"; import { SettingsInfoTip } from "./settings-info-tip"; interface SettingsGroupProps { @@ -40,7 +41,7 @@ export function SettingsGroup({ /> ) : null} - {trailing} + {trailing} {children} diff --git a/packages/app/src/components/settings/headings/settings-section.tsx b/packages/app/src/components/settings/headings/settings-section.tsx index d651a4782591..f393a5042373 100644 --- a/packages/app/src/components/settings/headings/settings-section.tsx +++ b/packages/app/src/components/settings/headings/settings-section.tsx @@ -3,6 +3,7 @@ import { useMemo, type ReactNode } from "react"; import { View, type StyleProp, type ViewStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link"; +import { HeadingTrailing } from "./heading-trailing"; import { SettingsInfoTip } from "./settings-info-tip"; import { settingsStyles } from "@/styles/settings"; @@ -67,7 +68,7 @@ export function SettingsSection({ ) : null} - {trailing} + {trailing} {children} diff --git a/packages/app/src/components/settings/index.tsx b/packages/app/src/components/settings/index.tsx index 567becfd01f5..f8153b0ff270 100644 --- a/packages/app/src/components/settings/index.tsx +++ b/packages/app/src/components/settings/index.tsx @@ -30,12 +30,17 @@ export { SettingsGroup } from "./headings/settings-group"; export { SettingsSection } from "./headings/settings-section"; export { SettingsCollapsibleRow } from "./collapsible-row"; export { SettingsDetailRow } from "./detail-row"; +export type { SettingsRowHintStatus } from "./row-header"; +export { SettingsAddRow } from "./add-row"; +export { SettingsBackLink, SettingsDetailHeader } from "./detail-header"; export { SettingsInfoTip } from "./headings/settings-info-tip"; export { MenuSettingsRows } from "./row-density"; /** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */ interface AppRowExtras { labelAccessory?: ReactNode; + /** An icon before the label, such as the thing the row is about. */ + leading?: ReactNode; } interface AppSettingsRowProps extends Omit, AppRowExtras { @@ -59,6 +64,7 @@ export function SettingsCard({ children, testID }: { children: ReactNode; testID export function SettingsRow({ label, + leading, labelAccessory, hint, error, @@ -71,6 +77,7 @@ export function SettingsRow({ const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]); return ( + {leading ? {leading} : null} {labelAccessory ? ( @@ -208,7 +215,11 @@ export function SettingsAction({ actionLabel, onPress, disabled, ...row }: Setti } const styles = StyleSheet.create((theme) => ({ - compactRow: { flexWrap: "wrap", gap: theme.spacing[3] }, + // A control that wraps under the label gets space above it. Across the row, the leading slot and + // the label already carry their own margins, so a column gap would double them. + compactRow: { flexWrap: "wrap", rowGap: theme.spacing[3] }, + // The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds. + leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" }, label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] }, labelRow: { flexDirection: "row", diff --git a/packages/app/src/components/settings/row-density.browser.test.tsx b/packages/app/src/components/settings/row-density.browser.test.tsx index d2742e31722b..cbe24e0a6064 100644 --- a/packages/app/src/components/settings/row-density.browser.test.tsx +++ b/packages/app/src/components/settings/row-density.browser.test.tsx @@ -2,7 +2,13 @@ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, describe, expect, it } from "vitest"; import { Button } from "@/components/ui/button"; -import { SettingsCard, SettingsCollapsibleRow, SettingsRow } from "@/components/settings"; +import { + SettingsCard, + SettingsCollapsibleRow, + SettingsDetailRow, + SettingsRow, + SettingsSwitch, +} from "@/components/settings"; let root: Root | null = null; let container: HTMLDivElement | null = null; @@ -14,6 +20,9 @@ afterEach(() => { container = null; }); +function openNothing() {} +function toggleNothing() {} + function mountRows() { container = document.createElement("div"); document.body.appendChild(container); @@ -26,6 +35,14 @@ function mountRows() { Download + + + + + + ); if (loading) return ( @@ -542,7 +546,7 @@ function PluginPageBody({ } const styles = StyleSheet.create((theme) => ({ - back: { alignSelf: "flex-start", paddingHorizontal: 0, marginBottom: theme.spacing[4] }, + back: { marginBottom: theme.spacing[4] }, header: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/plugins/host-navigation-model.ts b/packages/app/src/plugins/host-navigation-model.ts index f651370a9d62..d6700ccf2c37 100644 --- a/packages/app/src/plugins/host-navigation-model.ts +++ b/packages/app/src/plugins/host-navigation-model.ts @@ -1,24 +1,39 @@ import type { PluginSurfaceProps } from "@getpaseo/plugin/client"; import type { NavigateToWorkspaceInput } from "@/stores/navigation-active-workspace-store"; +import { parseServerIdFromPathname } from "@/utils/host-routes"; import { isHttpUrl } from "@/utils/http-url"; interface HostNavigationOwner { browserAvailable: boolean; - openAgent(input: { serverId: string; agentId: string }): void; - openWorkspace(input: NavigateToWorkspaceInput): void; + isHostRegistered(serverId: string): boolean; + openAgent(input: { serverId: string; agentId: string }): string; + openWorkspace(input: NavigateToWorkspaceInput): string; resolveWorkspace(input: { serverId: string; workspaceId: string }): string | null; createBrowser(input: { initialUrl: string }): { browserId: string }; + focusHost(serverId: string): void; } export function createPluginHostNavigation( serverId: string, owner: HostNavigationOwner, ): NonNullable { + const focusRouteHost = (route: string) => { + const destinationServerId = parseServerIdFromPathname(route); + if (destinationServerId && owner.isHostRegistered(destinationServerId)) { + owner.focusHost(destinationServerId); + } + }; + return { - openAgent: ({ agentId, serverId: targetServerId }) => - owner.openAgent({ serverId: targetServerId ?? serverId, agentId }), - openWorkspace: ({ workspaceId, serverId: targetServerId }) => - owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId }), + supportsFocusHost: true, + openAgent: ({ agentId, serverId: targetServerId, focusHost }) => { + const route = owner.openAgent({ serverId: targetServerId ?? serverId, agentId }); + if (focusHost) focusRouteHost(route); + }, + openWorkspace: ({ workspaceId, serverId: targetServerId, focusHost }) => { + const route = owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId }); + if (focusHost) focusRouteHost(route); + }, openBrowser: owner.browserAvailable ? ({ url, workspaceId, serverId: targetServerId }) => { if (!isHttpUrl(url)) throw new Error("Only absolute HTTP(S) URLs are supported."); diff --git a/packages/app/src/plugins/host-navigation.test.ts b/packages/app/src/plugins/host-navigation.test.ts index 22538b39763c..4da0e62df502 100644 --- a/packages/app/src/plugins/host-navigation.test.ts +++ b/packages/app/src/plugins/host-navigation.test.ts @@ -1,25 +1,58 @@ import { describe, expect, it } from "vitest"; +import { buildHostAgentDetailRoute, buildHostWorkspaceRoute } from "@/utils/host-routes"; import { createPluginHostNavigation } from "./host-navigation-model"; +import { useSidebarViewStore } from "../stores/sidebar-view-store"; describe("plugin host navigation", () => { function setup(electron = true) { const destinations: unknown[] = []; const browsers: string[] = []; + const focusedHosts: string[] = []; const workspaces = new Set(["selected:one", "remote:two"]); const navigation = createPluginHostNavigation("selected", { browserAvailable: electron, + isHostRegistered: (serverId: string) => serverId === "selected" || serverId === "remote", resolveWorkspace: ({ serverId, workspaceId }) => workspaces.has(`${serverId}:${workspaceId}`) ? workspaceId : null, - openAgent: (input) => destinations.push(input), - openWorkspace: (input) => destinations.push(input), + openAgent: (input) => { + destinations.push(input); + return buildHostAgentDetailRoute(input.serverId, input.agentId); + }, + openWorkspace: (input) => { + destinations.push(input); + return buildHostWorkspaceRoute(input.serverId, input.workspaceId); + }, + focusHost: (serverId) => { + focusedHosts.push(serverId); + useSidebarViewStore.getState().focusHost(serverId); + }, createBrowser: ({ initialUrl }) => { browsers.push(initialUrl); return { browserId: `browser-${browsers.length}` }; }, }); - return { navigation, destinations, browsers, workspaces }; + return { navigation, destinations, browsers, workspaces, focusedHosts }; } + it("focuses the destination host and clears filters that could hide its workspace", () => { + useSidebarViewStore.setState({ + groupMode: "status", + hostFilters: ["selected", "other"], + projectFilters: ["old-project"], + labelFilter: { labels: ["urgent"] }, + }); + const { navigation, destinations, focusedHosts } = setup(false); + navigation.openAgent({ serverId: "remote", agentId: "agent-2", focusHost: true }); + expect(focusedHosts).toEqual(["remote"]); + expect(destinations).toEqual([{ serverId: "remote", agentId: "agent-2" }]); + expect(useSidebarViewStore.getState()).toMatchObject({ + groupMode: "status", + hostFilters: ["remote"], + projectFilters: [], + labelFilter: { labels: [] }, + }); + }); + it("creates and focuses a local browser in the selected or explicit host workspace", () => { const { navigation, destinations, browsers } = setup(); navigation.openBrowser!({ url: "https://example.com/one", workspaceId: "one" }); @@ -43,6 +76,110 @@ describe("plugin host navigation", () => { ]); }); + it("can return from a remote workspace to the installation host without toggling it off", () => { + const { navigation, destinations, focusedHosts } = setup(); + navigation.openWorkspace({ serverId: "remote", workspaceId: "two", focusHost: true }); + navigation.openWorkspace({ workspaceId: "one", focusHost: true }); + navigation.openWorkspace({ workspaceId: "one", focusHost: true }); + expect(focusedHosts).toEqual(["remote", "selected", "selected"]); + expect(destinations).toEqual([ + { serverId: "remote", workspaceId: "two" }, + { serverId: "selected", workspaceId: "one" }, + { serverId: "selected", workspaceId: "one" }, + ]); + expect(useSidebarViewStore.getState().hostFilters).toEqual(["selected"]); + }); + + it("focuses the host in the returned route for padded host IDs", () => { + const { navigation, destinations, focusedHosts } = setup(); + navigation.openAgent({ serverId: " remote ", agentId: "agent-2", focusHost: true }); + navigation.openWorkspace({ serverId: " selected ", workspaceId: "one", focusHost: true }); + + expect(destinations).toEqual([ + { serverId: " remote ", agentId: "agent-2" }, + { serverId: " selected ", workspaceId: "one" }, + ]); + expect(focusedHosts).toEqual(["remote", "selected"]); + expect(useSidebarViewStore.getState().hostFilters).toEqual(["selected"]); + }); + + it("leaves existing sidebar filters alone unless explicitly requested", () => { + useSidebarViewStore.setState({ + hostFilters: ["remote"], + projectFilters: ["pinned-project"], + labelFilter: { labels: ["urgent"] }, + }); + const { navigation, destinations, focusedHosts } = setup(); + navigation.openAgent({ agentId: "agent-1", serverId: " remote " }); + navigation.openWorkspace({ workspaceId: "one", serverId: " selected ", focusHost: false }); + expect(destinations).toEqual([ + { serverId: " remote ", agentId: "agent-1" }, + { serverId: " selected ", workspaceId: "one" }, + ]); + expect(focusedHosts).toEqual([]); + expect(useSidebarViewStore.getState()).toMatchObject({ + hostFilters: ["remote"], + projectFilters: ["pinned-project"], + labelFilter: { labels: ["urgent"] }, + }); + expect(navigation.supportsFocusHost).toBe(true); + }); + + it("preserves sidebar filters when the navigation route has no destination", () => { + const filters = { + hostFilters: ["selected"], + projectFilters: ["pinned-project"], + labelFilter: { labels: ["urgent"] }, + }; + useSidebarViewStore.setState(filters); + const { navigation } = setup(); + navigation.openAgent({ serverId: "remote", agentId: " ", focusHost: true }); + navigation.openWorkspace({ serverId: "remote", workspaceId: "", focusHost: true }); + + expect(useSidebarViewStore.getState()).toMatchObject(filters); + }); + + it("preserves sidebar filters when the destination host has been removed", () => { + const filters = { + hostFilters: ["selected"], + projectFilters: ["pinned-project"], + labelFilter: { labels: ["urgent"] }, + }; + useSidebarViewStore.setState(filters); + const { navigation, destinations } = setup(); + navigation.openAgent({ serverId: "removed", agentId: "agent-2", focusHost: true }); + navigation.openWorkspace({ serverId: "removed", workspaceId: "two", focusHost: true }); + + expect(useSidebarViewStore.getState()).toMatchObject(filters); + expect(destinations).toEqual([ + { serverId: "removed", agentId: "agent-2" }, + { serverId: "removed", workspaceId: "two" }, + ]); + }); + + it("does not change the filter when navigation rejects the target", () => { + const focusedHosts: string[] = []; + const unavailable = () => { + throw new Error("Target unavailable"); + }; + const navigation = createPluginHostNavigation("selected", { + browserAvailable: false, + isHostRegistered: () => true, + resolveWorkspace: () => null, + openAgent: unavailable, + openWorkspace: unavailable, + createBrowser: unavailable, + focusHost: (serverId) => focusedHosts.push(serverId), + }); + expect(() => navigation.openAgent({ agentId: "missing", focusHost: true })).toThrow( + "Target unavailable", + ); + expect(() => navigation.openWorkspace({ workspaceId: "missing", focusHost: true })).toThrow( + "Target unavailable", + ); + expect(focusedHosts).toEqual([]); + }); + it("refuses unknown or removed workspaces before creating browser records", () => { const { navigation, destinations, browsers, workspaces } = setup(); expect(() => diff --git a/packages/app/src/plugins/host-navigation.ts b/packages/app/src/plugins/host-navigation.ts index 5f30f014aa47..36049f4499b4 100644 --- a/packages/app/src/plugins/host-navigation.ts +++ b/packages/app/src/plugins/host-navigation.ts @@ -4,10 +4,12 @@ import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity"; import { useMemo } from "react"; import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store"; import { navigateToAgent } from "@/utils/navigate-to-agent"; +import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { getIsElectron } from "@/constants/platform"; import { createWorkspaceBrowser } from "@/desktop/browser/store"; import { createPluginHostNavigation } from "./host-navigation-model"; +import { useSidebarViewStore } from "@/stores/sidebar-view-store"; export function usePluginHostNavigation( serverId: string, @@ -16,9 +18,14 @@ export function usePluginHostNavigation( () => createPluginHostNavigation(serverId, { browserAvailable: getIsElectron(), + isHostRegistered: (targetServerId) => + getHostRuntimeStore() + .getHosts() + .some((host) => host.serverId === targetServerId), openAgent: navigateToAgent, openWorkspace: navigateToWorkspace, createBrowser: createWorkspaceBrowser, + focusHost: (targetServerId) => useSidebarViewStore.getState().focusHost(targetServerId), resolveWorkspace: ({ serverId: targetServerId, workspaceId }) => resolveWorkspaceMapKeyByIdentity({ workspaces: useSessionStore.getState().sessions[targetServerId]?.workspaces, diff --git a/packages/app/src/provider-selection/provider-selection.test.ts b/packages/app/src/provider-selection/provider-selection.test.ts index 58032b8615c0..56cb2a8acaa9 100644 --- a/packages/app/src/provider-selection/provider-selection.test.ts +++ b/packages/app/src/provider-selection/provider-selection.test.ts @@ -7,6 +7,7 @@ import { buildProviderSelectorProviders, buildSelectableProviderSelectorProviders, buildSelectedTriggerLabel, + buildSelectorProvider, filterAndRankModelRows, matchesModelSearch, resolveEffectiveComposerModeId, @@ -22,7 +23,7 @@ describe("combined model selector data", () => { snapshotEntry({ provider: "waiting", status: "loading", models: [] }), snapshotEntry({ provider: "codex", status: "ready", models: [codexModel] }), ], - false, + { isConnected: false, selectedProvider: null }, ); expect(providers[0].modelSelection).toEqual({ kind: "error", @@ -54,16 +55,19 @@ describe("combined model selector data", () => { } it("orders provider accounts after their base provider and borrows its icon", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ provider: "claude", label: "Claude" }), - snapshotEntry({ provider: "codex", label: "Codex" }), - snapshotEntry({ - provider: "claude-work", - label: "Claude (Work)", - source: "custom", - baseProviderId: "claude", - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "claude", label: "Claude" }), + snapshotEntry({ provider: "codex", label: "Codex" }), + snapshotEntry({ + provider: "claude-work", + label: "Claude (Work)", + source: "custom", + baseProviderId: "claude", + }), + ], + { selectedProvider: null }, + ); expect(providers.map((provider) => provider.id)).toEqual(["claude", "claude-work", "codex"]); expect(resolveProviderIconId(providers, "claude-work")).toBe("claude"); @@ -75,13 +79,16 @@ describe("combined model selector data", () => { it("builds selector providers from ready enabled snapshot entries", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codex", - label: "Codex", - models: [codexModel], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codex", + label: "Codex", + models: [codexModel], + }), + ], + { selectedProvider: null }, + ), ).toEqual([ { id: "codex", @@ -112,9 +119,10 @@ describe("combined model selector data", () => { isSelectable: false, }; - const [provider] = buildSelectableProviderSelectorProviders([ - snapshotEntry({ provider: "codex", models: [codexModel, compatibilityModel] }), - ]); + const [provider] = buildSelectableProviderSelectorProviders( + [snapshotEntry({ provider: "codex", models: [codexModel, compatibilityModel] })], + { selectedProvider: null }, + ); expect(provider?.modelSelection).toMatchObject({ kind: "models", @@ -124,13 +132,16 @@ describe("combined model selector data", () => { it("synthesizes a default model row for ready enabled providers without explicit models", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codewhale", - label: "CodeWhale", - models: [], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codewhale", + label: "CodeWhale", + models: [], + }), + ], + { selectedProvider: null }, + ), ).toEqual([ { id: "codewhale", @@ -155,33 +166,34 @@ describe("combined model selector data", () => { it("excludes disabled providers from selector data", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codewhale", - label: "CodeWhale", - enabled: false, - models: [], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codewhale", + label: "CodeWhale", + enabled: false, + models: [], + }), + ], + { selectedProvider: null }, + ), ).toEqual([]); }); it("surfaces non-ready providers with their state-specific selection", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ provider: "loading-provider", status: "loading", models: [] }), - snapshotEntry({ - provider: "error-provider", - status: "error", - error: "boom", - models: [], - }), - snapshotEntry({ - provider: "unavailable-provider", - status: "unavailable", - models: [], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "loading-provider", status: "loading", models: [] }), + snapshotEntry({ + provider: "error-provider", + status: "error", + error: "boom", + models: [], + }), + ], + { selectedProvider: null }, + ), ).toEqual([ { id: "loading-provider", @@ -193,14 +205,45 @@ describe("combined model selector data", () => { label: "error-provider", modelSelection: { kind: "error", message: "boom" }, }, - { - id: "unavailable-provider", - label: "unavailable-provider", - modelSelection: { kind: "error", message: "Unavailable" }, - }, ]); }); + it("leaves out enabled providers that are not installed", () => { + expect( + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "codex", label: "Codex" }), + snapshotEntry({ provider: "gemini", status: "unavailable", models: [] }), + ], + { selectedProvider: null }, + ).map((provider) => provider.id), + ).toEqual(["codex"]); + }); + + it("keeps a saved choice whose provider is not installed, labelled Unavailable", () => { + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "codex", label: "Codex" }), + snapshotEntry({ provider: "gemini", status: "unavailable", models: [] }), + ], + { selectedProvider: "gemini" }, + ); + expect(providers.map((provider) => provider.id)).toEqual(["codex", "gemini"]); + expect(providers[1].modelSelection).toEqual({ kind: "error", message: "Unavailable" }); + }); + + it("keeps an agent's own provider in its selector when that provider is not installed", () => { + expect( + buildSelectorProvider( + snapshotEntry({ provider: "gemini", status: "unavailable", models: [] }), + ), + ).toEqual({ + id: "gemini", + label: "gemini", + modelSelection: { kind: "error", message: "Unavailable" }, + }); + }); + it("builds selector providers from an already-curated provider list", () => { const providerDefinitions: AgentProviderDefinition[] = [ { @@ -299,18 +342,21 @@ describe("combined model selector data", () => { }); it("resolves selected labels from explicit provider model-selection state", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codex", - label: "Codex", - models: [codexModel], - }), - snapshotEntry({ - provider: "codewhale", - label: "CodeWhale", - models: [], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codex", + label: "Codex", + models: [codexModel], + }), + snapshotEntry({ + provider: "codewhale", + label: "CodeWhale", + models: [], + }), + ], + { selectedProvider: null }, + ); expect( resolveSelectedModelLabel({ @@ -350,13 +396,16 @@ describe("combined model selector data", () => { }); it("keeps a stored selected model visible when current snapshot rows no longer offer it", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codex", - label: "Codex", - models: [{ provider: "codex", id: "gpt-5.4", label: "GPT-5.4", isDefault: true }], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codex", + label: "Codex", + models: [{ provider: "codex", id: "gpt-5.4", label: "GPT-5.4", isDefault: true }], + }), + ], + { selectedProvider: null }, + ); expect( resolveSelectedModelLabel({ @@ -369,15 +418,18 @@ describe("combined model selector data", () => { }); it("keeps provider snapshot errors visible in the selected trigger label", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "opencode", - label: "OpenCode", - status: "error", - error: "OpenCode app.agents timed out after 10s", - models: [], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "opencode", + label: "OpenCode", + status: "error", + error: "OpenCode app.agents timed out after 10s", + models: [], + }), + ], + { selectedProvider: null }, + ); expect( resolveSelectedModelLabel({ @@ -431,21 +483,27 @@ describe("combined model selector data", () => { it("uses the active app language for utility labels", async () => { await i18n.changeLanguage("zh-CN"); try { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "deepseek-tui", - label: "DeepSeek TUI", - models: [], - }), - snapshotEntry({ - provider: "unavailable-provider", - status: "unavailable", - models: [], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "deepseek-tui", + label: "DeepSeek TUI", + models: [], + }), + ], + { selectedProvider: null }, + ); expect(getAllModelLabels(providers)).toContain("默认"); - expect(providers[1]?.modelSelection).toEqual({ + expect( + buildSelectorProvider( + snapshotEntry({ + provider: "unavailable-provider", + status: "unavailable", + models: [], + }), + ).modelSelection, + ).toEqual({ kind: "error", message: "不可用", }); diff --git a/packages/app/src/provider-selection/provider-selection.ts b/packages/app/src/provider-selection/provider-selection.ts index af225de26f2f..906b505fbfba 100644 --- a/packages/app/src/provider-selection/provider-selection.ts +++ b/packages/app/src/provider-selection/provider-selection.ts @@ -173,22 +173,37 @@ export function buildProviderSelectorProviders(input: { ); } +/** One provider in a selector, whatever its state. */ +export function buildSelectorProvider( + entry: ProviderSnapshotEntry, + isConnected = true, +): ProviderSelectorProvider { + const label = entry.label ?? entry.provider; + return { + id: entry.provider, + label, + baseProviderId: entry.baseProviderId, + modelSelection: buildEntryModelSelection(entry, label, isConnected, entry.baseProviderId), + }; +} + +/** + * The providers a user can pick a model from: enabled, and installed or still being probed. The + * provider of the picker's current choice stays whatever its state, so the selector still names + * it. Every picker says what that choice is, or `null` for none, so none can forget it. + */ export function buildSelectableProviderSelectorProviders( entries: ProviderSnapshotEntry[] | undefined, - isConnected = true, + options: { isConnected?: boolean; selectedProvider: string | null }, ): ProviderSelectorProvider[] { + const { isConnected = true, selectedProvider } = options; return groupProviderAccountsBy( (entries ?? []) - .filter((entry) => entry.enabled) - .map((entry) => { - const label = entry.label ?? entry.provider; - return { - id: entry.provider, - label, - baseProviderId: entry.baseProviderId, - modelSelection: buildEntryModelSelection(entry, label, isConnected, entry.baseProviderId), - }; - }), + .filter( + (entry) => + entry.provider === selectedProvider || (entry.enabled && entry.status !== "unavailable"), + ) + .map((entry) => buildSelectorProvider(entry, isConnected)), (provider) => provider.baseProviderId, ); } diff --git a/packages/app/src/provider-settings/index.ts b/packages/app/src/provider-settings/index.ts new file mode 100644 index 000000000000..44a7fb50c23d --- /dev/null +++ b/packages/app/src/provider-settings/index.ts @@ -0,0 +1,4 @@ +export { ProviderList } from "./internal/provider-list"; +export { ProviderDetailPage } from "./internal/provider-detail-page"; +export { ProviderDetailSheet } from "./internal/provider-detail-sheet"; +export type { ProviderSheetFrame } from "./internal/sheet-frame"; diff --git a/packages/app/src/provider-settings/internal/add-provider-sheet.tsx b/packages/app/src/provider-settings/internal/add-provider-sheet.tsx new file mode 100644 index 000000000000..b0f7848b364d --- /dev/null +++ b/packages/app/src/provider-settings/internal/add-provider-sheet.tsx @@ -0,0 +1,187 @@ +import { PackagePlus } from "lucide-react-native"; +import { useCallback, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { SvgXml } from "react-native-svg"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { rankProviderCatalog } from "@/components/provider-catalog-search"; +import { SettingsCard, SettingsRow } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { + useAcpProviderCatalog, + type AcpProviderCatalogItem, +} from "@/hooks/use-acp-provider-catalog"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { settingsStyles } from "@/styles/settings"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; +import { useProviderConfigActions } from "./provider-config"; +import { OVERLAY_SHEET_FRAME, type ProviderSheetFrame } from "./sheet-frame"; + +const ThemedPackagePlus = withUnistyles(PackagePlus); +const ThemedSvgXml = withUnistyles(SvgXml); +const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); + +export interface AddProviderSheetProps { + serverId: string; + visible: boolean; + onClose: () => void; + /** The provider is in config and listed; open its detail. */ + onAdded: (providerId: string) => void; + frame?: ProviderSheetFrame; +} + +/** The catalog of providers not added yet, searchable, each with Add. */ +export function AddProviderSheet({ + serverId, + visible, + onClose, + onAdded, + frame = OVERLAY_SHEET_FRAME, +}: AddProviderSheetProps) { + const { t } = useTranslation(); + const { entries: catalog } = useAcpProviderCatalog(); + const { entries: providers } = useProvidersSnapshot(serverId); + const { add, addingProviderId } = useProviderConfigActions(serverId); + const [search, setSearch] = useState(""); + // Each opening starts from an empty search; the field clears when this changes. + const [session, setSession] = useState(0); + // Read when an add finishes, to tell whether the sheet it started in is still open. + const sessionRef = useRef(0); + const endSession = useCallback(() => { + setSearch(""); + sessionRef.current += 1; + setSession(sessionRef.current); + }, []); + const handleClose = useCallback(() => { + endSession(); + onClose(); + }, [endSession, onClose]); + + const available = useMemo(() => { + const added = new Set(providers?.map((entry) => entry.provider) ?? []); + return rankProviderCatalog( + catalog.filter((entry) => !added.has(entry.id)), + search, + ); + }, [catalog, providers, search]); + + const handleAdd = useCallback( + (entry: AcpProviderCatalogItem) => { + const startedIn = sessionRef.current; + void add(entry).then((added) => { + // Closed before the add finished: the provider is added, but the user has moved on. + if (!added || sessionRef.current !== startedIn) return added; + endSession(); + onAdded(entry.id); + return added; + }); + }, + [add, endSession, onAdded], + ); + + const header = useMemo( + () => ({ + title: t("settings.providers.addProvider"), + back: frame.returns + ? { + onPress: handleClose, + accessibilityLabel: t("settings.providers.detail.backToProviders"), + } + : undefined, + search: { + onChange: setSearch, + placeholder: t("providerCatalog.search"), + resetKey: session, + testID: "provider-catalog-search", + }, + }), + [frame.returns, handleClose, session, t], + ); + + return ( + + + {available.length === 0 ? ( + + {t("providerCatalog.noProviders")} + + ) : ( + available.map((entry) => ( + + )) + )} + + + ); +} + +function CatalogRow({ + entry, + adding, + disabled, + onAdd, +}: { + entry: AcpProviderCatalogItem; + adding: boolean; + disabled: boolean; + onAdd: (entry: AcpProviderCatalogItem) => void; +}) { + const { t } = useTranslation(); + const handleAdd = useCallback(() => onAdd(entry), [entry, onAdd]); + const icon = useMemo( + () => + entry.iconSvg ? ( + + ) : ( + + ), + [entry.iconSvg], + ); + return ( + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + empty: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/provider-settings/internal/detail-sections.test.ts b/packages/app/src/provider-settings/internal/detail-sections.test.ts new file mode 100644 index 000000000000..790f900f1581 --- /dev/null +++ b/packages/app/src/provider-settings/internal/detail-sections.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { ProviderInstallationState } from "@/components/provider-installation-section"; +import { readDetailPresence, readDetailSections, readShownInstallation } from "./detail-sections"; + +function entry(overrides: Partial = {}): ProviderSnapshotEntry { + return { + provider: "opencode", + label: "OpenCode", + status: "ready", + enabled: true, + modes: [], + models: [], + ...overrides, + }; +} + +const unsupported: ProviderInstallationState = { status: "unsupported" }; +const notInstalled: ProviderInstallationState = { + status: "ready", + installation: { inspection: { status: "not_installed" }, canUpdate: false }, +}; + +describe("provider detail sections", () => { + it("shows every model for a provider that runs", () => { + expect(readDetailSections(entry(), unsupported)).toEqual({ error: null, models: "all" }); + }); + + it("keeps every model while the provider is probed again", () => { + expect(readDetailSections(entry({ status: "loading" }), unsupported).models).toBe("all"); + }); + + it("leads with the error and keeps custom models when the provider fails", () => { + expect( + readDetailSections( + entry({ status: "error", error: "opencode exited with code 1" }), + unsupported, + ), + ).toEqual({ error: "opencode exited with code 1", models: "custom" }); + }); + + it("says nothing extra and lists no models when Installation already says Not installed", () => { + expect(readDetailSections(entry({ status: "unavailable" }), unsupported)).toEqual({ + error: null, + models: null, + }); + expect( + readDetailSections(entry({ status: "error", error: "spawn ENOENT" }), notInstalled), + ).toEqual({ error: null, models: null }); + }); + + it("hides models and the error for a disabled provider", () => { + expect( + readDetailSections(entry({ enabled: false, status: "error", error: "boom" }), unsupported), + ).toEqual({ error: null, models: null }); + }); + + it("gives an error with no message an empty one, so the alert still shows", () => { + expect(readDetailSections(entry({ status: "error" }), unsupported).error).toBe(""); + }); +}); + +describe("provider detail installation", () => { + const guide = "https://example.com/install"; + const noContract: ProviderInstallationState = { status: "ready", installation: null }; + + it("says Not installed with the install guide when the host reports nothing about it", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: noContract, + installGuide: guide, + }), + ).toEqual({ + status: "ready", + installation: { inspection: { status: "not_installed" }, installUrl: guide }, + }); + }); + + it("keeps the host's install link over the guide", () => { + const hosted: ProviderInstallationState = { + status: "ready", + installation: { + inspection: { status: "not_installed" }, + installUrl: "https://host.example/install", + canUpdate: false, + }, + }; + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: hosted, + installGuide: guide, + }), + ).toEqual(hosted); + }); + + it("gives the host's Not installed the guide when the host has no link", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: notInstalled, + installGuide: guide, + }), + ).toEqual({ + status: "ready", + installation: { + inspection: { status: "not_installed" }, + canUpdate: false, + installUrl: guide, + }, + }); + }); + + it("adds nothing for an installed or disabled provider", () => { + expect( + readShownInstallation({ entry: entry(), installation: noContract, installGuide: guide }), + ).toEqual(noContract); + expect( + readShownInstallation({ + entry: entry({ enabled: false, status: "unavailable" }), + installation: noContract, + installGuide: guide, + }), + ).toEqual(noContract); + }); + + it("says nothing it cannot back with a guide", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: noContract, + installGuide: null, + }), + ).toEqual(noContract); + }); + + it("says Not installed with the guide on a host that cannot report installations", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: unsupported, + installGuide: guide, + }), + ).toEqual({ + status: "ready", + installation: { inspection: { status: "not_installed" }, installUrl: guide }, + }); + // Without a guide, or for a provider the host runs, there is nothing to show. + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: unsupported, + installGuide: null, + }), + ).toEqual(unsupported); + expect( + readShownInstallation({ entry: entry(), installation: unsupported, installGuide: guide }), + ).toEqual(unsupported); + }); + + it("waits while the host is still checking", () => { + const checking: ProviderInstallationState = { status: "loading" }; + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: checking, + installGuide: guide, + }), + ).toEqual(checking); + }); +}); + +describe("provider detail presence", () => { + const loaded = [entry(), entry({ provider: "codex", label: "Codex" })]; + + it("finds the provider among the host's providers", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: true, + entries: loaded, + error: null, + removing: null, + }), + ).toEqual({ kind: "found", entry: loaded[1] }); + }); + + it("is loading until the host's providers arrive", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: true, + entries: undefined, + error: null, + removing: null, + }), + ).toEqual({ kind: "loading" }); + }); + + it("says the provider is missing once the host's providers have arrived without it", () => { + expect( + readDetailPresence({ + provider: "gone", + connected: true, + entries: loaded, + error: null, + removing: null, + }), + ).toEqual({ kind: "missing" }); + }); + + it("keeps showing a provider this page is removing once it leaves the list", () => { + const gone = entry({ provider: "gone", label: "Gone" }); + expect( + readDetailPresence({ + provider: "gone", + connected: true, + entries: loaded, + error: null, + removing: gone, + }), + ).toEqual({ kind: "found", entry: gone }); + }); + + it("says the host is offline rather than loading forever", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: false, + entries: undefined, + error: null, + removing: null, + }), + ).toEqual({ kind: "offline" }); + }); + + it("shows why the host's providers could not be read", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: true, + entries: undefined, + error: "Request timed out", + removing: null, + }), + ).toEqual({ kind: "failed", message: "Request timed out" }); + }); +}); diff --git a/packages/app/src/provider-settings/internal/detail-sections.ts b/packages/app/src/provider-settings/internal/detail-sections.ts new file mode 100644 index 000000000000..c582544d5f27 --- /dev/null +++ b/packages/app/src/provider-settings/internal/detail-sections.ts @@ -0,0 +1,97 @@ +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { ProviderInstallationState } from "@/components/provider-installation-section"; + +export interface DetailSections { + /** The failure the page leads with, or null. Empty when the provider gave no message. */ + error: string | null; + /** + * Which models the page lists. The provider reports its own only while it runs; custom models + * live in config, so they stay manageable while it fails. + */ + models: "all" | "custom" | null; +} + +/** Which of the detail's state-dependent parts show, so each fact is said once. */ +export function readDetailSections( + entry: ProviderSnapshotEntry, + installation: ProviderInstallationState, +): DetailSections { + const notInstalled = + entry.status === "unavailable" || + (installation.status === "ready" && + installation.installation?.inspection?.status === "not_installed"); + const failing = entry.enabled && entry.status === "error" && !notInstalled; + return { + error: failing ? (entry.error?.trim() ?? "") : null, + models: readShownModels(entry, notInstalled), + }; +} + +function readShownModels( + entry: ProviderSnapshotEntry, + notInstalled: boolean, +): DetailSections["models"] { + if (!entry.enabled || notInstalled) return null; + return entry.status === "error" ? "custom" : "all"; +} + +/** + * The installation the page shows. A provider added from the catalog has no installation the + * host can report, so when its CLI is missing the page says so with the catalog's install guide. + * The host's own install link wins over the guide. A host that cannot report installations gets + * the same row, because the guide is the app's own catalog data. + */ +export function readShownInstallation(input: { + entry: ProviderSnapshotEntry; + installation: ProviderInstallationState; + /** The catalog's install guide for this provider, or null. */ + installGuide: string | null; +}): ProviderInstallationState { + const { entry, installation, installGuide } = input; + if (!installGuide) return installation; + if (installation.status !== "ready" && installation.status !== "unsupported") return installation; + const reported = installation.status === "ready" ? installation.installation : null; + if (reported?.installUrl) return installation; + const notInstalled = + reported?.inspection?.status === "not_installed" || + (!reported?.inspection && entry.enabled && entry.status === "unavailable"); + if (!notInstalled) return installation; + return { + status: "ready", + installation: { + ...reported, + inspection: { status: "not_installed" }, + installUrl: installGuide, + }, + }; +} + +export type DetailPresence = + | { kind: "found"; entry: ProviderSnapshotEntry } + | { kind: "loading" } + | { kind: "missing" } + | { kind: "offline" } + | { kind: "failed"; message: string }; + +/** + * Whether the page has a provider to show. A page opened from its URL renders before the host's + * providers arrive, and its id may name a provider the host no longer has. A provider this page is + * removing leaves the list before the removal answers; the page keeps showing it until it closes. + */ +export function readDetailPresence(input: { + provider: string; + connected: boolean; + entries: ProviderSnapshotEntry[] | undefined; + error: string | null; + /** The provider this page's own Remove is deleting, as it was when the user confirmed. */ + removing: ProviderSnapshotEntry | null; +}): DetailPresence { + const entry = + input.entries?.find((candidate) => candidate.provider === input.provider) ?? + (input.removing?.provider === input.provider ? input.removing : undefined); + if (entry) return { kind: "found", entry }; + if (!input.connected) return { kind: "offline" }; + if (input.entries) return { kind: "missing" }; + if (input.error) return { kind: "failed", message: input.error }; + return { kind: "loading" }; +} diff --git a/packages/app/src/provider-settings/internal/diagnostic-sheet.tsx b/packages/app/src/provider-settings/internal/diagnostic-sheet.tsx new file mode 100644 index 000000000000..9f8c07d5d83b --- /dev/null +++ b/packages/app/src/provider-settings/internal/diagnostic-sheet.tsx @@ -0,0 +1,149 @@ +import * as Clipboard from "expo-clipboard"; +import { Copy, RotateCw } from "lucide-react-native"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { + AdaptiveModalSheet, + SheetHeaderIconButton, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface"; +import { useToast } from "@/contexts/toast-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import type { Theme } from "@/styles/theme"; + +const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); +const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const DIAGNOSTIC_SNAP_POINTS = ["50%", "85%"]; + +/** The provider's diagnostic report, run on open, with copy and run again. */ +export function DiagnosticSheet({ + serverId, + provider, + visible, + onClose, +}: { + serverId: string; + provider: string; + visible: boolean; + onClose: () => void; +}) { + const { t } = useTranslation(); + const toast = useToast(); + const client = useHostRuntimeClient(serverId); + const [diagnostic, setDiagnostic] = useState(null); + const [loading, setLoading] = useState(false); + + const fetchDiagnostic = useCallback(async () => { + if (!client) return; + setLoading(true); + try { + const result = await client.getProviderDiagnostic(provider); + setDiagnostic(result.diagnostic); + } catch (err) { + setDiagnostic( + err instanceof Error ? err.message : t("settings.providers.diagnostic.failedToFetch"), + ); + } finally { + setLoading(false); + } + }, [client, provider, t]); + + useEffect(() => { + if (visible) { + void fetchDiagnostic(); + } else { + setDiagnostic(null); + } + }, [visible, fetchDiagnostic]); + + const handleRefresh = useCallback(() => { + if (loading) return; + void fetchDiagnostic(); + }, [fetchDiagnostic, loading]); + const handleCopy = useCallback(() => { + if (!diagnostic) return; + void Clipboard.setStringAsync(diagnostic) + .then(() => toast.copied(t("settings.providers.diagnostic.copyLabel"))) + .catch(() => toast.error(t("settings.providers.diagnostic.copyFailed"))); + }, [diagnostic, t, toast]); + + const header = useMemo( + () => ({ + title: t("settings.providers.diagnostic.title"), + actions: ( + <> + + + + ), + }), + [diagnostic, handleCopy, handleRefresh, loading, t], + ); + + let body: React.ReactNode; + if (loading && !diagnostic) { + body = ( + + + + {t("settings.providers.diagnostic.running")} + + + ); + } else if (diagnostic) { + body = {diagnostic}; + } else { + body = ( + + + {t("settings.providers.diagnostic.none")} + + + ); + } + + return ( + + {body} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + placeholder: { + paddingVertical: theme.spacing[4], + paddingHorizontal: theme.spacing[4], + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + mutedText: { + fontSize: theme.fontSize.base, + color: theme.colors.foregroundMuted, + }, +})); diff --git a/packages/app/src/components/provider-diagnostic-models.test.ts b/packages/app/src/provider-settings/internal/discovered-models.test.ts similarity index 98% rename from packages/app/src/components/provider-diagnostic-models.test.ts rename to packages/app/src/provider-settings/internal/discovered-models.test.ts index 4ad536945f8c..0d139deb33de 100644 --- a/packages/app/src/components/provider-diagnostic-models.test.ts +++ b/packages/app/src/provider-settings/internal/discovered-models.test.ts @@ -3,7 +3,7 @@ import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types"; import { resolveProviderDiscoveredModels, type ProviderDiscoveredModelsCache, -} from "./provider-diagnostic-models"; +} from "./discovered-models"; const piModel: AgentModelDefinition = { provider: "pi", diff --git a/packages/app/src/components/provider-diagnostic-models.ts b/packages/app/src/provider-settings/internal/discovered-models.ts similarity index 100% rename from packages/app/src/components/provider-diagnostic-models.ts rename to packages/app/src/provider-settings/internal/discovered-models.ts diff --git a/packages/app/src/provider-settings/internal/provider-accounts-section.test.tsx b/packages/app/src/provider-settings/internal/provider-accounts-section.test.tsx new file mode 100644 index 000000000000..ba7b9fdf2a7c --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-accounts-section.test.tsx @@ -0,0 +1,223 @@ +/** + * @vitest-environment jsdom + */ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; + +const { snapshotState, configState, featureState, sheetState } = vi.hoisted(() => ({ + sheetState: { + onSave: null as + | ((input: { + providerId: string; + originalProviderId?: string; + patch: unknown; + }) => Promise) + | null, + }, + snapshotState: { entries: undefined as ProviderSnapshotEntry[] | undefined }, + configState: { config: null as MutableDaemonConfig | null }, + featureState: {} as Record, +})); + +vi.mock("react-native", async (importOriginal) => ({ + ...(await importOriginal()), + View: ({ children, testID }: { children?: React.ReactNode; testID?: string }) => + React.createElement("div", { "data-testid": testID }, children), +})); + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +vi.mock("@/components/settings", () => ({ + SettingsCard: ({ children }: { children?: React.ReactNode }) => + React.createElement("div", null, children), + SettingsDetailRow: ({ + label, + onPress, + testID, + }: { + label: string; + onPress?: () => void; + testID?: string; + }) => + React.createElement("div", { role: "button", "data-testid": testID, onClick: onPress }, label), +})); + +// The real sheet pulls in react-native-reanimated, which is untransformed here. +vi.mock("@/components/provider-account-sheet", () => ({ + ProviderAccountSheet: ({ + visible, + baseProviderId, + account, + onSave, + }: { + visible?: boolean; + baseProviderId?: string; + account?: { providerId: string }; + onSave?: typeof sheetState.onSave; + }) => { + sheetState.onSave = onSave ?? null; + return visible + ? React.createElement("div", { + "data-testid": `provider-account-sheet-${account?.providerId ?? baseProviderId}`, + "data-base": baseProviderId, + }) + : null; + }, +})); + +vi.mock("@/hooks/use-providers-snapshot", () => ({ + useProvidersSnapshot: () => ({ entries: snapshotState.entries, refresh: vi.fn() }), +})); + +vi.mock("@/hooks/use-daemon-config", () => ({ + useDaemonConfig: () => ({ config: configState.config, patchConfig: vi.fn() }), +})); + +vi.mock("@/runtime/host-features", () => ({ + useHostFeature: (_serverId: string, feature: string) => featureState[feature] ?? false, +})); + +vi.mock("@/styles/settings", () => ({ settingsStyles: { section: {} } })); + +import { ProviderAccountsSection } from "./provider-accounts-section"; + +function entry(overrides: Partial): ProviderSnapshotEntry { + return { + provider: "claude", + source: "builtin", + status: "ready", + enabled: true, + label: "Claude", + defaultModeId: null, + modes: [], + models: [], + ...overrides, + } as ProviderSnapshotEntry; +} + +const claudeEntry = entry({}); +const claudeWorkEntry = entry({ + provider: "claude-work", + source: "custom", + label: "Claude · Work", +}); + +function makeConfig(providers: Record = {}): MutableDaemonConfig { + return { providers } as unknown as MutableDaemonConfig; +} + +let container: HTMLDivElement | null = null; +let root: Root | null = null; + +function render(shown: ProviderSnapshotEntry, label: string, onRenamed?: () => void) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => { + root?.render( + React.createElement(ProviderAccountsSection, { + serverId: "host", + entry: shown, + label, + onRenamed, + }), + ); + }); +} + +function click(testId: string) { + const element = container?.querySelector(`[data-testid="${testId}"]`); + expect(element).not.toBeNull(); + act(() => { + element?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); + }); +} + +describe("ProviderAccountsSection", () => { + beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + snapshotState.entries = [claudeEntry, claudeWorkEntry]; + configState.config = makeConfig({ + "claude-work": { extends: "claude", label: "Claude · Work" }, + }); + for (const feature of Object.keys(featureState)) delete featureState[feature]; + sheetState.onSave = null; + }); + + afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + container = null; + root = null; + }); + + it("opens the account sheet from a builtin provider's detail", () => { + render(claudeEntry, "Claude"); + expect(container?.querySelector('[data-testid="provider-account-sheet-claude"]')).toBeNull(); + expect(container?.querySelector('[data-testid="provider-edit-account-claude"]')).toBeNull(); + + click("provider-add-account-claude"); + + expect( + container?.querySelector('[data-testid="provider-account-sheet-claude"]'), + ).not.toBeNull(); + }); + + it("edits an account against its base provider when the daemon supports exact replacement", () => { + featureState.providerConfigReplace = true; + render(claudeWorkEntry, "Claude · Work"); + expect(container?.querySelector('[data-testid="provider-add-account-claude-work"]')).toBeNull(); + + click("provider-edit-account-claude-work"); + + const sheet = container?.querySelector('[data-testid="provider-account-sheet-claude-work"]'); + expect(sheet?.getAttribute("data-base")).toBe("claude"); + }); + + it("shows nothing for an account when the daemon cannot replace it exactly", () => { + render(claudeWorkEntry, "Claude · Work"); + expect(container?.textContent).toBe(""); + }); + + it("leaves the detail after a save renames the account", async () => { + featureState.providerConfigReplace = true; + const onRenamed = vi.fn(); + render(claudeWorkEntry, "Claude · Work", onRenamed); + click("provider-edit-account-claude-work"); + + await act(async () => { + await sheetState.onSave?.({ + providerId: "claude-team", + originalProviderId: "claude-work", + patch: {}, + }); + }); + + expect(onRenamed).toHaveBeenCalledTimes(1); + expect( + container?.querySelector('[data-testid="provider-account-sheet-claude-work"]'), + ).toBeNull(); + }); + + it("stays on the detail after a save that keeps the account's ID", async () => { + featureState.providerConfigReplace = true; + const onRenamed = vi.fn(); + render(claudeWorkEntry, "Claude · Work", onRenamed); + click("provider-edit-account-claude-work"); + + await act(async () => { + await sheetState.onSave?.({ + providerId: "claude-work", + originalProviderId: "claude-work", + patch: {}, + }); + }); + + expect(onRenamed).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/provider-settings/internal/provider-accounts-section.tsx b/packages/app/src/provider-settings/internal/provider-accounts-section.tsx new file mode 100644 index 000000000000..d9b9c9d4d4cc --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-accounts-section.tsx @@ -0,0 +1,137 @@ +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Alert, View } from "react-native"; +import { + ProviderAccountSheet, + type ProviderAccountSaveInput, +} from "@/components/provider-account-sheet"; +import { SettingsCard, SettingsDetailRow } from "@/components/settings"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { + canAddProviderAccount, + resolveProviderAccountBaseId, +} from "@/provider-accounts/provider-account-form-model"; +import { useHostFeature } from "@/runtime/host-features"; +import { settingsStyles } from "@/styles/settings"; +import type { ProviderEntry } from "./provider-config"; + +type ProviderConfig = NonNullable< + ReturnType["config"] +>["providers"][string]; + +interface ProviderAccountTarget { + baseProviderId: string; + baseProviderLabel: string; + account?: { providerId: string; config: ProviderConfig }; +} + +/** + * Fork: provider accounts. A builtin provider offers Add account, which writes a custom provider + * that extends it; such an account offers Edit account. Hidden when neither applies. + */ +export function ProviderAccountsSection({ + serverId, + entry, + label, + onRenamed, +}: { + serverId: string; + entry: ProviderEntry; + label: string; + /** + * An Edit account save moved this provider to a new ID. The enclosing detail still targets the + * old one, which the next snapshot drops, so it has to leave. + */ + onRenamed?: () => void; +}) { + const { t } = useTranslation(); + const supportsReplace = useHostFeature(serverId, "providerConfigReplace"); + const supportsRename = useHostFeature(serverId, "providerConfigRename"); + const { entries, refresh } = useProvidersSnapshot(serverId); + const { config, patchConfig } = useDaemonConfig(serverId); + const [target, setTarget] = useState(null); + + const provider = entry.provider; + const accountBaseId = resolveProviderAccountBaseId(provider, config?.providers); + const canAdd = canAddProviderAccount({ providerId: provider, source: entry.source }); + const canEdit = supportsReplace && entry.source === "custom" && accountBaseId !== null; + const existingProviderIds = useMemo( + () => (entries ?? []).map((candidate) => candidate.provider), + [entries], + ); + + const openAdd = useCallback(() => { + setTarget({ baseProviderId: provider, baseProviderLabel: label }); + }, [label, provider]); + const openEdit = useCallback(() => { + const providerConfig = config?.providers[provider]; + if (!providerConfig || !accountBaseId) return; + const baseProviderLabel = + entries?.find((candidate) => candidate.provider === accountBaseId)?.label ?? accountBaseId; + setTarget({ + baseProviderId: accountBaseId, + baseProviderLabel, + account: { providerId: provider, config: providerConfig }, + }); + }, [accountBaseId, config?.providers, entries, provider]); + const close = useCallback(() => setTarget(null), []); + const save = useCallback( + async ({ providerId, originalProviderId, patch }: ProviderAccountSaveInput) => { + const renamed = Boolean(originalProviderId && originalProviderId !== providerId); + try { + await patchConfig(patch); + await refresh( + renamed && originalProviderId ? [originalProviderId, providerId] : [providerId], + ); + if (renamed) { + setTarget(null); + onRenamed?.(); + } + return true; + } catch (error) { + Alert.alert( + t("settings.providers.account.errorTitle"), + error instanceof Error ? error.message : String(error), + ); + return false; + } + }, + [onRenamed, patchConfig, refresh, t], + ); + + if (!canAdd && !canEdit) return null; + return ( + + + {canAdd ? ( + + ) : null} + {canEdit ? ( + + ) : null} + + {target ? ( + + ) : null} + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-config.ts b/packages/app/src/provider-settings/internal/provider-config.ts new file mode 100644 index 000000000000..bbef1c0f231b --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-config.ts @@ -0,0 +1,151 @@ +import { useCallback, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Alert } from "react-native"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { + buildAcpProviderConfigPatch, + getAcpProviderCatalog, + type AcpProviderCatalogItem, +} from "@/hooks/use-acp-provider-catalog"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { selectHostFeature, useHostFeature } from "@/runtime/host-features"; +import { useSessionStore } from "@/stores/session-store"; +import { confirmDialog } from "@/utils/confirm-dialog"; + +export type ProviderEntry = NonNullable["entries"]>[number]; + +export interface ProviderConfigActions { + /** The provider whose Enabled switch is being saved. */ + togglingProviderId: string | null; + setEnabled: (providerId: string, enabled: boolean) => void; + /** Config owns the provider, so Remove can delete it. */ + canRemove: (entry: ProviderEntry) => boolean; + /** + * The provider being removed, as it was when the user confirmed. It stays set once the removal + * succeeds, because whatever shows the provider closes next and keeps showing it until then, and + * ends when the host lists the provider again, as when the user adds it back. + */ + removing: ProviderEntry | null; + /** Asks first; resolves true once the provider is gone from config. */ + remove: (entry: ProviderEntry, providerLabel: string) => Promise; + /** The catalog provider being written to config. */ + addingProviderId: string | null; + /** Writes a catalog provider to config and probes it; resolves true once it is listed. */ + add: (entry: AcpProviderCatalogItem) => Promise; +} + +/** Writes a provider's Enabled flag, adds catalog providers and removes config-owned ones. */ +export function useProviderConfigActions(serverId: string): ProviderConfigActions { + const { t } = useTranslation(); + const toast = useToast(); + const { config, patchConfig } = useDaemonConfig(serverId); + const { entries, refresh } = useProvidersSnapshot(serverId); + const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval"); + const [togglingProviderId, setTogglingProviderId] = useState(null); + const [removal, setRemoval] = useState<{ entry: ProviderEntry; done: boolean } | null>(null); + const removingRef = useRef(null); + const [addingProviderId, setAddingProviderId] = useState(null); + const addingRef = useRef(null); + + const setEnabled = useCallback( + (providerId: string, enabled: boolean) => { + setTogglingProviderId(providerId); + void patchConfig({ providers: { [providerId]: { enabled } } }) + .catch((error: unknown) => { + Alert.alert( + t("settings.providers.updateErrorTitle"), + error instanceof Error ? error.message : String(error), + ); + }) + .finally(() => { + setTogglingProviderId((current) => (current === providerId ? null : current)); + }); + }, + [patchConfig, t], + ); + + // Config owns derived providers and the opt-in bundled catalog providers. + const canRemove = useCallback( + (entry: ProviderEntry) => { + const providerConfig = config?.providers?.[entry.provider]; + if (!supportsProviderRemoval || entry.source !== "custom" || !providerConfig) return false; + return Boolean( + providerConfig.extends || + getAcpProviderCatalog().some( + (catalogEntry) => catalogEntry.id === entry.provider && catalogEntry.bundledProvider, + ), + ); + }, + [config, supportsProviderRemoval], + ); + + const remove = useCallback( + async (entry: ProviderEntry, providerLabel: string) => { + if (removingRef.current) return false; + removingRef.current = entry.provider; + try { + const confirmed = await confirmDialog({ + title: t("settings.providers.remove.confirmTitle", { name: providerLabel }), + message: t("settings.providers.remove.confirmMessage"), + confirmLabel: t("settings.providers.remove.confirm"), + destructive: true, + }); + if (!confirmed) return false; + setRemoval({ entry, done: false }); + await patchConfig({ removeProviders: [entry.provider] }); + setRemoval({ entry, done: true }); + return true; + } catch (error) { + setRemoval(null); + Alert.alert( + t("settings.providers.remove.errorTitle"), + error instanceof Error ? error.message : String(error), + ); + return false; + } finally { + removingRef.current = null; + } + }, + [patchConfig, t], + ); + + // A sheet outlives each opening, so a finished removal ends here rather than with the sheet. + if (removal?.done && entries?.some((entry) => entry.provider === removal.entry.provider)) { + setRemoval(null); + } + + const add = useCallback( + async (entry: AcpProviderCatalogItem) => { + if (addingRef.current) return false; + addingRef.current = entry.id; + setAddingProviderId(entry.id); + try { + await patchConfig( + buildAcpProviderConfigPatch(entry, (feature) => + selectHostFeature(useSessionStore.getState(), serverId, feature), + ), + ); + await refresh([entry.id]); + return true; + } catch (error) { + toast.error(error instanceof Error ? error.message : String(error)); + return false; + } finally { + if (addingRef.current === entry.id) addingRef.current = null; + setAddingProviderId((current) => (current === entry.id ? null : current)); + } + }, + [patchConfig, refresh, serverId, toast], + ); + + return { + togglingProviderId, + setEnabled, + canRemove, + removing: removal?.entry ?? null, + remove, + addingProviderId, + add, + }; +} diff --git a/packages/app/src/provider-settings/internal/provider-detail-page.tsx b/packages/app/src/provider-settings/internal/provider-detail-page.tsx new file mode 100644 index 000000000000..c5cde33137fd --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-detail-page.tsx @@ -0,0 +1,63 @@ +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { withUnistyles } from "react-native-unistyles"; +import { SettingsDetailHeader } from "@/components/settings"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; +import { ProviderDetail, useProviderDetail } from "./provider-detail"; +import { ProviderGlyph } from "./provider-glyph"; + +/** + * A provider's detail as a Settings page, shaped like a project's. On wide layouts the page is + * titled "Providers > name" and "Providers" goes back. On compact layouts the screen titles it + * "Providers" and the page names the provider. + */ +export function ProviderDetailPage({ + serverId, + provider, + onBack, +}: { + serverId: string; + provider: string; + onBack: () => void; +}) { + const { t } = useTranslation(); + const isCompact = useIsCompactFormFactor(); + const detail = useProviderDetail({ serverId, provider, onRemoved: onBack }); + const parent = useMemo( + () => ({ + label: t("settings.hostSections.providers"), + accessibilityLabel: t("settings.providers.detail.backToProviders"), + onPress: onBack, + testID: "provider-detail-back", + }), + [onBack, t], + ); + const icon = useMemo( + () => ( + + ), + [isCompact, provider, serverId], + ); + return ( + + + + + ); +} + +// The glyph is as large as the name beside it. The page title scales with the interface size. +const ThemedProviderGlyph = withUnistyles(ProviderGlyph); +const pageTitleSize = (theme: Theme) => ({ size: theme.fontSize["4xl"] }); +const rowTitleSize = () => ({ size: ICON_SIZE.md }); diff --git a/packages/app/src/provider-settings/internal/provider-detail-sheet.tsx b/packages/app/src/provider-settings/internal/provider-detail-sheet.tsx new file mode 100644 index 000000000000..c2b8f07db626 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-detail-sheet.tsx @@ -0,0 +1,52 @@ +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { ProviderDetail, useProviderDetail } from "./provider-detail"; +import { ProviderGlyph } from "./provider-glyph"; +import { OVERLAY_SHEET_FRAME, type ProviderSheetFrame } from "./sheet-frame"; + +/** A provider's detail as a sheet, for surfaces with no Settings route to push. */ +export function ProviderDetailSheet({ + serverId, + provider, + visible, + onClose, + frame = OVERLAY_SHEET_FRAME, +}: { + serverId: string; + provider: string; + visible: boolean; + onClose: () => void; + frame?: ProviderSheetFrame; +}) { + const { t } = useTranslation(); + const detail = useProviderDetail({ serverId, provider, onRemoved: onClose }); + const label = detail.label; + const header = useMemo( + () => ({ + title: label, + leading: , + back: frame.returns + ? { + onPress: onClose, + accessibilityLabel: t("settings.providers.detail.backToProviders"), + } + : undefined, + }), + [frame.returns, label, onClose, provider, serverId, t], + ); + return ( + + + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-detail.tsx b/packages/app/src/provider-settings/internal/provider-detail.tsx new file mode 100644 index 000000000000..ab39277ddded --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-detail.tsx @@ -0,0 +1,281 @@ +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { ProviderInstallationSection } from "@/components/provider-installation-section"; +import { useProviderInstallation } from "@/components/provider-installation"; +import { + SettingsCard, + SettingsDetailRow, + SettingsRow, + SettingsSection, + SettingsSwitch, +} from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { readAcpProviderInstallGuide } from "@/hooks/use-acp-provider-catalog"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { settingsStyles } from "@/styles/settings"; +import { openExternalUrl } from "@/utils/open-external-url"; +import { + readDetailPresence, + readDetailSections, + readShownInstallation, + type DetailPresence, +} from "./detail-sections"; +import { DiagnosticSheet } from "./diagnostic-sheet"; +import { ProviderAccountsSection } from "./provider-accounts-section"; +import { useProviderConfigActions, type ProviderEntry } from "./provider-config"; +import { ProviderModels } from "./provider-models"; +import { ProviderNotice } from "./provider-notice"; +import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh"; + +export interface ProviderDetailState { + provider: string; + /** The provider's name, kept while this page removes it. */ + label: string; + presence: DetailPresence; + /** Config owns the provider, so Remove can delete it. */ + canRemove: (entry: ProviderEntry) => boolean; + /** This page's Remove is running, or has succeeded and the page is closing. */ + removing: boolean; + remove: () => void; + /** Fork: leave this detail, as after Remove; an account rename moves the provider to a new ID. */ + leave: () => void; +} + +/** + * What a provider's detail shows and its Remove, shared by the frame's title and the body. A + * provider this page removes leaves the host's list before the removal answers; both keep showing + * it until the frame closes. + */ +export function useProviderDetail({ + serverId, + provider, + onRemoved, +}: { + serverId: string; + provider: string; + /** The provider was removed; leave its detail. */ + onRemoved: () => void; +}): ProviderDetailState { + const { entries, error } = useProvidersSnapshot(serverId); + const connected = useHostRuntimeIsConnected(serverId); + const { canRemove, remove, removing } = useProviderConfigActions(serverId); + const presence = readDetailPresence({ provider, connected, entries, error, removing }); + const shown = presence.kind === "found" ? presence.entry : null; + const label = shown?.label ?? provider; + const handleRemove = useCallback(() => { + if (!shown) return; + void remove(shown, label).then((removed) => { + if (removed) onRemoved(); + return removed; + }); + }, [label, onRemoved, remove, shown]); + return { + provider, + label, + presence, + canRemove, + removing: removing?.provider === provider, + remove: handleRemove, + leave: onRemoved, + }; +} + +/** + * Everything about one provider, top to bottom: what is wrong, whether it runs, its installation, + * its models, then the rare actions. The page and the sheet frame the same body. + * + * Refresh sits with the model list, which is what it is most often pressed for. A provider that + * lists no models of its own keeps it under Troubleshooting. + */ +export function ProviderDetail({ + serverId, + detail, +}: { + serverId: string; + detail: ProviderDetailState; +}) { + const { provider, presence, label } = detail; + const { refresh, isRefreshing } = useProvidersSnapshot(serverId); + const installation = useProviderInstallation({ serverId, provider, visible: true }); + const refreshInstallation = installation.refresh; + const handleRefresh = useCallback(() => { + void refresh([provider]); + refreshInstallation(); + }, [provider, refresh, refreshInstallation]); + if (presence.kind !== "found") return ; + + const entry = presence.entry; + const shownInstallation = readShownInstallation({ + entry, + installation: installation.state, + installGuide: readAcpProviderInstallGuide(provider), + }); + const sections = readDetailSections(entry, shownInstallation); + const listsModels = sections.models === "all"; + const providerRefresh: ProviderRefresh = { + checkedAt: entry.fetchedAt, + // The probe running again is a refresh too, whoever asked for it. + busy: isRefreshing || installation.refreshing || entry.status === "loading", + run: handleRefresh, + }; + + return ( + + {sections.error !== null ? : null} + + + {sections.models ? ( + + ) : null} + + + {/* Config no longer owns a provider whose removal has succeeded. */} + {detail.removing || detail.canRemove(entry) ? ( + + ) : null} + + ); +} + +function AbsentProvider({ presence }: { presence: Exclude }) { + const { t } = useTranslation(); + const messages = { + loading: t("settings.providers.loading"), + missing: t("settings.providers.detail.notOnHost"), + offline: t("settings.providers.unavailable"), + }; + const message = presence.kind === "failed" ? presence.message : messages[presence.kind]; + return ; +} + +function ProviderErrorAlert({ label, error }: { label: string; error: string }) { + const { t } = useTranslation(); + return ( + + + + ); +} + +function EnabledCard({ serverId, entry }: { serverId: string; entry: ProviderEntry }) { + const { t } = useTranslation(); + const { setEnabled, togglingProviderId } = useProviderConfigActions(serverId); + const handleChange = useCallback( + (enabled: boolean) => setEnabled(entry.provider, enabled), + [entry.provider, setEnabled], + ); + return ( + + + + + + ); +} + +function Troubleshooting({ + serverId, + entry, + refresh, +}: { + serverId: string; + entry: ProviderEntry; + /** Null when the model list carries Refresh. */ + refresh: ProviderRefresh | null; +}) { + const { t } = useTranslation(); + const [diagnosticOpen, setDiagnosticOpen] = useState(false); + const openDiagnostic = useCallback(() => setDiagnosticOpen(true), []); + const closeDiagnostic = useCallback(() => setDiagnosticOpen(false), []); + const docsUrl = entry.docsUrl; + const openDocs = useCallback(() => { + if (docsUrl) void openExternalUrl(docsUrl); + }, [docsUrl]); + + return ( + + + {refresh ? : null} + + {docsUrl ? ( + + ) : null} + + + + ); +} + +function ProviderStatusRow({ refresh }: { refresh: ProviderRefresh }) { + const { t } = useTranslation(); + const checked = useCheckedLabel(refresh); + return ( + + + + ); +} + +function DangerZone({ removing, onRemove }: { removing: boolean; onRemove: () => void }) { + const { t } = useTranslation(); + return ( + + + + + + + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-glyph.tsx b/packages/app/src/provider-settings/internal/provider-glyph.tsx new file mode 100644 index 000000000000..92bfe99eb41c --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-glyph.tsx @@ -0,0 +1,21 @@ +import { StyleSheet } from "react-native-unistyles"; +import { useProviderIcon } from "@/components/provider-icons"; +import { ICON_SIZE } from "@/styles/theme"; + +/** A provider's icon in the foreground colour, at row size unless the caller names another. */ +export function ProviderGlyph({ + serverId, + provider, + size = ICON_SIZE.md, +}: { + serverId: string; + provider: string; + size?: number; +}) { + const Icon = useProviderIcon(provider, serverId); + return ; +} + +const styles = StyleSheet.create((theme) => ({ + glyph: { color: theme.colors.foreground }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-list.tsx b/packages/app/src/provider-settings/internal/provider-list.tsx new file mode 100644 index 000000000000..258d4c2c5061 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-list.tsx @@ -0,0 +1,222 @@ +import { Plus } from "lucide-react-native"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { useProviderInstallation } from "@/components/provider-installation"; +import { SettingsAddRow, SettingsCard, SettingsSection } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { + groupProviderAccounts, + resolveProviderAccountBaseId, +} from "@/provider-accounts/provider-account-form-model"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { settingsStyles } from "@/styles/settings"; +import { buildProviderDefinitions } from "@/utils/provider-definitions"; +import { AddProviderSheet } from "./add-provider-sheet"; +import { useProviderConfigActions, type ProviderEntry } from "./provider-config"; +import { ProviderGlyph } from "./provider-glyph"; +import { ProviderNotice } from "./provider-notice"; +import { ProviderRow } from "./provider-row"; +import { readRowSummary } from "./row-summary"; +import type { ProviderSheetFrame } from "./sheet-frame"; + +export interface ProviderListProps { + serverId: string; + /** Opens a provider's detail wherever the host shows it: a Settings page or a sheet. */ + onOpenProvider: (providerId: string) => void; + /** Where the sheets the list opens sit. Defaults to a sheet over the current screen. */ + sheetFrame?: ProviderSheetFrame; +} + +/** The host's providers, each saying how it is, and the way to add one. */ +export function ProviderList({ serverId, onOpenProvider, sheetFrame }: ProviderListProps) { + const { t } = useTranslation(); + const isConnected = useHostRuntimeIsConnected(serverId) && serverId.length > 0; + const { entries, isLoading } = useProvidersSnapshot(serverId); + const { setEnabled, togglingProviderId } = useProviderConfigActions(serverId); + const { config } = useDaemonConfig(serverId); + // Fork: a provider account sits under the builtin provider it extends. + const definitions = useMemo( + () => groupProviderAccounts(buildProviderDefinitions(entries), config?.providers), + [config?.providers, entries], + ); + const [adding, setAdding] = useState(false); + const openAdd = useCallback(() => setAdding(true), []); + const closeAdd = useCallback(() => setAdding(false), []); + const handleAdded = useCallback( + (providerId: string) => { + setAdding(false); + onOpenProvider(providerId); + }, + [onOpenProvider], + ); + + const addButton = useMemo( + () => + isConnected ? ( + + ) : null, + [isConnected, openAdd, t], + ); + + let body: React.ReactNode; + if (!isConnected) { + body = ; + } else if (isLoading) { + body = ; + } else { + body = ( + + {definitions.map((definition) => { + const entry = entries?.find((candidate) => candidate.provider === definition.id); + if (!entry) return null; + return ( + + ); + })} + + + ); + } + + return ( + <> + + {body} + + {isConnected ? ( + + ) : null} + + ); +} + +/** A row reads its provider's installation itself; the detail shares the same requests. */ +function ListedProvider({ + serverId, + entry, + label, + iconProvider, + toggling, + onOpen, + onToggle, +}: { + serverId: string; + entry: ProviderEntry; + label: string; + /** The provider whose icon the row shows; an account shows its base provider's. */ + iconProvider: string; + toggling: boolean; + onOpen: (provider: string) => void; + onToggle: (provider: string, enabled: boolean) => void; +}) { + const installation = useProviderInstallation({ + serverId, + provider: entry.provider, + visible: true, + }); + const icon = useMemo( + () => , + [iconProvider, serverId], + ); + return ( + + ); +} + +const SKELETON_ROW_KEYS = [0, 1, 2, 3].map((index) => `provider-skeleton-row-${index}`); + +function ProviderRowsSkeleton() { + const { t } = useTranslation(); + const pulse = useSkeletonPulse(); + return ( + + {SKELETON_ROW_KEYS.map((key, index) => ( + 0 && settingsStyles.rowBorder]}> + + + + + + + ))} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + skeletonContent: { + flex: 1, + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + }, + skeletonIcon: { + width: 16, + height: 16, + borderRadius: theme.borderRadius.md, + backgroundColor: theme.colors.surface2, + }, + skeletonTitle: { + width: 160, + height: 12, + borderRadius: theme.borderRadius.sm, + backgroundColor: theme.colors.surface2, + }, + skeletonSwitch: { + width: 36, + height: 20, + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.surface2, + }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-models.tsx b/packages/app/src/provider-settings/internal/provider-models.tsx new file mode 100644 index 000000000000..641d8220eac7 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-models.tsx @@ -0,0 +1,469 @@ +import { Plus, Trash2 } from "lucide-react-native"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { ScrollView, Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types"; +import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config"; +import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; +import { + AdaptiveModalSheet, + AdaptiveTextInput, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import { SettingsSection } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { SearchField } from "@/components/ui/search-field"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { isWeb } from "@/constants/platform"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { CODE_SURFACE_DATASET } from "@/styles/code-surface"; +import { settingsStyles } from "@/styles/settings"; +import type { Theme } from "@/styles/theme"; +import { + resolveProviderDiscoveredModels, + type ProviderDiscoveredModelsCache, +} from "./discovered-models"; +import type { ProviderEntry } from "./provider-config"; +import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh"; + +const ThemedTrash = withUnistyles(Trash2); +const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive }); +const ThemedTextInput = withUnistyles(AdaptiveTextInput, (theme: Theme) => ({ + placeholderTextColor: theme.colors.foregroundMuted, +})); + +function rankModels(items: T[], query: string, fields: (item: T) => string[]): T[] { + if (!query) return items; + const scored = items + .map((item) => ({ item, score: scoreTextFields(query, fields(item)) })) + .filter( + (entry): entry is { item: T; score: NonNullable } => entry.score !== null, + ); + scored.sort((a, b) => compareMatchScores(a.score, b.score)); + return scored.map((entry) => entry.item); +} + +/** + * A provider's models: search, the ones it reports, and the ones added by hand. The caller decides + * whether it appears and whether the provider's own models are listed. + */ +export function ProviderModels({ + serverId, + entry, + refresh, +}: { + serverId: string; + entry: ProviderEntry; + /** + * Lists the models the provider reports, with search and the way to ask for them again. Null for + * a provider that is not running, which reports none. + */ + refresh: ProviderRefresh | null; +}) { + const { t } = useTranslation(); + const provider = entry.provider; + const discovered = refresh !== null; + const { config, patchConfig } = useDaemonConfig(serverId); + const [query, setQuery] = useState(""); + const [addSheetOpen, setAddSheetOpen] = useState(false); + const [deletingModelId, setDeletingModelId] = useState(null); + + const additionalModels = useMemo( + () => config?.providers?.[provider]?.additionalModels ?? [], + [config?.providers, provider], + ); + const loading = entry.status === "loading"; + // A refresh briefly empties the snapshot's models; keep the last list on screen meanwhile. + const discoveredCacheRef = useRef(null); + const { models: discoveredModels, cache } = resolveProviderDiscoveredModels({ + serverId, + provider, + currentModels: entry.models, + providerSnapshotRefreshing: loading, + previousCache: discoveredCacheRef.current, + }); + discoveredCacheRef.current = cache; + + // Search shows only beside the provider's own models; a query typed then must not hide custom ones. + const q = discovered ? query.trim() : ""; + const filteredDiscovered = useMemo( + () => rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]), + [discoveredModels, q], + ); + const filteredCustom = useMemo( + () => rankModels(additionalModels, q, (m) => [m.label, m.id]), + [additionalModels, q], + ); + + const handleOpenAddSheet = useCallback(() => setAddSheetOpen(true), []); + const handleCloseAddSheet = useCallback(() => setAddSheetOpen(false), []); + const handleDeleteCustom = useCallback( + (modelId: string) => { + setDeletingModelId(modelId); + void patchConfig({ + providers: { + [provider]: { + additionalModels: additionalModels.filter((model) => model.id !== modelId), + }, + }, + }).finally(() => { + setDeletingModelId((current) => (current === modelId ? null : current)); + }); + }, + [additionalModels, patchConfig, provider], + ); + + const customTrailing = useMemo( + () => ( + + {additionalModels.length > 0 ? ( + {additionalModels.length} + ) : null} + + + + + + ); +} + +const ADD_SNAP_POINTS = ["40%"]; + +const styles = StyleSheet.create((theme) => ({ + // The search field sizes itself along a row. + searchRow: { + flexDirection: "row", + }, + // Nine rows and part of a tenth, so a longer list visibly continues. + discoveredList: { + maxHeight: 320, + }, + headerTrailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1], + }, + // The facts give way before the button does. + headerFacts: { + flexShrink: 1, + }, + modelRow: { + flexDirection: "row", + alignItems: "center", + paddingVertical: theme.spacing[2], + paddingHorizontal: theme.spacing[4], + gap: theme.spacing[3], + }, + modelTitle: { + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + flexShrink: 0, + }, + monoHint: { + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + color: theme.colors.foregroundMuted, + flexShrink: 0, + }, + descriptionInline: { + flex: 1, + fontSize: theme.fontSize.sm, + color: theme.colors.foregroundMuted, + }, + customModelText: { + flexShrink: 1, + minWidth: 0, + }, + modelRowFiller: { + flex: 1, + }, + formGroup: { + gap: theme.spacing[3], + }, + formLabel: { + fontSize: theme.fontSize.base, + fontWeight: theme.fontWeight.medium, + color: theme.colors.foreground, + }, + formInput: { + backgroundColor: theme.colors.surface2, + borderRadius: theme.borderRadius.lg, + paddingHorizontal: theme.spacing[4], + paddingVertical: theme.spacing[3], + color: theme.colors.foreground, + borderWidth: 1, + borderColor: theme.colors.border, + fontSize: theme.fontSize.base, + }, + errorText: { + fontSize: theme.fontSize.sm, + color: theme.colors.destructive, + }, + formActions: { + flexDirection: "row", + justifyContent: "flex-end", + gap: theme.spacing[2], + }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-notice.tsx b/packages/app/src/provider-settings/internal/provider-notice.tsx new file mode 100644 index 000000000000..62482bdd9075 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-notice.tsx @@ -0,0 +1,23 @@ +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { settingsStyles } from "@/styles/settings"; + +/** A card holding one muted line, where a provider list or page has nothing to show yet. */ +export function ProviderNotice({ message, testID }: { message: string; testID?: string }) { + return ( + + {message} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + card: { + padding: theme.spacing[4], + alignItems: "center", + }, + text: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-refresh.tsx b/packages/app/src/provider-settings/internal/provider-refresh.tsx new file mode 100644 index 000000000000..44dfc69818f4 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-refresh.tsx @@ -0,0 +1,55 @@ +import { RotateCw } from "lucide-react-native"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; +import { useTimeAgo } from "@/hooks/use-time-ago"; + +/** Asking the provider again for its status, version and models. */ +export interface ProviderRefresh { + /** When the provider last answered. Absent before its first answer. */ + checkedAt: string | undefined; + /** A check is running, whoever asked for it. */ + busy: boolean; + run: () => void; +} + +/** "Checked 5m ago", kept current, or nothing before the provider's first answer. */ +export function useCheckedLabel(refresh: ProviderRefresh): string | undefined { + const { t } = useTranslation(); + const time = useTimeAgo(refresh.checkedAt ? new Date(refresh.checkedAt) : null); + return refresh.checkedAt ? t("settings.providers.detail.checked", { time }) : undefined; +} + +export function ProviderRefreshButton({ + refresh, + form, +}: { + refresh: ProviderRefresh; + /** `icon` in a section header, `labelled` in a row. */ + form: "icon" | "labelled"; +}) { + const { t } = useTranslation(); + const label = refresh.busy + ? t("settings.providers.diagnostic.refreshing") + : t("settings.providers.diagnostic.refresh"); + if (form === "icon") + return ( + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-row.browser.test.tsx b/packages/app/src/provider-settings/internal/provider-row.browser.test.tsx new file mode 100644 index 000000000000..e8e9177410a5 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-row.browser.test.tsx @@ -0,0 +1,178 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { within } from "@testing-library/dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Text } from "react-native"; +import { i18n as testI18n } from "@/i18n/i18next"; +import { ProviderRow } from "./provider-row"; +import type { RowSummary } from "./row-summary"; + +// Load translations so rows expose their real accessible names and copy. +void testI18n; + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +const mounted: { root: Root; container: HTMLDivElement }[] = []; +afterEach(() => { + for (const entry of mounted.splice(0)) { + act(() => entry.root.unmount()); + entry.container.remove(); + } +}); + +const ICON = *; + +function mount(summary: RowSummary, options: { enabled?: boolean; label?: string } = {}) { + const onOpen = vi.fn(); + const onToggle = vi.fn(); + const label = options.label ?? "Claude"; + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + act(() => + root.render( + , + ), + ); + mounted.push({ root, container }); + const view = within(container); + return { + view, + onOpen, + onToggle, + row: () => view.getByTestId("provider-row-claude"), + opener: () => view.getByRole("button", { name: `${label} provider details` }), + toggle: () => view.queryByRole("switch", { name: `Enable ${label}` }), + }; +} + +function pressEnter(target: HTMLElement) { + target.focus(); + for (const type of ["keydown", "keyup"]) { + target.dispatchEvent( + new KeyboardEvent(type, { key: "Enter", bubbles: true, cancelable: true }), + ); + } +} + +function textOrder(row: HTMLElement, texts: string[]): number[] { + const content = row.textContent ?? ""; + return texts.map((text) => content.indexOf(text)); +} + +describe("provider row", () => { + it("names the provider with its label and says Disabled when it is off", () => { + const row = mount({ kind: "disabled" }, { enabled: false, label: "Codex" }); + expect(row.row().textContent).toContain("Codex"); + expect(row.view.getByText("Disabled")).toBeTruthy(); + expect(row.toggle()?.getAttribute("aria-checked")).toBe("false"); + }); + + it("composes the row as icon, label, version and models, then switch", () => { + const row = mount({ kind: "ready", version: "2.1.321", models: 3 }); + const element = row.row(); + expect(row.view.getByText("2.1.321 · 3 models")).toBeTruthy(); + const [icon, label, summary] = textOrder(element, ["*", "Claude", "2.1.321 · 3 models"]); + expect(icon).toBeLessThan(label); + expect(label).toBeLessThan(summary); + const toggle = row.toggle(); + expect(toggle).not.toBeNull(); + expect( + row.view.getByText("2.1.321 · 3 models").compareDocumentPosition(toggle as Node) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + }); + + it("asks its host to open the provider when the row is pressed", () => { + const row = mount({ kind: "disabled" }, { enabled: false }); + act(() => row.opener().click()); + expect(row.onOpen).toHaveBeenCalledWith("claude"); + }); + + it("keeps the switch out of the row's button, so Enter on the switch only toggles", () => { + const row = mount({ kind: "ready", version: null, models: 3 }); + const toggle = row.toggle() as HTMLElement; + expect(row.opener().contains(toggle)).toBe(false); + // Dispatched in one act, so the test ends before the Switch's animation runs a frame. + act(() => pressEnter(toggle)); + expect(row.onToggle).toHaveBeenCalledWith("claude", false); + expect(row.onOpen).not.toHaveBeenCalled(); + }); + + it("toggles the provider from the switch without opening it", () => { + const row = mount({ kind: "ready", version: null, models: 3 }); + act(() => row.toggle()?.click()); + expect(row.onToggle).toHaveBeenCalledWith("claude", false); + expect(row.onOpen).not.toHaveBeenCalled(); + }); + + it("leaves the state line readable to screen readers, and the name to the row's button", () => { + const row = mount({ kind: "failing", message: "opencode exited with code 1" }); + expect(row.view.getByText("opencode exited with code 1").closest("[aria-hidden]")).toBeNull(); + expect(row.view.getByText("Claude").closest("[aria-hidden]")).not.toBeNull(); + }); + + it("says an update is available after the version", () => { + const row = mount({ kind: "updateAvailable", version: "2.1.321" }); + expect(row.view.getByText("2.1.321 · Update available")).toBeTruthy(); + }); + + it("names the target while an update runs, or says Updating... without one", () => { + expect( + mount({ kind: "updating", target: "1.0.31" }).view.getByText("Updating to 1.0.31..."), + ).toBeTruthy(); + expect(mount({ kind: "updating", target: null }).view.getByText("Updating...")).toBeTruthy(); + }); + + it("shows the error in the hint", () => { + const row = mount({ kind: "failing", message: "opencode exited with code 1" }); + expect(row.view.getByText("opencode exited with code 1")).toBeTruthy(); + expect(row.toggle()).not.toBeNull(); + }); + + it("offers no switch on a provider that is not installed", () => { + const row = mount({ kind: "notInstalled" }); + expect(row.view.getByText("Not installed")).toBeTruthy(); + expect(row.toggle()).toBeNull(); + act(() => row.opener().click()); + expect(row.onOpen).toHaveBeenCalledWith("claude"); + }); + + it("keeps the row as tall while its line loads as once it has arrived", () => { + const pending = mount({ kind: "pending" }).row().getBoundingClientRect().height; + const ready = mount({ kind: "ready", version: "2.1.321", models: 3 }) + .row() + .getBoundingClientRect().height; + const updating = mount({ kind: "updating", target: "1.0.31" }) + .row() + .getBoundingClientRect().height; + const failing = mount({ kind: "failing", message: "boom" }) + .row() + .getBoundingClientRect().height; + expect(pending).toBe(ready); + expect(updating).toBe(ready); + expect(failing).toBe(ready); + }); + + it("keeps a long, multi-line error to the row's one line", () => { + const ready = mount({ kind: "ready", version: "2.1.321", models: 3 }) + .row() + .getBoundingClientRect().height; + const message = [ + "ACP agent process exited before initialization completed (exit code 1)", + "broken-acp: exited with code 1", + ].join("\n"); + const failing = mount({ kind: "failing", message }).row().getBoundingClientRect().height; + expect(failing).toBe(ready); + }); +}); diff --git a/packages/app/src/provider-settings/internal/provider-row.tsx b/packages/app/src/provider-settings/internal/provider-row.tsx new file mode 100644 index 000000000000..d69a22200d36 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-row.tsx @@ -0,0 +1,110 @@ +import type { TFunction } from "i18next"; +import { useCallback, useMemo, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { SettingsDetailRow, type SettingsRowHintStatus } from "@/components/settings"; +import { Switch } from "@/components/ui/switch"; +import { rowHasSwitch, type RowSummary } from "./row-summary"; + +export interface ProviderRowProps { + provider: string; + label: string; + icon: ReactNode; + summary: RowSummary; + enabled: boolean; + /** The Enabled switch is being saved. */ + toggling: boolean; + onOpen: (provider: string) => void; + onToggle: (provider: string, enabled: boolean) => void; +} + +/** + * One provider in the list: its icon and name, a line saying how it is, the Enabled switch when + * there is something to switch, and the chevron to its detail. + */ +export function ProviderRow({ + provider, + label, + icon, + summary, + enabled, + toggling, + onOpen, + onToggle, +}: ProviderRowProps) { + const { t } = useTranslation(); + const handleOpen = useCallback(() => onOpen(provider), [onOpen, provider]); + const handleToggle = useCallback( + (value: boolean) => onToggle(provider, value), + [onToggle, provider], + ); + const hint = describeRowSummary(summary, t); + const hasSwitch = rowHasSwitch(summary); + const toggle = useMemo( + () => + hasSwitch ? ( + + ) : null, + [enabled, handleToggle, hasSwitch, label, t, toggling], + ); + return ( + + ); +} + +function describeRowSummary( + summary: RowSummary, + t: TFunction, +): { text: string | undefined; status: SettingsRowHintStatus | undefined } { + switch (summary.kind) { + case "pending": + return { text: undefined, status: "pending" }; + case "ready": { + const models = + summary.models === 1 + ? t("settings.providers.models.one") + : t("settings.providers.models.many", { count: summary.models }); + const parts = [summary.version, summary.models > 0 ? models : null].filter(Boolean); + return { + text: parts.length ? parts.join(" · ") : t("settings.providers.statuses.available"), + status: undefined, + }; + } + case "updateAvailable": + return { + text: [summary.version, t("settings.providers.installation.updateAvailable")] + .filter(Boolean) + .join(" · "), + status: undefined, + }; + case "updating": + return { + text: summary.target + ? t("settings.providers.list.updatingTo", { version: summary.target }) + : t("settings.providers.installation.updating"), + status: "busy", + }; + case "failing": + return { + text: summary.message ?? t("settings.providers.diagnostic.unknownError"), + status: "error", + }; + case "notInstalled": + return { text: t("settings.providers.statuses.notInstalled"), status: undefined }; + case "disabled": + return { text: t("settings.providers.statuses.disabled"), status: undefined }; + } +} diff --git a/packages/app/src/provider-settings/internal/row-summary.test.ts b/packages/app/src/provider-settings/internal/row-summary.test.ts new file mode 100644 index 000000000000..ad46913f0aae --- /dev/null +++ b/packages/app/src/provider-settings/internal/row-summary.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderInstallationUpdate } from "@getpaseo/protocol/messages"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { ProviderInstallationRead } from "@/components/provider-installation"; +import { readRowSummary } from "./row-summary"; + +type Read = Pick; + +function entry(overrides: Partial = {}): ProviderSnapshotEntry { + return { + provider: "claude", + label: "Claude", + status: "ready", + enabled: true, + modes: [], + models: [ + { provider: "claude", id: "opus", label: "Opus" }, + { provider: "claude", id: "sonnet", label: "Sonnet" }, + ], + ...overrides, + }; +} + +function installed(version: string | undefined, overrides: Partial = {}): Read { + return { + state: { + status: "ready", + installation: { inspection: { status: "installed", version }, canUpdate: true }, + }, + updates: { status: "ready", updateCheck: { status: "current" } }, + action: { current: null, starting: false, startError: null, start: () => undefined }, + ...overrides, + }; +} + +function update(operation: ProviderInstallationUpdate["operation"]): ProviderInstallationUpdate { + return { operation, output: [] }; +} + +const oldHost: Read = { + state: { status: "unsupported" }, + updates: { status: "hidden" }, + action: undefined, +}; + +describe("provider row summary", () => { + it("reads version and model count for a provider that runs", () => { + expect(readRowSummary(entry(), installed("2.1.321"))).toEqual({ + kind: "ready", + version: "2.1.321", + models: 2, + }); + }); + + it("says an update is available after the version", () => { + const read = installed("2.1.321", { + updates: { status: "ready", updateCheck: { status: "available", versions: ["2.1.400"] } }, + }); + expect(readRowSummary(entry(), read)).toEqual({ kind: "updateAvailable", version: "2.1.321" }); + }); + + it("names the target version while an update runs, when the check reported one", () => { + const running = update({ status: "running", id: "u1", startedAt: "2026-11-14T10:00:00Z" }); + const one = installed("1.0.30", { + updates: { status: "ready", updateCheck: { status: "available", versions: ["1.0.31"] } }, + action: { current: running, starting: false, startError: null, start: () => undefined }, + }); + expect(readRowSummary(entry(), one)).toEqual({ kind: "updating", target: "1.0.31" }); + + const unknown = installed("1.0.30", { + updates: { status: "ready", updateCheck: { status: "available" } }, + action: { current: null, starting: true, startError: null, start: () => undefined }, + }); + expect(readRowSummary(entry(), unknown)).toEqual({ kind: "updating", target: null }); + }); + + it("reports a failed update as the fault", () => { + const failed = update({ + status: "failed", + id: "u1", + startedAt: "2026-11-14T10:00:00Z", + finishedAt: "2026-11-14T10:01:00Z", + message: "npm exited with code 1", + }); + const read = installed("1.0.30", { + action: { current: failed, starting: false, startError: null, start: () => undefined }, + }); + expect(readRowSummary(entry(), read)).toEqual({ + kind: "failing", + message: "npm exited with code 1", + }); + }); + + it("reads the provider's own state once Refresh drops a failed update", () => { + const failed = update({ + status: "failed", + id: "u1", + startedAt: "2026-11-14T10:00:00Z", + finishedAt: "2026-11-14T10:01:00Z", + message: "npm exited with code 1", + }); + const stillFailed = { current: failed, starting: false, startError: null, start: () => {} }; + // A fresh inspection alone leaves the failure: reopening without Refresh still shows it. + expect(readRowSummary(entry(), installed("2.1.400", { action: stillFailed }))).toEqual({ + kind: "failing", + message: "npm exited with code 1", + }); + + // Refresh drops the failed update, so the row has no current update to report. + const cleared = { current: null, starting: false, startError: null, start: () => {} }; + expect(readRowSummary(entry(), installed("2.1.400", { action: cleared }))).toEqual({ + kind: "ready", + version: "2.1.400", + models: 2, + }); + const pending = installed("2.1.321", { + updates: { status: "ready", updateCheck: { status: "available", versions: ["2.1.400"] } }, + action: cleared, + }); + expect(readRowSummary(entry(), pending)).toEqual({ + kind: "updateAvailable", + version: "2.1.321", + }); + }); + + it("reports the provider's error", () => { + expect( + readRowSummary(entry({ status: "error", error: " opencode exited with code 1 " }), oldHost), + ).toEqual({ kind: "failing", message: "opencode exited with code 1" }); + expect(readRowSummary(entry({ status: "error" }), oldHost)).toEqual({ + kind: "failing", + message: null, + }); + }); + + it("calls a missing CLI Not installed, not a fault", () => { + expect(readRowSummary(entry({ status: "unavailable" }), oldHost)).toEqual({ + kind: "notInstalled", + }); + const missing: Read = { + ...oldHost, + state: { status: "ready", installation: { inspection: { status: "not_installed" } } }, + }; + expect(readRowSummary(entry({ status: "error", error: "spawn ENOENT" }), missing)).toEqual({ + kind: "notInstalled", + }); + }); + + it("says Disabled for a provider that is off", () => { + expect(readRowSummary(entry({ enabled: false }), installed("2.1.321"))).toEqual({ + kind: "disabled", + }); + }); + + it("calls a disabled provider whose CLI is missing Not installed, so turning it on changes nothing", () => { + const missing: Read = { + ...oldHost, + state: { status: "ready", installation: { inspection: { status: "not_installed" } } }, + }; + expect(readRowSummary(entry({ enabled: false, status: "unavailable" }), missing)).toEqual({ + kind: "notInstalled", + }); + // A disabled provider is never probed, so without an inspection it is only Disabled. + expect(readRowSummary(entry({ enabled: false, status: "unavailable" }), oldHost)).toEqual({ + kind: "disabled", + }); + }); + + it("holds the line until the installation is read", () => { + const reading: Read = { ...oldHost, state: { status: "loading" } }; + expect(readRowSummary(entry(), reading)).toEqual({ kind: "pending" }); + }); + + it("holds the line while the provider's first probe runs", () => { + expect(readRowSummary(entry({ status: "loading", models: [] }), oldHost)).toEqual({ + kind: "pending", + }); + }); + + it("keeps the last count while the provider is probed again", () => { + expect(readRowSummary(entry({ status: "loading" }), installed("2.1.321"))).toEqual({ + kind: "ready", + version: "2.1.321", + models: 2, + }); + }); + + it("reads a count alone on hosts that cannot report installations", () => { + expect(readRowSummary(entry(), oldHost)).toEqual({ kind: "ready", version: null, models: 2 }); + }); +}); diff --git a/packages/app/src/provider-settings/internal/row-summary.ts b/packages/app/src/provider-settings/internal/row-summary.ts new file mode 100644 index 000000000000..4198eb4232f7 --- /dev/null +++ b/packages/app/src/provider-settings/internal/row-summary.ts @@ -0,0 +1,69 @@ +import type { ProviderInstallationRead } from "@/components/provider-installation"; +import { filterSelectableModels } from "@/provider-selection/model-catalog"; +import type { ProviderEntry } from "./provider-config"; + +/** What a provider's list row says under its name. */ +export type RowSummary = + /** Not known yet; the row holds the line's space. */ + | { kind: "pending" } + | { kind: "ready"; version: string | null; models: number } + | { kind: "updateAvailable"; version: string | null } + | { kind: "updating"; target: string | null } + /** The provider or its last update failed. A null message has no detail to show. */ + | { kind: "failing"; message: string | null } + | { kind: "notInstalled" } + | { kind: "disabled" }; + +type InstallationFacts = Pick; + +/** + * One line per provider, from the snapshot and the installation read. A running update leads + * because the user just started it; then whatever keeps the provider from running, where a missing + * CLI is not a fault; then the version and update state once the host has answered. + */ +export function readRowSummary(entry: ProviderEntry, facts: InstallationFacts): RowSummary { + return readRunningUpdate(facts) ?? readBlocker(entry, facts) ?? readSettled(entry, facts); +} + +function readRunningUpdate({ updates, action }: InstallationFacts): RowSummary | null { + if (!action || !(action.starting || action.current?.operation.status === "running")) return null; + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + const versions = updateCheck?.status === "available" ? updateCheck.versions : undefined; + return { kind: "updating", target: versions?.length === 1 ? versions[0] : null }; +} + +function readBlocker( + entry: ProviderEntry, + { state, action }: InstallationFacts, +): RowSummary | null { + // A missing CLI wins over Disabled, so the row offers no switch that turning on would take away. + // Without an inspection a disabled provider is only Disabled: the host never probes it. + const inspection = state.status === "ready" ? state.installation?.inspection : undefined; + if (inspection?.status === "not_installed") return { kind: "notInstalled" }; + if (!entry.enabled) return { kind: "disabled" }; + if (entry.status === "unavailable") return { kind: "notInstalled" }; + if (entry.status === "error") return { kind: "failing", message: entry.error?.trim() || null }; + const operation = action?.current?.operation; + if (operation?.status === "failed") { + return { kind: "failing", message: operation.message.trim() || null }; + } + return null; +} + +function readSettled(entry: ProviderEntry, { state, updates }: InstallationFacts): RowSummary { + const models = filterSelectableModels(entry.models ?? null)?.length ?? 0; + // The last count stays while the provider is probed again; only a first probe holds the line. + if (state.status === "loading" || (entry.status === "loading" && models === 0)) { + return { kind: "pending" }; + } + const inspection = state.status === "ready" ? state.installation?.inspection : undefined; + const version = inspection?.status === "installed" ? (inspection.version ?? null) : null; + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + if (updateCheck?.status === "available") return { kind: "updateAvailable", version }; + return { kind: "ready", version, models }; +} + +/** A provider that is not installed has nothing to switch: the picker leaves it out already. */ +export function rowHasSwitch(summary: RowSummary): boolean { + return summary.kind !== "notInstalled"; +} diff --git a/packages/app/src/provider-settings/internal/sheet-frame.ts b/packages/app/src/provider-settings/internal/sheet-frame.ts new file mode 100644 index 000000000000..c41cb5261cb6 --- /dev/null +++ b/packages/app/src/provider-settings/internal/sheet-frame.ts @@ -0,0 +1,15 @@ +import type { DimensionValue } from "react-native"; + +/** + * Where a provider sheet sits, decided by the surface that opens it. Setup passes its own card's + * size so the sheet covers the card exactly and reads as a page of setup. + */ +export interface ProviderSheetFrame { + desktopMaxWidth?: number; + desktopHeight?: DimensionValue; + snapPoints?: string[]; + /** A back arrow replaces the close button: the sheet stands in for a page of the surface below. */ + returns?: boolean; +} + +export const OVERLAY_SHEET_FRAME: ProviderSheetFrame = { snapPoints: ["65%", "92%"] }; diff --git a/packages/app/src/runtime/directory-sync/index.test.ts b/packages/app/src/runtime/directory-sync/index.test.ts index e4db5dfb7106..61b15ad5ec62 100644 --- a/packages/app/src/runtime/directory-sync/index.test.ts +++ b/packages/app/src/runtime/directory-sync/index.test.ts @@ -10,7 +10,10 @@ import type { DaemonClient, WorkspaceLabelListPayload, } from "@getpaseo/client/internal/daemon-client"; -import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; +import type { + SessionOutboundMessage, + WorkspaceDescriptorPayload, +} from "@getpaseo/protocol/messages"; import { normalizeProjectDescriptor, normalizeWorkspaceDescriptor, @@ -1667,6 +1670,187 @@ it("fills every cached workspace beneath live updates received during the SQLite database.close(); }); +/** + * A host whose cache was damaged before the eviction fix: workspaces survived, project rows did not, + * and a version 1 checkpoint still claims the project directory is current. The daemon holds + * projects A and B; renaming A is its update at `renameSeq`. + */ +async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq: number) { + serverIds.add(serverId); + const { cache, database, storage, reopen, holdRead } = createSqliteCache(); + cache.setHosts([serverId]); + const workspacePayload = (id: string, projectId: string): WorkspaceDescriptorPayload => ({ + id, + projectId, + projectDisplayName: projectId, + projectRootPath: `/repo/${projectId}`, + workspaceDirectory: `/repo/${projectId}`, + projectKind: "git", + workspaceKind: "local_checkout", + name: id, + status: "done", + statusEnteredAt: null, + activityAt: null, + archivingAt: null, + diffStat: null, + scripts: [], + }); + const project = (projectId: string, projectDisplayName: string) => ({ + projectId, + projectDisplayName, + projectRootPath: `/repo/${projectId}`, + projectKind: "git" as const, + }); + const workspaceEntries = [workspacePayload("wa", "A"), workspacePayload("wb", "B")]; + cache.replaceDirectoryBaseline(serverId, { + agents: new Map(), + workspaces: new Map( + workspaceEntries.map((entry) => [entry.id, normalizeWorkspaceDescriptor(entry)]), + ), + projects: new Map(), + }); + await cache.flush(); + await storage.apply({ + deletes: [], + upserts: [ + { + serverId, + kind: "checkpoint", + id: "singleton", + payload: JSON.stringify({ + version: 1, + cursors: { projects: { generation: "g", afterSeq: renameSeq - 1 } }, + }), + }, + ], + }); + const reopened = reopen(); + reopened.setHosts([serverId]); + const client = new FakeDirectoryClient(); + let failNextProjectRequest = false; + client.listProjects = async (options?: unknown): Promise => { + client.lastProjectOptions = options; + if (failNextProjectRequest) { + failNextProjectRequest = false; + throw new Error("Request timed out"); + } + const resumesAfterRename = + (options as { sync?: { afterSeq?: number } } | undefined)?.sync?.afterSeq === renameSeq; + return resumesAfterRename + ? { + requestId: "projects", + projects: [], + sync: { generation: "g", headSeq: renameSeq, mode: "changes", removals: [] }, + } + : { + requestId: "projects", + projects: [project("A", "Renamed"), project("B", "B")], + sync: { generation: "g", headSeq: renameSeq, mode: "snapshot", removals: [] }, + }; + }; + client.fetchWorkspaces = async (): Promise => ({ + requestId: "workspaces", + entries: workspaceEntries, + emptyProjects: [], + pageInfo: { hasMore: false, nextCursor: null, prevCursor: null }, + sync: { generation: "g", headSeq: 2, mode: "snapshot", removals: [] }, + }); + const directory = new DirectorySync( + serverId, + { + onAgentStoppedRunning: () => {}, + markAgentLoading: () => {}, + markAgentReady: () => {}, + markAgentError: () => {}, + }, + reopened, + ); + const store = useSessionStore.getState(); + store.initializeSession(serverId, client as unknown as DaemonClient, 1); + store.updateSessionServerInfo(serverId, { + serverId, + hostname: null, + version: "test", + features: { workspaceMultiplicity: true, directorySync: true, projectList: true }, + }); + directory.connectionChanged({ + client: client as unknown as DaemonClient, + status: "online", + source: { clientGeneration: 1, connectionEpoch: 1 }, + }); + return { + client, + directory, + holdRead, + failNextProjectRequest: () => { + failNextProjectRequest = true; + }, + renameProjectA: () => + client.emit({ + type: "project.update", + payload: { + kind: "upsert", + project: project("A", "Renamed"), + generation: "g", + seq: renameSeq, + }, + }), + sessionProjectIds: () => + [...useSessionStore.getState().sessions[serverId].projects.keys()].sort(), + persistedProjectIds: async () => { + await reopened.flush(); + const restarted = reopen(); + restarted.setHosts([serverId]); + return [...(await restarted.readDirectory(serverId)).projects.keys()].sort(); + }, + close: async () => { + directory.dispose(); + await reopened.flush(); + database.close(); + }, + }; +} + +it("re-syncs every project when a project update lands while an untrusted cache loads", async () => { + const damaged = await createDamagedLegacyProjectDirectory("untrusted-checkpoint-race", 6); + try { + let renamed = false; + damaged.holdRead(async () => { + if (renamed) return; + renamed = true; + damaged.renameProjectA(); + }); + + damaged.directory.setDemand({}, true); + await damaged.directory.refreshDemand(); + + expect(renamed).toBe(true); + expect(damaged.client.lastProjectOptions).toEqual({ sync: {} }); + expect(damaged.sessionProjectIds()).toEqual(["A", "B"]); + expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]); + } finally { + await damaged.close(); + } +}); + +it("re-syncs every project when a project update lands after the first sync fails", async () => { + const damaged = await createDamagedLegacyProjectDirectory("failed-first-sync", 3); + try { + damaged.failNextProjectRequest(); + damaged.directory.setDemand({}, true); + await expect(damaged.directory.refreshDemand()).rejects.toThrow("Request timed out"); + + damaged.renameProjectA(); + await damaged.directory.refreshDemand(); + + expect(damaged.client.lastProjectOptions).toEqual({ sync: {} }); + expect(damaged.sessionProjectIds()).toEqual(["A", "B"]); + expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]); + } finally { + await damaged.close(); + } +}); + function createWorkspaceLabelDirectory(serverId: string) { const { client, directory } = createDirectory(serverId, { workspaceLabels: true }); const store = useSessionStore.getState(); diff --git a/packages/app/src/runtime/directory-sync/index.ts b/packages/app/src/runtime/directory-sync/index.ts index 0f539a2b1de0..b9114deb21c9 100644 --- a/packages/app/src/runtime/directory-sync/index.ts +++ b/packages/app/src/runtime/directory-sync/index.ts @@ -288,7 +288,7 @@ export class DirectorySync { this.revision += 1; if (this.agentTransactions.record(source, delta)) return; this.agents.applyDelta(delta); - this.noteLiveCursor("agents", delta); + if (this.extendsRefreshedBaseline(source)) this.noteLiveCursor("agents", delta); this.persistCheckpoint(); } @@ -300,7 +300,7 @@ export class DirectorySync { this.workspaceRevision += 1; if (this.workspaceTransactions.record(source, delta)) return; this.applyWorkspaceDelta(delta); - if (delta.kind !== "script_status") + if (delta.kind !== "script_status" && this.extendsRefreshedBaseline(source)) this.noteLiveCursor( "projectId" in delta || "project" in delta ? "projects" : "workspaces", delta, @@ -308,6 +308,20 @@ export class DirectorySync { this.persistCheckpoint(); } + /** + * A live event's sequence covers everything before it only when a refresh completed on the + * subscriptions that delivered it. Before that (first sync still pending or failed) or after + * they lapse, the client may have missed earlier changes, so the event updates rows but leaves + * the cursor where the next refresh can still fetch what was missed. + */ + private extendsRefreshedBaseline(source: DirectorySourceToken): boolean { + const refreshed = this.satisfiedDemandSource; + return ( + refreshed?.clientGeneration === source.clientGeneration && + refreshed.connectionEpoch === source.connectionEpoch + ); + } + private observeDirectoryEvents(): void { if (this.eventSubscription) return; const { client, source } = this.requireOnline(); @@ -566,24 +580,16 @@ export class DirectorySync { input: { subscribe?: boolean } | undefined, loadDirectoryCache: boolean, ): Promise { - if (loadDirectoryCache) await this.loadCachedDirectory(); + if (loadDirectoryCache) { + this.primeWorkspaceTransactionForCacheLoad(); + await this.loadCachedDirectory(); + } const onlineConnection = this.getOnlineConnection(); if (!onlineConnection) return; const { client, source } = onlineConnection; - const transaction = this.workspaceTransactions.begin(source, () => { - const baseline = this.workspaces.snapshot(); - return { - workspaces: new Map(baseline.workspaces), - projects: new Map(baseline.projects), - // Cache hydration can advance the live replica while these requests await responses. - // Every page must use the cursors belonging to the maps captured here. - requestCursors: { ...this.cursors }, - syncCursors: {}, - syncModes: {}, - touchedWorkspaceIds: new Set(), - touchedProjectIds: new Set(), - }; - }); + const transaction = this.workspaceTransactions.begin(source, () => + this.createWorkspaceRefreshSnapshot(), + ); try { await this.waitForSessionMetadata(client, source); const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo; @@ -807,6 +813,31 @@ export class DirectorySync { })); } + // Updates that arrive before a refresh completes have no trusted baseline to advance from. + // Holding them keeps their cursor out of the cache until the refresh they are applied over. + private primeWorkspaceTransactionForCacheLoad(): void { + const connection = this.getOnlineConnection(); + if (!connection) return; + this.workspaceTransactions.begin(connection.source, () => + this.createWorkspaceRefreshSnapshot(), + ); + } + + private createWorkspaceRefreshSnapshot(): WorkspaceRefreshSnapshot { + const baseline = this.workspaces.snapshot(); + return { + workspaces: new Map(baseline.workspaces), + projects: new Map(baseline.projects), + // Cache hydration can advance the live replica while these requests await responses. + // Every page must use the cursors belonging to the maps captured here. + requestCursors: { ...this.cursors }, + syncCursors: {}, + syncModes: {}, + touchedWorkspaceIds: new Set(), + touchedProjectIds: new Set(), + }; + } + private supportsDirectorySync(): boolean { return ( useSessionStore.getState().sessions[this.serverId]?.serverInfo?.features?.directorySync === diff --git a/packages/app/src/runtime/host-runtime.test.ts b/packages/app/src/runtime/host-runtime.test.ts index 69210defb670..55c7479d087c 100644 --- a/packages/app/src/runtime/host-runtime.test.ts +++ b/packages/app/src/runtime/host-runtime.test.ts @@ -21,6 +21,7 @@ import { useSessionStore, type Agent } from "@/stores/session-store"; import { normalizeAgentSnapshot } from "@/utils/agent-snapshots"; import { isAgentArchiving, setAgentArchiving } from "@/hooks/use-archive-agent"; import { queryClient } from "@/data/query-client"; +import { checkoutStatusQueryKey } from "@/git/query-keys"; import { HostRuntimeController, HostRuntimeStore, @@ -1748,7 +1749,7 @@ describe("HostRuntimeController", () => { }); latencies["relay:relay.paseo.sh:443"] = 30; - await vi.advanceTimersByTimeAsync(120_000); + await vi.advanceTimersByTimeAsync(240_000); await controller.runProbeCycleNow(); expect(controller.getSnapshot().activeConnectionId).toBe("direct:lan:6767"); @@ -1807,6 +1808,429 @@ describe("HostRuntimeController", () => { await controller.stop(); }); + it("ignores busy active heartbeat spikes when comparing against an idle alternate probe", async () => { + // Replays the recorded 10:04-10:08 relay sequence (#9149): the active relay has a ~250-300 ms + // baseline over its recent heartbeats, spikes to 383/503/491 ms right before each alternate + // probe, and the idle alternate measures 236/322/291 ms. + useHostRuntimeClock(); + const host = makeHost({ + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + let alternateProbes = 0; + const latencies: Record = { + [relayPrimary.id]: 260, + [relayAlternate.id]: 280, + }; + const baseDeps = makeDeps(latencies, clients); + const controller = new HostRuntimeController({ + host, + deps: { + ...baseDeps, + connectToDaemon: async (input) => { + if (input.connection.id === relayAlternate.id) { + alternateProbes += 1; + } + return baseDeps.connectToDaemon(input); + }, + }, + }); + + await controller.start({ autoProbe: false }); + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient; + + const rounds = [ + { intervalMs: 120_000, baseline: 295, spike: 383, alternate: 236 }, + { intervalMs: 240_000, baseline: 251, spike: 503, alternate: 322 }, + { intervalMs: 480_000, baseline: 341, spike: 491, alternate: 291 }, + ]; + for (const round of rounds) { + await vi.advanceTimersByTimeAsync(round.intervalMs - 10_000); + activeClient.heartbeatReportsRtt(round.baseline); + await controller.runProbeCycleNow(); + await vi.advanceTimersByTimeAsync(10_000); + activeClient.heartbeatReportsRtt(round.spike); + latencies[relayAlternate.id] = round.alternate; + await controller.runProbeCycleNow(); + } + + expect(alternateProbes).toBe(4); + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + expect(controller.getSnapshot().client).toBe(activeClient); + expect(activeClient.isDisposed()).toBe(false); + await controller.stop(); + }); + + it("requires a proportional RTT improvement before switching away from a high-latency link", async () => { + useHostRuntimeClock(); + const host = makeHost({ + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + const latencies: Record = { + [relayPrimary.id]: 300, + [relayAlternate.id]: 320, + }; + const controller = new HostRuntimeController({ + host, + deps: makeDeps(latencies, clients), + }); + + await controller.start({ autoProbe: false }); + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient; + + // 60 ms faster on a 300 ms link (20%) is noise, not enough to justify a switch. + activeClient.heartbeatReportsRtt(300); + latencies[relayAlternate.id] = 240; + for (let index = 0; index < 3; index += 1) { + await vi.advanceTimersByTimeAsync(30 * 60_000); + await controller.runProbeCycleNow(); + } + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + + // 150 ms faster on a 300 ms link (50%) is a real win and switches after 3 consecutive probes. + latencies[relayAlternate.id] = 150; + for (let index = 0; index < 3; index += 1) { + await vi.advanceTimersByTimeAsync(index === 0 ? 30 * 60_000 : 120_000); + await controller.runProbeCycleNow(); + } + expect(controller.getSnapshot().activeConnectionId).toBe(relayAlternate.id); + await controller.stop(); + }); + + it("exponentially backs off inactive connection probes while the active connection keeps winning", async () => { + useHostRuntimeClock(); + const host = makeHost({ + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + let alternateProbes = 0; + const baseDeps = makeDeps( + { + [relayPrimary.id]: 250, + [relayAlternate.id]: 260, + }, + clients, + ); + const controller = new HostRuntimeController({ + host, + deps: { + ...baseDeps, + connectToDaemon: async (input) => { + if (input.connection.id === relayAlternate.id) { + alternateProbes += 1; + } + return baseDeps.connectToDaemon(input); + }, + }, + }); + + await controller.start({ autoProbe: false }); + const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient; + activeClient.heartbeatReportsRtt(250); + expect(alternateProbes).toBe(1); + + // First inactive online probe runs at 2m -> active wins, next interval backs off to 4m. + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + expect(alternateProbes).toBe(2); + + // At +2m (still < 4m), no inactive probe runs. + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + expect(alternateProbes).toBe(2); + + // At +4m total, second inactive probe runs -> backs off to 8m. + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + expect(alternateProbes).toBe(3); + + // At +6m (< 8m), still quiet; at +8m, third inactive probe runs -> backs off to 16m. + await vi.advanceTimersByTimeAsync(6 * 60_000); + await controller.runProbeCycleNow(); + expect(alternateProbes).toBe(3); + await vi.advanceTimersByTimeAsync(2 * 60_000); + await controller.runProbeCycleNow(); + expect(alternateProbes).toBe(4); + + // Foreground verification resets backoff back to 2m without forcing an immediate probe. + await vi.advanceTimersByTimeAsync(3 * 60_000); + controller.ensureConnected({ verify: true }); + await controller.runProbeCycleNow(); + expect(alternateProbes).toBe(5); + await controller.stop(); + }); + + it("keeps the active connection online while connecting the replacement during an adaptive switch", async () => { + useHostRuntimeClock(); + const host = makeHost({ + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + const latencies: Record = { + [relayPrimary.id]: 300, + [relayAlternate.id]: 320, + }; + let replacementConnectGate: ReturnType> | null = null; + let shouldFailReplacement = false; + const baseDeps = makeDeps(latencies, clients); + const controller = new HostRuntimeController({ + host, + deps: { + ...baseDeps, + createClient: (input) => { + const client = baseDeps.createClient(input) as unknown as FakeDaemonClient; + if (input.connection.id === relayAlternate.id) { + const origConnect = client.connect.bind(client); + client.connect = async () => { + if (replacementConnectGate) { + await replacementConnectGate.promise; + } + if (shouldFailReplacement) { + throw new Error("replacement handshake failed"); + } + return origConnect(); + }; + } + return client as unknown as DaemonClient; + }, + }, + }); + + await controller.start({ autoProbe: false }); + const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient; + initialClient.heartbeatReportsRtt(300); + latencies[relayAlternate.id] = 100; + + const observedSnapshots: Array<{ + status: string; + connectionId: string | null; + hasClient: boolean; + }> = []; + const unsubscribe = controller.subscribe(() => { + const snap = controller.getSnapshot(); + observedSnapshots.push({ + status: snap.connectionStatus, + connectionId: snap.activeConnectionId, + hasClient: snap.client !== null, + }); + }); + + // Two wins first. + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + + // Third win triggers a switch, but replacement connect fails: active client must stay online. + shouldFailReplacement = true; + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + expect(controller.getSnapshot().client).toBe(initialClient); + expect(initialClient.isDisposed()).toBe(false); + + // Now let replacement succeed after a delay: host must stay online on initialClient while + // replacement connects, and never emit connecting or client=null. + shouldFailReplacement = false; + observedSnapshots.length = 0; + for (let index = 0; index < 2; index += 1) { + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + } + replacementConnectGate = createDeferred(); + await vi.advanceTimersByTimeAsync(120_000); + const switchingCycle = controller.runProbeCycleNow(); + await vi.advanceTimersByTimeAsync(0); + + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + expect(controller.getSnapshot().client).toBe(initialClient); + expect(initialClient.isDisposed()).toBe(false); + + replacementConnectGate.resolve(); + await switchingCycle; + + expect(controller.getSnapshot().activeConnectionId).toBe(relayAlternate.id); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + expect(controller.getSnapshot().client).not.toBeNull(); + expect(controller.getSnapshot().client).not.toBe(initialClient); + expect(initialClient.isDisposed()).toBe(true); + expect(observedSnapshots.some((snap) => snap.status !== "online" || !snap.hasClient)).toBe( + false, + ); + + unsubscribe(); + await controller.stop(); + }); + + it("keeps active client status updates working after a failed make-before-break upgrade", async () => { + useHostRuntimeClock(); + const host = makeHost({ + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + const latencies: Record = { + [relayPrimary.id]: 300, + [relayAlternate.id]: 320, + }; + const baseDeps = makeDeps(latencies, clients); + const controller = new HostRuntimeController({ + host, + deps: { + ...baseDeps, + createClient: (input) => { + const client = baseDeps.createClient(input) as unknown as FakeDaemonClient; + if (input.connection.id === relayAlternate.id) { + client.connect = async () => { + throw new Error("replacement handshake failed"); + }; + } + return client as unknown as DaemonClient; + }, + }, + }); + + await controller.start({ autoProbe: false }); + const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient; + initialClient.heartbeatReportsRtt(300); + latencies[relayAlternate.id] = 100; + + for (let index = 0; index < 3; index += 1) { + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + } + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + + initialClient.setConnectionState({ status: "disconnected", reason: "transport closed" }); + expect(controller.getSnapshot().connectionStatus).toBe("error"); + expect(controller.getSnapshot().lastError).toBe("transport closed"); + await controller.stop(); + }); + + it("aborts a pending make-before-break upgrade when the candidate connection is removed", async () => { + useHostRuntimeClock(); + const host = makeHost({ + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + const latencies: Record = { + [relayPrimary.id]: 300, + [relayAlternate.id]: 320, + }; + const replacementGate = createDeferred(); + const replacementClients: FakeDaemonClient[] = []; + const baseDeps = makeDeps(latencies, clients); + const controller = new HostRuntimeController({ + host, + deps: { + ...baseDeps, + createClient: (input) => { + const client = baseDeps.createClient(input) as unknown as FakeDaemonClient; + if (input.connection.id === relayAlternate.id) { + replacementClients.push(client); + const origConnect = client.connect.bind(client); + client.connect = async () => { + await replacementGate.promise; + return origConnect(); + }; + } + return client as unknown as DaemonClient; + }, + }, + }); + + await controller.start({ autoProbe: false }); + const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient; + initialClient.heartbeatReportsRtt(300); + latencies[relayAlternate.id] = 100; + + for (let index = 0; index < 2; index += 1) { + await vi.advanceTimersByTimeAsync(120_000); + await controller.runProbeCycleNow(); + } + + await vi.advanceTimersByTimeAsync(120_000); + const switchingCycle = controller.runProbeCycleNow(); + await vi.advanceTimersByTimeAsync(0); + expect(replacementClients).toHaveLength(1); + + const updatePromise = controller.updateHost({ + ...host, + connections: [relayPrimary], + }); + await vi.advanceTimersByTimeAsync(0); + replacementGate.resolve(); + await Promise.all([switchingCycle, updatePromise]); + + expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + expect(controller.getSnapshot().client).toBe(initialClient); + expect(initialClient.isDisposed()).toBe(false); + expect(replacementClients[0]?.isDisposed()).toBe(true); + await controller.stop(); + }); + + it("runs store cache recovery when a make-before-break adaptive switch advances the online epoch", async () => { + useHostRuntimeClock(); + const host = makeHost({ + serverId: "srv_upgrade_cache_recovery", + connections: [relayPrimary, relayAlternate], + preferredConnectionId: relayPrimary.id, + }); + const clients: FakeDaemonClient[] = []; + const latencies: Record = { + [relayPrimary.id]: 300, + [relayAlternate.id]: 320, + }; + const store = new HostRuntimeStore({ + storage: createMemoryHostRuntimeStorage(), + deps: makeDeps(latencies, clients), + }); + const queryKey = checkoutStatusQueryKey(host.serverId, "/repo"); + + try { + store.syncHosts([host]); + await vi.advanceTimersByTimeAsync(0); + expect(store.getSnapshot(host.serverId)?.connectionStatus).toBe("online"); + const initialEpoch = store.getSnapshot(host.serverId)?.connectionEpoch ?? 0; + const activeClient = store.getSnapshot(host.serverId)?.client as unknown as FakeDaemonClient; + const initialHistoryGen = + useSessionStore.getState().sessions[host.serverId]?.historySyncGeneration ?? 0; + + queryClient.setQueryData(queryKey, { branch: "main" }); + expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false); + + activeClient.heartbeatReportsRtt(300); + latencies[relayAlternate.id] = 100; + for (let index = 0; index < 3; index += 1) { + await vi.advanceTimersByTimeAsync(120_000); + await store.runProbeCycleNow(host.serverId); + } + + expect(store.getSnapshot(host.serverId)?.activeConnectionId).toBe(relayAlternate.id); + expect(store.getSnapshot(host.serverId)?.connectionStatus).toBe("online"); + expect(store.getSnapshot(host.serverId)?.connectionEpoch).toBeGreaterThan(initialEpoch); + expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true); + expect( + useSessionStore.getState().sessions[host.serverId]?.historySyncGeneration ?? 0, + ).toBeGreaterThan(initialHistoryGen); + } finally { + queryClient.removeQueries({ queryKey }); + store.syncHosts([]); + } + }); + it("exposes one snapshot with active connection and status from same source", async () => { const host = makeHost(); const clients: FakeDaemonClient[] = []; diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index 7788094ee919..f35cd90cf4f8 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -245,8 +245,11 @@ export interface HostRuntimeStartOptions { const PROBE_TICK_MS = 2_000; const PROBE_STEADY_MS = 10_000; const PROBE_MAX_BACKOFF_MS = 30_000; -const PROBE_INACTIVE_WHILE_ONLINE_MS = 120_000; +const PROBE_INACTIVE_WHILE_ONLINE_INITIAL_MS = 120_000; +const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000; +const ACTIVE_RTT_WINDOW_MS = 60_000; const ADAPTIVE_SWITCH_THRESHOLD_MS = 40; +const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35; const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3; const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000; @@ -549,13 +552,14 @@ function probeIntervalForConnection( firstSeenAt: number, isActiveOnline: boolean, hasActiveOnlineConnection: boolean, + inactiveOnlineIntervalMs: number, now: number, ): number { if (isActiveOnline) { return PROBE_STEADY_MS; } if (hasActiveOnlineConnection) { - return PROBE_INACTIVE_WHILE_ONLINE_MS; + return inactiveOnlineIntervalMs; } const age = now - firstSeenAt; if (age < 10_000) return 2_000; @@ -730,6 +734,8 @@ export class HostRuntimeController { private connectionLastProbedAt = new Map(); private switchCandidateConnectionId: string | null = null; private switchCandidateHitCount = 0; + private inactiveOnlineProbeBackoffStep = 0; + private activeRttSamples: Array<{ at: number; rttMs: number }> = []; private clientIdPromise: Promise | null = null; private clientIdHash: string | null = null; private switchRequestVersion = 0; @@ -825,6 +831,9 @@ export class HostRuntimeController { this.activeClient = null; await prev.close().catch(() => undefined); } + this.resetSwitchCandidate(); + this.clearActiveRttSamples(); + this.resetInactiveOnlineProbeBackoff(); this.applyConnectionEvent({ type: "stopped" }); this.updateSnapshot({ ...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch), @@ -834,11 +843,15 @@ export class HostRuntimeController { async updateHost(host: HostProfile): Promise { const passwordChanged = this.host.password !== host.password; + const connectionsChanged = !equal(this.host.connections, host.connections); if (passwordChanged) { this.probeRequestVersion += 1; this.authRejectedConnectionIds.clear(); this.updateSnapshot({ authFailureReason: null }); } + if (passwordChanged || connectionsChanged) { + this.resetInactiveOnlineProbeBackoff(); + } const activeConnectionId = this.snapshot.activeConnectionId; const previousActiveConnection = findConnectionById(this.host, activeConnectionId); this.host = host; @@ -864,6 +877,9 @@ export class HostRuntimeController { } ensureConnected(options?: { verify?: boolean }): void { + if (options?.verify) { + this.resetInactiveOnlineProbeBackoff(); + } this.activeClient?.ensureConnected(options); } @@ -964,6 +980,7 @@ export class HostRuntimeController { const activeConnectionId = this.snapshot.activeConnectionId; const hasActiveOnlineConnection = isOnline && activeConnectionId !== null; + const inactiveOnlineIntervalMs = this.inactiveOnlineProbeIntervalMs(); const connectionsToProbe = this.host.connections.filter((connection) => { if (this.authRejectedConnectionIds.has(connection.id)) return false; const lastProbed = this.connectionLastProbedAt.get(connection.id); @@ -976,6 +993,7 @@ export class HostRuntimeController { firstSeen, isActiveOnline, hasActiveOnlineConnection, + inactiveOnlineIntervalMs, now, ); return now - lastProbed >= interval; @@ -1083,10 +1101,10 @@ export class HostRuntimeController { // Adaptive switching counts fresh comparisons only. The probe map keeps the last known // sample per connection for display and failover; a streak hit needs a candidate measured - // in this cycle and a heartbeat RTT from the socket that is active right now. Re-reading - // the cached map at every ten-second active tick turned one idle-probe sample into three - // "consecutive" wins, and a reconnected socket inherited its predecessor's RTT, so a - // working relay connection was replaced within seconds of coming online. + // in this cycle and a baseline RTT from the socket that is active right now. Using the + // rolling minimum of recent active heartbeats filters out single busy/stalled ticks so a + // loaded working socket does not lose to an idle probe, and a proportional threshold avoids + // flapping on normal jitter on high-RTT links. const sampledCandidates = connectionsToProbe.filter( (connection) => connection.id !== currentActiveConnectionId, ); @@ -1104,22 +1122,29 @@ export class HostRuntimeController { }) .sort((left, right) => left.latencyMs - right.latencyMs)[0] ?? null; if (!fastest) { - // Every candidate sampled this cycle failed: that breaks the streak. + // Every candidate sampled this cycle failed: that breaks the streak and backs off. this.resetSwitchCandidate(); + this.advanceInactiveOnlineProbeBackoff(); return; } - const activeRttMs = this.currentActiveSocketRttMs(); + const activeRttMs = this.currentActiveSocketBaselineRttMs(performance.now()); if (activeRttMs === null) { return; } + const requiredImprovementMs = Math.max( + ADAPTIVE_SWITCH_THRESHOLD_MS, + activeRttMs * ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO, + ); const improvement = activeRttMs - fastest.latencyMs; - if (improvement < ADAPTIVE_SWITCH_THRESHOLD_MS) { + if (improvement < requiredImprovementMs) { this.resetSwitchCandidate(); + this.advanceInactiveOnlineProbeBackoff(); return; } + this.resetInactiveOnlineProbeBackoff(); if (this.switchCandidateConnectionId === fastest.connectionId) { this.switchCandidateHitCount += 1; } else { @@ -1132,6 +1157,7 @@ export class HostRuntimeController { await this.switchToConnection({ connectionId: fastest.connectionId, expectedProbeVersion: requestVersion, + keepActiveUntilConnected: true, }); } }; @@ -1196,6 +1222,7 @@ export class HostRuntimeController { return; } if (rttMs !== null) { + this.recordActiveRttSample(rttMs, performance.now()); probeByConnectionId.set(connection.id, { status: "available", latencyMs: rttMs, @@ -1247,6 +1274,45 @@ export class HostRuntimeController { return client.getLastLivenessRttMs(); } + private recordActiveRttSample(rttMs: number, now: number): void { + this.activeRttSamples = this.activeRttSamples.filter( + (sample) => now - sample.at <= ACTIVE_RTT_WINDOW_MS, + ); + this.activeRttSamples.push({ at: now, rttMs }); + } + + private clearActiveRttSamples(): void { + this.activeRttSamples = []; + } + + private currentActiveSocketBaselineRttMs(now: number): number | null { + const currentRttMs = this.currentActiveSocketRttMs(); + if (currentRttMs === null) return null; + this.recordActiveRttSample(currentRttMs, now); + let baseline = this.activeRttSamples[0]!.rttMs; + for (const sample of this.activeRttSamples) { + if (sample.rttMs < baseline) baseline = sample.rttMs; + } + return baseline; + } + + private inactiveOnlineProbeIntervalMs(): number { + return Math.min( + PROBE_INACTIVE_WHILE_ONLINE_INITIAL_MS * 2 ** this.inactiveOnlineProbeBackoffStep, + PROBE_INACTIVE_WHILE_ONLINE_MAX_MS, + ); + } + + private advanceInactiveOnlineProbeBackoff(): void { + if (this.inactiveOnlineProbeIntervalMs() < PROBE_INACTIVE_WHILE_ONLINE_MAX_MS) { + this.inactiveOnlineProbeBackoffStep += 1; + } + } + + private resetInactiveOnlineProbeBackoff(): void { + this.inactiveOnlineProbeBackoffStep = 0; + } + private resetSwitchCandidate(): void { this.switchCandidateConnectionId = null; this.switchCandidateHitCount = 0; @@ -1436,6 +1502,7 @@ export class HostRuntimeController { connectionId: string; expectedProbeVersion?: number; existingClient?: DaemonClient; + keepActiveUntilConnected?: boolean; }): Promise { const { connectionId, expectedProbeVersion, existingClient } = input; if (!this.canProceedForProbe(expectedProbeVersion)) { @@ -1457,6 +1524,24 @@ export class HostRuntimeController { return; } + const makeBeforeBreak = + Boolean(input.keepActiveUntilConnected) && + !existingClient && + this.activeClient !== null && + this.connectionMachineState.tag === "online"; + + const nextGeneration = this.snapshot.clientGeneration + 1; + if (makeBeforeBreak) { + await this.switchToConnectionMakeBeforeBreak({ + connection, + clientId, + nextGeneration, + requestVersion, + expectedProbeVersion, + }); + return; + } + await this.disposePreviousActiveClient(); if (!this.isSwitchStillValid(requestVersion, expectedProbeVersion)) { @@ -1464,7 +1549,6 @@ export class HostRuntimeController { return; } - const nextGeneration = this.snapshot.clientGeneration + 1; const client = existingClient ?? this.deps.createClient({ @@ -1481,6 +1565,8 @@ export class HostRuntimeController { } this.activeClient = client; + this.clearActiveRttSamples(); + this.resetInactiveOnlineProbeBackoff(); this.applyConnectionEvent({ type: "select_connection", connectionId: connection.id, @@ -1492,67 +1578,148 @@ export class HostRuntimeController { client: null, }); - const failConnection = async (error: unknown) => { + try { + if (!existingClient) await client.connect(); if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return; + this.attachActiveClient({ client, connection }); + } catch (error) { + await this.failActiveConnection({ client, connection, error }); + } + } + + private async switchToConnectionMakeBeforeBreak(input: { + connection: HostConnection; + clientId: string; + nextGeneration: number; + requestVersion: number; + expectedProbeVersion?: number; + }): Promise { + const { connection, clientId, nextGeneration, requestVersion, expectedProbeVersion } = input; + const replacement = this.deps.createClient({ + host: this.host, + connection, + clientId, + runtimeGeneration: nextGeneration, + }); + replacement.setReconnectEnabled(false); + try { + await replacement.connect(); + } catch (error) { const authFailure = getConnectionAuthFailureReason(error); - if (authFailure) this.authRejectedConnectionIds.add(connection.id); - this.unsubscribeClientStatus?.(); - this.unsubscribeClientStatus = null; - this.unsubscribeClientHandlers?.(); - this.unsubscribeClientHandlers = null; - client.setReconnectEnabled(false); - this.applyConnectionEvent({ type: "connect_failed", message: toErrorMessage(error) }); - this.updateSnapshot({ - ...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch), - client: null, - authFailureReason: authFailure, - }); if (authFailure) { + this.authRejectedConnectionIds.add(connection.id); const probes = new Map(this.snapshot.probeByConnectionId); probes.set(connection.id, { status: "unavailable", latencyMs: null }); this.updateSnapshot({ probeByConnectionId: probes }); - for (const candidate of this.host.connections) { - if (!this.authRejectedConnectionIds.has(candidate.id)) { - this.connectionLastProbedAt.delete(candidate.id); - } - } - } - try { - await client.close(); - } catch { - /* Preserve the compatibility/connection error. */ - } - if ( - authFailure && - this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id)) - ) { - void this.runProbeCycleNow(); } + await replacement.close().catch(() => undefined); + return; + } + + const resolveValidTarget = (): HostConnection | null => { + if (!this.isSwitchStillValid(requestVersion, expectedProbeVersion)) return null; + const saved = findConnectionById(this.host, connection.id); + if (!saved || connectionNeedsNewClient(connection, saved, replacement)) return null; + return saved; }; - try { - if (!existingClient) await client.connect(); - if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return; - this.unsubscribeClientHandlers = - this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null; - this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => { - if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return; - if (client.authFailureReason) { - void failConnection(new DaemonAuthenticationError(client.authFailureReason)); - return; - } - if (state.status === "connected") this.learnRelaySecurity(client, connection.id); - // Switch evidence belongs to the socket it was measured against. - if (state.status !== "connected") this.resetSwitchCandidate(); - this.applyConnectionEvent({ type: "client_state", state, lastError: client.lastError }); - this.updateSnapshot({ - ...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch), - ...this.buildAgentDirectoryStatusPatch(), + + if (!resolveValidTarget()) { + await replacement.close().catch(() => undefined); + return; + } + + replacement.setReconnectEnabled(true); + await this.disposePreviousActiveClient(); + + const target = resolveValidTarget(); + if (!target) { + await replacement.close().catch(() => undefined); + return; + } + + this.activeClient = replacement; + this.clearActiveRttSamples(); + this.resetInactiveOnlineProbeBackoff(); + this.applyConnectionEvent({ + type: "select_connection", + connectionId: target.id, + connection: toActiveConnection(target), + }); + this.snapshot = { ...this.snapshot, clientGeneration: nextGeneration }; + this.attachActiveClient({ client: replacement, connection: target }); + } + + private attachActiveClient(input: { client: DaemonClient; connection: HostConnection }): void { + const { client, connection } = input; + this.unsubscribeClientHandlers = + this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null; + this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => { + if (this.activeClient !== client) return; + if (client.authFailureReason) { + void this.failActiveConnection({ client, - authFailureReason: null, + connection, + error: new DaemonAuthenticationError(client.authFailureReason), }); + return; + } + if (state.status === "connected") this.learnRelaySecurity(client, connection.id); + // Switch evidence belongs to the socket it was measured against. + if (state.status !== "connected") { + this.resetSwitchCandidate(); + this.clearActiveRttSamples(); + this.resetInactiveOnlineProbeBackoff(); + } + this.applyConnectionEvent({ type: "client_state", state, lastError: client.lastError }); + this.updateSnapshot({ + ...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch), + ...this.buildAgentDirectoryStatusPatch(), + client, + authFailureReason: null, }); - } catch (error) { - await failConnection(error); + }); + } + + private async failActiveConnection(input: { + client: DaemonClient; + connection: HostConnection; + error: unknown; + }): Promise { + const { client, connection, error } = input; + if (this.activeClient !== client) return; + const authFailure = getConnectionAuthFailureReason(error); + if (authFailure) this.authRejectedConnectionIds.add(connection.id); + this.unsubscribeClientStatus?.(); + this.unsubscribeClientStatus = null; + this.unsubscribeClientHandlers?.(); + this.unsubscribeClientHandlers = null; + client.setReconnectEnabled(false); + this.applyConnectionEvent({ type: "connect_failed", message: toErrorMessage(error) }); + this.updateSnapshot({ + ...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch), + client: null, + authFailureReason: authFailure, + }); + if (authFailure) { + const probes = new Map(this.snapshot.probeByConnectionId); + probes.set(connection.id, { status: "unavailable", latencyMs: null }); + this.updateSnapshot({ probeByConnectionId: probes }); + for (const candidate of this.host.connections) { + if (!this.authRejectedConnectionIds.has(candidate.id)) { + this.connectionLastProbedAt.delete(candidate.id); + } + } + } + try { + await client.close(); + } catch { + /* Preserve the compatibility/connection error. */ + } + if ( + authFailure && + this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id)) + ) { + void this.runProbeCycleNow(); } } @@ -1695,6 +1862,7 @@ export class HostRuntimeStore { private hostRegistryStatus: HostRegistryStatus = "loading"; private deps: HostRuntimeControllerDeps; private lastConnectionStatusByServer = new Map(); + private lastOnlineEpochByServer = new Map(); private connectionStatusStartedAtByServer = new Map(); private queuedAgentDrainInFlight = new Set(); private directorySyncByServer = new Map(); @@ -1952,6 +2120,7 @@ export class HostRuntimeStore { rekeyMap(this.controllers, oldServerId, newServerId); rekeyMap(this.lastConnectionStatusByServer, oldServerId, newServerId); + rekeyMap(this.lastOnlineEpochByServer, oldServerId, newServerId); rekeyMap(this.connectionStatusStartedAtByServer, oldServerId, newServerId); this.replicaCache.reconcileServerId(oldServerId, newServerId); projectIconCache.reconcileServerId(oldServerId, newServerId); @@ -2444,6 +2613,7 @@ export class HostRuntimeStore { this.fleetDirectoryDemand.delete(serverId); this.controllers.delete(serverId); this.lastConnectionStatusByServer.delete(serverId); + this.lastOnlineEpochByServer.delete(serverId); this.connectionStatusStartedAtByServer.delete(serverId); this.directorySyncByServer.get(serverId)?.dispose(); this.directorySyncByServer.delete(serverId); @@ -2494,6 +2664,9 @@ export class HostRuntimeStore { ); const initialSnapshot = controller.getSnapshot(); this.lastConnectionStatusByServer.set(host.serverId, initialSnapshot.connectionStatus); + if (initialSnapshot.connectionStatus === "online") { + this.lastOnlineEpochByServer.set(host.serverId, initialSnapshot.connectionEpoch); + } this.connectionStatusStartedAtByServer.set(host.serverId, Date.now()); controller.subscribe(() => { const snapshot = controller.getSnapshot(); @@ -2593,6 +2766,7 @@ export class HostRuntimeStore { const controller = this.controllers.get(serverId); if (!controller) { this.lastConnectionStatusByServer.delete(serverId); + this.lastOnlineEpochByServer.delete(serverId); this.connectionStatusStartedAtByServer.delete(serverId); return; } @@ -2607,6 +2781,7 @@ export class HostRuntimeStore { }, }); const previousStatus = this.lastConnectionStatusByServer.get(serverId); + const previousOnlineEpoch = this.lastOnlineEpochByServer.get(serverId); const statusChanged = previousStatus !== snapshot.connectionStatus; const isUnavailable = snapshot.connectionStatus !== "online" && snapshot.connectionStatus !== "idle"; @@ -2617,7 +2792,11 @@ export class HostRuntimeStore { } this.lastConnectionStatusByServer.set(serverId, snapshot.connectionStatus); const didTransitionOnline = - snapshot.connectionStatus === "online" && previousStatus !== "online"; + snapshot.connectionStatus === "online" && + (previousStatus !== "online" || previousOnlineEpoch !== snapshot.connectionEpoch); + if (snapshot.connectionStatus === "online") { + this.lastOnlineEpochByServer.set(serverId, snapshot.connectionEpoch); + } if (didTransitionOnline) { useSessionStore.getState().bumpHistorySyncGeneration(serverId); for (const child of this.controllers.values()) void child.reconnectVia(serverId); diff --git a/packages/app/src/runtime/replica-cache/index.test.ts b/packages/app/src/runtime/replica-cache/index.test.ts index f0187e831972..6801e088238d 100644 --- a/packages/app/src/runtime/replica-cache/index.test.ts +++ b/packages/app/src/runtime/replica-cache/index.test.ts @@ -37,6 +37,9 @@ class MemoryStorage implements ReplicaRowStore { onRead: (() => void) | null = null; /** Throws once a read goes past this count, so a non-terminating read loop fails the test. */ readLimit: number | null = null; + /** Awaited before the store lists every row or deletes a host, so a test can interleave there. */ + beforeReadAll: (() => Promise) | null = null; + beforeDeleteHost: (() => Promise) | null = null; private key(row: Pick): string { return `${row.serverId}:${row.kind}:${row.id}`; @@ -68,6 +71,7 @@ class MemoryStorage implements ReplicaRowStore { } async readAll(): Promise { + await this.beforeReadAll?.(); const hosts = new Map(); for (const row of this.rows.values()) { const rows = hosts.get(row.serverId) ?? []; @@ -91,6 +95,7 @@ class MemoryStorage implements ReplicaRowStore { } async deleteHost(serverId: string): Promise { + await this.beforeDeleteHost?.(); for (const [key, row] of this.rows) if (row.serverId === serverId) this.rows.delete(key); } @@ -436,40 +441,49 @@ describe("ReplicaCache", () => { await expectLegacyWorkspaceRefresh(cached); }); - it("rejects pre-baseline-fix checkpoints without discarding cached rows or timelines", async () => { - const storage = new MemoryStorage(); - const writer = createCache(storage); - const baseline = directory(); - writer.replaceDirectoryBaseline(SERVER_ID, baseline); - writer.commitTimeline(SERVER_ID, "agent-1", timeline()); - await writer.flush(); - await storage.apply({ - deletes: [], - upserts: [ - { - serverId: SERVER_ID, - kind: "checkpoint", - id: "singleton", - payload: JSON.stringify(baseline.checkpoint), - }, - ], - }); - - const reader = createCache(storage); - const restored = await reader.readDirectory(SERVER_ID); - expect(restored.checkpoint).toBeUndefined(); - expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]); - expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]); - expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]); - expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline()); - expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]); + it.each([ + ["before the baseline fix", (checkpoint: DirectoryCheckpoint): unknown => checkpoint], + [ + "before the eviction fix", + (checkpoint: DirectoryCheckpoint): unknown => ({ version: 1, cursors: checkpoint }), + ], + ])( + "rejects checkpoints written %s without discarding cached rows or timelines", + async (_era, legacyPayload) => { + const storage = new MemoryStorage(); + const writer = createCache(storage); + const baseline = directory(); + writer.replaceDirectoryBaseline(SERVER_ID, baseline); + writer.commitTimeline(SERVER_ID, "agent-1", timeline()); + await writer.flush(); + await storage.apply({ + deletes: [], + upserts: [ + { + serverId: SERVER_ID, + kind: "checkpoint", + id: "singleton", + payload: JSON.stringify(legacyPayload(baseline.checkpoint)), + }, + ], + }); - reader.replaceDirectoryBaseline(SERVER_ID, baseline); - await reader.flush(); - expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual( - baseline.checkpoint, - ); - }); + const reader = createCache(storage); + const restored = await reader.readDirectory(SERVER_ID); + expect(restored.checkpoint).toBeUndefined(); + expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]); + expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]); + expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]); + expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline()); + expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]); + + reader.replaceDirectoryBaseline(SERVER_ID, baseline); + await reader.flush(); + expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual( + baseline.checkpoint, + ); + }, + ); it("does nothing until an owner explicitly commits data", async () => { const storage = new MemoryStorage(); @@ -792,6 +806,28 @@ describe("ReplicaCache", () => { expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([timelineItem("New")]); }); + it("keeps a turn's stats on its footer row across cache reopen", async () => { + const storage = new MemoryStorage(); + const writer = createCache(storage); + const answer: StreamItem = { + ...(timelineItem("Done") as Extract), + turnMetrics: [ + { label: "Model", value: "gemini-3.6-flash" }, + { label: "Cache", value: "64%", tone: "ok" }, + ], + }; + writer.commitTimeline(SERVER_ID, "agent-1", { + agentId: "agent-1", + items: [answer], + range: { epoch: "epoch-1", startSeq: 12, endSeq: 12 }, + hasOlder: false, + }); + await writer.flush(); + + const reader = createCache(storage); + expect((await reader.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([answer]); + }); + it("round-trips plugin timeline items", async () => { const storage = new MemoryStorage(); const writer = createCache(storage); @@ -1102,6 +1138,113 @@ describe("ReplicaCache", () => { ).toEqual(["agent", "checkpoint", "project", "workspace"]); }); + it.each(["beforeReadAll", "beforeDeleteHost"] as const)( + "stores no checkpoint for a host evicted after its update was queued (%s)", + async (pausePoint) => { + const storage = new MemoryStorage(); + const previousSession = new ReplicaCache(storage, noLegacyCleanup); + previousSession.setHosts([SERVER_ID, "other-host"]); + previousSession.replaceDirectoryBaseline(SERVER_ID, directory()); + previousSession.replaceDirectoryBaseline("other-host", directory()); + await previousSession.flush(); + + const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 8_192 }); + cache.setHosts([SERVER_ID, "other-host"]); + const paused = deferred(); + const resume = deferred(); + storage[pausePoint] = async () => { + storage[pausePoint] = null; + paused.resolve(); + await resume.promise; + }; + // Larger than the whole budget, so this persist evicts both hosts. + cache.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384))); + const eviction = cache.flush(); + await paused.promise; + cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 13 } }); + resume.resolve(); + await eviction; + await cache.flush(); + + const restored = await createCache(storage).readDirectory(SERVER_ID); + expect(restored.agents.size).toBe(0); + expect(restored.checkpoint).toBeUndefined(); + }, + ); + + it("stores no checkpoint for a host evicted while a malformed row is repaired", async () => { + const { storage } = await cacheWithoutBackgroundVisibility(); + const reader = createCache(storage, 8_192); + storage.onRead = () => { + if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return; + storage.onRead = null; + // Larger than the whole budget, so this persist evicts the host before the repair writes. + reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384))); + void reader.flush(); + }; + + expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined(); + await reader.flush(); + + const restored = await createCache(storage).readDirectory(SERVER_ID); + expect(restored.projects.size).toBe(0); + expect(restored.checkpoint).toBeUndefined(); + }); + + it("repairs a malformed row's cursor when the overlapping eviction fails", async () => { + const { storage } = await cacheWithoutBackgroundVisibility(); + const reader = createCache(storage, 8_192); + storage.onRead = () => { + if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return; + storage.onRead = null; + storage.beforeDeleteHost = async () => { + storage.beforeDeleteHost = null; + throw new Error("Eviction aborted"); + }; + reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384))); + void reader.flush(); + }; + + expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined(); + // A newer timeline fits the budget, so no later eviction clears the checkpoint. + reader.commitTimeline(SERVER_ID, "agent-1", timeline()); + await reader.flush(); + + const restored = await createCache(storage).readDirectory(SERVER_ID); + expect(restored.workspaces.size).toBe(0); + expect(restored.checkpoint).toEqual({ + agents: { generation: "g", afterSeq: 12 }, + projects: { generation: "g", afterSeq: 4 }, + }); + }); + + it("keeps an update queued behind the baseline that rebuilds an evicted host", async () => { + const storage = new MemoryStorage(); + const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 2_500 }); + cache.setHosts([SERVER_ID, "other-host"]); + const baseline = directory(); + cache.replaceDirectoryBaseline(SERVER_ID, baseline); + await cache.flush(); + cache.replaceDirectoryBaseline("other-host", baseline); + await cache.flush(); + expect((await cache.readDirectory(SERVER_ID)).agents.size).toBe(0); + + const renamed = { ...agent(), title: "Renamed agent" }; + cache.replaceDirectoryBaseline(SERVER_ID, baseline); + cache.commitDirectoryMutations( + SERVER_ID, + [{ kind: "agent", type: "upsert", id: renamed.id, value: renamed }], + { agents: { generation: "g", afterSeq: 13 } }, + ); + await cache.flush(); + cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 14 } }); + await cache.flush(); + + const restored = await createCache(storage).readDirectory(SERVER_ID); + expect(restored.checkpoint).toEqual({ agents: { generation: "g", afterSeq: 14 } }); + expect(restored.agents.get(renamed.id)?.title).toBe("Renamed agent"); + }); + it("runs legacy cleanup once when storage is first used", async () => { const storage = new MemoryStorage(); const cache = new ReplicaCache(storage, { diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index 59ebf90de5fa..2aa104576207 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -2,6 +2,7 @@ import { findMountedWindowStart } from "@/agent-stream/history-window"; import { z } from "zod"; import { AgentBackgroundWorkSummarySchema, + AgentMetricSchema, AgentStatusSchema, AgentTimelineItemPayloadSchema, ForgeWebSchema, @@ -131,6 +132,7 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [ ...TimelineItemBaseShape, kind: z.literal("assistant_message"), messageId: z.string().optional(), + turnMetrics: z.array(AgentMetricSchema).optional(), text: z.string(), // Reject old caches containing display fragments; refetch the complete source text. }), @@ -165,6 +167,7 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [ ...TimelineItemBaseShape, kind: z.literal("tool_call"), provider: AgentProviderSchema, + turnMetrics: z.array(AgentMetricSchema).optional(), item: AgentTimelineItemPayloadSchema.refine((item) => item.type === "tool_call"), }), z.strictObject({ @@ -402,15 +405,19 @@ const DirectoryCheckpointSchema = z.strictObject({ agents: DirectoryCursorSchema.optional(), }); -// Old checkpoints could describe a baseline that an overlapping refresh had discarded. -// Revalidate directory contents once without evicting cached rows or timelines. +// A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a +// directory the cache no longer held: unversioned ones after an overlapping refresh, version 1 +// after an eviction. Rejecting them revalidates directory contents once without evicting cached +// rows or timelines. +const DIRECTORY_CHECKPOINT_VERSION = 2; + const StoredDirectoryCheckpointSchema = z.strictObject({ - version: z.literal(1), + version: z.literal(DIRECTORY_CHECKPOINT_VERSION), cursors: DirectoryCheckpointSchema, }); function serializeDirectoryCheckpoint(cursors: DirectoryCheckpoint) { - return { version: 1 as const, cursors }; + return { version: DIRECTORY_CHECKPOINT_VERSION, cursors }; } function deserializeDirectoryCheckpoint(payload: string): DirectoryCheckpoint { @@ -483,6 +490,7 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null { ...base, kind: item.kind, ...(item.messageId ? { messageId: item.messageId } : {}), + ...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}), text: item.text, }; case "thought": @@ -517,6 +525,7 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null { ...base, kind: item.kind, provider: item.payload.data.provider, + ...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}), item: serializeAgentToolCall(item.payload.data), }; case "plugin": @@ -576,6 +585,7 @@ function deserializeBuiltinTimelineItem( ...base, kind: item.kind, ...(item.messageId ? { messageId: item.messageId } : {}), + ...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}), text: item.text, }; case "thought": @@ -612,6 +622,7 @@ function deserializeBuiltinTimelineItem( return { ...base, kind: item.kind, + ...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}), payload: { source: "agent", data: { @@ -984,6 +995,7 @@ export class ReplicaCache { private pendingUpserts = new Map(); private pendingDeletes = new Map(); private pendingBaselines = new Set(); + // Hosts whose stored directory was evicted. Only a baseline stores their directory again. private readonly invalidatedHosts = new Set(); private readonly maxBytes: number; private totalBytes = 0; @@ -1125,11 +1137,7 @@ export class ReplicaCache { private async deleteInvalidRow(row: ReplicaRow): Promise { const invalidEntity = directoryEntityForRow(row); if (!invalidEntity) { - const changes = { upserts: [], deletes: [row] } satisfies ReplicaRowChanges; - await this.queueOperation(async () => { - await this.rowStore.apply(changes); - this.applyStoredChanges(changes); - }); + await this.applyRepair(row.serverId, { upserts: [], deletes: [row] }); return; } @@ -1160,10 +1168,7 @@ export class ReplicaCache { ] : [], }; - await this.queueOperation(async () => { - await this.rowStore.apply(changes); - this.applyStoredChanges(changes); - }); + await this.applyRepair(row.serverId, changes); } private async repairInvalidDirectoryRows( @@ -1186,9 +1191,16 @@ export class ReplicaCache { ] : [], }; - await this.queueOperation(async () => { - await this.rowStore.apply(changes); - this.applyStoredChanges(changes); + await this.applyRepair(serverId, changes); + } + + // A repair is queued behind writes that can evict its host. If one did, the host has no + // directory left for the repaired checkpoint to describe, so only the deletes still apply. + private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise { + return this.queueOperation(async () => { + const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes; + await this.rowStore.apply(applied); + this.applyStoredChanges(applied); }); } @@ -1198,7 +1210,6 @@ export class ReplicaCache { checkpoint?: DirectoryCheckpoint, ): void { if (!this.activeServerIds.has(serverId)) return; - if (this.invalidatedHosts.has(serverId)) return; for (const mutation of mutations) { if (mutation.type === "delete") { this.queueEntityDelete(serverId, mutation.kind, mutation.id); @@ -1428,9 +1439,17 @@ export class ReplicaCache { } private materializePendingChanges(pending: PendingReplicaChanges): ReplicaRowChanges { - const deletes = new Map(pending.deletes.map((row) => [pendingRowKey(row), row])); + // Decided here, inside the serialized write, because eviction happens there too. A mutation + // queued before its host was evicted would otherwise store a checkpoint without its directory. + const isStorable = (row: ReplicaRowKey): boolean => + row.kind === "timeline" || + !this.invalidatedHosts.has(row.serverId) || + pending.baselines.has(row.serverId); + const deletes = new Map( + pending.deletes.filter(isStorable).map((row) => [pendingRowKey(row), row]), + ); const upserts: ReplicaRow[] = []; - for (const upsert of pending.upserts) { + for (const upsert of pending.upserts.filter(isStorable)) { const row = this.materializeUpsert(upsert); if (row) upserts.push(row); else deletes.set(pendingRowKey(upsert), upsert); @@ -1579,8 +1598,10 @@ export class ReplicaCache { projectedTotal -= bytes; projectedBytes.delete(serverId); evicted.add(serverId); - this.invalidatedHosts.add(serverId); if (this.storedRows.has(serverId)) await this.rowStore.deleteHost(serverId); + // Only after the delete commits: a failed eviction leaves the rows stored, and writers that + // check this set must keep their checkpoint in step with those rows. + this.invalidatedHosts.add(serverId); this.removeStoredHost(serverId); } diff --git a/packages/app/src/schedules/schedule-form-model.ts b/packages/app/src/schedules/schedule-form-model.ts index 5c5be3a6413a..52cc3e5b72cc 100644 --- a/packages/app/src/schedules/schedule-form-model.ts +++ b/packages/app/src/schedules/schedule-form-model.ts @@ -1008,7 +1008,9 @@ export function openScheduleForm(snapshot: ScheduleFormSnapshot): ScheduleFormMo } publish({ ...resolved, - modelSelectorProviders: buildSelectableProviderSelectorProviders(providerEntries), + modelSelectorProviders: buildSelectableProviderSelectorProviders(providerEntries, { + selectedProvider: resolved.selectedProvider, + }), providerResolutionByServerId, providerSnapshotRequest: isPendingResolution ? null : state.providerSnapshotRequest, }); diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index 8e322c9ad6c2..45606df738a7 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -24,6 +24,7 @@ import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region"; import { MenuHeader } from "@/components/headers/menu-header"; import { useIsCompactFormFactor } from "@/constants/layout"; import { useToast } from "@/contexts/toast-context"; +import { draftCreationKey } from "@/composer/draft/creation-key"; import { useAgentInputDraft } from "@/composer/draft/input-draft"; import { useForgeSearchQuery } from "@/git/use-forge-search-query"; import { getForgePresentation } from "@/git/forge"; @@ -339,6 +340,7 @@ interface WorkspaceCreationResult { async function createMultiplicityWorkspace(input: { idempotencyKey: string; + launchTarget: LaunchTarget; worktreeSlug: string; client: NonNullable>; isolation: "local" | "worktree"; @@ -368,10 +370,8 @@ async function createMultiplicityWorkspace(input: { prompt: input.prompt, attachments: input.attachments, }); - const payload = await input.client.createWorkspace({ - idempotencyKey: input.idempotencyKey, + const request: Omit = { agent: input.agent, - onEvent: input.onEvent, source: isWorktree ? { kind: "worktree", @@ -390,6 +390,14 @@ async function createMultiplicityWorkspace(input: { }, ...(firstAgentContext ? { firstAgentContext } : {}), ...(Object.keys(input.metadata).length > 0 ? { metadata: { ...input.metadata } } : {}), + }; + const payload = await input.client.createWorkspace({ + ...request, + idempotencyKey: draftCreationKey(input.idempotencyKey, { + request, + launchTarget: input.launchTarget, + }), + onEvent: input.onEvent, }); if (payload.error || !payload.workspace) { throw new Error(payload.error ?? input.createFailedMessage); @@ -511,7 +519,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise = { config: { provider, @@ -548,7 +556,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise execute()) }; - await agentCreation.result; - if (outcome === "background") clearConsumedDraft(); - return outcome; + try { + await agentCreation.result; + } catch (error) { + // Once handed off to the workspace draft tab, that tab owns surfacing agent startup errors. + if (delivery.outcome === "navigated") return delivery.outcome; + throw error; + } + if (delivery.outcome === "background") clearConsumedDraft(); + return delivery.outcome; } function buildComposerConfig(input: { @@ -1362,6 +1376,7 @@ export function NewWorkspaceScreen({ : undefined; const normalizedWorkspace = await createMultiplicityWorkspace({ idempotencyKey: creationIdentity.draftId, + launchTarget, worktreeSlug: creationIdentity.worktreeSlug, client: connectedClient, isolation: createsWorktree ? "worktree" : "local", @@ -1386,6 +1401,7 @@ export function NewWorkspaceScreen({ creationIdentity, creationResult, effectiveIsolation, + launchTarget, mergeWorkspaces, queryClient, selectedItem, @@ -1456,7 +1472,9 @@ export function NewWorkspaceScreen({ const message = toErrorMessage(error); setPendingAction(null); setErrorMessage(message); - toast.error(message); + if (!isStillOnCreateScreen()) { + toast.error(message); + } } }, [ @@ -1537,7 +1555,9 @@ export function NewWorkspaceScreen({ const message = toErrorMessage(error); setPendingAction(null); setErrorMessage(message); - toast.error(message); + if (!isStillOnCreateScreen()) { + toast.error(message); + } } }, [ ensureWorkspace, @@ -1675,6 +1695,7 @@ export function NewWorkspaceScreen({ clearDraft={noopClearDraft} autoFocus={terminalTakesPrompt} autoFocusKey={launchFocusKey} + error={errorMessage} /> ) : ( ); return ( @@ -1718,7 +1740,6 @@ export function NewWorkspaceScreen({ onImportSession={importSession.open} > {composer} - {errorMessage ? {errorMessage} : null} {importSession.sheet} @@ -1888,11 +1909,6 @@ const styles = StyleSheet.create((theme) => ({ fontWeight: theme.fontWeight.normal, color: theme.colors.foreground, }, - errorText: { - fontSize: theme.fontSize.base, - color: theme.colors.destructive, - lineHeight: 20, - }, })); /** diff --git a/packages/app/src/screens/project-settings-screen.tsx b/packages/app/src/screens/project-settings-screen.tsx index ae6f31fef117..762f2f7a4f65 100644 --- a/packages/app/src/screens/project-settings-screen.tsx +++ b/packages/app/src/screens/project-settings-screen.tsx @@ -5,7 +5,7 @@ import { Pressable, Text, View } from "react-native"; import { useFocusEffect } from "expo-router/react-navigation"; import { StyleSheet } from "react-native-unistyles"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, MoreVertical, Pencil, Plus } from "lucide-react-native"; +import { MoreVertical, Pencil, Plus } from "lucide-react-native"; import { ProjectIconView } from "@/components/project-icon-view"; import type { PaseoConfigRaw, @@ -29,6 +29,9 @@ import { EditingTextInput as TextInput } from "@/components/ui/text-input"; import { SettingsTextAreaCard } from "@/components/settings-textarea"; import { SettingsGroup } from "@/components/settings/headings/settings-group"; import { SettingsSection } from "@/components/settings/headings/settings-section"; +import type { PageTitleParent } from "@/components/page-layout"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { SettingsDetailHeader } from "@/components/settings"; import { settingsStyles } from "@/styles/settings"; import { useProjects } from "@/hooks/use-projects"; import type { ProjectEditFormSnapshot } from "@/projects/edit-form"; @@ -94,14 +97,12 @@ export interface ProjectSettingsScreenProps { serverId: string; projectId: string; onBackToProjects: () => void; - showBackToProjects: boolean; } export default function ProjectSettingsScreen({ serverId, projectId, onBackToProjects, - showBackToProjects, }: ProjectSettingsScreenProps) { const { projects } = useProjects(); const project = useMemo( @@ -122,12 +123,7 @@ export default function ProjectSettingsScreen({ selectedHost.repoRoot.trim().length > 0; if (!project || !selectedHost || !client || !canEdit) { - return ( - - ); + return ; } return ( @@ -137,24 +133,29 @@ export default function ProjectSettingsScreen({ client={client} isHostGone={isHostGone} onBackToProjects={onBackToProjects} - showBackToProjects={showBackToProjects} /> ); } -function NoEditableTarget({ - onBackToProjects, - showBackToProjects, -}: { - onBackToProjects: () => void; - showBackToProjects: boolean; -}) { +/** A project page with no project to name: the title is the way back to Projects. */ +function NoProject({ onBackToProjects }: { onBackToProjects: () => void }) { + const parent = useProjectsParent(onBackToProjects); + return ( + <> + + + + ); +} + +function NoEditableTarget({ onBackToProjects }: { onBackToProjects: () => void }) { const { t } = useTranslation(); + // The compact back header already goes back to Projects. + const isCompact = useIsCompactFormFactor(); return ( - {showBackToProjects ? : null} {t("settings.project.noEditableTarget")} - {showBackToProjects ? ( + {isCompact ? null : ( - ) : null} + )} ); } -function BackToProjectsButton({ onPress }: { onPress: () => void }) { +/** Projects as the first part of a project page's title, which goes back to the list. */ +function useProjectsParent(onPress: () => void): PageTitleParent { const { t } = useTranslation(); - return ( - + return useMemo( + () => ({ + label: t("settings.projects"), + accessibilityLabel: t("settings.project.backToProjects"), + onPress, + testID: "project-settings-back-link", + }), + [onPress, t], ); } @@ -189,7 +188,6 @@ interface ProjectSettingsBodyProps { client: DaemonClient; isHostGone: boolean; onBackToProjects: () => void; - showBackToProjects: boolean; } function ProjectSettingsBody({ @@ -198,7 +196,6 @@ function ProjectSettingsBody({ client, isHostGone, onBackToProjects, - showBackToProjects, }: ProjectSettingsBodyProps) { const { t } = useTranslation(); const [isEditSheetOpen, setIsEditSheetOpen] = useState(false); @@ -260,33 +257,41 @@ function ProjectSettingsBody({ const handleReload = useCallback(() => { void readQuery.refetch(); }, [readQuery]); + const parent = useProjectsParent(onBackToProjects); + const titleIcon = useMemo( + () => ( + + ), + [project.viewKey, projectIconDataUri, selectedHost.projectName], + ); + const editButton = useMemo( + () => ( + + + + ), + [openEditSheet, t], + ); return ( - - {showBackToProjects ? : null} - - - - - - {selectedHost.projectName} - - - - - - + + ); @@ -331,7 +335,6 @@ interface RenderContentInput { onReload: () => void; isHostGone: boolean; onBackToProjects: () => void; - showBackToProjects: boolean; } function renderContent({ @@ -346,7 +349,6 @@ function renderContent({ onReload, isHostGone, onBackToProjects, - showBackToProjects, }: RenderContentInput) { if (readQuery.isLoading) { return ( @@ -365,12 +367,7 @@ function renderContent({ } if (isHostGone) { - return ( - - ); + return ; } if (!loadedConfig) { @@ -1104,30 +1101,6 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.foregroundMuted, fontSize: theme.fontSize.base, }, - body: { - padding: theme.spacing[4], - gap: theme.spacing[2], - }, - backButton: { - alignSelf: "flex-start", - paddingHorizontal: 0, - }, - headerBlock: { - marginTop: theme.spacing[2], - marginBottom: theme.spacing[4], - gap: theme.spacing[2], - }, - titleRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[3], - }, - projectTitle: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - flexShrink: 1, - }, editButton: { padding: theme.spacing[1], }, diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 7fc6dbe2487e..0288d82707f4 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -118,6 +118,7 @@ import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-p import { HostVoicePage } from "@/screens/settings/voice/voice-page"; import ProjectsScreen from "@/screens/projects-screen"; import ProjectSettingsScreen from "@/screens/project-settings-screen"; +import { ProviderDetailPage } from "@/provider-settings"; import { SETTINGS_DESKTOP_DETAIL_MIN_WIDTH, SETTINGS_DESKTOP_SIDEBAR_WIDTH, @@ -990,6 +991,7 @@ function SettingsSidebar({ let selectedHostSection: HostSectionSlug | null = null; if (view.kind === "host") selectedHostSection = view.section; if (view.kind === "project") selectedHostSection = "projects"; + if (view.kind === "provider") selectedHostSection = "providers"; if (view.kind === "plugin" || view.kind === "pluginListing") selectedHostSection = "plugins"; const sidebarBody = ( @@ -1137,7 +1139,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { view.kind === "host" || view.kind === "project" || view.kind === "plugin" || - view.kind === "pluginListing" + view.kind === "pluginListing" || + view.kind === "provider" ) return view.serverId; return resolveActiveHostServerId({ @@ -1216,8 +1219,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { const handleSelectHost = useCallback( (serverId: string) => { selectSettingsHost(serverId); - if (view.kind === "project") { - const target = buildSettingsHostSectionRoute(serverId, "projects"); + if (view.kind === "project" || view.kind === "provider") { + // The detail belongs to the old host; open the same list on the new one. + const target = buildSettingsHostSectionRoute( + serverId, + view.kind === "project" ? "projects" : "providers", + ); if (isCompactLayout) { router.push(target); } else { @@ -1296,6 +1303,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { if (view.kind === "project") { return t("settings.projects"); } + if (view.kind === "provider") return t("settings.hostSections.providers"); return undefined; })(); @@ -1327,7 +1335,15 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { serverId={view.serverId} projectId={view.projectId} onBackToProjects={handleBackFromDetail} - showBackToProjects={!isCompactLayout} + /> + ); + } + if (view.kind === "provider") { + return ( + ); } @@ -1432,7 +1448,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { void; -} - -function ContentWidthRow({ value, onChange }: ContentWidthRowProps) { +function ContentWidthRow({ + value, + onChange, +}: { + value: AppSettings["contentWidth"]; + onChange: (value: ContentWidthPreset) => void; +}) { const { t } = useTranslation(); - const width = resolveContentMaxWidth({ contentMaxWidth: value }); - // The field is uncontrolled, so a saved or reset width is written into it directly. - const input = useRef(null); - - useEffect(() => { - input.current?.replaceText(String(width)); - }, [width]); - - const commit = useCallback(() => { - const next = parseContentMaxWidth(input.current?.getText()) ?? width; - input.current?.replaceText(String(next)); - // Typing the width already in effect keeps following the default. - if (next !== width) { - onChange(next); - } - }, [onChange, width]); - - const reset = useCallback(() => { - onChange(null); - }, [onChange]); return ( - - + + {t("settings.appearance.layout.contentWidth")} - {t("settings.appearance.layout.contentWidthHint")} + {typeof value === "number" + ? t("settings.appearance.layout.contentWidthCustom", { width: value }) + : t("settings.appearance.layout.contentWidthHint")} - - {value === null ? null : ( - - )} - - px - + + testID="content-width-options" + value={typeof value === "number" ? null : value} + onValueChange={onChange} + options={[ + { value: "default", label: t("settings.appearance.layout.contentWidthDefault") }, + { value: "wide", label: t("settings.appearance.layout.contentWidthWide") }, + { value: "full", label: t("settings.appearance.layout.contentWidthFull") }, + ]} + /> ); } @@ -333,9 +299,9 @@ export function AppearanceSection() { setCodeSizeDraft(String(settings.codeFontSize)); }, [settings.codeFontSize]); - const handleContentMaxWidthChange = useCallback( - (contentMaxWidth: AppSettings["contentMaxWidth"]) => { - void updateSettings({ contentMaxWidth }); + const handleContentWidthChange = useCallback( + (contentWidth: ContentWidthPreset) => { + void updateSettings({ contentWidth }); }, [updateSettings], ); @@ -504,10 +470,7 @@ export function AppearanceSection() { - + @@ -571,18 +534,10 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, textAlign: "right", }, - widthInput: { - width: 80, - minHeight: 36, - paddingVertical: theme.spacing[2], - paddingHorizontal: theme.spacing[3], - borderRadius: theme.borderRadius.md, - borderWidth: theme.borderWidth[1], - borderColor: theme.colors.border, - backgroundColor: theme.colors.surface2, - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - textAlign: "right", + contentWidthRow: { + alignItems: "flex-start", + gap: theme.spacing[2], + padding: theme.spacing[4], }, unit: { color: theme.colors.foregroundMuted, diff --git a/packages/app/src/screens/settings/host-page.tsx b/packages/app/src/screens/settings/host-page.tsx index 9c0c95248840..6e27f7065010 100644 --- a/packages/app/src/screens/settings/host-page.tsx +++ b/packages/app/src/screens/settings/host-page.tsx @@ -49,7 +49,8 @@ import { useHostRuntimeSnapshot, useHosts, } from "@/runtime/host-runtime"; -import { ProvidersSection } from "@/screens/settings/providers-section"; +import { ProviderList } from "@/provider-settings"; +import { openProviderSettings } from "@/navigation/settings-navigation"; import { HostUsageSection } from "@/usage"; import { HostAppearanceSection } from "@/screens/settings/host-appearance-section"; import { SettingsSection } from "@/components/settings/headings/settings-section"; @@ -334,6 +335,10 @@ export function HostWorkspacesPage({ serverId }: { serverId: string }) { export function HostProvidersPage({ serverId }: { serverId: string }) { const host = useHostProfile(serverId); + const openProvider = useCallback( + (providerId: string) => openProviderSettings(serverId, providerId), + [serverId], + ); if (!host) { return ; @@ -341,7 +346,7 @@ export function HostProvidersPage({ serverId }: { serverId: string }) { return ( - + ); } diff --git a/packages/app/src/screens/settings/metadata-generation-page.tsx b/packages/app/src/screens/settings/metadata-generation-page.tsx index 0e8d895228ab..e88c379df63f 100644 --- a/packages/app/src/screens/settings/metadata-generation-page.tsx +++ b/packages/app/src/screens/settings/metadata-generation-page.tsx @@ -19,12 +19,15 @@ export function MetadataGenerationPage({ serverId }: { serverId: string }) { const { t } = useTranslation(); const { config, isLoading: isConfigLoading, patchConfig } = useDaemonConfig(serverId); const snapshot = useProvidersSnapshot(serverId); - const providers = useMemo( - () => buildSelectableProviderSelectorProviders(snapshot.entries), - [snapshot.entries], - ); const configuredProviders = config?.metadataGeneration.providers; const configuredProvider = configuredProviders?.[0] ?? null; + const providers = useMemo( + () => + buildSelectableProviderSelectorProviders(snapshot.entries, { + selectedProvider: configuredProvider?.provider ?? null, + }), + [configuredProvider?.provider, snapshot.entries], + ); const savedMode: SelectionMode = configuredProvider ? "preferred" : "automatic"; const [draftMode, setDraftMode] = useState(null); const [isSaving, setIsSaving] = useState(false); diff --git a/packages/app/src/screens/settings/providers-section.test.tsx b/packages/app/src/screens/settings/providers-section.test.tsx deleted file mode 100644 index 4a290629cb50..000000000000 --- a/packages/app/src/screens/settings/providers-section.test.tsx +++ /dev/null @@ -1,581 +0,0 @@ -/** - * @vitest-environment jsdom - */ -import React, { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; -import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; -import { ToastApiProvider } from "@/contexts/toast-api-context"; - -const { snapshotState, configState, featureState, patchConfigMock, openProviderSettingsMock } = - vi.hoisted(() => ({ - snapshotState: { - entries: undefined as ProviderSnapshotEntry[] | undefined, - isLoading: false, - isRefreshing: false, - }, - configState: { - config: null as MutableDaemonConfig | null, - }, - featureState: {} as Record, - patchConfigMock: vi.fn(async () => undefined), - openProviderSettingsMock: vi.fn(), - })); - -vi.mock("react-native", async (importOriginal) => ({ - ...(await importOriginal()), - View: ({ children, testID }: { children?: React.ReactNode; testID?: string }) => - React.createElement("div", { "data-testid": testID }, children), - Text: ({ children }: { children?: React.ReactNode }) => - React.createElement("span", null, children), - Pressable: ({ - children, - onPress, - onHoverIn, - onHoverOut, - accessibilityRole, - accessibilityLabel, - disabled, - testID, - }: { - children?: - | React.ReactNode - | ((state: { pressed: boolean; hovered: boolean }) => React.ReactNode); - onPress?: (event: React.MouseEvent) => void; - onHoverIn?: () => void; - onHoverOut?: () => void; - accessibilityRole?: string; - accessibilityLabel?: string; - disabled?: boolean; - testID?: string; - }) => - React.createElement( - "div", - { - role: accessibilityRole, - "aria-label": accessibilityLabel, - "aria-disabled": disabled ? "true" : undefined, - "data-testid": testID, - onClick: disabled ? undefined : onPress, - onMouseEnter: onHoverIn, - onMouseLeave: onHoverOut, - }, - typeof children === "function" ? children({ pressed: false, hovered: false }) : children, - ), - ActivityIndicator: () => React.createElement("span", { "data-testid": "activity-indicator" }), -})); - -vi.mock("lucide-react-native", () => { - const icon = (name: string) => () => React.createElement("span", { "data-icon": name }); - return { - ChevronRight: icon("ChevronRight"), - MoreHorizontal: icon("MoreHorizontal"), - Trash2: icon("Trash2"), - UserPlus: icon("UserPlus"), - Pencil: icon("Pencil"), - }; -}); - -vi.mock("react-i18next", () => ({ - useTranslation: () => ({ - t: (key: string, values?: Record) => - ( - ({ - "settings.providers.providerDetails": "{{name}} provider details", - "settings.providers.enableProvider": "Enable {{name}}", - "settings.providers.statuses.disabled": "Disabled", - "settings.providers.statuses.available": "Available", - "settings.providers.statuses.loading": "Loading", - "settings.providers.statuses.error": "Error", - "settings.providers.statuses.notInstalled": "Not installed", - "settings.providers.models.one": "1 model", - "settings.providers.models.many": "{{count}} models", - "settings.providers.addErrorTitle": "Unable to add provider", - "settings.providers.updateErrorTitle": "Unable to update provider", - "settings.providers.actions.menu": "{{name}} actions", - "settings.providers.actions.addAccount": "Add account", - "settings.providers.actions.editAccount": "Edit account", - "settings.providers.actions.remove": "Remove provider", - "settings.providers.actions.removing": "Removing...", - "settings.providers.remove.confirmTitle": "Remove {{name}}?", - "settings.providers.remove.confirmMessage": - "This deletes the provider entry from config.json. It cannot be undone.", - "settings.providers.remove.confirm": "Remove", - "settings.providers.remove.errorTitle": "Unable to remove provider", - })[key] ?? key - ) - .replaceAll("{{name}}", String(values?.name ?? "")) - .replaceAll("{{count}}", String(values?.count ?? "")), - }), -})); - -vi.mock("@/components/ui/switch", () => ({ - Switch: ({ - value, - onValueChange, - disabled, - accessibilityLabel, - testID, - }: { - value: boolean; - onValueChange?: (next: boolean) => void; - disabled?: boolean; - accessibilityLabel?: string; - testID?: string; - }) => - React.createElement("div", { - role: "switch", - "aria-checked": value ? "true" : "false", - "aria-disabled": disabled ? "true" : undefined, - "aria-label": accessibilityLabel, - "data-testid": testID ?? "provider-switch", - onClick: (event: React.MouseEvent) => { - event.stopPropagation(); - if (disabled) return; - onValueChange?.(!value); - }, - }), -})); - -vi.mock("@/components/ui/loading-spinner", () => ({ - LoadingSpinner: () => React.createElement("span", { "data-testid": "loading-spinner" }), -})); - -vi.mock("@/components/settings/headings/settings-info-tip", () => ({ - SettingsInfoTip: () => null, -})); - -vi.mock("@/components/ui/external-link", () => ({ - ExternalLink: () => null, - ExternalLinkLabel: () => null, -})); - -vi.mock("@/components/ui/dropdown-menu", () => ({ - DropdownMenu: ({ children }: { children?: React.ReactNode }) => - React.createElement("div", null, children), - DropdownMenuTrigger: ({ - children, - onPressIn, - accessibilityRole, - accessibilityLabel, - testID, - }: { - children?: - | React.ReactNode - | ((state: { pressed: boolean; hovered: boolean; open: boolean }) => React.ReactNode); - onPressIn?: (event: { stopPropagation: () => void }) => void; - accessibilityRole?: string; - accessibilityLabel?: string; - testID?: string; - }) => - React.createElement( - "button", - { - type: "button", - role: accessibilityRole, - "aria-label": accessibilityLabel, - "data-testid": testID, - onMouseDown: (event: React.MouseEvent) => onPressIn?.(event), - onClick: (event: React.MouseEvent) => event.stopPropagation(), - }, - typeof children === "function" - ? children({ pressed: false, hovered: false, open: false }) - : children, - ), - DropdownMenuContent: ({ children }: { children?: React.ReactNode }) => - React.createElement("div", null, children), - DropdownMenuItem: ({ - children, - onSelect, - status, - pendingLabel, - testID, - }: { - children?: React.ReactNode; - onSelect?: () => void; - status?: "idle" | "pending" | "success"; - pendingLabel?: string; - testID?: string; - }) => - React.createElement( - "button", - { - type: "button", - "data-testid": testID, - disabled: status === "pending" || status === "success", - onClick: (event: React.MouseEvent) => { - event.stopPropagation(); - onSelect?.(); - }, - }, - status === "pending" ? pendingLabel : children, - ), -})); - -vi.mock("@/components/provider-icons", () => ({ - useProviderIcon: (provider: string) => () => - React.createElement("span", { "data-icon": `provider-${provider}` }), -})); - -vi.mock("@/stores/provider-settings-store", () => ({ - useProviderSettingsStore: (selector: (state: unknown) => unknown) => - selector({ open: openProviderSettingsMock }), -})); - -vi.mock("@/components/provider-catalog-list", () => ({ - ProviderCatalogList: () => null, -})); - -// The real sheet pulls in react-native-reanimated, which is untransformed here. -vi.mock("@/components/provider-account-sheet", () => ({ - ProviderAccountSheet: ({ - visible, - baseProviderId, - account, - }: { - visible?: boolean; - baseProviderId?: string; - account?: { providerId: string }; - }) => - visible - ? React.createElement("div", { - "data-testid": `provider-account-sheet-${account?.providerId ?? baseProviderId}`, - }) - : null, -})); - -vi.mock("@/hooks/use-providers-snapshot", () => ({ - useProvidersSnapshot: () => ({ - entries: snapshotState.entries, - isLoading: snapshotState.isLoading, - isFetching: false, - isRefreshing: snapshotState.isRefreshing, - error: null, - supportsSnapshot: true, - refresh: vi.fn(async () => {}), - refetchIfStale: vi.fn(), - }), -})); - -vi.mock("@/hooks/use-daemon-config", () => ({ - useDaemonConfig: () => ({ - config: configState.config, - isLoading: false, - patchConfig: patchConfigMock, - }), -})); - -vi.mock("@/runtime/host-runtime", () => ({ - useHostRuntimeIsConnected: () => true, -})); - -vi.mock("@/runtime/host-features", () => ({ - useHostFeature: (_serverId: string, feature: string) => featureState[feature] ?? false, -})); - -vi.mock("@/utils/confirm-dialog", () => ({ - confirmDialog: vi.fn(async () => true), -})); - -import { ProvidersSection } from "./providers-section"; - -function unexpectedToast(): never { - throw new Error("Provider row interactions should not display a toast"); -} - -const toastApi = { show: unexpectedToast, copied: unexpectedToast, error: unexpectedToast }; - -const claudeEntry: ProviderSnapshotEntry = { - provider: "claude", - status: "ready", - enabled: true, - label: "Claude", - description: "Claude Code", - defaultModeId: null, - modes: [], - models: [ - { provider: "claude", id: "claude-opus-4-7", label: "Claude Opus 4.7" }, - { provider: "claude", id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" }, - { provider: "claude", id: "claude-haiku-4-5", label: "Claude Haiku 4.5" }, - ], -}; - -const disabledCodexEntry: ProviderSnapshotEntry = { - provider: "codex", - status: "unavailable", - enabled: false, - label: "Codex", - description: "OpenAI Codex", - defaultModeId: null, - modes: [], -}; - -const claudeWorkEntry: ProviderSnapshotEntry = { - provider: "claude-work", - source: "custom", - status: "ready", - enabled: true, - label: "Claude · Work", - description: "Claude Code work account", - defaultModeId: null, - modes: [], - models: [], -}; - -function makeConfig(providers: MutableDaemonConfig["providers"] = {}): MutableDaemonConfig { - return { - relay: { enabled: false }, - mcp: { injectIntoAgents: false }, - browserTools: { enabled: false }, - providers, - metadataGeneration: { providers: [] }, - autoArchiveAfterMerge: false, - enableTerminalAgentHooks: false, - appendSystemPrompt: "", - }; -} - -function descendants(el: HTMLElement): HTMLElement[] { - return Array.from(el.querySelectorAll("*")); -} - -function indexOfMatches(nodes: HTMLElement[], selector: string): number { - return nodes.findIndex((node) => node.matches(selector)); -} - -function indexOfText(nodes: HTMLElement[], text: string): number { - return nodes.findIndex((node) => node.textContent?.trim() === text); -} - -describe("ProvidersSection", () => { - let root: Root | null = null; - let container: HTMLElement | null = null; - - beforeEach(() => { - vi.stubGlobal("React", React); - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - - snapshotState.entries = undefined; - snapshotState.isLoading = false; - snapshotState.isRefreshing = false; - configState.config = null; - for (const feature of Object.keys(featureState)) delete featureState[feature]; - patchConfigMock.mockReset(); - patchConfigMock.mockResolvedValue(undefined); - openProviderSettingsMock.mockReset(); - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - root = null; - container?.remove(); - container = null; - vi.unstubAllGlobals(); - }); - - function render(): void { - act(() => { - root?.render( - - - , - ); - }); - } - - function findRow(accessibilityLabel: string): HTMLElement { - const row = container?.querySelector( - `[role="button"][aria-label="${accessibilityLabel}"]`, - ); - if (!row) throw new Error(`Expected row with aria-label "${accessibilityLabel}"`); - return row; - } - - it("renders the disabled provider with its server-provided label in snapshot order", () => { - snapshotState.entries = [claudeEntry, disabledCodexEntry]; - configState.config = makeConfig({ codex: { enabled: false } }); - - render(); - - const rows = Array.from( - container?.querySelectorAll('[role="button"][aria-label$="provider details"]') ?? - [], - ); - expect(rows.map((row) => row.getAttribute("aria-label"))).toEqual([ - "Claude provider details", - "Codex provider details", - ]); - - const codexRow = findRow("Codex provider details"); - const codexNodes = descendants(codexRow); - expect(indexOfText(codexNodes, "Codex")).toBeGreaterThanOrEqual(0); - expect(indexOfText(codexNodes, "codex")).toBe(-1); - expect(indexOfText(codexNodes, "Disabled")).toBeGreaterThanOrEqual(0); - }); - - it("composes the row as chevron, icon, label, status, model count, then switch", () => { - snapshotState.entries = [claudeEntry]; - configState.config = makeConfig(); - - render(); - - const row = findRow("Claude provider details"); - const nodes = descendants(row); - const chevron = indexOfMatches(nodes, '[data-icon="ChevronRight"]'); - const icon = indexOfMatches(nodes, '[data-icon="provider-claude"]'); - const label = indexOfText(nodes, "Claude"); - const status = indexOfText(nodes, "Available"); - const modelCount = indexOfText(nodes, "3 models"); - const switchEl = indexOfMatches(nodes, '[role="switch"]'); - - expect(chevron).toBeGreaterThanOrEqual(0); - expect(icon).toBeGreaterThan(chevron); - expect(label).toBeGreaterThan(icon); - expect(status).toBeGreaterThan(label); - expect(modelCount).toBeGreaterThan(status); - expect(switchEl).toBeGreaterThan(modelCount); - }); - - it("groups an account with its base provider and reuses the base icon", () => { - snapshotState.entries = [claudeEntry, disabledCodexEntry, claudeWorkEntry]; - configState.config = makeConfig({ - codex: { enabled: false }, - "claude-work": { extends: "claude", label: "Claude · Work" }, - }); - - render(); - - const rows = Array.from( - container?.querySelectorAll('[role="button"][aria-label$="provider details"]') ?? - [], - ); - expect(rows.map((row) => row.getAttribute("aria-label"))).toEqual([ - "Claude provider details", - "Claude · Work provider details", - "Codex provider details", - ]); - expect( - findRow("Claude · Work provider details").querySelector('[data-icon="provider-claude"]'), - ).not.toBeNull(); - expect( - container?.querySelector('[data-testid="provider-edit-account-claude-work"]'), - ).toBeNull(); - }); - - it("opens the diagnostic sheet when the outer row is pressed for a disabled provider", () => { - snapshotState.entries = [disabledCodexEntry]; - configState.config = makeConfig({ codex: { enabled: false } }); - - render(); - - expect(openProviderSettingsMock).not.toHaveBeenCalled(); - - const row = findRow("Codex provider details"); - act(() => { - row.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); - }); - - expect(openProviderSettingsMock).toHaveBeenCalledTimes(1); - expect(openProviderSettingsMock).toHaveBeenCalledWith({ - serverId: "server-1", - provider: "codex", - }); - }); - - it("opens the account sheet from the actions menu of a builtin provider", () => { - snapshotState.entries = [claudeEntry]; - configState.config = makeConfig(); - - render(); - - const sheetSelector = '[data-testid="provider-account-sheet-claude"]'; - expect(container?.querySelector(sheetSelector)).toBeNull(); - expect(container?.querySelector('[data-testid="provider-remove-claude"]')).toBeNull(); - - const addAccount = container?.querySelector( - '[data-testid="provider-add-account-claude"]', - ); - expect(addAccount).not.toBeNull(); - - act(() => { - addAccount?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); - }); - - expect(container?.querySelector(sheetSelector)).not.toBeNull(); - expect(openProviderSettingsMock).not.toHaveBeenCalled(); - }); - - it("opens an existing account for editing when the daemon supports exact replacement", () => { - snapshotState.entries = [claudeEntry, claudeWorkEntry]; - configState.config = makeConfig({ - "claude-work": { - extends: "claude", - label: "Claude · Work", - env: { CLAUDE_CONFIG_DIR: "/work/claude" }, - }, - }); - featureState.providerConfigReplace = true; - - render(); - - const editAccount = container?.querySelector( - '[data-testid="provider-edit-account-claude-work"]', - ); - expect(editAccount).not.toBeNull(); - act(() => { - editAccount?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); - }); - - expect( - container?.querySelector('[data-testid="provider-account-sheet-claude-work"]'), - ).not.toBeNull(); - expect(openProviderSettingsMock).not.toHaveBeenCalled(); - }); - - it("hides account editing when the daemon does not support exact replacement", () => { - snapshotState.entries = [claudeEntry, claudeWorkEntry]; - configState.config = makeConfig({ - "claude-work": { - extends: "claude", - label: "Claude · Work", - env: { CLAUDE_CONFIG_DIR: "/work/claude" }, - }, - }); - - render(); - - expect( - container?.querySelector('[data-testid="provider-edit-account-claude-work"]'), - ).toBeNull(); - }); - - it("toggles the provider enabled flag through patchConfig when the switch is pressed", async () => { - snapshotState.entries = [claudeEntry]; - configState.config = makeConfig(); - - render(); - - const row = findRow("Claude provider details"); - const switchEl = row.querySelector('[role="switch"]'); - expect(switchEl).not.toBeNull(); - expect(switchEl?.getAttribute("aria-checked")).toBe("true"); - - await act(async () => { - switchEl?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); - }); - - expect(patchConfigMock).toHaveBeenCalledTimes(1); - expect(patchConfigMock).toHaveBeenCalledWith({ - providers: { claude: { enabled: false } }, - }); - }); -}); diff --git a/packages/app/src/screens/settings/providers-section.tsx b/packages/app/src/screens/settings/providers-section.tsx deleted file mode 100644 index ab4c6ae65e9a..000000000000 --- a/packages/app/src/screens/settings/providers-section.tsx +++ /dev/null @@ -1,780 +0,0 @@ -import { useCallback, useMemo, useRef, useState } from "react"; -import type { TFunction } from "i18next"; -import { useTranslation } from "react-i18next"; -import { - Alert, - Pressable, - Text, - View, - type GestureResponderEvent, - type PressableStateCallbackType, -} from "react-native"; -import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { useIsCompactFormFactor } from "@/constants/layout"; -import { useToast } from "@/contexts/toast-api-context"; -import { settingsStyles } from "@/styles/settings"; -import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; -import { selectHostFeature, useHostFeature } from "@/runtime/host-features"; -import { useSessionStore } from "@/stores/session-store"; -import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; -import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { buildProviderDefinitions } from "@/utils/provider-definitions"; -import { - buildAcpProviderConfigPatch, - getAcpProviderCatalog, - type AcpProviderCatalogItem, -} from "@/hooks/use-acp-provider-catalog"; -import { ProviderCatalogList } from "@/components/provider-catalog-list"; -import { - ProviderAccountSheet, - type ProviderAccountSaveInput, -} from "@/components/provider-account-sheet"; -import { - canAddProviderAccount, - groupProviderAccounts, - resolveProviderAccountBaseId, -} from "@/provider-accounts/provider-account-form-model"; -import { useProviderIcon } from "@/components/provider-icons"; -import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton"; -import { Switch } from "@/components/ui/switch"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { SettingsSection } from "@/components/settings/headings/settings-section"; -import { useProviderSettingsStore } from "@/stores/provider-settings-store"; -import { confirmDialog } from "@/utils/confirm-dialog"; -import { filterSelectableModels } from "@/provider-selection/model-catalog"; -import { ChevronRight, MoreHorizontal, Pencil, Trash2, UserPlus } from "lucide-react-native"; - -type ProviderDefinition = ReturnType[number]; -type ProviderEntry = NonNullable["entries"]>[number]; - -type StatusTone = "success" | "warning" | "danger" | "muted" | "loading"; - -interface ProviderStatus { - tone: StatusTone; - label: string; - modelCount: number | null; -} - -function getProviderStatus( - status: string, - enabled: boolean, - modelCount: number, - t: TFunction, -): ProviderStatus { - if (!enabled) - return { tone: "muted", label: t("settings.providers.statuses.disabled"), modelCount: null }; - if (status === "loading") { - return { tone: "loading", label: t("settings.providers.statuses.loading"), modelCount: null }; - } - if (status === "error") { - return { tone: "danger", label: t("settings.providers.statuses.error"), modelCount: null }; - } - if (status === "ready") { - return { - tone: "success", - label: t("settings.providers.statuses.available"), - modelCount: modelCount > 0 ? modelCount : null, - }; - } - return { - tone: "warning", - label: t("settings.providers.statuses.notInstalled"), - modelCount: null, - }; -} - -interface ProviderRowProps { - serverId: string; - def: ProviderDefinition; - entry: ProviderEntry; - enabled: boolean; - isToggling: boolean; - isRemoving: boolean; - canRemove: boolean; - canAddAccount: boolean; - canEditAccount: boolean; - iconProviderId: string; - isFirst: boolean; - onPress: (providerId: string) => void; - onToggleEnabled: (providerId: string, enabled: boolean) => void; - onRemove: (providerId: string, providerLabel: string) => void; - onAddAccount: (providerId: string, providerLabel: string) => void; - onEditAccount: (providerId: string) => void; -} - -function stopPressInPropagation(event: GestureResponderEvent) { - event.stopPropagation(); -} - -interface ProviderActionsMenuProps { - providerId: string; - providerLabel: string; - isRemoving: boolean; - canRemove: boolean; - canAddAccount: boolean; - canEditAccount: boolean; - iconSize: number; - foregroundColor: string; - foregroundMutedColor: string; - dangerColor: string; - onRemove: (providerId: string, providerLabel: string) => void; - onAddAccount: (providerId: string, providerLabel: string) => void; - onEditAccount: (providerId: string) => void; -} - -function ProviderActionsMenu({ - providerId, - providerLabel, - isRemoving, - canRemove, - canAddAccount, - canEditAccount, - iconSize, - foregroundColor, - foregroundMutedColor, - dangerColor, - onRemove, - onAddAccount, - onEditAccount, -}: ProviderActionsMenuProps) { - const { t } = useTranslation(); - const handleRemove = useCallback(() => { - onRemove(providerId, providerLabel); - }, [onRemove, providerId, providerLabel]); - const handleAddAccount = useCallback(() => { - onAddAccount(providerId, providerLabel); - }, [onAddAccount, providerId, providerLabel]); - const handleEditAccount = useCallback(() => { - onEditAccount(providerId); - }, [onEditAccount, providerId]); - const triggerStyle = useCallback( - ({ - pressed, - hovered, - open, - }: PressableStateCallbackType & { hovered?: boolean; open?: boolean }) => [ - styles.menuButton, - (hovered || open) && styles.menuButtonHovered, - pressed && styles.menuButtonPressed, - ], - [], - ); - const trashLeading = useMemo(() => , [dangerColor]); - const addAccountLeading = useMemo( - () => , - [foregroundMutedColor], - ); - const editAccountLeading = useMemo( - () => , - [foregroundMutedColor], - ); - - return ( - - - {({ hovered, open }) => ( - - )} - - - {canAddAccount ? ( - - {t("settings.providers.actions.addAccount")} - - ) : null} - {canEditAccount ? ( - - {t("settings.providers.actions.editAccount")} - - ) : null} - {canRemove ? ( - - {t("settings.providers.actions.remove")} - - ) : null} - - - ); -} - -const SKELETON_ROW_KEYS = [0, 1, 2, 3].map((index) => `provider-skeleton-row-${index}`); - -function ProviderRowsSkeleton() { - const { t } = useTranslation(); - const pulse = useSkeletonPulse(); - return ( - - {SKELETON_ROW_KEYS.map((key, index) => ( - 0 && settingsStyles.rowBorder, styles.row]} - > - - - - - - - ))} - - ); -} - -function ProviderRow({ - serverId, - def, - entry, - enabled, - isToggling, - isRemoving, - canRemove, - canAddAccount, - canEditAccount, - iconProviderId, - isFirst, - onPress, - onToggleEnabled, - onRemove, - onAddAccount, - onEditAccount, -}: ProviderRowProps) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const isCompact = useIsCompactFormFactor(); - const ProviderIcon = useProviderIcon(iconProviderId, serverId); - const providerError = - enabled && - entry.status === "error" && - typeof entry.error === "string" && - entry.error.trim().length > 0 - ? entry.error.trim() - : null; - const modelCount = filterSelectableModels(entry.models ?? null)?.length ?? 0; - const providerStatus = getProviderStatus(entry.status, enabled, modelCount, t); - - const handlePress = useCallback(() => { - onPress(def.id); - }, [def.id, onPress]); - const handleToggleValueChange = useCallback( - (value: boolean) => { - onToggleEnabled(def.id, value); - }, - [def.id, onToggleEnabled], - ); - const rowStyle = useCallback( - ({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => [ - settingsStyles.row, - !isFirst && settingsStyles.rowBorder, - styles.row, - hovered && styles.rowHovered, - pressed && styles.rowPressed, - ], - [isFirst], - ); - - return ( - - {({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => ( - <> - - - - - - - {def.label} - - {!isCompact ? · : null} - - - {providerError && !isCompact ? ( - - {providerError} - - ) : null} - - - {/* The menu leads the switch, so every switch sits on the row's right edge without - rows that have no menu reserving room for one. */} - - {canRemove || canAddAccount || canEditAccount ? ( - - ) : null} - - - - )} - - ); -} - -function getDotColor(tone: StatusTone, theme: ReturnType["theme"]): string { - switch (tone) { - case "success": - return theme.colors.statusSuccess; - case "warning": - return theme.colors.statusWarning; - case "danger": - return theme.colors.statusDanger; - default: - return theme.colors.foregroundMuted; - } -} - -function StatusIndicator({ status, compact }: { status: ProviderStatus; compact: boolean }) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const dotStyle = useMemo( - () => [styles.statusDot, { backgroundColor: getDotColor(status.tone, theme) }], - [status.tone, theme], - ); - - return ( - - {status.tone === "loading" ? ( - - ) : ( - - )} - {!compact ? ( - <> - {status.label} - {status.modelCount !== null ? ( - <> - · - - {status.modelCount === 1 - ? t("settings.providers.models.one") - : t("settings.providers.models.many", { count: status.modelCount })} - - - ) : null} - - ) : null} - - ); -} - -interface ProviderAccountTarget { - baseProviderId: string; - baseProviderLabel: string; - account?: { - providerId: string; - config: NonNullable["config"]>["providers"][string]; - }; -} - -export interface ProvidersSectionProps { - serverId: string; -} - -export function ProvidersSection({ serverId }: ProvidersSectionProps) { - const { t } = useTranslation(); - const toast = useToast(); - const isConnected = useHostRuntimeIsConnected(serverId); - const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval"); - const supportsProviderConfigReplace = useHostFeature(serverId, "providerConfigReplace"); - const supportsProviderConfigRename = useHostFeature(serverId, "providerConfigRename"); - const { entries, isLoading, refresh } = useProvidersSnapshot(serverId); - const { config, patchConfig } = useDaemonConfig(serverId); - const openProviderSettings = useProviderSettingsStore((state) => state.open); - const [pendingProviderId, setPendingProviderId] = useState(null); - const [removingProviderId, setRemovingProviderId] = useState(null); - const removingProviderIdRef = useRef(null); - const [installingProviderId, setInstallingProviderId] = useState(null); - const [accountTarget, setAccountTarget] = useState(null); - - const providerDefinitions = useMemo( - () => groupProviderAccounts(buildProviderDefinitions(entries), config?.providers), - [config?.providers, entries], - ); - const existingProviderIds = useMemo( - () => (entries ?? []).map((entry) => entry.provider), - [entries], - ); - const hasServer = serverId.length > 0; - - /** Config owns derived providers and opt-in bundled catalog providers. */ - const isConfigOwnedProvider = useCallback( - (providerId: string) => - Boolean( - config?.providers?.[providerId] && - (config.providers[providerId].extends || - getAcpProviderCatalog().some( - (entry) => entry.id === providerId && entry.bundledProvider, - )), - ), - [config], - ); - - const handleOpenProviderSettings = useCallback( - (providerId: string) => { - openProviderSettings({ serverId, provider: providerId }); - }, - [openProviderSettings, serverId], - ); - - const handleToggleEnabled = useCallback( - async (providerId: string, enabled: boolean) => { - setPendingProviderId(providerId); - try { - await patchConfig({ providers: { [providerId]: { enabled } } }); - } catch (error) { - Alert.alert( - t("settings.providers.updateErrorTitle"), - error instanceof Error ? error.message : String(error), - ); - } finally { - setPendingProviderId((current) => (current === providerId ? null : current)); - } - }, - [patchConfig, t], - ); - - const handleRemoveProvider = useCallback( - async (providerId: string, providerLabel: string) => { - if (removingProviderIdRef.current) return; - removingProviderIdRef.current = providerId; - setRemovingProviderId(providerId); - try { - const confirmed = await confirmDialog({ - title: t("settings.providers.remove.confirmTitle", { name: providerLabel }), - message: t("settings.providers.remove.confirmMessage"), - confirmLabel: t("settings.providers.remove.confirm"), - destructive: true, - }); - if (!confirmed) { - return; - } - - await patchConfig({ removeProviders: [providerId] }); - } catch (error) { - Alert.alert( - t("settings.providers.remove.errorTitle"), - error instanceof Error ? error.message : String(error), - ); - } finally { - if (removingProviderIdRef.current === providerId) { - removingProviderIdRef.current = null; - } - setRemovingProviderId((current) => (current === providerId ? null : current)); - } - }, - [patchConfig, t], - ); - - const handleInstall = useCallback( - async (entry: AcpProviderCatalogItem) => { - if (installingProviderId) return; - setInstallingProviderId(entry.id); - try { - await patchConfig( - buildAcpProviderConfigPatch(entry, (feature) => - selectHostFeature(useSessionStore.getState(), serverId, feature), - ), - ); - await refresh([entry.id]); - } catch (error) { - toast.error(error instanceof Error ? error.message : String(error)); - } finally { - setInstallingProviderId((current) => (current === entry.id ? null : current)); - } - }, - [installingProviderId, patchConfig, refresh, serverId, toast], - ); - - const handleOpenAddAccount = useCallback((providerId: string, providerLabel: string) => { - setAccountTarget({ baseProviderId: providerId, baseProviderLabel: providerLabel }); - }, []); - - const handleOpenEditAccount = useCallback( - (providerId: string) => { - const providerConfig = config?.providers[providerId]; - const baseProviderId = resolveProviderAccountBaseId(providerId, config?.providers); - if (!providerConfig || !baseProviderId) return; - const baseProviderLabel = - entries?.find((entry) => entry.provider === baseProviderId)?.label ?? baseProviderId; - setAccountTarget({ - baseProviderId, - baseProviderLabel, - account: { providerId, config: providerConfig }, - }); - }, - [config?.providers, entries], - ); - - const handleCloseAccount = useCallback(() => { - setAccountTarget(null); - }, []); - - const handleSaveAccount = useCallback( - async ({ providerId, originalProviderId, patch }: ProviderAccountSaveInput) => { - try { - await patchConfig(patch); - await refresh( - originalProviderId && originalProviderId !== providerId - ? [originalProviderId, providerId] - : [providerId], - ); - return true; - } catch (error) { - Alert.alert( - t("settings.providers.account.errorTitle"), - error instanceof Error ? error.message : String(error), - ); - return false; - } - }, - [patchConfig, refresh, t], - ); - - return ( - <> - - {!hasServer || !isConnected ? ( - - {t("settings.providers.unavailable")} - - ) : null} - {hasServer && isConnected && isLoading ? : null} - {hasServer && isConnected && !isLoading && providerDefinitions.length > 0 ? ( - - {providerDefinitions.map((def, index) => { - const entry = entries?.find((candidate) => candidate.provider === def.id); - if (!entry) return null; - return ( - - ); - })} - - ) : null} - - - {hasServer && isConnected ? ( - - - - ) : null} - - {accountTarget ? ( - - ) : null} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - sectionSpacing: { - marginBottom: theme.spacing[4], - }, - addProviderSection: { - marginTop: theme.spacing[4], - }, - emptyCard: { - padding: theme.spacing[4], - alignItems: "center", - }, - emptyText: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, - row: { - gap: theme.spacing[3], - minHeight: 56, - }, - rowHovered: { - backgroundColor: theme.colors.surface2, - }, - skeletonIcon: { - width: 20, - height: 20, - marginLeft: theme.spacing[6], - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - }, - skeletonTitle: { - width: 160, - height: 12, - borderRadius: theme.borderRadius.sm, - backgroundColor: theme.colors.surface2, - }, - skeletonSwitch: { - width: 36, - height: 20, - borderRadius: theme.borderRadius.full, - backgroundColor: theme.colors.surface2, - }, - rowPressed: { - backgroundColor: theme.colors.surface3, - }, - rowContent: { - flex: 1, - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - textColumn: { - flex: 1, - minWidth: 0, - }, - titleRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - statusRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1.5], - }, - statusDot: { - width: 8, - height: 8, - borderRadius: 4, - }, - statusLabel: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, - separator: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, - errorText: { - color: theme.colors.palette.red[300], - fontSize: theme.fontSize.sm, - marginTop: theme.spacing[1], - }, - trailingControls: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1], - }, - menuButton: { - width: 32, - height: 32, - borderRadius: theme.borderRadius.lg, - alignItems: "center", - justifyContent: "center", - }, - menuButtonHovered: { - backgroundColor: theme.colors.surface2, - }, - menuButtonPressed: { - backgroundColor: theme.colors.surface3, - }, -})); diff --git a/packages/app/src/screens/workspace/compact-workspace-header/index.browser.test.tsx b/packages/app/src/screens/workspace/compact-workspace-header/index.browser.test.tsx index bc87c9da5989..7bcb0a0e23c1 100644 --- a/packages/app/src/screens/workspace/compact-workspace-header/index.browser.test.tsx +++ b/packages/app/src/screens/workspace/compact-workspace-header/index.browser.test.tsx @@ -20,8 +20,6 @@ afterEach(async () => { await act(async () => root.render(null)); usePanelStore.setState(initialPanel, true); }); -const noop = () => {}; -const explorerState = { expanded: false }; const geometry: WindowLayout = { bounds: { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight }, verticalBarEdge: "trailing", @@ -42,9 +40,8 @@ it("updates compact header actions on panel changes without rendering the worksp title="Workspace" subtitle="Project" isSubtitleDistinct - onToggleExplorer={noop} - explorerToggleLabel="Explorer" - explorerToggleAccessibilityState={explorerState} + explorerAction={null} + inDesktopTitlebar={false} tabSwitcher={null} headerVariant="full" > diff --git a/packages/app/src/screens/workspace/compact-workspace-header/index.tsx b/packages/app/src/screens/workspace/compact-workspace-header/index.tsx index b87de93e36f9..0d6c90d5dbb8 100644 --- a/packages/app/src/screens/workspace/compact-workspace-header/index.tsx +++ b/packages/app/src/screens/workspace/compact-workspace-header/index.tsx @@ -1,11 +1,6 @@ import { Fragment, useMemo, type ReactNode } from "react"; -import { useTranslation } from "react-i18next"; import { usePanelStore } from "@/stores/panel-store"; import { CompactHeader } from "@/components/headers/compact-header"; -import { - EXPLORER_TOGGLE_KEYS, - WorkspaceExplorerToggle, -} from "@/screens/workspace/workspace-explorer-toggle"; import { WorkspaceHeaderProjectRow } from "@/screens/workspace/workspace-header-project-row"; import { useWindowLayout, @@ -23,10 +18,9 @@ interface CompactWorkspaceHeaderProps { title: string; subtitle: string; isSubtitleDistinct: boolean; - onToggleExplorer: () => void; - explorerToggleLabel: string; - explorerToggleAccessibilityState: { expanded: boolean }; + explorerAction: ReactNode; tabSwitcher: ReactNode; + inDesktopTitlebar: boolean; /** Workspace overflow menu. */ children: ReactNode; headerVariant: "compact" | "full"; @@ -40,17 +34,15 @@ export function CompactWorkspaceHeader({ title, subtitle, isSubtitleDistinct, - onToggleExplorer, - explorerToggleLabel, - explorerToggleAccessibilityState, + explorerAction, children, tabSwitcher, + inDesktopTitlebar, serverId, headerVariant, isRouteFocused, isCompact, }: CompactWorkspaceHeaderProps) { - const { t } = useTranslation(); const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar"; const projectRow = useMemo( () => ( @@ -65,16 +57,7 @@ export function CompactWorkspaceHeader({ const symbols = { "tab-count": tabSwitcher, overflow: children, - explorer: ( - - ), + explorer: explorerAction, }; const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => ( {symbols[symbol]} @@ -85,6 +68,7 @@ export function CompactWorkspaceHeader({ {headerVariant === "compact" ? ( void; label: string; tooltipLabel: string; - tooltipKeys: ShortcutKey[]; accessibilityState: { expanded: boolean }; mobile: boolean; style?: StyleProp; } -export type WorkspaceExplorerToggleOwner = "mobile" | "header" | "window"; - -export function resolveWorkspaceExplorerToggleOwner({ - isMobile, - hasMacTrafficLights, -}: { - isMobile: boolean; - hasMacTrafficLights: boolean; -}): WorkspaceExplorerToggleOwner { - if (isMobile) return "mobile"; - return hasMacTrafficLights ? "window" : "header"; -} - -export function WorkspaceExplorerToggle({ +function WorkspaceExplorerToggle({ onPress, label, tooltipLabel, - tooltipKeys, accessibilityState, mobile, style, @@ -51,7 +41,7 @@ export function WorkspaceExplorerToggle({ testID="workspace-explorer-toggle" onPress={onPress} tooltipLabel={tooltipLabel} - tooltipKeys={tooltipKeys} + tooltipKeys={EXPLORER_TOGGLE_KEYS} tooltipSide="left" style={style} accessible @@ -68,42 +58,97 @@ export function WorkspaceExplorerToggle({ ); } -interface DesktopWorkspaceExplorerToggleProps extends Omit { - owner: WorkspaceExplorerToggleOwner; -} +export function useWorkspaceExplorerControls({ + hasWorkspace, + compact, + focusMode, + expanded, + onToggle, +}: { + hasWorkspace: boolean; + compact: boolean; + focusMode: boolean; + expanded: boolean; + onToggle: () => void; +}) { + const { t } = useTranslation(); + const hasLeadingWindowControls = useHasWindowChromeObstruction("top-left"); + const inDesktopTitlebar = hasLeadingWindowControls && hasWorkspace && !compact && !focusMode; -export function WorkspaceHeaderExplorerToggle({ - owner, - accessibilityState, - style, - ...toggleProps -}: DesktopWorkspaceExplorerToggleProps) { - if (owner === "mobile" || (owner === "window" && accessibilityState.expanded)) return null; - return ( - - ); -} + return useMemo(() => { + const props = { + label: expanded + ? t("workspace.tabs.explorerSidebar.close") + : t("workspace.tabs.explorerSidebar.open"), + tooltipLabel: t("workspace.tabs.explorerSidebar.toggle"), + onPress: onToggle, + accessibilityState: { expanded }, + }; -export function WorkspaceExplorerSidebarToggle({ - owner, - ...toggleProps -}: DesktopWorkspaceExplorerToggleProps) { - if (owner === "header") return null; - if (owner === "mobile") { - // The compact Explorer is an overlay like the compact agent list, so it closes with the same X. - return ( - - ); - } - return ; + if (inDesktopTitlebar) { + // Keep the button in the header Tab order. The active rail carves its slot out of the drag region. + const headerSlot = expanded ? null : ( + + ); + return { + inDesktopTitlebar, + headerAction: headerSlot, + compactAction: headerSlot, + dockAction: ( + + ), + titlebarAction: ( + + + + ), + }; + } + + return { + inDesktopTitlebar, + headerAction: compact ? null : ( + + ), + compactAction: , + dockAction: compact ? ( + + ) : null, + titlebarAction: null, + }; + }, [compact, expanded, inDesktopTitlebar, onToggle, t]); } + +const styles = StyleSheet.create((theme) => ({ + headerAction: { + marginRight: { xs: 0, md: -theme.spacing[2] }, + }, + dockAction: { + // The dock divider is absolutely positioned. Match the other headers' content center. + marginBottom: theme.borderWidth[1], + }, + titlebarSlot: { + position: "absolute", + top: 0, + right: theme.spacing[1], + height: WORKSPACE_SECONDARY_HEADER_HEIGHT, + // Center with the bordered workspace header and Explorer tabs row. + borderBottomWidth: theme.borderWidth[1], + borderBottomColor: "transparent", + justifyContent: "center", + zIndex: 1, + }, +})); diff --git a/packages/app/src/screens/workspace/workspace-header-menu.tsx b/packages/app/src/screens/workspace/workspace-header-menu.tsx index e70503af5c78..be356febe778 100644 --- a/packages/app/src/screens/workspace/workspace-header-menu.tsx +++ b/packages/app/src/screens/workspace/workspace-header-menu.tsx @@ -3,7 +3,14 @@ import React, { useCallback, useMemo, useState } from "react"; import { View } from "react-native"; import { useRouter, type Href } from "expo-router"; import { useTranslation } from "react-i18next"; -import { Copy, Ellipsis, Globe, Import as ImportIcon, Settings } from "lucide-react-native"; +import { + Archive, + Copy, + Ellipsis, + Globe, + Import as ImportIcon, + Settings, +} from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import type { TerminalProfile } from "@getpaseo/protocol/messages"; import { @@ -21,6 +28,7 @@ import { useIconButtonChromeStyle, } from "@/components/ui/icon-button-chrome"; import { TerminalProfileIcon } from "@/components/terminal-profile-icon"; +import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive"; import { useDaemonConfig } from "@/hooks/use-daemon-config"; import { getTerminalProfileIcon, @@ -35,6 +43,7 @@ import { import { usePluginWorkspaceMenu } from "@/plugins"; const ThemedEllipsis = withUnistyles(Ellipsis); +const ThemedArchive = withUnistyles(Archive); const ThemedCopy = withUnistyles(Copy); const ThemedGlobe = withUnistyles(Globe); const ThemedImport = withUnistyles(ImportIcon); @@ -45,6 +54,7 @@ const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMut const MENU_NEW_BROWSER_ICON = ; const MENU_IMPORT_ICON = ; const MENU_COPY_ICON = ; +const MENU_ARCHIVE_ICON = ; const MENU_SETTINGS_ICON = ; function WorkspaceHeaderMenuTriggerIcon() { return ( @@ -260,6 +270,10 @@ export function WorkspaceHeaderMenuMobile({ router.push(buildSettingsHostSectionRoute(normalizedServerId, "terminals") as Href); }, [normalizedServerId, router]); const [menuOpen, setMenuOpen] = useState(false); + const { canArchive, archive } = useActiveWorkspaceArchive(); + const handleArchiveWorkspace = useCallback(() => { + archive(); + }, [archive]); // Discovery belongs to the open menu: the scripts page asks for package scripts only once the // user opens it, so a compact workspace does not poll for scripts it never shows. const scriptsMenu = useWorkspaceScriptsMenuPages({ ...scripts, menuOpen }); @@ -333,6 +347,15 @@ export function WorkspaceHeaderMenuMobile({ ) : null} + + {t("sidebar.workspace.actions.archiveWorkspace")} + + {t("workspace.tabs.actions.terminalProfilesMenu")} {profiles.map((profile) => ( state.layoutMode); - const hasMacTrafficLights = useHasWindowChromeObstruction("top-left"); - const explorerToggleOwner = resolveWorkspaceExplorerToggleOwner({ - isMobile, - hasMacTrafficLights, - }); const isFocusModeEnabled = usePanelStore((state) => state.desktop.focusModeEnabled); + const desktopFocusModeEnabled = isFocusModeEnabled && !isMobile; const toggleFocusMode = usePanelStore((state) => state.toggleFocusMode); const normalizedServerId = useMemo(() => trimNonEmpty(decodeSegment(serverId)) ?? "", [serverId]); @@ -1345,11 +1332,6 @@ function WorkspaceScreenContent({ explorerOpen: isExplorerSidebarShowing, }); - const explorerSidebarToggleAccessibilityState = useMemo( - () => ({ expanded: isExplorerSidebarShowing }), - [isExplorerSidebarShowing], - ); - useEffect(() => { // Back dismisses the compact overlay only. On a wide native layout the // explorer is a tab, `showMobileAgent` has no rendered consumer, and @@ -1857,9 +1839,6 @@ function WorkspaceScreenContent({ }), [t], ); - const explorerSidebarToggleLabel = isExplorerSidebarShowing - ? t("workspace.tabs.explorerSidebar.close") - : t("workspace.tabs.explorerSidebar.open"); const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]); const handleCreateDraftTab = useCallback( @@ -3301,6 +3280,13 @@ function WorkspaceScreenContent({ workspaceKey: persistenceKey, }); + const explorerControls = useWorkspaceExplorerControls({ + hasWorkspace: !!workspaceDirectory, + compact: isMobile, + focusMode: desktopFocusModeEnabled, + expanded: isExplorerSidebarShowing, + onToggle: handleToggleExplorerSidebar, + }); const headerRight = useMemo( () => ( @@ -3330,17 +3316,7 @@ function WorkspaceScreenContent({ {workspaceDirectory ? ( <> - {workspaceActionsInBar ? null : ( - - )} + {workspaceActionsInBar ? null : explorerControls.headerAction} ) : null} @@ -3356,12 +3332,8 @@ function WorkspaceScreenContent({ scriptActions, handleViewScriptTerminal, handleOpenUrlInBrowserTab, - handleToggleExplorerSidebar, - explorerSidebarToggleLabel, - explorerSidebarToggleAccessibilityState, - explorerToggleOwner, + explorerControls.headerAction, workspaceActionsInBar, - t, ], ); @@ -3369,25 +3341,6 @@ function WorkspaceScreenContent({ () => shouldShowWorkspaceScreenHeader({ isFocusModeEnabled, isMobile }), [isFocusModeEnabled, isMobile], ); - const renderExplorerSidebarHeaderAction = useCallback( - () => ( - - ), - [ - explorerSidebarToggleAccessibilityState, - explorerSidebarToggleLabel, - explorerToggleOwner, - handleToggleExplorerSidebar, - t, - ], - ); const createTerminalDisabled = useMemo( () => createTerminalMutation.isPending || pendingTerminalCreateInput !== null, [createTerminalMutation.isPending, pendingTerminalCreateInput], @@ -3410,10 +3363,6 @@ function WorkspaceScreenContent({ ], ); const focusedPaneIdOrUndefined = useMemo(() => focusedPaneId ?? undefined, [focusedPaneId]); - const desktopFocusModeEnabled = useMemo( - () => isFocusModeEnabled && !isMobile, - [isFocusModeEnabled, isMobile], - ); const workspaceFloatingPanelPortalHostName = useMemo( () => `${WORKSPACE_FLOATING_PANEL_PORTAL_HOST_PREFIX}:${normalizedServerId}:${normalizedWorkspaceId}`, @@ -3550,14 +3499,13 @@ function WorkspaceScreenContent({ isRouteFocused={isRouteFocused} isCompact={isMobile} tabSwitcher={tabSwitcher} + inDesktopTitlebar={explorerControls.inDesktopTitlebar} + explorerAction={explorerControls.compactAction} isLoading={isWorkspaceHeaderLoading} title={workspaceHeaderTitle} subtitle={workspaceHeaderSubtitle} isSubtitleDistinct={isWorkspaceHeaderSubtitleDistinct} serverId={normalizedServerId} - onToggleExplorer={handleToggleExplorerSidebar} - explorerToggleLabel={explorerSidebarToggleLabel} - explorerToggleAccessibilityState={explorerSidebarToggleAccessibilityState} > ); return ( @@ -3865,7 +3812,7 @@ function WorkspaceScreenContent({ toggleFocusMode, handleReorderTabsInPane, buildDesktopPaneContentModel, - renderExplorerSidebarHeaderAction, + explorerControls.dockAction, desktopFocusModeEnabled, ]); @@ -3939,6 +3886,7 @@ function WorkspaceScreenContent({ onReorderTabsInPane={handleReorderTabsInPane} onSplitPane={handleSplitPane} > + {explorerControls.titlebarAction} {workspaceCenterColumn} {sharedExplorer} @@ -4076,12 +4024,6 @@ const styles = StyleSheet.create((theme) => ({ md: theme.spacing[2], }, }, - compactHeaderActionButton: { - marginRight: { - xs: 0, - md: -theme.spacing[2], - }, - }, compactHeaderMenuCluster: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/screens/workspace/workspace-tab-layout.test.ts b/packages/app/src/screens/workspace/workspace-tab-layout.test.ts index 9b428bc0bcd5..4b8eb174b0ce 100644 --- a/packages/app/src/screens/workspace/workspace-tab-layout.test.ts +++ b/packages/app/src/screens/workspace/workspace-tab-layout.test.ts @@ -1,10 +1,5 @@ import { buildDesktopFrameStyle } from "@/components/ui/combobox-frame-style"; -import { - WorkspaceHeaderExplorerToggle, - WorkspaceExplorerSidebarToggle, -} from "./workspace-explorer-toggle"; import { describe, expect, it } from "vitest"; -import { SidebarCloseButton } from "@/components/headers/sidebar-close-button"; import { resolveWorkspaceTabChipBackdrop } from "@/screens/workspace/workspace-tab-chip-backdrop"; import { darkPureBlackTheme, darkTheme, lightTheme } from "@/styles/theme"; import { @@ -190,37 +185,6 @@ describe("retainWorkspaceTabMeasuredWidth", () => { }); }); -describe("Explorer toggle ownership", () => { - const toggleProps = { - onPress: () => {}, - label: "Close Explorer sidebar", - tooltipLabel: "Toggle Explorer sidebar", - tooltipKeys: [], - accessibilityState: { expanded: true }, - }; - - it("keeps only the header toggle when window controls do not obstruct it", () => { - expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner: "header" })).not.toBeNull(); - expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "header" })).toBeNull(); - }); - - it("keeps the dock toggle for window-owned and compact overlay chrome", () => { - for (const owner of ["window", "mobile"] as const) { - expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner })).toBeNull(); - expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner })).not.toBeNull(); - } - }); - - it("closes the compact overlay with the same X as the compact agent list", () => { - expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "mobile" })?.type).toBe( - SidebarCloseButton, - ); - expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "window" })?.type).not.toBe( - SidebarCloseButton, - ); - }); -}); - describe("resolveWorkspaceTabChipBackdrop", () => { const themes = { light: lightTheme, dark: darkTheme, pureBlack: darkPureBlackTheme }; const rails = { diff --git a/packages/app/src/sidebar-nav/model.test.ts b/packages/app/src/sidebar-nav/model.test.ts index f7e7ba093375..c294cd2a3b10 100644 --- a/packages/app/src/sidebar-nav/model.test.ts +++ b/packages/app/src/sidebar-nav/model.test.ts @@ -115,12 +115,12 @@ describe("resolveSidebarNavItems", () => { }); describe("resolveSidebarNavItems for the Usage item", () => { - it("hides the Usage item until it is turned on", () => { + it("shows the Usage item by default and honors an explicit off choice", () => { const resolve = (preferences: SidebarNavPreference[]) => summarize(resolveSidebarNavItems({ section: "footer", pluginGroups: [], preferences })); - expect(resolve([])).toEqual([{ key: "usage", visible: false }]); - expect(resolve([{ key: "usage", visible: true }])).toEqual([{ key: "usage", visible: true }]); + expect(resolve([])).toEqual([{ key: "usage", visible: true }]); + expect(resolve([{ key: "usage", visible: false }])).toEqual([{ key: "usage", visible: false }]); }); }); @@ -297,7 +297,7 @@ describe("footer section", () => { }); expect(summarize(items)).toEqual([ - { key: "usage", visible: false }, + { key: "usage", visible: true }, { key: syncKey, visible: true }, ]); }); @@ -309,7 +309,7 @@ describe("footer section", () => { preferences: [{ key: "history", visible: false }], }); - expect(summarize(items)).toEqual([{ key: "usage", visible: false }]); + expect(summarize(items)).toEqual([{ key: "usage", visible: true }]); }); it("ignores the footer icon buttons, which are fixed and not items", () => { diff --git a/packages/app/src/sidebar-nav/model.ts b/packages/app/src/sidebar-nav/model.ts index 6b98821e93fa..838571b222df 100644 --- a/packages/app/src/sidebar-nav/model.ts +++ b/packages/app/src/sidebar-nav/model.ts @@ -69,11 +69,8 @@ export function builtinSidebarNavShortcutAction(id: BuiltinSidebarItemId): strin return BUILTIN_SHORTCUT_ACTIONS[id]; } -/** Builtins that start hidden until the user turns them on: the Usage summary is opt-in. */ -const HIDDEN_BY_DEFAULT: ReadonlySet = new Set(["usage"]); - -function builtinVisibleByDefault(id: BuiltinSidebarItemId): boolean { - return !HIDDEN_BY_DEFAULT.has(id); +function builtinVisibleByDefault(_id: BuiltinSidebarItemId): boolean { + return true; } export function pluginSidebarNavKey( diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index cdbe8073bd36..ace11e2e96b5 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -34,6 +34,7 @@ import type { AgentCapabilityFlags, AgentUsage, AgentArtifact, + AgentMetric, AgentPersistenceHandle, } from "@getpaseo/protocol/agent-types"; import type { @@ -102,6 +103,8 @@ export interface Agent { runtimeInfo?: AgentRuntimeInfo; usageScopeKey?: string; lastUsage?: AgentUsage; + /** What the provider reports about the session, as label and value rows. */ + sessionMetrics?: AgentMetric[]; lastError?: string | null; title: string | null; cwd: string; diff --git a/packages/app/src/stores/sidebar-view-store.ts b/packages/app/src/stores/sidebar-view-store.ts index 1b53fdfe9ddb..2e94a0d88725 100644 --- a/packages/app/src/stores/sidebar-view-store.ts +++ b/packages/app/src/stores/sidebar-view-store.ts @@ -69,6 +69,7 @@ interface SidebarViewStoreState { setWorkspaceSort: (sort: WorkspaceSort) => void; toggleHostFilter: (serverId: string) => void; clearHostFilters: () => void; + focusHost: (serverId: string) => void; toggleProjectFilter: (viewKey: string) => void; clearProjectFilters: () => void; toggleLabelFilter: (name: string) => void; @@ -205,6 +206,9 @@ export const useSidebarViewStore = create()( toggleHostFilter: (serverId) => set((state) => ({ hostFilters: toggleFilterEntry(state.hostFilters, serverId) })), clearHostFilters: () => set({ hostFilters: [] }), + // An explicit navigation target must not be hidden by another host's facets. + focusHost: (serverId) => + set({ hostFilters: [serverId], projectFilters: [], labelFilter: emptyLabelFilter() }), toggleProjectFilter: (viewKey) => set((state) => ({ projectFilters: toggleFilterEntry(state.projectFilters, viewKey) })), clearProjectFilters: () => set({ projectFilters: [] }), diff --git a/packages/app/src/styles/settings.ts b/packages/app/src/styles/settings.ts index 4fa4dcd22d11..fbb25b731ddf 100644 --- a/packages/app/src/styles/settings.ts +++ b/packages/app/src/styles/settings.ts @@ -1,4 +1,5 @@ import { StyleSheet } from "react-native-unistyles"; +import { mapLayout, SWITCH_HEIGHT } from "@/components/ui/control-geometry"; export const settingsStyles = StyleSheet.create((theme) => ({ section: { @@ -34,6 +35,8 @@ export const settingsStyles = StyleSheet.create((theme) => ({ justifyContent: "space-between", paddingVertical: theme.spacing[4], paddingHorizontal: theme.spacing[4], + // As tall as a row holding a switch, so rows with and without one line up. + minHeight: mapLayout(SWITCH_HEIGHT, (height) => height + theme.spacing[4] * 2), }, rowBorder: { borderTopWidth: 1, diff --git a/packages/app/src/styles/theme.ts b/packages/app/src/styles/theme.ts index f90594fa5567..a1bff0292bd5 100644 --- a/packages/app/src/styles/theme.ts +++ b/packages/app/src/styles/theme.ts @@ -1,4 +1,5 @@ -import { Platform } from "react-native"; +import { Platform, type ViewStyle } from "react-native"; +import { isWeb } from "@/constants/platform"; import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight"; import { deriveSurfaceStates } from "./derive-colors"; @@ -641,6 +642,17 @@ export const DEFAULT_MONO_FONT_STACK: string = Platform.select({ // Chat and markdown content column; the appearance updater patches the user's width in. export const DEFAULT_CONTENT_MAX_WIDTH = 820; +// On web Unistyles puts string tokens in CSS variables, so mounted content +// receives width changes without regenerating its classes. The px string is +// emitted as CSS by Unistyles. Native always receives a number or percentage. +export function themeContentMaxWidth( + width: number | undefined, +): NonNullable { + return isWeb && width !== undefined + ? (`${width}px` as NonNullable) + : (width ?? "100%"); +} + // `fontSize`, `fontFamily`, `lineHeight`, and `contentMaxWidth` are deliberately widened to plain // `number`/`string` (not narrowed by `as const`) so the appearance updater can patch // them at runtime via `UnistylesRuntime.updateTheme`. The remaining tokens keep their @@ -650,7 +662,7 @@ interface CommonTheme { fontSize: Record; fontFamily: { ui: string; mono: string }; lineHeight: Record; - contentMaxWidth: number; + contentMaxWidth: ReturnType; iconSize: typeof ICON_SIZE; fontWeight: typeof FONT_WEIGHT; borderRadius: typeof BORDER_RADIUS; @@ -663,7 +675,7 @@ const commonTheme: CommonTheme = { fontSize: FONT_SIZE, fontFamily: { ui: DEFAULT_UI_FONT_STACK, mono: DEFAULT_MONO_FONT_STACK }, lineHeight: LINE_HEIGHT, - contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + contentMaxWidth: themeContentMaxWidth(DEFAULT_CONTENT_MAX_WIDTH), iconSize: ICON_SIZE, fontWeight: FONT_WEIGHT, borderRadius: BORDER_RADIUS, diff --git a/packages/app/src/subagents/parent/callout.tsx b/packages/app/src/subagents/parent/callout.tsx index d1bb31204abb..e20058355b0c 100644 --- a/packages/app/src/subagents/parent/callout.tsx +++ b/packages/app/src/subagents/parent/callout.tsx @@ -3,6 +3,7 @@ import { Text, View } from "react-native"; import { useTranslation } from "react-i18next"; import { CornerUpLeft } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail"; import { StatusIcon } from "@/components/status-icon"; import { Button } from "@/components/ui/button"; import { FOOTER_HEIGHT } from "@/constants/layout"; @@ -37,7 +38,7 @@ export function ParentAgentCallout({ const parent = useParentAgent(serverId, parentAgentId); return ( - + diff --git a/packages/app/src/terminal/native-renderer/terminal-input.native.tsx b/packages/app/src/terminal/native-renderer/terminal-input.native.tsx index 7ca7020cb0e0..f748ee70fb06 100644 --- a/packages/app/src/terminal/native-renderer/terminal-input.native.tsx +++ b/packages/app/src/terminal/native-renderer/terminal-input.native.tsx @@ -22,7 +22,10 @@ import { export const TERMINAL_INPUT_CONTEXT_MENU_HIDDEN = true; export const TERMINAL_INPUT_HITBOX_SIZE = 1; -/** Matched by the Android hardware keyboard module to claim arrow keys for this input. */ +/** + * Matched on Android by the hardware keyboard module to claim arrow keys for this input, and by + * PaseoTerminal to keep the keyboard from learning what is typed here, such as passwords. + */ export const TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"; export interface TerminalTextInputChange { diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index 1b08faad8557..0869cbf5671b 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -1104,12 +1104,19 @@ export class TerminalEmulatorRuntime { if (!terminal) { return; } + terminal.textarea?.removeAttribute("virtualkeyboardpolicy"); if (input?.forceRefocus) { terminal.blur(); } terminal.focus(); } + suppressAutomaticKeyboard(): void { + // Android Chrome can reopen the keyboard during a drag after Back leaves the input + // focused. Manual policy prevents that without closing an already open keyboard. + this.terminal?.textarea?.setAttribute("virtualkeyboardpolicy", "manual"); + } + blur(): void { this.terminal?.blur(); } diff --git a/packages/app/src/timeline/session-stream-reducers.test.ts b/packages/app/src/timeline/session-stream-reducers.test.ts index 45b4e293dd38..96f085b5d976 100644 --- a/packages/app/src/timeline/session-stream-reducers.test.ts +++ b/packages/app/src/timeline/session-stream-reducers.test.ts @@ -4558,3 +4558,262 @@ describe("createAgentStreamReducerQueue", () => { expect(scheduler.size).toBe(0); }); }); + +describe("turn metrics", () => { + const metrics = [ + { label: "Model", value: "opus" }, + { label: "Cache", value: "82%", tone: "ok" as const }, + ]; + + function liveTurn(events: AgentStreamEventPayload[]) { + let seq = 0; + return processAgentStreamEvents({ + events: events.map((event) => + event.type === "timeline" + ? makeStreamReducerEvent(event, ++seq) + : { event, seq: undefined, epoch: undefined, timestamp: new Date(1000 + seq) }, + ), + currentTail: [], + currentHead: [], + currentCursor: undefined, + }); + } + + function inTurn(event: AgentStreamEventPayload, turnId: string): AgentStreamEventPayload { + return { ...event, turnId } as AgentStreamEventPayload; + } + + function turnCompleted(turnId?: string, turnMetrics = metrics): AgentStreamEventPayload { + return { + type: "turn_completed", + provider: "claude", + ...(turnId ? { turnId } : {}), + metrics: turnMetrics, + }; + } + + function metricsByKind(items: StreamItem[]) { + return items.map((item) => ({ + kind: item.kind, + turnMetrics: "turnMetrics" in item ? item.turnMetrics : undefined, + })); + } + + it("puts a live turn's metrics on its last assistant message", () => { + const result = liveTurn([ + inTurn(makeTimelineEvent("question", "user_message"), "turn-1"), + inTurn(makeAssistantTimelineEvent("Looking."), "turn-1"), + inTurn(makeToolCallTimelineEvent("read-1"), "turn-1"), + inTurn(makeAssistantTimelineEvent("Done."), "turn-1"), + turnCompleted("turn-1"), + ]); + + expect(metricsByKind([...result.tail, ...result.head])).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: undefined }, + { kind: "tool_call", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: metrics }, + ]); + }); + + it("puts a live tool-only turn's metrics on its last tool call", () => { + const result = liveTurn([ + inTurn(makeTimelineEvent("question", "user_message"), "turn-1"), + inTurn(makeToolCallTimelineEvent("read-1"), "turn-1"), + inTurn(makeToolCallTimelineEvent("read-2"), "turn-1"), + turnCompleted("turn-1"), + ]); + + expect(metricsByKind(result.tail)).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "tool_call", turnMetrics: undefined }, + { kind: "tool_call", turnMetrics: metrics }, + ]); + }); + + it("does not put a turn's metrics on an earlier turn's reply", () => { + const result = liveTurn([ + inTurn(makeTimelineEvent("first", "user_message"), "turn-1"), + inTurn(makeAssistantTimelineEvent("First reply."), "turn-1"), + turnCompleted("turn-1", [{ label: "Model", value: "first" }]), + inTurn(makeTimelineEvent("second", "user_message"), "turn-2"), + inTurn(makeToolCallTimelineEvent("read-1"), "turn-2"), + inTurn(makeTimelineEvent("thinking", "reasoning"), "turn-2"), + turnCompleted("turn-2"), + ]); + + expect(metricsByKind(result.tail)).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: [{ label: "Model", value: "first" }] }, + { kind: "user_message", turnMetrics: undefined }, + { kind: "tool_call", turnMetrics: undefined }, + { kind: "thought", turnMetrics: undefined }, + ]); + }); + + it("leaves the timeline untouched when a turn completes without metrics", () => { + const before = liveTurn([ + inTurn(makeTimelineEvent("question", "user_message"), "turn-1"), + inTurn(makeAssistantTimelineEvent("Done."), "turn-1"), + turnCompleted("turn-1", []), + ]); + const after = processAgentStreamEvent({ + ...baseStreamInput, + event: { type: "turn_completed", provider: "claude", turnId: "turn-1" }, + currentTail: before.tail, + currentHead: before.head, + }); + + expect(after.tail).toBe(before.tail); + expect(metricsByKind(after.tail)).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: undefined }, + ]); + }); + + it("hydrates turn metrics from a replaced history page", () => { + const result = processTimelineResponse({ + ...baseTimelineInput, + payload: { + ...baseTimelineInput.payload, + reset: true, + startCursor: { seq: 1 }, + endCursor: { seq: 4 }, + entries: [ + makeTimelineEntry(1, "question", "user_message"), + { ...makeTimelineEntry(2, "Reply."), turnMetrics: metrics }, + makeTimelineEntry(3, "next question", "user_message"), + { + ...makeToolCallTimelineEntry(4, "read-1", "completed", { + type: "read", + filePath: "/tmp/a.ts", + }), + turnMetrics: [{ label: "Model", value: "sonnet" }], + }, + ], + }, + }); + + expect(metricsByKind(result.tail)).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: metrics }, + { kind: "user_message", turnMetrics: undefined }, + { kind: "tool_call", turnMetrics: [{ label: "Model", value: "sonnet" }] }, + ]); + }); + + it("hydrates turn metrics from an older history page", () => { + const currentTail: StreamItem[] = [ + { kind: "user_message", id: "current-3", text: "current-3", timestamp: new Date(3000) }, + ]; + const result = processTimelineResponse({ + ...baseTimelineInput, + currentTail, + currentCursor: { epoch: "epoch-1", startSeq: 3, endSeq: 3 }, + payload: { + ...baseTimelineInput.payload, + direction: "before", + startCursor: { seq: 1 }, + endCursor: { seq: 2 }, + entries: [ + makeTimelineEntry(1, "older question", "user_message"), + { ...makeTimelineEntry(2, "Older reply."), turnMetrics: metrics }, + ], + }, + }); + + expect(metricsByKind(result.tail)).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: metrics }, + { kind: "user_message", turnMetrics: undefined }, + ]); + }); + + it("hydrates turn metrics on a projected reply that replaces the live one", () => { + const live = processAgentStreamEvents({ + events: [makeStreamReducerEvent(makeAssistantTimelineEvent("Partial"), 2)], + currentTail: [], + currentHead: [], + currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 1 }, + }); + + const result = processTimelineResponse({ + ...baseTimelineInput, + currentTail: live.tail, + currentHead: live.head, + currentCursor: live.cursor ?? undefined, + payload: { + ...baseTimelineInput.payload, + startCursor: { seq: 3 }, + endCursor: { seq: 3 }, + entries: [ + { + ...makeTimelineEntry(2, "Partial reply.", "assistant_message", 3), + sourceSeqRanges: [{ startSeq: 2, endSeq: 3 }], + turnMetrics: metrics, + }, + ], + }, + }); + + expect(metricsByKind([...result.tail, ...result.head])).toEqual([ + { kind: "assistant_message", turnMetrics: metrics }, + ]); + }); + + it("keeps live turn metrics when canonical history replaces the timeline", () => { + const live = liveTurn([ + makeTimelineEvent("question", "user_message"), + makeAssistantTimelineEvent("Done."), + turnCompleted(), + ]); + + const result = processTimelineResponse({ + ...baseTimelineInput, + currentTail: live.tail, + currentHead: live.head, + currentCursor: live.cursor ?? undefined, + payload: { + ...baseTimelineInput.payload, + reset: true, + startCursor: { seq: 1 }, + endCursor: { seq: 2 }, + entries: [ + makeTimelineEntry(1, "question", "user_message"), + { ...makeTimelineEntry(2, "Done."), turnMetrics: metrics }, + ], + }, + }); + + expect(metricsByKind(result.tail)).toEqual([ + { kind: "user_message", turnMetrics: undefined }, + { kind: "assistant_message", turnMetrics: metrics }, + ]); + }); + + it("keeps row identity when a page repeats metrics the row already has", () => { + const first = processTimelineResponse({ + ...baseTimelineInput, + payload: { + ...baseTimelineInput.payload, + reset: true, + startCursor: { seq: 1 }, + endCursor: { seq: 1 }, + entries: [{ ...makeTimelineEntry(1, "Reply."), turnMetrics: metrics }], + }, + }); + const repeated = processTimelineResponse({ + ...baseTimelineInput, + currentTail: first.tail, + currentCursor: first.cursor ?? undefined, + payload: { + ...baseTimelineInput.payload, + startCursor: { seq: 1 }, + endCursor: { seq: 1 }, + entries: [{ ...makeTimelineEntry(1, "Reply."), turnMetrics: [...metrics] }], + }, + }); + + expect(repeated.tail).toBe(first.tail); + }); +}); diff --git a/packages/app/src/timeline/session-stream-reducers.ts b/packages/app/src/timeline/session-stream-reducers.ts index 1eec63ed9a0d..f74bb8781b37 100644 --- a/packages/app/src/timeline/session-stream-reducers.ts +++ b/packages/app/src/timeline/session-stream-reducers.ts @@ -1,8 +1,9 @@ -import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; +import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types"; import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages"; import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store"; import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream"; import type { TurnLivenessTransition } from "@/timeline/turn-liveness"; +import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics"; import { applyStreamEvent, flushHeadToTail, @@ -133,6 +134,7 @@ interface TimelineResponseEntry { turnId?: string; item: AgentTimelineItem; timestamp: string; + turnMetrics?: AgentMetric[]; } export interface ProcessTimelineResponseInput { @@ -1268,7 +1270,8 @@ export function processTimelineResponse( // ------------------------------------------------------------------ // Convert entries to timeline units // ------------------------------------------------------------------ - const timelineUnits = selectEntriesOwnedByTimelinePage(payload).map((entry) => ({ + const pageEntries = selectEntriesOwnedByTimelinePage(payload); + const timelineUnits = pageEntries.map((entry) => ({ seq: entry.seqStart, seqEnd: entry.seqEnd, sourceSeqRanges: @@ -1379,8 +1382,8 @@ export function processTimelineResponse( }); } - const nextTail = timelineResult.tail; - const nextHead = timelineResult.head; + const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries); + const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries); const nextCursor = timelineResult.cursor; const cursorChanged = timelineResult.cursorChanged; sideEffects.push(...timelineResult.sideEffects); diff --git a/packages/app/src/timeline/turn-metrics.ts b/packages/app/src/timeline/turn-metrics.ts new file mode 100644 index 000000000000..d04b59451c2c --- /dev/null +++ b/packages/app/src/timeline/turn-metrics.ts @@ -0,0 +1,101 @@ +import type { AgentMetric } from "@getpaseo/protocol/agent-types"; +import { continuesResponse } from "@/agent-stream/turn-membership"; +import type { StreamItem, TimelinePosition } from "@/types/stream"; + +type TurnFooterAnchor = Extract; + +/** + * Puts a completed turn's metrics on the row its footer hangs on: the turn's last assistant + * message, else its last row when that row is a tool call. The daemon stamps the same row, so a + * later timeline fetch agrees with what the live event showed. + */ +export function stampCompletedTurnMetrics( + items: StreamItem[], + metrics: AgentMetric[] | undefined, + turnId: string | undefined, +): StreamItem[] { + if (!metrics || metrics.length === 0) return items; + const index = findTurnFooterAnchorIndex(items, turnId); + if (index === null) return items; + return replaceAt(items, index, metrics); +} + +/** + * Puts the metrics a timeline page carries on the rows it wrote. Every reducer path leaves a row + * with the cursor of the last entry that wrote it, which is the entry the daemon stamped. + */ +export function stampTimelineTurnMetrics( + items: StreamItem[], + epoch: string, + entries: ReadonlyArray<{ seqEnd: number; turnMetrics?: AgentMetric[] }>, +): StreamItem[] { + const metricsBySeq = new Map(); + for (const entry of entries) { + if (entry.turnMetrics && entry.turnMetrics.length > 0) { + metricsBySeq.set(entry.seqEnd, entry.turnMetrics); + } + } + if (metricsBySeq.size === 0) return items; + + let next = items; + items.forEach((item, index) => { + const metrics = isTurnFooterAnchor(item) + ? metricsBySeq.get(cursorSeqIn(item.timelineCursor, epoch) ?? -1) + : undefined; + if (metrics) next = replaceAt(next, index, metrics); + }); + return next; +} + +function findTurnFooterAnchorIndex(items: StreamItem[], turnId: string | undefined): number | null { + const last = lastIndexOfTurn(items, turnId); + if (last === null) return null; + for (let index = last; index >= 0; index--) { + if (index < last && !continuesResponse(items[index], items[index + 1])) break; + if (items[index].kind === "assistant_message") return index; + } + return items[last].kind === "tool_call" ? last : null; +} + +function lastIndexOfTurn(items: StreamItem[], turnId: string | undefined): number | null { + const tail = items.length - 1; + if (tail < 0) return null; + if (turnId === undefined) return tail; + const index = items.findLastIndex((item) => item.turnId === turnId); + if (index >= 0) return index; + // Rows from daemons without turn ids belong to the trailing turn. A tail owned by another + // turn means this turn wrote no rows. + return items[tail].turnId === undefined ? tail : null; +} + +function isTurnFooterAnchor(item: StreamItem): item is TurnFooterAnchor { + return item.kind === "assistant_message" || item.kind === "tool_call"; +} + +function cursorSeqIn(cursor: TimelinePosition | undefined, epoch: string): number | null { + return cursor?.epoch === epoch ? cursor.seq : null; +} + +/** Returns `items` itself when the row already shows these metrics, so unchanged rows keep identity. */ +function replaceAt(items: StreamItem[], index: number, metrics: AgentMetric[]): StreamItem[] { + const item = items[index]; + if (!item || !isTurnFooterAnchor(item) || areMetricsEqual(item.turnMetrics, metrics)) { + return items; + } + const next = [...items]; + next[index] = { ...item, turnMetrics: metrics }; + return next; +} + +function areMetricsEqual(left: AgentMetric[] | undefined, right: AgentMetric[]): boolean { + return ( + left !== undefined && + left.length === right.length && + left.every( + (metric, index) => + metric.label === right[index].label && + metric.value === right[index].value && + metric.tone === right[index].tone, + ) + ); +} diff --git a/packages/app/src/timeline/viewed-timeline-sync.test.ts b/packages/app/src/timeline/viewed-timeline-sync.test.ts index 6550350829b9..7417556e3099 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.test.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.test.ts @@ -92,13 +92,14 @@ test("visible catch-up settles before hidden open chats start fetching", async ( world.sync.dispose(); }); -test("a failed visible catch-up releases hidden chats without bypassing its error", async () => { +test("a failed visible catch-up with a parked gap releases hidden chats without retrying", async () => { const world = new TimelineWorld(); world.openedEarlier(["a-hidden"]); world.sync.replaceVisibleAgentIds("pane", ["z-visible"]); world.sync.setConnected(true); (await world.nextMembership()).succeed(); const visible = await world.nextFetch("z-visible"); + world.sync.recoverGap("z-visible", { epoch: "epoch-z-visible", endSeq: 1 }); world.expectNoPendingFetch(); visible.fail("temporarily unavailable"); const hidden = await world.nextFetch("a-hidden"); @@ -127,6 +128,63 @@ test("switching chats promotes the newly visible catch-up while another visible world.sync.dispose(); }); +test("reconnect drains hidden chats two at a time after the visible chat settles", async () => { + const world = new TimelineWorld(); + const hidden = Array.from({ length: 15 }, (_, index) => `hidden-${10 + index}`); + world.openedEarlier(hidden); + world.show("pane", ["visible"]); + world.sync.setConnected(true); + (await world.nextMembership()).succeed(); + const beforeDisconnect = await world.nextFetch("visible"); + world.sync.setConnected(false); + beforeDisconnect.respond({ hasNewer: false }); + world.sync.setConnected(true); + (await world.nextMembership()).succeed(); + const visible = await world.nextFetch("visible"); + world.expectNoPendingFetch(); + visible.respond({ hasNewer: false }); + const first = await world.nextFetch(hidden[0]); + let current = await world.nextFetch(hidden[1]); + world.expectNoPendingFetch(); + + first.fail("timeline request timed out"); + for (const agentId of hidden.slice(2)) { + const next = await world.nextFetch(agentId); + world.expectNoPendingFetch(); + current.respond({ hasNewer: false }); + current = next; + } + current.respond({ hasNewer: false }); + await vi.waitFor(() => { + expect(world.sync.getAgentTimelineStatus(hidden[0])).toBe("error"); + for (const agentId of hidden.slice(1)) { + expect(world.sync.getAgentTimelineStatus(agentId)).toBe("ready"); + } + }); + world.expectNoPendingFetch(); + world.sync.dispose(); +}); + +test("focusing a queued chat starts it while both hidden catch-ups are running", async () => { + const world = new TimelineWorld(); + world.openedEarlier(["hidden-a", "hidden-b", "next-visible"]); + world.show("pane", ["visible"]); + world.sync.setConnected(true); + (await world.nextMembership()).succeed(); + (await world.nextFetch("visible")).respond({ hasNewer: false }); + const first = await world.nextFetch("hidden-a"); + const second = await world.nextFetch("hidden-b"); + world.expectNoPendingFetch(); + + world.show("pane", ["next-visible"]); + expect(world.pendingFetchCount).toBe(1); + (await world.nextFetch("next-visible")).respond({ hasNewer: false }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("next-visible")).toBe("ready")); + first.respond({ hasNewer: false }); + second.respond({ hasNewer: false }); + world.sync.dispose(); +}); + class TimelineWorld { constructor( private readonly observeMembership?: ViewedTimelineSyncPorts["observe"], @@ -441,7 +499,7 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); }); -test("a gap parked behind a running tail resumes after the rows that tail applied", async () => { +test("a parked gap pages forward from the coverage established by the running tail", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); @@ -460,7 +518,13 @@ test("a gap parked behind a running tail resumes after the rows that tail applie projection: "projected", wholeTurns: true, }); - recovery.respond({ hasNewer: false, seq: 7 }); + recovery.respond({ hasNewer: true, seq: 47 }); + const followUp = await world.nextFetch("agent-a"); + expect(followUp.request).toMatchObject({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 47 }, + }); + followUp.respond({ hasNewer: false, seq: 55 }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); world.sync.dispose(); }); @@ -941,14 +1005,51 @@ test("redeclaring unchanged visibility does not bypass catch-up error", async () await world.nextError(); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); - world.sync.setActive(false); - world.sync.setActive(true); world.expectNoPendingMembership(); world.expectNoPendingFetch(); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); }); +test.each(["refocusing", "foregrounding"])( + "%s retries a timed-out visible timeline once", + async (trigger) => { + const world = new TimelineWorld(); + world.show("pane", ["agent-a"]); + world.sync.setConnected(true); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-a")).fail("timeline request timed out"); + await world.nextError(); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); + + const revisit = () => { + if (trigger === "refocusing") { + world.show("pane", []); + world.show("pane", ["agent-a"]); + } else { + world.sync.setActive(false); + world.sync.setActive(true); + } + }; + revisit(); + expect(world.pendingFetchCount).toBe(1); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("pending"); + (await world.nextFetch("agent-a")).fail("timeline request timed out again"); + await vi.waitFor(() => expect(world.errors).toHaveLength(2)); + expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); + world.show("pane", ["agent-a"]); + world.sync.setActive(true); + world.expectNoPendingFetch(); + + revisit(); + (await world.nextFetch("agent-a")).respond({ hasNewer: false }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + expect(world.sync.getAgentTimelineError("agent-a")).toBeNull(); + world.expectNoPendingMembership(); + world.sync.dispose(); + }, +); + test("a manual retry that fails returns to the error state", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); @@ -968,6 +1069,37 @@ test("a manual retry that fails returns to the error state", async () => { await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error")); }); +test("refocusing during a membership update retries a reconnect without replaying the backlog", async () => { + const world = freshnessWorld(); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 }); + world.show("pane", ["agent-a"]); + world.sync.setConnected(true); + (await world.nextMembership()).succeed({ "agent-a": "current" }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + + world.sync.setConnected(false); + world.sync.setConnected(true); + (await world.nextMembership()).succeed({ "agent-a": "behind" }); + const failed = await world.nextFetch("agent-a"); + expect(failed.request.direction).toBe("after"); + failed.fail("timeline request timed out"); + await world.nextError(); + + world.show("pane", ["agent-b"]); + const membership = await world.nextMembership(); + world.show("pane", ["agent-a"]); + expect(world.pendingFetchCount).toBe(1); + const retry = await world.nextFetch("agent-a"); + expect(retry.request).toEqual(failed.request); + membership.succeed(); + retry.respond({ hasNewer: true, seq: 82 }); + const tail = await world.nextFetch("agent-a"); + expect(tail.request.direction).toBe("tail"); + tail.respond({ hasNewer: false }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + test("gap recovery supersedes completed catch-up and pages through the current tail", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); diff --git a/packages/app/src/timeline/viewed-timeline-sync.ts b/packages/app/src/timeline/viewed-timeline-sync.ts index b6423de9c31a..45b237d558f4 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.ts @@ -545,12 +545,27 @@ export function createViewedTimelineOwner(input: { }; } +const MAX_HIDDEN_CATCH_UPS = 2; + type CatchUpStatus = "running" | "complete" | "error"; +interface CatchUpRequest { + page: ProjectedTimelineForwardFetchPlan; + kind: "resume" | "gap"; +} + interface CatchUpState { generation: number; status: CatchUpStatus; - request?: ProjectedTimelineForwardFetchPlan; + request?: CatchUpRequest; +} + +function planCatchUpRequest( + request: CatchUpRequest | undefined, + applied: { epoch: string; endSeq: number } | undefined, +): CatchUpRequest { + if (!request) return { page: planTimelineResumeFetch(applied), kind: "resume" }; + return { ...request, page: planTimelineCatchUpPastApplied(request.page, applied) }; } function isSameCatchUpRequest( @@ -573,11 +588,11 @@ function decideCatchUp(input: { if (input.supersede) { if ( input.current.status === "running" && - isSameCatchUpRequest(input.current.request, input.request) + isSameCatchUpRequest(input.current.request?.page, input.request) ) { return "keep"; } - if (input.current.status === "running" && input.current.request?.direction === "tail") { + if (input.current.status === "running" && input.current.request?.page.direction === "tail") { return "keep-and-park"; } return "replace"; @@ -597,9 +612,11 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed const sources = new Map(); const catchUps = new Map(); const catchUpGenerations = new Map(); - // Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or parked. + // Fetches can outlive their catch-up generation when superseded or when a tab closes. + const inFlightCatchUps = new Set<{ agentId: string }>(); + // Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or queued. // Membership acknowledgement and catch-up completion drain parked requests. - const pendingCatchUps = new Map(); + const pendingCatchUps = new Map(); const visibilityCatchUpPending = new Set(); const visibilityCatchUpErrors = new Map(); // A user-initiated retry owes a pending state until it settles. @@ -723,16 +740,16 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed const fetchUntilCurrent = async ( agentId: string, generation: number, - request: ProjectedTimelineForwardFetchPlan, + request: CatchUpRequest, fallbackToLatestTailOnOverflow: boolean, ): Promise => { if (!ownsCatchUp(agentId, generation)) return; try { - const page = await ports.fetchPage(agentId, request); + const page = await ports.fetchPage(agentId, request.page); if (!ownsCatchUp(agentId, generation)) return; if (page.hasNewer && page.endCursor) { - if (fallbackToLatestTailOnOverflow) { + if (request.page.direction === "after" && fallbackToLatestTailOnOverflow) { await ports.fetchLatestTail(agentId); if (!ownsCatchUp(agentId, generation)) return; catchUps.set(agentId, { generation, status: "complete" }); @@ -742,10 +759,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed await fetchUntilCurrent( agentId, generation, - planTimelineCatchUpPastApplied( - planTimelineCatchUpAfter(page.endCursor), - ports.readCursor(agentId), - ), + { + ...request, + page: planTimelineCatchUpPastApplied( + planTimelineCatchUpAfter(page.endCursor), + ports.readCursor(agentId), + ), + }, false, ); return; @@ -754,20 +774,15 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed throw new Error(`Timeline page for ${agentId} hasNewer without an end cursor`); } catchUps.set(agentId, { generation, status: "complete" }); - const pendingCatchUp = pendingCatchUps.get(agentId); - if (pendingCatchUp) { - startCatchUp(agentId, { request: pendingCatchUp, supersede: true }); - return; - } - setVisibilityCatchUpReady(agentId); + if (!pendingCatchUps.has(agentId)) setVisibilityCatchUpReady(agentId); } catch (error) { if (catchUps.get(agentId)?.generation === generation) { + // The parked follow-up belongs to the failed attempt. A retry owns the next request. + pendingCatchUps.delete(agentId); catchUps.set(agentId, { generation, status: "error", request }); setVisibilityCatchUpError([agentId], error); ports.reportError(error); } - } finally { - startAcknowledgedCatchUps(); } }; @@ -798,23 +813,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed ); }; + const hiddenCatchUpSlotsAreFull = (agentId: string) => { + const visible = new Set(visibleAgentIds()); + if (visible.has(agentId)) return false; + let hidden = 0; + for (const attempt of inFlightCatchUps) { + if (!visible.has(attempt.agentId)) hidden += 1; + } + return hidden >= MAX_HIDDEN_CATCH_UPS; + }; + const startCatchUp = ( agentId: string, options: { - request?: ProjectedTimelineForwardFetchPlan; + request?: CatchUpRequest; supersede?: boolean; } = {}, ) => { const { request, supersede = false } = options; - if (freshnessChecks.has(agentId)) { - if (request) pendingCatchUps.set(agentId, request); - return; - } - if (!canCatchUp(agentId)) { - if (request) pendingCatchUps.set(agentId, request); - return; - } - if (shouldWaitForVisibleCatchUp(agentId)) { + if ( + freshnessChecks.has(agentId) || + !canCatchUp(agentId) || + shouldWaitForVisibleCatchUp(agentId) + ) { if (request) pendingCatchUps.set(agentId, request); return; } @@ -824,11 +845,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed return; } const applied = ports.readCursor(agentId); - const nextRequest = request - ? planTimelineCatchUpPastApplied(request, applied) - : planTimelineResumeFetch(applied); + const nextRequest = planCatchUpRequest(request, applied); const current = catchUps.get(agentId); - const decision = decideCatchUp({ current, request: nextRequest, supersede }); + const decision = decideCatchUp({ current, request: nextRequest.page, supersede }); if (decision === "keep-and-park") { pendingCatchUps.set(agentId, nextRequest); return; @@ -836,18 +855,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed if (decision === "keep") { return; } + if (hiddenCatchUpSlotsAreFull(agentId)) { + if (request) pendingCatchUps.set(agentId, request); + return; + } const generation = (catchUpGenerations.get(agentId) ?? 0) + 1; catchUpGenerations.set(agentId, generation); catchUps.set(agentId, { generation, status: "running", request: nextRequest }); pendingCatchUps.delete(agentId); - // A gap recovery pages forward to keep the coverage it extends. Without coverage there is - // nothing to keep, so an overflowing page falls back to the latest tail, as a resume does. + const attempt = { agentId }; + inFlightCatchUps.add(attempt); + if (current?.status === "error" && !manualRetries.has(agentId)) { + visibilityCatchUpErrors.delete(agentId); + markCatchUpOwed(agentId); + notifyListeners(); + } + // A queued gap uses the coverage available when its fetch starts. void fetchUntilCurrent( agentId, generation, nextRequest, - nextRequest.direction === "after" && (request === undefined || applied === undefined), - ); + nextRequest.kind === "resume" || !applied, + ).finally(() => { + inFlightCatchUps.delete(attempt); + startAcknowledgedCatchUps(); + }); }; const startAcknowledgedCatchUps = () => { @@ -859,9 +891,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed for (const agentId of ordered) { const pendingCatchUp = pendingCatchUps.get(agentId); const current = catchUps.get(agentId); - // Completion of a different chat must not bypass a failed chat's error or - // supersede an in-flight tail that owns its parked gap recovery. - if (current && !(current.status === "complete" && pendingCatchUp)) continue; + // A running tail owns its parked gap. A failed catch-up can only have a queued retry. + if (current?.status === "running" || (current && !pendingCatchUp)) continue; startCatchUp(agentId, { request: pendingCatchUp, supersede: Boolean(pendingCatchUp), @@ -869,6 +900,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed } }; + const retryFailedCatchUp = (agentId: string) => { + const catchUp = catchUps.get(agentId); + if (catchUp?.status === "error") { + startCatchUp(agentId, { request: catchUp.request, supersede: true }); + } + }; + const membershipIsSettled = (requested: string[]) => !membershipNeedsRetry && !freshnessCheckOwed && @@ -975,9 +1013,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed void reconcileMembership(); return; } - if (catchUp?.status === "error") { - startCatchUp(agentId, { request: catchUp.request, supersede: true }); - } + retryFailedCatchUp(agentId); }; const commitDesiredMembership = ( @@ -1068,11 +1104,17 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed publishVisibleMembership(); }, replaceVisibleAgentIds(sourceId, agentIds) { + const previouslyVisible = new Set(visibleAgentIds()); const normalized = normalizeAgentIds(agentIds); if (normalized.length === 0) sources.delete(sourceId); else sources.set(sourceId, normalized); rememberOpenedAgentIds(normalized); publishVisibleMembership(); + if (active) { + for (const agentId of normalized) { + if (!previouslyVisible.has(agentId)) retryFailedCatchUp(agentId); + } + } startAcknowledgedCatchUps(); }, setActive(nextActive) { @@ -1085,7 +1127,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed } const canCheck = connected && ports.canCheckFreshness(); for (const agentId of visibleAgentIds()) { - if (visibilityCatchUpErrors.has(agentId)) continue; + if (visibilityCatchUpErrors.has(agentId)) { + retryFailedCatchUp(agentId); + continue; + } markCatchUpOwed(agentId); if ( canCheck && @@ -1132,7 +1177,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed recoverGap(agentId, cursor) { if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return; startCatchUp(agentId, { - request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }), + request: { + page: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }), + kind: "gap", + }, supersede: true, }); }, diff --git a/packages/app/src/types/stream.ts b/packages/app/src/types/stream.ts index 9ca830918acd..47138a257579 100644 --- a/packages/app/src/types/stream.ts +++ b/packages/app/src/types/stream.ts @@ -1,5 +1,6 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message"; import type { + AgentMetric, AgentProvider, AgentTimelineItem, JsonValue, @@ -9,6 +10,7 @@ import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity"; import type { AgentAttachment, AgentStreamEventPayload } from "@getpaseo/protocol/messages"; import type { AttachmentMetadata } from "@/attachments/types"; import type { OverviewSummary } from "@/tool-calls/detail-level/overview/model"; +import { stampCompletedTurnMetrics } from "@/timeline/turn-metrics"; import { extractTaskEntriesFromToolCall } from "../utils/tool-call-parsers"; /** @@ -715,6 +717,8 @@ export interface AssistantMessageItem { timelineCursor?: TimelinePosition; text: string; timestamp: Date; + /** Set when this message carries its turn's footer. */ + turnMetrics?: AgentMetric[]; /** Display-only fields, assigned after source-item plugin transforms. */ } @@ -769,6 +773,8 @@ export interface ToolCallItem { turnId?: string; timestamp: Date; payload: ToolCallPayload; + /** Set when this call carries its turn's footer. */ + turnMetrics?: AgentMetric[]; } export type AgentToolCallItem = ToolCallItem & { @@ -1630,9 +1636,10 @@ export function reduceStreamUpdate( ); return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated); } + case "turn_completed": + return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId); case "thread_started": case "turn_started": - case "turn_completed": case "turn_failed": case "turn_canceled": case "permission_requested": diff --git a/packages/app/src/usage/balance-bar.tsx b/packages/app/src/usage/balance-bar.tsx index bcd33873cccc..ea6b86094fdc 100644 --- a/packages/app/src/usage/balance-bar.tsx +++ b/packages/app/src/usage/balance-bar.tsx @@ -9,7 +9,7 @@ import { formatResetTime, } from "./format"; import { UsageMeter } from "./meter"; -import { UsageResetLine } from "./reset-line"; +import { UsageDatapointLine } from "./datapoint-line"; import type { UsageBalance } from "./types"; import { useRelativeTimeTick } from "./use-relative-time-tick"; @@ -77,9 +77,8 @@ export function UsageBalanceBar({ {usedPct != null ? : null} - diff --git a/packages/app/src/usage/bars.browser.test.tsx b/packages/app/src/usage/bars.browser.test.tsx index 7b978f7ced61..2e8ba2483e17 100644 --- a/packages/app/src/usage/bars.browser.test.tsx +++ b/packages/app/src/usage/bars.browser.test.tsx @@ -5,8 +5,10 @@ import { i18n } from "@/i18n/i18next"; import { UsageWindowBar } from "./window-bar"; import type { UsageBalance, UsageWindow } from "./types"; import { UsageBalanceBar } from "./balance-bar"; +import { UsageMeter } from "./meter"; const window: UsageWindow = { id: "session", label: "Session", usedPct: 70 }; +const exhaustedWindow: UsageWindow = { ...window, usedPct: 100 }; const balance: UsageBalance = { id: "credits", label: "Credits", unit: "usd", remaining: 12 }; const ignorePin = () => {}; @@ -32,6 +34,7 @@ it("translates mounted usage rows when the language changes", async () => { <> { expect(container.textContent).toContain("セッション70% 使用済み"); expect(container.textContent).toContain("クレジット"); }); + +it("colors healthy quota bars green and keeps the warning and danger colors", () => { + act(() => + root.render( + <> + + + + + + , + ), + ); + const colors = Array.from( + container.children, + (track) => getComputedStyle(track.firstElementChild!).backgroundColor, + ); + expect(colors).toEqual([ + "rgb(21, 128, 61)", + "rgb(21, 128, 61)", + "rgb(217, 119, 6)", + "rgb(185, 28, 28)", + "rgb(212, 212, 216)", + ]); +}); + +it("keeps an exhausted quota red when a failed refresh removes its forecast", () => { + act(() => + root.render( + , + ), + ); + expect(container.textContent).toBe("Session100% used"); + const fill = container.firstElementChild!.children[1].firstElementChild!; + expect(getComputedStyle(fill).backgroundColor).toBe("rgb(185, 28, 28)"); +}); + +const narrowReadingMs = Date.now(); +const narrowForecastAt = new Date(narrowReadingMs).toISOString(); +const narrowWindow: UsageWindow = { + id: "weekly", + label: "Weekly", + usedPct: 6, + durationSeconds: 604_800, + resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(), +}; + +const onTrackWindow: UsageWindow = { + id: "session", + label: "Session", + usedPct: 40, + durationSeconds: 18_000, + resetsAt: new Date(narrowReadingMs + 3_600_000).toISOString(), +}; +const tightWindow: UsageWindow = { ...onTrackWindow, usedPct: 77 }; + +it.each([ + ["green", onTrackWindow, "rgb(21, 128, 61)"], + ["amber", tightWindow, "rgb(217, 119, 6)"], +] as const)("shows only the reset details for an on-track %s bar", (_, usageWindow, color) => { + act(() => + root.render( + , + ), + ); + + const row = container.firstElementChild!; + const [label, track, datapoints] = row.children; + expect(label.textContent).toBe(`Session${usageWindow.usedPct}% used`); + expect(datapoints.textContent).toMatch(/^resets in [^·]+\s· [^·]+$/); + expect(getComputedStyle(track.firstElementChild!).backgroundColor).toBe(color); +}); + +it("shows the forecast as one more datapoint after the reset countdown, in the same line", async () => { + act(() => + root.render( + , + ), + ); + + const line = Array.from(container.querySelectorAll("*")).find((node) => + node.textContent.startsWith("resets in"), + ); + expect(line?.textContent).toMatch(/^resets in [^·]+\s· [^·]+\s· runs out .+$/); +}); + +it("wraps the forecast below the countdown in a narrow French card instead of overlapping it", async () => { + await i18n.changeLanguage("fr"); + container.style.width = "272px"; + act(() => + root.render( + , + ), + ); + + function textBounds(prefix: string) { + const element = Array.from(container.querySelectorAll("*")).find( + (node) => node.childElementCount === 0 && node.textContent.startsWith(prefix), + ); + expect(element).toBeDefined(); + const range = document.createRange(); + range.selectNodeContents(element!); + return range.getBoundingClientRect(); + } + + const countdown = textBounds("se réinitialise"); + const forecast = textBounds("épuisement prévu"); + expect(forecast.left >= countdown.right || forecast.top >= countdown.bottom).toBe(true); +}); diff --git a/packages/app/src/usage/card.tsx b/packages/app/src/usage/card.tsx index 8000472743b7..d381519bc1e7 100644 --- a/packages/app/src/usage/card.tsx +++ b/packages/app/src/usage/card.tsx @@ -1,5 +1,5 @@ import { GripVertical, RotateCw } from "lucide-react-native"; -import { useCallback, useMemo } from "react"; +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { Text, View, type StyleProp, type TextStyle } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; @@ -9,14 +9,13 @@ import { smallIconButtonChromeFrameSize, } from "@/components/ui/icon-button-chrome"; import { DraggableListHandle } from "@/components/draggable-list"; -import { ControlSizeProvider } from "@/components/ui/control-size"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; import { StatusBadge } from "@/components/ui/status-badge"; -import { Switch } from "@/components/ui/switch"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isNative } from "@/constants/platform"; import type { TFunction } from "i18next"; +import { useCallback } from "react"; import { UsageBalanceBar } from "./balance-bar"; import type { UsageDisplay } from "./display"; import { formatAgo, formatProviderUsageLabel, formatUsageAccountName } from "./format"; @@ -37,10 +36,8 @@ function statusText(report: UsageReport, t: TFunction): string | null { const ThemedRotateCw = withUnistyles(RotateCw); const ThemedGripVertical = withUnistyles(GripVertical); -/** A card in the user's arrangement: dragged by its handle, turned off from its switch. */ +/** A card in the user's arrangement: dragged by its handle. */ export interface UsageCardArrangement { - on: boolean; - onSetOn: (on: boolean) => void; /** The handle is always there; it shows while the card is hovered or where there is no hover. */ handleVisible: boolean; } @@ -64,18 +61,17 @@ export function UsageCard({ pinnable: boolean; /** Whether the header has a Refresh button. Without one the freshness shows on the card. */ refreshable: boolean; - /** Present where the user arranges cards. An off card collapses to its header. */ + /** Present where the user arranges cards. */ arrangement?: UsageCardArrangement; compact?: boolean; }) { const { t } = useTranslation(); const isCompact = useIsCompactFormFactor(); - const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId); + const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId); // Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip. const showsFreshnessInline = isNative || isCompact || !refreshable; const usage = entry.report; const status = statusText(usage, t); - const collapsed = arrangement?.on === false; const report = resolveUsageReport(entry, t); const { planLabel, successfulAt, retained } = report; @@ -105,23 +101,15 @@ export function UsageCard({ {entry.sourceLabel} - {collapsed && entry.account.label ? ( - // The body that names the account is gone, and two off cards of one source must differ. - - {entry.account.label} - - ) : null} - {planLabel && !collapsed ? ( - - ) : null} + {planLabel ? : null} - {status && !collapsed ? ( + {status ? ( {status} ) : null} - {refreshable && !collapsed ? ( + {refreshable ? ( ) : null} - {arrangement ? ( - - - - ) : null} - {collapsed ? null : ( - - )} + ); } @@ -176,7 +149,7 @@ function UsageCardBody({ refreshState: UsageRefresh; }) { const { t } = useTranslation(); - const { windows, balances, details, retained, successfulAt, messages } = report; + const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report; const footer = entry.account.label ?? null; return ( <> @@ -194,6 +167,7 @@ function UsageCardBody({ entry={entry} window={window} retained={retained} + forecastAt={forecastAt} display={display} pinnable={pinnable} /> @@ -267,8 +241,10 @@ function CardWindowBar({ display, pinnable, retained, + forecastAt, }: { retained: boolean; + forecastAt: string | null; entry: UsageReportEntry; window: UsageWindow; display: UsageDisplay; @@ -285,6 +261,7 @@ function CardWindowBar({ ({ color: theme.colors.foreground, fontSize: theme.fontSize.base, }, - collapsedAccount: { - flexShrink: 1, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, headerSpacer: { flex: 1, }, @@ -506,10 +478,6 @@ const styles = StyleSheet.create((theme) => ({ }, dragHandle: dragHandleSlot(theme.spacing), dragHandleHidden: { ...dragHandleSlot(theme.spacing), opacity: 0 }, - // The switch's reserved control height overhangs the header like the Refresh button's hitbox. - cardSwitch: { - marginVertical: -theme.spacing[2], - }, refreshButton: iconHitboxOverhang(false), refreshButtonCompact: iconHitboxOverhang(true), })); diff --git a/packages/app/src/usage/cards.test.ts b/packages/app/src/usage/cards.test.ts index 86e62b3d21c5..6614ae04549d 100644 --- a/packages/app/src/usage/cards.test.ts +++ b/packages/app/src/usage/cards.test.ts @@ -3,6 +3,7 @@ import { arrangeUsageCards, arrangeUsageReports, DEFAULT_USAGE_PREFERENCES, + isUsageCardOn, setUsageCardOn, UsagePreferencesSchema, usageReportsOn, @@ -11,13 +12,19 @@ import { import { resolvePinnedUsage } from "./pinned"; import type { UsageReportEntry } from "./types"; -function report(sourceId: string, sourceLabel: string, account?: string): UsageReportEntry { +function report( + sourceId: string, + sourceLabel: string, + account?: string, + defaultEnabled?: boolean, +): UsageReportEntry { return { id: `${sourceId}:${account ?? "default"}`, sourceId, sourceLabel, account: account ? { label: account } : {}, fetchedAt: "2026-01-01T00:00:00.000Z", + ...(defaultEnabled === undefined ? {} : { defaultEnabled }), report: { status: "available", windows: [{ id: "weekly", label: "Weekly", summary: true, usedPct: 40 }], @@ -114,8 +121,31 @@ describe("usage card order", () => { describe("usage cards turned off", () => { it("turns a card off and back on", () => { const off = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, "codex:default", false); - expect(off.cardsOff).toEqual(["codex:default"]); - expect(setUsageCardOn(off, "codex:default", true).cardsOff).toEqual([]); + expect(off.cardVisibility).toEqual({ "codex:default": false }); + expect(isUsageCardOn(off, codex)).toBe(false); + const on = setUsageCardOn(off, "codex:default", true); + expect(on.cardVisibility).toEqual({ "codex:default": true }); + expect(isUsageCardOn(on, codex)).toBe(true); + }); + + it("hides sources hinted off by default until the user explicitly turns them on", () => { + const uninstalledCopilot = report("copilot", "GitHub Copilot", undefined, false); + expect(isUsageCardOn(DEFAULT_USAGE_PREFERENCES, uninstalledCopilot)).toBe(false); + expect(ids(usageReportsOn([codex, uninstalledCopilot], DEFAULT_USAGE_PREFERENCES))).toEqual([ + "codex:default", + ]); + expect( + resolvePinnedUsage([codex, uninstalledCopilot], DEFAULT_USAGE_PREFERENCES).map( + (source) => source.key, + ), + ).toEqual(["codex:default"]); + + const optedIn = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, uninstalledCopilot.id, true); + expect(isUsageCardOn(optedIn, uninstalledCopilot)).toBe(true); + expect(ids(usageReportsOn([codex, uninstalledCopilot], optedIn))).toEqual([ + "codex:default", + "copilot:default", + ]); }); it("leaves off cards out of the sidebar summary", () => { @@ -143,11 +173,24 @@ describe("stored card preferences", () => { ); }); + it("migrates legacy cardsOff into cardVisibility", () => { + expect( + UsagePreferencesSchema.parse({ + displayAs: "used", + serverId: null, + cardsOff: ["codex:default"], + }), + ).toEqual({ + ...DEFAULT_USAGE_PREFERENCES, + cardVisibility: { "codex:default": false }, + }); + }); + it("survives a save and reload, and ignores a malformed arrangement", () => { const saved = setUsageCardOn(arranged(["codex:default"]), "claude:work", false); expect(UsagePreferencesSchema.parse(JSON.parse(JSON.stringify(saved)))).toEqual(saved); expect( - UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardsOff: [1] }), + UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardVisibility: [1] }), ).toEqual(DEFAULT_USAGE_PREFERENCES); }); }); diff --git a/packages/app/src/usage/controls.tsx b/packages/app/src/usage/controls.tsx index b4637778c7a5..994c07a33ee5 100644 --- a/packages/app/src/usage/controls.tsx +++ b/packages/app/src/usage/controls.tsx @@ -1,8 +1,9 @@ import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; -import { useMemo, type ReactElement } from "react"; +import { useCallback, useMemo, useState, type ReactElement } from "react"; import { UsageRefreshButton } from "./refresh-button"; import { UsageOptions } from "./options"; +import { useUsageDisplay, type UsageDisplay } from "./display"; import { hasHostChoice, type UsageHostSelection } from "./hosts"; import { useHostUsage } from "./queries"; import type { UsageView } from "./types"; @@ -15,13 +16,19 @@ import type { UsageView } from "./types"; export function UsageControls({ view, serverId, + display, onRefresh, hostSelection, + optionsOpen, + onOptionsOpenChange, }: { view: UsageView; serverId: string; + display?: UsageDisplay; onRefresh: () => void; hostSelection?: UsageHostSelection; + optionsOpen?: boolean; + onOptionsOpenChange?: (open: boolean) => void; }) { const busy = view.kind === "loading" || (view.kind === "ready" && view.isRefreshing); if (!hasUsageControls(view, hostSelection)) return null; @@ -30,7 +37,14 @@ export function UsageControls({ {view.kind === "off" || view.kind === "unavailable" ? null : ( )} - + ); } @@ -54,10 +68,15 @@ const styles = StyleSheet.create((theme) => ({ */ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { view: UsageView; + display: UsageDisplay; refresh: () => void; controls: ReactElement | null; + openOptions: () => void; } { const { view, refresh } = useHostUsage(hostSelection.serverId); + const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); + const [optionsOpen, setOptionsOpen] = useState(false); + const openOptions = useCallback(() => setOptionsOpen(true), []); const controls = useMemo( () => hasUsageControls(view, hostSelection) ? ( @@ -67,11 +86,14 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { key={hostSelection.serverId} serverId={hostSelection.serverId} view={view} + display={display} onRefresh={refresh} hostSelection={hostSelection} + optionsOpen={optionsOpen} + onOptionsOpenChange={setOptionsOpen} /> ) : null, - [hostSelection, refresh, view], + [display, hostSelection, optionsOpen, refresh, view], ); - return { view, refresh, controls }; + return { view, display, refresh, controls, openOptions }; } diff --git a/packages/app/src/usage/datapoint-line.tsx b/packages/app/src/usage/datapoint-line.tsx new file mode 100644 index 000000000000..f0d1a145f541 --- /dev/null +++ b/packages/app/src/usage/datapoint-line.tsx @@ -0,0 +1,38 @@ +import { Fragment } from "react"; +import { Text } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; + +/** + * The secondary datapoints under a usage meter, separated by " · ": reset countdown, exact reset + * time, quota forecast. They are one line of equal text that wraps at the separators when narrow. + */ +export function UsageDatapointLine({ + datapoints, + testID, +}: { + datapoints: readonly (string | null)[]; + testID?: string; +}) { + const shown = datapoints.filter((datapoint): datapoint is string => Boolean(datapoint)); + if (shown.length === 0) return null; + return ( + + {shown.map((datapoint, index) => ( + // Datapoints are distinct strings, so the text is a stable key. + + {/* The no-break space keeps the dot on the line of the datapoint before it. */} + {index > 0 ? "\u00a0· " : null} + {datapoint} + + ))} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + line: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + fontWeight: theme.fontWeight.normal, + }, +})); diff --git a/packages/app/src/usage/display.ts b/packages/app/src/usage/display.ts index f54c16883436..1efb0ac111d8 100644 --- a/packages/app/src/usage/display.ts +++ b/packages/app/src/usage/display.ts @@ -3,7 +3,7 @@ import { useAppSettings } from "@/hooks/use-settings"; import { arrangeUsageCards, arrangeUsageReports, - isUsageCardOff, + isUsageCardOn, isUsagePinned, setUsageCardOn, setUsageDisplayAs, @@ -25,7 +25,7 @@ export interface UsageDisplay { arrange: (reports: readonly UsageReportEntry[]) => UsageReportEntry[]; /** Saves the order of the shown cards after the user drops one. */ arrangeCards: (drop: UsageCardDrop) => void; - isCardOn: (reportId: string) => boolean; + isCardOn: (entry: Pick) => boolean; setCardOn: (reportId: string, on: boolean) => void; } @@ -72,7 +72,7 @@ export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePref togglePin, arrange: (shown) => arrangeUsageReports(shown, preferences), arrangeCards, - isCardOn: (reportId) => !isUsageCardOff(preferences, reportId), + isCardOn: (entry) => isUsageCardOn(preferences, entry), setCardOn, }), [arrangeCards, preferences, reports, setCardOn, setDisplayAs, togglePin], diff --git a/packages/app/src/usage/format.test.ts b/packages/app/src/usage/format.test.ts index 89fb9a7ed684..80fc0001b474 100644 --- a/packages/app/src/usage/format.test.ts +++ b/packages/app/src/usage/format.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { i18n } from "@/i18n/i18next"; import { formatDisplayPct, @@ -38,11 +38,9 @@ describe("formatAmount", () => { expect(formatPct(7, "en")).toBe("7%"); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("resets in 2h"); - expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("runs out in 2h"); await i18n.changeLanguage("ja"); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("2時間後にリセット"); - expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("2時間後に上限に到達"); expect(formatAgo(threeDaysAgo, NOW)).toBe("3日前"); }); @@ -57,18 +55,15 @@ describe("formatAmount", () => { const daysAgo = new Date(NOW - days * 24 * 60 * 60 * 1000).toISOString(); expect(formatResetLabel(daysFromNow, false, NOW)).toBe("se réinitialise dans 1\u202f234 j"); - expect(formatRunsOutLabel(daysFromNow, NOW)).toBe("s’épuise dans 1\u202f234 j"); expect(formatAgo(daysAgo, NOW)).toBe("il y a 1\u202f234 j"); }); it("selects Arabic plural forms for relative durations", async () => { await i18n.changeLanguage("ar"); const twoHoursFromNow = new Date(NOW + 2 * 60 * 60 * 1000).toISOString(); - const threeHoursFromNow = new Date(NOW + 3 * 60 * 60 * 1000).toISOString(); const twoDaysAgo = new Date(NOW - 2 * 24 * 60 * 60 * 1000).toISOString(); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("تتم إعادة التعيين خلال ساعتين"); - expect(formatRunsOutLabel(threeHoursFromNow, NOW)).toBe("ينفد خلال 3 ساعات"); expect(formatAgo(twoDaysAgo, NOW)).toBe("قبل يومين"); }); @@ -111,20 +106,21 @@ describe("reset countdown", () => { }); it("says two units, dropping a unit that is zero", () => { - expect(countdown(DAY + 30 * MINUTE)).toBe("resets in 1d"); expect(countdown(4 * HOUR + 59 * MINUTE)).toBe("resets in 4h 59m"); expect(countdown(HOUR)).toBe("resets in 1h"); expect(countdown(37 * MINUTE)).toBe("resets in 37m"); expect(countdown(59 * 1000)).toBe("resets in 0m"); }); - it("joins the at-risk countdown the same way", () => { - const iso = new Date(NOW + 3 * HOUR + 5 * MINUTE).toISOString(); - expect(formatRunsOutLabel(iso, NOW)).toBe("runs out in 3h 5m"); + it("shows a single day as 24 hours in the reset countdown", () => { + expect(countdown(DAY)).toBe("resets in 24h"); + expect(countdown(DAY + 30 * MINUTE)).toBe("resets in 24h"); + expect(countdown(DAY + HOUR)).toBe("resets in 1d 1h"); + expect(countdown(2 * DAY)).toBe("resets in 2d"); }); }); -describe("exact reset time", () => { +describe("exact quota times", () => { // Local-time dates, so the thresholds hold in any timezone the tests run in. const now = new Date(2026, 9, 29, 12, 0).getTime(); const at = (...args: [number, number, number, number, number]) => @@ -134,18 +130,51 @@ describe("exact reset time", () => { await i18n.changeLanguage("en"); }); - it("shows only the time within 24 hours", () => { + it("shows only the time for the same local day", () => { expect(at(2026, 9, 29, 15, 0)).toMatch(/^(3:00 PM|15:00)$/); - expect(at(2026, 9, 30, 11, 59)).toMatch(/^(11:59 AM|11:59)$/); }); - it("adds the weekday within 7 days", () => { - expect(at(2026, 9, 30, 12, 0)).toMatch(/^Fri (12:00 PM|12:00)$/); - expect(at(2026, 10, 5, 11, 59)).toMatch(/^Thu (11:59 AM|11:59)$/); + it("shows the weekday for tomorrow even when it is less than 24 hours away", () => { + expect(at(2026, 9, 30, 11, 59)).toMatch(/^Fri (11:59 AM|11:59)$/); + expect(at(2026, 10, 4, 15, 0)).toMatch(/^Wed (3:00 PM|15:00)$/); }); - it("adds the date after 7 days", () => { - expect(at(2026, 10, 5, 12, 0)).toMatch(/^Nov 5, (12:00 PM|12:00)$/); + it("includes the date on the same weekday next week even when fewer than 7 days elapse", () => { + expect(at(2026, 10, 5, 10, 0)).toMatch(/^Thu, Nov 5, (10:00 AM|10:00)$/); + }); + + it("includes the weekday and date seven or more calendar days out", () => { + expect(at(2026, 10, 5, 12, 0)).toMatch(/^Thu, Nov 5, (12:00 PM|12:00)$/); + expect(at(2026, 10, 6, 15, 0)).toMatch(/^Fri, Nov 6, (3:00 PM|15:00)$/); + }); + + it("counts calendar days across the spring daylight-saving transition", () => { + vi.stubEnv("TZ", "America/New_York"); + try { + const before = new Date(2026, 2, 7, 12); + const after = new Date(2026, 2, 14, 12); + expect(after.getTime() - before.getTime()).toBe(167 * 3_600_000); + expect(formatResetTime(after.toISOString(), before.getTime())).toMatch(/^Sat, Mar 14, /); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("shows the exhaustion clock time with the same weekday and date rules as reset time", () => { + const runsOut = (...args: [number, number, number, number, number]) => + formatRunsOutLabel(new Date(...args).toISOString(), now)?.replace(/\s/g, " "); + + expect(runsOut(2026, 9, 29, 15, 0)).toMatch(/^runs out (3:00 PM|15:00)$/); + expect(runsOut(2026, 9, 30, 9, 32)).toMatch(/^runs out Fri (9:32 AM|09:32|9:32)$/); + expect(runsOut(2026, 10, 5, 15, 30)).toMatch(/^runs out Thu, Nov 5, (3:30 PM|15:30)$/); + }); + + it("uses the app language for the exhaustion label and weekday", async () => { + await i18n.changeLanguage("ja"); + const time = new Date(2026, 9, 30, 15, 30).toISOString(); + expect(formatRunsOutLabel(time, now)?.replace(/\s/g, " ")).toMatch( + /^金 (?:3:30 PM|15:30)に上限に到達$/, + ); }); it("names the weekday in the app language", async () => { diff --git a/packages/app/src/usage/format.ts b/packages/app/src/usage/format.ts index 16386810fae3..8bc6720fdaf1 100644 --- a/packages/app/src/usage/format.ts +++ b/packages/app/src/usage/format.ts @@ -1,6 +1,6 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; -import { formatTimeOfDay } from "@/utils/time"; +import { formatTimeOfDay, localCalendarDaysBetween } from "@/utils/time"; import type { UsageDisplayAs } from "./preferences"; import type { UsageBalanceUnit, UsageReportEntry } from "./types"; @@ -79,6 +79,7 @@ function relativeDuration(iso: string, now: number): RelativeDuration | null { const days = Math.floor(diffMs / DAY_MS); const hours = Math.floor((diffMs % DAY_MS) / HOUR_MS); const minutes = Math.floor((diffMs % HOUR_MS) / MINUTE_MS); + if (days === 1 && hours === 0) return remaining({ unit: "hours", count: 24 }); if (days > 0) return remaining({ unit: "days", count: days }, { unit: "hours", count: hours }); if (hours > 0) return remaining({ unit: "hours", count: hours }, { unit: "minutes", count: minutes }); @@ -120,8 +121,8 @@ export function formatResetLabel( } /** - * When a window resets on the clock: "3:00 PM" within a day, "Fri 3:00 PM" within a week, - * "Oct 31, 3:00 PM" after that. Names follow the app language; 12/24h follows the device. + * A clock time today, a weekday for the next six calendar days, and a weekday plus date after that. + * Names follow the app language. The clock uses the device's 12/24h preference. * Nothing for a time that has passed, where the countdown already says so. */ export function formatResetTime( @@ -135,12 +136,13 @@ export function formatResetTime( if (!Number.isFinite(diffMs) || diffMs <= 0) return null; const time = formatTimeOfDay(at); const locale = i18n.resolvedLanguage; - if (diffMs < DAY_MS) return time; - if (diffMs < 7 * DAY_MS) { + const dayDiff = localCalendarDaysBetween(new Date(now), at); + if (dayDiff === 0) return time; + if (dayDiff <= 6) { const weekday = at.toLocaleDateString(locale, { weekday: "short" }); return t("providerUsage.timing.resetsAtWeekday", { weekday, time }); } - const date = at.toLocaleDateString(locale, { month: "short", day: "numeric" }); + const date = at.toLocaleDateString(locale, { weekday: "short", month: "short", day: "numeric" }); return t("providerUsage.timing.resetsAtDate", { date, time }); } @@ -149,11 +151,8 @@ export function formatRunsOutLabel( now = Date.now(), t: TFunction = i18n.t, ): string | null { - if (!iso) return null; - const rel = relativeDuration(iso, now); - if (!rel) return null; - if (rel.kind === "now") return t("providerUsage.timing.runsOutNow"); - return t("providerUsage.timing.runsOutIn", { duration: formatRelativeDuration(rel, t) }); + const time = formatResetTime(iso, now, t); + return time ? t("providerUsage.timing.runsOutAt", { time }) : null; } export function formatAgo( diff --git a/packages/app/src/usage/list.tsx b/packages/app/src/usage/list.tsx index e9218ae32642..6052466c8be0 100644 --- a/packages/app/src/usage/list.tsx +++ b/packages/app/src/usage/list.tsx @@ -16,8 +16,8 @@ function reportKey(entry: UsageReportEntry): string { } /** - * One card per report (source + account), in the user's order. Each card drags by its handle and - * turns off from its switch. Window rows pin while the sidebar summary is on. + * One card per shown report (source + account), in the user's order. Each card drags by its handle. + * Window rows pin while the sidebar summary is on. */ export function UsageList({ serverId, @@ -29,8 +29,7 @@ export function UsageList({ display: UsageDisplay; }) { const { inSidebar } = useUsageInSidebar(); - const { arrange, arrangeCards } = display; - const arranged = useMemo(() => arrange(reports), [arrange, reports]); + const { arrangeCards } = display; const handleDragEnd = useCallback( (next: UsageReportEntry[], moved: string) => arrangeCards({ moved, after: next.map(reportKey) }), @@ -52,7 +51,7 @@ export function UsageList({ ); return ( setHasFocus(true), []); const handleBlur = useCallback(() => setHasFocus(false), []); - const { isCardOn, setCardOn } = display; - const on = isCardOn(entry.id); - const handleSetOn = useCallback( - (next: boolean) => setCardOn(entry.id, next), - [entry.id, setCardOn], - ); const arrangement = useMemo( () => ({ - on, - onSetOn: handleSetOn, handleVisible: isHovered || hasFocus || dragging || isNative || isCompact, }), - [dragging, handleSetOn, hasFocus, isCompact, isHovered, on], + [dragging, hasFocus, isCompact, isHovered], ); return ( ({ fillQuiet: { backgroundColor: theme.colors.surface4, }, - fillDefault: { - backgroundColor: theme.colors.foregroundMuted, - }, fillOk: { backgroundColor: theme.colors.statusSuccess, }, diff --git a/packages/app/src/usage/model.test.ts b/packages/app/src/usage/model.test.ts index 3090ac79e4aa..a6916b9cf9e5 100644 --- a/packages/app/src/usage/model.test.ts +++ b/packages/app/src/usage/model.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { i18n } from "@/i18n/i18next"; import { resolveUsageReport, + markUsageRefreshFailure, displayPercent, resolveAgentUsageView, replaceReport, @@ -82,7 +83,7 @@ describe("resolveUsageView", () => { expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" }); expect( resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }), - ).toEqual({ kind: "ready", reports: [], isRefreshing: true }); + ).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false }); expect( resolveUsageView({ ...base, @@ -90,6 +91,19 @@ describe("resolveUsageView", () => { }), ).toEqual({ kind: "error", message: "boom" }); }); + + it("shows a failed Refresh all alongside the reports still on screen", () => { + const reports = [entry({})]; + expect( + resolveUsageView({ + hostLabel: "Laptop", + isConnected: true, + supportsUsage: true, + query: ready(reports), + refreshState: "failed", + }), + ).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true }); + }); }); afterEach(async () => { @@ -203,15 +217,12 @@ describe("displayPercent", () => { describe("resolveUsageRefresh", () => { it("is pending while a refresh runs, even after an earlier failure", () => { - expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending"); + expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending"); }); - it("is failed after a refresh errors", () => { - expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed"); - }); - - it("is idle before and after a successful refresh", () => { - expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle"); + it("reports the request outcome independently of the reading", () => { + expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed"); + expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle"); }); }); @@ -352,6 +363,7 @@ it("resolves retained usage and successful time without inventing old-daemon his details: [], planLabel: null, successfulAt: success.fetchedAt, + forecastAt: null, retained: true, messages: ["Rate limited"], }); @@ -361,6 +373,7 @@ it("resolves retained usage and successful time without inventing old-daemon his details: [], planLabel: null, successfulAt: null, + forecastAt: null, retained: false, messages: ["Rate limited"], }); @@ -370,11 +383,48 @@ it("resolves retained usage and successful time without inventing old-daemon his details: [], planLabel: null, successfulAt: success.fetchedAt, + forecastAt: success.fetchedAt, retained: false, messages: [], }); }); +it("uses the quota observation time for pace and keeps the reading after a failed request", () => { + const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] }); + if (success.report.status !== "available") throw new Error("fixture must be available"); + const observedAt = success.fetchedAt; + const successfulAt = "2026-01-01T00:15:00.000Z"; + const report = { ...success, successfulAt, report: { ...success.report, observedAt } }; + expect(resolveUsageReport(report, i18n.t)).toMatchObject({ + successfulAt, + forecastAt: observedAt, + }); + expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({ + windows: success.report.windows, + successfulAt, + forecastAt: null, + }); +}); + +it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => { + const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] }); + const other = entry({ sourceId: "other" }); + const refreshedAt = "2026-01-01T00:06:00.000Z"; + const streamed = { ...other, fetchedAt: refreshedAt }; + const attempted = [before, other]; + const failed = markUsageRefreshFailure([before, streamed], attempted)!; + + expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({ + forecastAt: null, + windows: before.report.status === "available" ? before.report.windows : [], + }); + expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt); + expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull(); + + const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]); + expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt); +}); + it("orders failed polls by attempt time even when successful data is older", () => { const success = entry({}); if (success.report.status !== "available") throw new Error("fixture must be available"); diff --git a/packages/app/src/usage/model.ts b/packages/app/src/usage/model.ts index ac2cf62db2c9..ae9a8e98d514 100644 --- a/packages/app/src/usage/model.ts +++ b/packages/app/src/usage/model.ts @@ -38,18 +38,31 @@ export function usageWindowRowLabel(input: { return `${input.pinLabel}, ${summary}`; } -/** A user-requested refresh of one report. The previous report stays on screen throughout. */ +/** The outcome of a user-requested usage refresh. */ export type UsageRefresh = "idle" | "pending" | "failed"; export function resolveUsageRefresh(mutation: { isPending: boolean; - error: unknown; + isError: boolean; }): UsageRefresh { if (mutation.isPending) return "pending"; - if (mutation.error) return "failed"; + if (mutation.isError) return "failed"; return "idle"; } +/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */ +export function markUsageRefreshFailure( + current: UsageReportEntry[] | undefined, + attempted: readonly UsageReportEntry[], +): UsageReportEntry[] | undefined { + const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt])); + return current?.map((entry) => + attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale + ? { ...entry, forecastStale: true } + : entry, + ); +} + /** * A host's report list with one report swapped for its refreshed copy, in place. * `null` means the daemon no longer knows the ID, so the report leaves the list. @@ -60,7 +73,9 @@ export function replaceReport( refreshed: UsageReportEntry | null, ): UsageReportEntry[] { if (!refreshed) return reports.filter((report) => report.id !== reportId); - return reports.map((report) => (report.id === reportId ? refreshed : report)); + return reports.map((report) => + report.id === reportId ? laterFetched(report, refreshed) : report, + ); } /** @@ -68,7 +83,9 @@ export function replaceReport( * started, so a Refresh that lands while it streams is newer than what the request still delivers. */ function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry { - return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving; + const shownAt = Date.parse(shown.fetchedAt); + const arrivingAt = Date.parse(arriving.fetchedAt); + return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving; } /** @@ -117,10 +134,11 @@ export function resolveUsageView( isConnected: boolean; supportsUsage: boolean; query: UsageQueryState | undefined; + refreshState?: UsageRefresh; }, t: TFunction = i18n.t, ): UsageView { - const { hostLabel, isConnected, supportsUsage, query } = input; + const { hostLabel, isConnected, supportsUsage, query, refreshState } = input; if (!isConnected) return { kind: "unavailable", @@ -135,7 +153,12 @@ export function resolveUsageView( if (input.enabled === false) return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) }; if (query?.data) { - return { kind: "ready", reports: query.data, isRefreshing: query.isFetching }; + return { + kind: "ready", + reports: query.data, + isRefreshing: query.isFetching || refreshState === "pending", + refreshFailed: refreshState === "failed", + }; } if (query?.error) { return { @@ -250,7 +273,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) { // COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0. else messages.push(usageProblemText(entry.report, t)); } + const forecastAt = + snapshot && !snapshot.retained && !entry.forecastStale + ? (snapshot.report.observedAt ?? snapshot.successfulAt) + : null; return { + forecastAt, windows: snapshot?.report.windows ?? [], balances: snapshot?.report.balances ?? [], details: snapshot?.report.details ?? [], diff --git a/packages/app/src/usage/options.tsx b/packages/app/src/usage/options.tsx index 53277eb20afd..6c3197663f17 100644 --- a/packages/app/src/usage/options.tsx +++ b/packages/app/src/usage/options.tsx @@ -2,9 +2,10 @@ import { useTranslation } from "react-i18next"; import { View } from "react-native"; import { Settings } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; -import { useMemo } from "react"; +import { useCallback, useMemo } from "react"; import { DropdownMenu, + DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuSubTrigger, type MenuPageDefinition, @@ -23,26 +24,36 @@ import { Alert } from "@/components/ui/alert"; import { useHosts } from "@/runtime/host-runtime"; import { settingsStyles } from "@/styles/settings"; import { useUsageSetting } from "./setting"; -import { useUsageDisplay } from "./display"; +import { useUsageDisplay, type UsageDisplay } from "./display"; import { useUsageInSidebar } from "./in-sidebar"; import { hasHostChoice, type UsageHostSelection } from "./hosts"; import type { UsageDisplayAs } from "./preferences"; +import { UsageSourceIcon } from "./source-icon"; +import type { UsageReportEntry } from "./types"; const ThemedSettings = withUnistyles(Settings); const HOST_PAGE = "host"; +const SOURCES_PAGE = "sources"; /** - * The shared usage preferences, opened from a cog as a popover or compact sheet. With more than - * one host, it leads with the host whose usage shows: the row reads as the current host, and the - * hosts are a page of the same surface, so a compact sheet never opens a second sheet over it. + * The shared usage preferences, opened from a cog as a popover or compact sheet. Host and Sources + * open as pages of the same surface, so a compact sheet never opens a second sheet over it. */ export function UsageOptions({ serverId, hostSelection, + reports = [], + display: providedDisplay, + open, + onOpenChange, }: { serverId: string | null; hostSelection?: UsageHostSelection; + reports?: readonly UsageReportEntry[]; + display?: UsageDisplay; + open?: boolean; + onOpenChange?: (open: boolean) => void; }) { const setting = useUsageSetting(serverId); const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId; @@ -57,24 +68,37 @@ export function UsageOptions({ ]; const compact = useIsCompactFormFactor(); const glyphSize = useIconButtonChromeGlyphSize("small", compact); - const { display } = useUsageDisplay([]); + const fallbackDisplay = useUsageDisplay(providedDisplay ? [] : reports).display; + const display = providedDisplay ?? fallbackDisplay; const { inSidebar, setInSidebar } = useUsageInSidebar(); const hostChoice = hasHostChoice(hostSelection) ? hostSelection : null; - const pages = useMemo( - () => - hostChoice - ? [ - { - id: HOST_PAGE, - title: t("providerUsage.host"), - content: , - }, - ] - : undefined, - [hostChoice, t], + const arrangedReports = useMemo(() => display.arrange(reports), [display, reports]); + const hasSources = arrangedReports.length > 0; + const shownCount = useMemo( + () => arrangedReports.filter((entry) => display.isCardOn(entry)).length, + [arrangedReports, display], ); + const pages = useMemo(() => { + const definitions: MenuPageDefinition[] = []; + if (hostChoice) { + definitions.push({ + id: HOST_PAGE, + title: t("providerUsage.host"), + content: , + }); + } + if (hasSources) { + definitions.push({ + id: SOURCES_PAGE, + title: t("providerUsage.sources"), + content: , + }); + } + return definitions.length > 0 ? definitions : undefined; + }, [arrangedReports, display, hasSources, hostChoice, t]); + const hasSubTriggers = Boolean(hostChoice || hasSources); return ( - + ) : null} + {hasSources ? ( + + {t("providerUsage.sources")} + + ) : null} @@ -156,3 +192,60 @@ function UsageHostPage({ hostSelection }: { hostSelection: UsageHostSelection }) ); } + +function UsageSourcesPage({ + reports, + display, +}: { + reports: readonly UsageReportEntry[]; + display: UsageDisplay; +}) { + const { t } = useTranslation(); + const inactiveLabel = t("providerUsage.providerInactive"); + return ( + <> + {reports.map((entry) => ( + + ))} + + ); +} + +function UsageSourceMenuItem({ + entry, + on, + onToggle, + inactiveLabel, +}: { + entry: UsageReportEntry; + on: boolean; + onToggle: (reportId: string, on: boolean) => void; + inactiveLabel: string; +}) { + const handleSelect = useCallback(() => onToggle(entry.id, !on), [entry.id, on, onToggle]); + const leading = useMemo( + () => , + [entry.icon], + ); + const description = + [entry.account.label, !on && entry.defaultEnabled === false ? inactiveLabel : null] + .filter(Boolean) + .join(" · ") || undefined; + return ( + + {entry.sourceLabel} + + ); +} diff --git a/packages/app/src/usage/pace.test.ts b/packages/app/src/usage/pace.test.ts new file mode 100644 index 000000000000..37dbbc90b8ef --- /dev/null +++ b/packages/app/src/usage/pace.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest"; +import { usagePace } from "./pace"; +import type { UsageWindow } from "./types"; + +const day = "2026-11-20T"; +const reading = (time: string) => `${day}${time}:00.000Z`; +const window: UsageWindow = { + id: "five_hour", + label: "Session", + durationSeconds: 18_000, + usedPct: 65, + resetsAt: reading("15:00"), +}; + +describe("usage pace", () => { + it("projects the limit from the sample time and keeps it fixed between readings", () => { + const sampledAt = reading("12:00"); + const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` }; + expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate); + expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate); + }); + + it("updates after a later reading and works with a remaining percentage", () => { + const close = reading("13:30"); + const safe = reading("14:00"); + expect(usagePace(window, close, Date.parse(close))).toEqual({ kind: "tight" }); + expect( + usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)), + ).toEqual({ kind: "onTrack" }); + }); + + it("projects a weekly window after 100 minutes when 6% is already used", () => { + const sampledAt = "2026-11-21T10:28:17.000Z"; + const weekly: UsageWindow = { + id: "gemini-weekly", + label: "Gemini · Weekly", + durationSeconds: 604_800, + usedPct: 6, + resetsAt: "2026-11-28T08:48:17.000Z", + }; + expect(usagePace(weekly, sampledAt, Date.parse("2026-11-21T10:33:03Z"))).toEqual({ + kind: "runsOut", + at: "2026-11-22T12:34:57.000Z", + }); + }); + + it("only forecasts with timing and an active, usable reading", () => { + const sampledAt = reading("12:00"); + const now = Date.parse(sampledAt); + expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({ + kind: "unknown", + }); + expect(usagePace(window, null, now)).toEqual({ kind: "unknown" }); + expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" }); + expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" }); + expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" }); + }); +}); diff --git a/packages/app/src/usage/pace.ts b/packages/app/src/usage/pace.ts new file mode 100644 index 000000000000..0908a3d0bbbb --- /dev/null +++ b/packages/app/src/usage/pace.ts @@ -0,0 +1,47 @@ +import { usedPercent } from "./model"; +import type { UsageWindow } from "./types"; + +type UsagePace = + | { kind: "unknown" } + | { kind: "reached" } + | { kind: "runsOut"; at: string } + | { kind: "onTrack" | "tight" }; + +/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */ +export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace { + if (observedAt === null) return { kind: "unknown" }; + const reset = Date.parse(window.resetsAt ?? ""); + if (reset <= now) return { kind: "unknown" }; + + const used = usedPercent(window); + if (used != null && used >= 100) return { kind: "reached" }; + + const supplied = window.runsOutAt; + const suppliedAt = Date.parse(supplied ?? ""); + if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) { + return { kind: "runsOut", at: supplied }; + } + + const duration = (window.durationSeconds ?? 0) * 1_000; + const sampled = Date.parse(observedAt); + const elapsed = sampled - (reset - duration); + // Wait for an initial sample without holding back multi-day forecasts for several hours. + const minimumElapsed = Math.max(60_000, Math.min(duration * 0.01, 3_600_000)); + if ( + used == null || + !Number.isFinite(used) || + used < 0 || + !Number.isFinite(elapsed) || + sampled >= reset || + elapsed < minimumElapsed + ) { + return { kind: "unknown" }; + } + + const projectedAtReset = (used / elapsed) * duration; + if (projectedAtReset > 100) { + const runsOut = sampled + ((100 - used) / used) * elapsed; + return { kind: "runsOut", at: new Date(runsOut).toISOString() }; + } + return { kind: projectedAtReset >= 90 ? "tight" : "onTrack" }; +} diff --git a/packages/app/src/usage/pinned.test.ts b/packages/app/src/usage/pinned.test.ts index b780659043b7..93ce214eeedf 100644 --- a/packages/app/src/usage/pinned.test.ts +++ b/packages/app/src/usage/pinned.test.ts @@ -53,7 +53,7 @@ function preferences( } describe("choosePinnedUsageLayout", () => { - const widths = { labelsWidth: 200, percentsWidth: 120, windowCount: 2 }; + const widths = { labelsWidth: 200, compactWidth: 200, percentsWidth: 120, windowCount: 2 }; it("shows meters only when every window's meter fits beside the labels", () => { expect(choosePinnedUsageLayout({ ...widths, available: 240 })).toBe("meters"); @@ -64,11 +64,27 @@ describe("choosePinnedUsageLayout", () => { expect(choosePinnedUsageLayout({ ...widths, available: 199 })).toBe("percents"); }); + it("uses compact period shorthands when full labels overflow but compact labels fit", () => { + const scoped = { labelsWidth: 485, compactWidth: 388, percentsWidth: 268, windowCount: 6 }; + expect(choosePinnedUsageLayout({ ...scoped, available: 485 })).toBe("labels"); + expect(choosePinnedUsageLayout({ ...scoped, available: 399 })).toBe("compact"); + expect(choosePinnedUsageLayout({ ...scoped, available: 388 })).toBe("compact"); + expect(choosePinnedUsageLayout({ ...scoped, available: 387 })).toBe("percents"); + }); + + it("skips compact mode when no window has a compact label", () => { + const noPeriod = { labelsWidth: 220, compactWidth: 120, percentsWidth: 120, windowCount: 2 }; + expect(choosePinnedUsageLayout({ ...noPeriod, available: 180 })).toBe("percents"); + }); + it("shows labels until the widths are measured", () => { expect(choosePinnedUsageLayout({ ...widths, available: null })).toBe("labels"); expect(choosePinnedUsageLayout({ ...widths, available: 999, labelsWidth: null })).toBe( "labels", ); + expect(choosePinnedUsageLayout({ ...widths, available: 999, compactWidth: null })).toBe( + "labels", + ); }); }); @@ -145,6 +161,7 @@ describe("resolvePinnedUsage", () => { key: "claude:default/five-hour", label: "Claude Session 31% used", shortLabel: "5h", + compactLabel: "5h", percent: 31, percentText: "31%", tone: "default", @@ -153,6 +170,7 @@ describe("resolvePinnedUsage", () => { key: "claude:default/weekly", label: "Claude Weekly 80% used", shortLabel: "wk", + compactLabel: "wk", percent: 80, percentText: "80%", tone: "warning", @@ -216,6 +234,52 @@ describe("resolvePinnedUsage", () => { const items = windows([opencode], preferences(null)); expect(items.map((item) => item.shortLabel)).toEqual([""]); + expect(items.map((item) => item.compactLabel)).toEqual([""]); + }); + + it("extracts bare period tokens as compact labels for scoped or verbose short labels", () => { + const mixed = report({ + sourceId: "mixed", + sourceLabel: "Mixed", + windows: [ + { id: "a", label: "Session", shortLabel: "5h", summary: true, usedPct: 10 }, + { id: "b", label: "Weekly · Opus", shortLabel: "wk Opus", summary: true, usedPct: 20 }, + { + id: "c", + label: "Code review · Weekly", + shortLabel: "Code review wk", + summary: true, + usedPct: 30, + }, + { + id: "d", + label: "Gemini Models · Weekly", + shortLabel: "Gemini Models weekly", + summary: true, + usedPct: 40, + }, + { + id: "e", + label: "Gemini Models · 5h", + shortLabel: "Gemini Models 5h", + summary: true, + usedPct: 50, + }, + { id: "f", label: "Monthly", shortLabel: "Monthly", summary: true, usedPct: 60 }, + { id: "g", label: "Premium requests", summary: true, usedPct: 70 }, + ], + }); + const items = windows([mixed], preferences(null)); + + expect(items.map((item) => [item.shortLabel, item.compactLabel])).toEqual([ + ["5h", "5h"], + ["wk Opus", "wk"], + ["Code review wk", "wk"], + ["Gemini Models weekly", "wk"], + ["Gemini Models 5h", "5h"], + ["Monthly", "mo"], + ["Premium requests", ""], + ]); }); it("formats the share left when the user reads usage as remaining", () => { diff --git a/packages/app/src/usage/pinned.ts b/packages/app/src/usage/pinned.ts index b725c3e08653..6b6fbdcd7390 100644 --- a/packages/app/src/usage/pinned.ts +++ b/packages/app/src/usage/pinned.ts @@ -18,6 +18,8 @@ export interface PinnedUsageWindow { label: string; /** The window's short name ("5h"), empty for none, or its label when the source sends none. */ shortLabel: string; + /** Bare period token ("5h", "wk", "mo") used when full short labels overflow the sidebar row. */ + compactLabel: string; /** The share shown, under the user's used/remaining preference. */ percent: number; percentText: string; @@ -34,28 +36,66 @@ export interface PinnedUsageSource { } /** How much of each window the one-line summary has room for. */ -export type PinnedUsageLayout = "meters" | "labels" | "percents"; +export type PinnedUsageLayout = "meters" | "labels" | "compact" | "percents"; // A meter narrower than this is a sliver that reads as noise rather than a share. export const MIN_METER_WIDTH = 16; /** The space between a meter and its text. */ export const METER_GAP = 4; +const DURATION_TOKEN_PATTERN = /^\d+[smhd]$/i; + +function normalizePeriodToken(token: string): string | null { + const lower = token.toLowerCase(); + if (lower === "wk" || lower === "weekly") return "wk"; + if (lower === "mo" || lower === "monthly") return "mo"; + if (DURATION_TOKEN_PATTERN.test(token)) return lower; + return null; +} + +/** + * Extracts a bare period token ("5h", "wk", "mo") from a window's short label so tight sidebar + * rows can keep shorthands visible instead of dropping every label when one window is scoped. + */ +function compactShortLabel(shortLabel: string): string { + const trimmed = shortLabel.trim(); + if (trimmed === "") return ""; + const exact = normalizePeriodToken(trimmed); + if (exact !== null) return exact; + const parts = trimmed.split(/\s+/); + if (parts.length > 1) { + const first = normalizePeriodToken(parts[0]!); + if (first !== null) return first; + const last = normalizePeriodToken(parts[parts.length - 1]!); + if (last !== null) return last; + } + return ""; +} + /** * The richest layout that fits on one line: every window's meter, else its short label, else its - * percent alone. Meters are all or none; a line never mixes them. Until the widths are known it - * shows labels, which never flashes meters that turn out not to fit. + * bare period shorthand, else its percent alone. Meters are all or none; a line never mixes them. + * Until the widths are known it shows labels, which never flashes meters that turn out not to fit. */ export function choosePinnedUsageLayout(input: { available: number | null; labelsWidth: number | null; + compactWidth: number | null; percentsWidth: number | null; windowCount: number; }): PinnedUsageLayout { - const { available, labelsWidth, percentsWidth, windowCount } = input; - if (available === null || labelsWidth === null || percentsWidth === null) return "labels"; + const { available, labelsWidth, compactWidth, percentsWidth, windowCount } = input; + if ( + available === null || + labelsWidth === null || + compactWidth === null || + percentsWidth === null + ) { + return "labels"; + } if (labelsWidth + windowCount * (MIN_METER_WIDTH + METER_GAP) <= available) return "meters"; if (labelsWidth <= available) return "labels"; + if (compactWidth <= available && compactWidth > percentsWidth) return "compact"; return percentsWidth < labelsWidth ? "percents" : "labels"; } @@ -85,10 +125,13 @@ export function resolvePinnedUsage( .map((window) => { const percent = displayPercent(window, preferences.displayAs) ?? 0; const percentText = formatPct(percent); + const shortLabel = + window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t); return { key: `${entry.id}/${window.id}`, label: `${describe(entry, formatProviderUsageLabel(window.id, window.label, t))} ${formatDisplayPct(percent, preferences.displayAs, undefined, t)}`, - shortLabel: window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t), + shortLabel, + compactLabel: compactShortLabel(shortLabel), percent, percentText, tone: windowTone(window), diff --git a/packages/app/src/usage/preferences.ts b/packages/app/src/usage/preferences.ts index 7ad7d5a3e8d7..6ee91680c578 100644 --- a/packages/app/src/usage/preferences.ts +++ b/packages/app/src/usage/preferences.ts @@ -20,8 +20,8 @@ export interface UsagePreferences { serverId: string | null; /** Report IDs the user arranged, in their order. Shared by every host. */ cardOrder: string[]; - /** Report IDs the user turned off. Their cards collapse and leave the sidebar summary. */ - cardsOff: string[]; + /** Explicit per-report visibility overrides; absent IDs follow the host's `defaultEnabled` hint. */ + cardVisibility: Record; } export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = { @@ -29,11 +29,12 @@ export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = { pins: null, serverId: null, cardOrder: [], - cardsOff: [], + cardVisibility: {}, }; const pinsSchema = z.array(z.object({ sourceId: z.string(), windowId: z.string() })); const reportIdsSchema = z.array(z.string()).optional().catch(undefined); +const cardVisibilitySchema = z.record(z.string(), z.boolean()).optional().catch(undefined); export const UsagePreferencesSchema = z .object({ @@ -44,18 +45,34 @@ export const UsagePreferencesSchema = z pinned: pinsSchema.optional().catch([]), serverId: z.string().nullable().catch(null), cardOrder: reportIdsSchema, + cardVisibility: cardVisibilitySchema, + // COMPAT(usageCardsOff): replaced by cardVisibility in v0.18, remove after 2027-05-22. cardsOff: reportIdsSchema, }) - .transform(({ displayAs, pins, pinned, serverId, cardOrder, cardsOff }): UsagePreferences => { - const legacyPins = pinned && pinned.length > 0 ? pinned : null; - return { + .transform( + ({ displayAs, - pins: pins === undefined ? legacyPins : pins, + pins, + pinned, serverId, - cardOrder: cardOrder ?? [], - cardsOff: cardsOff ?? [], - }; - }) + cardOrder, + cardVisibility, + cardsOff, + }): UsagePreferences => { + const legacyPins = pinned && pinned.length > 0 ? pinned : null; + const legacyVisibility = + cardsOff && cardsOff.length > 0 + ? Object.fromEntries(cardsOff.map((id) => [id, false] as const)) + : {}; + return { + displayAs, + pins: pins === undefined ? legacyPins : pins, + serverId, + cardOrder: cardOrder ?? [], + cardVisibility: cardVisibility ?? legacyVisibility, + }; + }, + ) .catch(DEFAULT_USAGE_PREFERENCES); function samePin(a: UsagePin, b: UsagePin): boolean { @@ -154,8 +171,8 @@ export function usageReportsOn( reports: readonly UsageReportEntry[], preferences: UsagePreferences, ): UsageReportEntry[] { - return arrangeUsageReports(reports, preferences).filter( - (entry) => !isUsageCardOff(preferences, entry.id), + return arrangeUsageReports(reports, preferences).filter((entry) => + isUsageCardOn(preferences, entry), ); } @@ -188,8 +205,14 @@ export function arrangeUsageCards( return { ...preferences, cardOrder: rest }; } -export function isUsageCardOff(preferences: UsagePreferences, reportId: string): boolean { - return preferences.cardsOff.includes(reportId); +/** Whether a report card is shown, honoring an explicit user override before the host's default hint. */ +export function isUsageCardOn( + preferences: UsagePreferences, + entry: Pick, +): boolean { + const explicit = preferences.cardVisibility[entry.id]; + if (explicit !== undefined) return explicit; + return entry.defaultEnabled !== false; } export function setUsageCardOn( @@ -197,6 +220,8 @@ export function setUsageCardOn( reportId: string, on: boolean, ): UsagePreferences { - const others = preferences.cardsOff.filter((id) => id !== reportId); - return { ...preferences, cardsOff: on ? others : [...others, reportId] }; + return { + ...preferences, + cardVisibility: { ...preferences.cardVisibility, [reportId]: on }, + }; } diff --git a/packages/app/src/usage/queries.ts b/packages/app/src/usage/queries.ts index 702f115253a0..a0c934afe0b0 100644 --- a/packages/app/src/usage/queries.ts +++ b/packages/app/src/usage/queries.ts @@ -20,6 +20,7 @@ import { useSessionStore, type SessionState } from "@/stores/session-store"; import { useUsageSetting } from "./setting"; import { usageCopy } from "./copy"; import { + markUsageRefreshFailure, replaceReport, resolveAgentUsageView, resolveUsageRefresh, @@ -97,17 +98,32 @@ async function streamReports(input: { return settleReports(queryClient.getQueryData(queryKey), reports); } -function listReports( +async function listReports( queryClient: QueryClient, serverId: string, forceRefresh = false, ): Promise { - return streamReports({ - queryClient, - queryKey: usageReportsQueryKey(serverId), - serverId, - forceRefresh, - }); + const queryKey = usageReportsQueryKey(serverId); + const attempted = queryClient.getQueryData(queryKey) ?? []; + try { + return await streamReports({ queryClient, queryKey, serverId, forceRefresh }); + } catch (error) { + recordUsageRefreshFailure(queryClient, queryKey, attempted); + throw error; + } +} + +function recordUsageRefreshFailure( + queryClient: QueryClient, + queryKey: QueryKey, + attempted: readonly UsageReportEntry[], +): void { + const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {}; + queryClient.setQueryData( + queryKey, + (current) => markUsageRefreshFailure(current, attempted), + { updatedAt: dataUpdatedAt }, + ); } async function getReport( @@ -158,9 +174,12 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () = dataShape: "value", staleTimeMs: REPORTS_STALE_TIME_MS, }); - const refresh = useCallback(() => { - void refreshReports(queryClient, serverId).catch(() => undefined); - }, [queryClient, serverId]); + const mutation = useMutation({ + mutationKey: [...usageReportsQueryKey(serverId), "refresh"], + mutationFn: (hostId: string) => refreshReports(queryClient, hostId), + }); + const { mutate, variables } = mutation; + const refresh = useCallback(() => mutate(serverId), [mutate, serverId]); const { t } = useTranslation(); const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId; const view = resolveUsageView( @@ -170,6 +189,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () = isConnected, supportsUsage: isSupported, query: toQueryState(query), + refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle", }, t, ); @@ -265,23 +285,26 @@ export function useUsageHosts(): UsageHost[] { */ export function useReportRefresh( serverId: string, - reportId: string, + entry: UsageReportEntry, agentId?: string, ): { refresh: () => void; refreshState: UsageRefresh } { const queryClient = useQueryClient(); const usageScopeKey = useAgentUsageScopeKey(serverId, agentId); + const queryKey = + agentId === undefined + ? usageReportsQueryKey(serverId) + : agentUsageQueryKey(serverId, agentId, usageScopeKey); const mutation = useMutation({ - mutationFn: () => getReport(serverId, reportId, true, agentId), - onSuccess: (report) => { - queryClient.setQueryData( - agentId === undefined - ? usageReportsQueryKey(serverId) - : agentUsageQueryKey(serverId, agentId, usageScopeKey), - (reports) => (reports ? replaceReport(reports, reportId, report) : reports), + mutationKey: [...queryKey, "refresh", entry.id], + mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId), + onSuccess: (report, attempted) => { + queryClient.setQueryData(queryKey, (reports) => + reports ? replaceReport(reports, attempted.id, report) : reports, ); }, + onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]), }); const { mutate } = mutation; - const refresh = useCallback(() => mutate(), [mutate]); + const refresh = useCallback(() => mutate(entry), [mutate, entry]); return { refresh, refreshState: resolveUsageRefresh(mutation) }; } diff --git a/packages/app/src/usage/reset-line.tsx b/packages/app/src/usage/reset-line.tsx deleted file mode 100644 index 8016df29265a..000000000000 --- a/packages/app/src/usage/reset-line.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { Text, View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; - -/** - * The reset data of a window or balance: the countdown first, then the exact time. When the line - * is too narrow the exact time gives way (truncates) and the countdown stays whole. - */ -export function UsageResetLine({ - countdown, - exactTime, - atRisk = false, - testID, -}: { - countdown: string | null; - exactTime: string | null; - /** The countdown is a runs-out warning rather than a reset. */ - atRisk?: boolean; - testID?: string; -}) { - if (!countdown) return null; - return ( - - {countdown} - {exactTime ? ( - - {`\u00a0·\u00a0${exactTime}`} - - ) : null} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - line: { flexDirection: "row", alignItems: "center" }, - text: { - flexShrink: 0, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.normal, - }, - atRisk: { - flexShrink: 0, - color: theme.colors.statusDanger, - fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.normal, - }, - exactTime: { flexShrink: 1 }, -})); diff --git a/packages/app/src/usage/sidebar-item.tsx b/packages/app/src/usage/sidebar-item.tsx index 32136b0639aa..4832513099c3 100644 --- a/packages/app/src/usage/sidebar-item.tsx +++ b/packages/app/src/usage/sidebar-item.tsx @@ -29,6 +29,7 @@ import { resolvePinnedUsage, type PinnedUsageLayout, type PinnedUsageSource, + type PinnedUsageWindow, } from "./pinned"; import { UsageModal } from "./usage-modal"; @@ -123,8 +124,8 @@ function layoutWidth(event: LayoutChangeEvent): number { /** * One line: each account's icon, then per window a meter and "31% 5h". Off-screen copies measure - * the line with labels and with percents alone; the richest layout that fits is shown, and what - * it leaves out takes no space at all. + * the line with full labels, bare period shorthands, and percents alone; the richest layout that + * fits is shown, and what it leaves out takes no space at all. */ function PinnedUsageTrigger({ label, @@ -139,6 +140,7 @@ function PinnedUsageTrigger({ }) { const [available, setAvailable] = useState(null); const [labelsWidth, setLabelsWidth] = useState(null); + const [compactWidth, setCompactWidth] = useState(null); const [percentsWidth, setPercentsWidth] = useState(null); const handleAvailableLayout = useCallback((event: LayoutChangeEvent) => { setAvailable(layoutWidth(event)); @@ -146,12 +148,16 @@ function PinnedUsageTrigger({ const handleLabelsLayout = useCallback((event: LayoutChangeEvent) => { setLabelsWidth(layoutWidth(event)); }, []); + const handleCompactLayout = useCallback((event: LayoutChangeEvent) => { + setCompactWidth(layoutWidth(event)); + }, []); const handlePercentsLayout = useCallback((event: LayoutChangeEvent) => { setPercentsWidth(layoutWidth(event)); }, []); const layout = choosePinnedUsageLayout({ available, labelsWidth, + compactWidth, percentsWidth, windowCount: sources.reduce((count, source) => count + source.windows.length, 0), }); @@ -177,6 +183,9 @@ function PinnedUsageTrigger({ + + + @@ -185,6 +194,12 @@ function PinnedUsageTrigger({ ); } +function windowSuffix(window: PinnedUsageWindow, layout: PinnedUsageLayout): string { + if (layout === "percents") return ""; + if (layout === "compact") return window.compactLabel; + return window.shortLabel; +} + /** * The line's items as direct children of one row, so every meter shares the leftover width * equally. @@ -215,6 +230,7 @@ function PinnedUsageLine({ {source.windows.map((window, windowIndex) => { const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap; + const suffix = windowSuffix(window, layout); return ( {layout === "meters" ? ( @@ -228,9 +244,7 @@ function PinnedUsageLine({ testID={measuring ? undefined : "sidebar-usage-pinned-window"} > {window.percentText} - {layout === "percents" || window.shortLabel === "" ? null : ( - {` ${window.shortLabel}`} - )} + {suffix === "" ? null : {` ${suffix}`}} ); diff --git a/packages/app/src/usage/types.ts b/packages/app/src/usage/types.ts index 9e36f58c8471..9fc390a094b7 100644 --- a/packages/app/src/usage/types.ts +++ b/packages/app/src/usage/types.ts @@ -1,6 +1,12 @@ -import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages"; +import type { + ProviderUsageTone, + UsageReportEntry as WireUsageReportEntry, +} from "@getpaseo/protocol/messages"; -export type { UsageReportEntry }; +export interface UsageReportEntry extends WireUsageReportEntry { + /** A refresh failed while this reading was cached. */ + forecastStale?: true; +} export type UsageReport = UsageReportEntry["report"]; export type UsageTone = ProviderUsageTone; export type AvailableUsageReport = Extract; @@ -14,4 +20,4 @@ export type UsageView = | { kind: "unavailable"; message: string } | { kind: "loading" } | { kind: "error"; message: string } - | { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean }; + | { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean }; diff --git a/packages/app/src/usage/usage-modal.tsx b/packages/app/src/usage/usage-modal.tsx index d93bea8b1b08..15970870b790 100644 --- a/packages/app/src/usage/usage-modal.tsx +++ b/packages/app/src/usage/usage-modal.tsx @@ -4,7 +4,6 @@ import { View } from "react-native"; import { AdaptiveModalSheet, SheetHeaderSubtitle } from "@/components/adaptive-modal-sheet"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; import { useHostUsageWithControls } from "./controls"; -import { useUsageDisplay } from "./display"; import { getHostPickerLabel } from "@/components/hosts/host-picker"; import { hasHostChoice, useUsageHostSelection } from "./hosts"; import type { UsageHost } from "./model"; @@ -50,8 +49,7 @@ function HostUsageModal({ () => ({ hosts, serverId, onSelect: onSelectHost }), [hosts, onSelectHost, serverId], ); - const { view, refresh, controls } = useHostUsageWithControls(hostSelection); - const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); + const { view, display, refresh, controls, openOptions } = useHostUsageWithControls(hostSelection); const hostLabel = hasHostChoice(hostSelection) ? getHostPickerLabel(hostSelection.hosts, hostSelection.serverId) : undefined; @@ -61,7 +59,13 @@ function HostUsageModal({ host's cards. The frame is not keyed: remounting it would dismiss a compact sheet, and Usage with it. */} - + ); diff --git a/packages/app/src/usage/usage-section.tsx b/packages/app/src/usage/usage-section.tsx index 1eae545f3941..9e6d788f2c3b 100644 --- a/packages/app/src/usage/usage-section.tsx +++ b/packages/app/src/usage/usage-section.tsx @@ -1,5 +1,5 @@ import { useTranslation } from "react-i18next"; -import { useMemo } from "react"; +import { useCallback, useMemo, useState } from "react"; import { Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { Alert } from "@/components/ui/alert"; @@ -27,14 +27,31 @@ export function UsageSection({ onRefresh: () => void; testID?: string; }) { + const [optionsOpen, setOptionsOpen] = useState(false); + const openOptions = useCallback(() => setOptionsOpen(true), []); const trailing = useMemo( - () => , - [onRefresh, view, serverId], + () => ( + + ), + [display, onRefresh, optionsOpen, serverId, view], ); return ( - + ); } @@ -45,14 +62,23 @@ export function UsageBody({ view, display, onRefresh, + onOpenSources, }: { serverId: string; view: UsageView; display: UsageDisplay; onRefresh: () => void; + onOpenSources?: () => void; }) { const { t } = useTranslation(); const setting = useUsageSetting(serverId); + const visibleReports = useMemo( + () => + view.kind === "ready" + ? display.arrange(view.reports).filter((entry) => display.isCardOn(entry)) + : [], + [display, view], + ); if (view.kind === "off") return ( @@ -84,11 +110,32 @@ export function UsageBody({ ); } + let content: React.ReactNode; if (view.reports.length === 0) { - return ; + content = ; + } else if (visibleReports.length === 0) { + content = ( + + {t("providerUsage.allSourcesHidden")} + {onOpenSources ? ( + + ) : null} + + ); + } else { + content = ; } - return ; + return ( + + {view.refreshFailed ? ( + + ) : null} + {content} + + ); } export function UsageMessage({ text }: { text: string }) { @@ -100,8 +147,10 @@ export function UsageMessage({ text }: { text: string }) { } const styles = StyleSheet.create((theme) => ({ + reports: { gap: theme.spacing[3] }, emptyCard: { padding: theme.spacing[4], + gap: theme.spacing[3], alignItems: "center", }, emptyText: { diff --git a/packages/app/src/usage/window-bar.tsx b/packages/app/src/usage/window-bar.tsx index b837872e017a..5376106175cd 100644 --- a/packages/app/src/usage/window-bar.tsx +++ b/packages/app/src/usage/window-bar.tsx @@ -1,3 +1,4 @@ +import type { TFunction } from "i18next"; import { Pin } from "lucide-react-native"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; @@ -13,7 +14,8 @@ import { } from "./format"; import { UsageMeter } from "./meter"; import { displayPercent, usageWindowRowLabel } from "./model"; -import { UsageResetLine } from "./reset-line"; +import { usagePace } from "./pace"; +import { UsageDatapointLine } from "./datapoint-line"; import type { UsageDisplayAs } from "./preferences"; import { windowTone } from "./tone"; import type { UsageTone, UsageWindow } from "./types"; @@ -28,8 +30,10 @@ export function UsageWindowBar({ pinLabel, pinTestID, retained = false, + forecastAt, }: { retained?: boolean; + forecastAt: string | null; window: UsageWindow; displayAs: UsageDisplayAs; /** Whether the row pins the window to the sidebar. When false the row is a plain bar. */ @@ -42,31 +46,22 @@ export function UsageWindowBar({ }) { const { t, i18n } = useTranslation(); const shownPct = displayPercent(window, displayAs); - const tone = windowTone(window); - const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null }); - const isAtRisk = - window.runsOutAt != null && - window.shortfallPct != null && - (!retained || Date.parse(window.runsOutAt) > now); - const countdown = isAtRisk - ? formatRunsOutLabel(window.runsOutAt, now, t) - : formatResetLabel(window.resetsAt, retained, now, t); - // The exact time belongs to the reset; beside a runs-out warning it would read as the moment - // the quota runs out. - const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t); + const pace = usagePace(window, forecastAt, now); + const forecast = formatPace(pace, now, t); + const countdown = formatResetLabel(window.resetsAt, retained, now, t); + const exactTime = formatResetTime(window.resetsAt, now, t); const value = shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—"; const accessibilityState = useMemo(() => ({ checked: pinned }), [pinned]); + const datapoints = [countdown, exactTime, forecast?.label ?? null]; const content = { label: formatProviderUsageLabel(window.id, window.label, t), value, - countdown, - exactTime, - isAtRisk, + datapoints, percent: shownPct ?? 0, - tone, + tone: forecast?.tone ?? windowTone(window), pinned, }; @@ -86,7 +81,7 @@ export function UsageWindowBar({ accessibilityLabel={usageWindowRowLabel({ pinLabel, value, - trailing: [countdown, exactTime].filter(Boolean).join(" · "), + trailing: datapoints.filter(Boolean).join(" · "), })} accessibilityState={accessibilityState} aria-checked={pinned} @@ -101,9 +96,7 @@ export function UsageWindowBar({ function WindowRowContent({ label, value, - countdown, - exactTime, - isAtRisk, + datapoints, percent, tone, pinnable, @@ -111,9 +104,7 @@ function WindowRowContent({ }: { label: string; value: string; - countdown: string | null; - exactTime: string | null; - isAtRisk: boolean; + datapoints: readonly (string | null)[]; percent: number; tone: UsageTone; pinnable: boolean; @@ -131,11 +122,40 @@ function WindowRowContent({ {pinnable ? : null} - + ); } +interface PaceDisplay { + label: string | null; + tone: UsageTone; +} + +function formatPace( + pace: ReturnType, + now: number, + t: TFunction, +): PaceDisplay | null { + switch (pace.kind) { + case "reached": + return { label: t("providerUsage.timing.limitReached"), tone: "danger" }; + case "runsOut": { + const label = + Date.parse(pace.at) <= now + ? t("providerUsage.timing.mayHaveRunOut") + : formatRunsOutLabel(pace.at, now, t); + return label ? { label, tone: "danger" } : null; + } + case "tight": + return { label: null, tone: "warning" }; + case "onTrack": + return { label: null, tone: "default" }; + case "unknown": + return null; + } +} + const ThemedPin = withUnistyles(Pin); function UsagePinGlyph({ pinned }: { pinned: boolean }) { diff --git a/packages/app/src/utils/agent-directory-reconciliation.test.ts b/packages/app/src/utils/agent-directory-reconciliation.test.ts index 35feb27cd277..0ee18b22c3e9 100644 --- a/packages/app/src/utils/agent-directory-reconciliation.test.ts +++ b/packages/app/src/utils/agent-directory-reconciliation.test.ts @@ -199,6 +199,44 @@ describe("agent directory reconciliation", () => { }); }); + it("accepts session metrics from a stale buffered upsert without regressing metadata", () => { + const result = reconcileAgentDirectory({ + snapshot: [ + { + ...entry("agent", "idle"), + agent: { + ...snapshot("agent", "idle"), + title: "newer page", + updatedAt: "2026-07-12T12:00:00.000Z", + sessionMetrics: [{ label: "Cost", value: "$0.10" }], + }, + }, + ], + deltas: [ + { + kind: "upsert", + agent: { + ...snapshot("agent", "running"), + title: "stale live", + updatedAt: "2026-07-12T11:00:00.000Z", + sessionMetrics: [{ label: "Cost", value: "$0.42" }], + }, + project: entry("agent", "idle").project, + }, + ], + }); + + expect({ + title: result[0]?.agent.title, + status: result[0]?.agent.status, + sessionMetrics: result[0]?.agent.sessionMetrics, + }).toEqual({ + title: "newer page", + status: "idle", + sessionMetrics: [{ label: "Cost", value: "$0.42" }], + }); + }); + it("preserves usage when a stale buffered upsert omits it", () => { const result = reconcileAgentDirectory({ snapshot: [ diff --git a/packages/app/src/utils/agent-directory-update-policy.ts b/packages/app/src/utils/agent-directory-update-policy.ts index 4d14f101b6b5..60735a024b47 100644 --- a/packages/app/src/utils/agent-directory-update-policy.ts +++ b/packages/app/src/utils/agent-directory-update-policy.ts @@ -1,11 +1,16 @@ import equal from "fast-deep-equal"; -import type { AgentUsage } from "@getpaseo/protocol/agent-types"; +import type { AgentMetric, AgentUsage } from "@getpaseo/protocol/agent-types"; interface AgentUpdateValue { updatedAt: Date | string; lastUsage?: AgentUsage; + sessionMetrics?: AgentMetric[]; } +// The daemon reports these without bumping `updatedAt`, so a stale upsert can still carry the +// newest value. +const FIELDS_UPDATED_IN_PLACE = ["lastUsage", "sessionMetrics"] as const; + function timestamp(value: Date | string): number { return value instanceof Date ? value.getTime() : Date.parse(value); } @@ -15,7 +20,9 @@ export function acceptAgentDirectoryUpdate( incoming: T, ): T { if (!current || timestamp(incoming.updatedAt) >= timestamp(current.updatedAt)) return incoming; - if (incoming.lastUsage === undefined) return current; - if (equal(incoming.lastUsage, current.lastUsage)) return current; - return { ...current, lastUsage: incoming.lastUsage }; + const newer = FIELDS_UPDATED_IN_PLACE.filter( + (field) => incoming[field] !== undefined && !equal(incoming[field], current[field]), + ); + if (newer.length === 0) return current; + return { ...current, ...Object.fromEntries(newer.map((field) => [field, incoming[field]])) }; } diff --git a/packages/app/src/utils/agent-snapshots.test.ts b/packages/app/src/utils/agent-snapshots.test.ts index 49c4bcb983c0..17f4fd89a371 100644 --- a/packages/app/src/utils/agent-snapshots.test.ts +++ b/packages/app/src/utils/agent-snapshots.test.ts @@ -35,6 +35,7 @@ function createSnapshot( labels: (input.labels ?? {}) as AgentSnapshotPayload["labels"], ...(input.controls ? { controls: input.controls } : {}), ...(input.options ? { options: input.options } : {}), + ...(input.sessionMetrics ? { sessionMetrics: input.sessionMetrics } : {}), }; } @@ -78,6 +79,15 @@ describe("normalizeAgentSnapshot", () => { }); }); + it("round-trips session metrics through the canonical snapshot boundary", () => { + const sessionMetrics = [{ label: "Cost", value: "$0.42", tone: "warning" as const }]; + + const agent = normalizeAgentSnapshot(createSnapshot({ sessionMetrics }), "server-1"); + + expect(agent.sessionMetrics).toEqual(sessionMetrics); + expect(projectAgentSnapshot(agent).sessionMetrics).toEqual(sessionMetrics); + }); + it("normalizes identified and legacy active turns at the snapshot boundary", () => { const startedAt = "2026-07-31T12:00:00.000Z"; expect( diff --git a/packages/app/src/utils/agent-snapshots.ts b/packages/app/src/utils/agent-snapshots.ts index c3eea36d79f2..8283581e2834 100644 --- a/packages/app/src/utils/agent-snapshots.ts +++ b/packages/app/src/utils/agent-snapshots.ts @@ -81,6 +81,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload { ...(agent.runtimeInfo ? { runtimeInfo: agent.runtimeInfo } : {}), ...(agent.usageScopeKey ? { usageScopeKey: agent.usageScopeKey } : {}), ...(agent.lastUsage ? { lastUsage: agent.lastUsage } : {}), + ...(agent.sessionMetrics ? { sessionMetrics: agent.sessionMetrics } : {}), ...(agent.lastError ? { lastError: agent.lastError } : {}), title: agent.title, labels: agent.labels, @@ -129,6 +130,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId: runtimeInfo: snapshot.runtimeInfo, usageScopeKey: snapshot.usageScopeKey, lastUsage: snapshot.lastUsage, + sessionMetrics: snapshot.sessionMetrics, lastError: snapshot.lastError ?? null, title: snapshot.title ?? null, cwd: snapshot.cwd, diff --git a/packages/app/src/utils/host-routes.test.ts b/packages/app/src/utils/host-routes.test.ts index 1687563603cd..2defc505f62b 100644 --- a/packages/app/src/utils/host-routes.test.ts +++ b/packages/app/src/utils/host-routes.test.ts @@ -17,6 +17,7 @@ import { isSettingsSectionSlug, normalizeHostSectionSlug, normalizeProjectSettingsRouteId, + buildProviderSettingsRoute, parseHostAgentRouteFromPathname, parseHostWorkspaceOpenIntentFromPathname, parseHostWorkspaceRouteFromPathname, @@ -199,6 +200,14 @@ describe("projects settings routes", () => { }); }); +describe("provider settings routes", () => { + it("buildProviderSettingsRoute addresses one provider on a host", () => { + expect(buildProviderSettingsRoute("host a", "acp/gemini")).toBe( + "/settings/hosts/host%20a/providers/acp%2Fgemini", + ); + }); +}); + describe("global routes", () => { it("buildSessionsRoute returns the all-host Sessions route", () => { expect(buildSessionsRoute()).toBe("/sessions"); diff --git a/packages/app/src/utils/host-routes.ts b/packages/app/src/utils/host-routes.ts index 7df5f62a6d67..1982631d7801 100644 --- a/packages/app/src/utils/host-routes.ts +++ b/packages/app/src/utils/host-routes.ts @@ -588,6 +588,13 @@ export function buildProjectSettingsRoute(serverId: string, projectId: string) { return `/settings/hosts/${encodeSegment(serverId)}/projects/${encodeSegment(projectId)}` as const; } +export function buildProviderSettingsRoute(serverId: string, providerId: string) { + if (!serverId.trim() || !providerId.trim()) { + throw new Error("buildProviderSettingsRoute requires a serverId and providerId"); + } + return `/settings/hosts/${encodeSegment(serverId)}/providers/${encodeSegment(providerId)}` as const; +} + export function normalizeProjectSettingsRouteId(value: string | string[] | undefined): string { const id = Array.isArray(value) ? value[0] : value; return typeof id === "string" ? id : ""; diff --git a/packages/app/src/utils/time.ts b/packages/app/src/utils/time.ts index 1c063d1a2784..61ce230dfe99 100644 --- a/packages/app/src/utils/time.ts +++ b/packages/app/src/utils/time.ts @@ -97,14 +97,10 @@ export function formatCompactTimeAgoAsProse(label: string): string { return label; } -/** - * How many local midnights lie between two instants: 0 for the same day, 1 for yesterday. - * Counted on the calendar rather than in elapsed time, so six days and 23 hours ago on - * today's weekday is 7, and rounded so a DST day of 23 or 25 hours still counts as one. - */ -function localCalendarDaysBetween(earlier: Date, later: Date): number { - const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()); - return Math.round((startOfDay(later).getTime() - startOfDay(earlier).getTime()) / DAY_MS); +/** Count local calendar dates using equally spaced UTC values for their year, month and day. */ +export function localCalendarDaysBetween(earlier: Date, later: Date): number { + const calendarDay = (date: Date) => Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); + return (calendarDay(later) - calendarDay(earlier)) / DAY_MS; } // Cached Intl formatter. Explicitly carrying `hourCycle` from the resolved diff --git a/packages/app/src/utils/tool-call-parsers.test.ts b/packages/app/src/utils/tool-call-parsers.test.ts index 16c2f57f5b03..9fb7f66c8e76 100644 --- a/packages/app/src/utils/tool-call-parsers.test.ts +++ b/packages/app/src/utils/tool-call-parsers.test.ts @@ -14,6 +14,47 @@ describe("tool-call-parsers", () => { expect(diff.some((entry) => entry.type === "add")).toBe(true); }); + it("keeps an edit visible in a compact preview of a 6,000-line file", () => { + const context = "- a\n".repeat(3_000); + const before = context + context; + const after = `${context}- b\n${context.slice(4)}`; + + const preview = buildLineDiff(before, after); + + expect(preview).toHaveLength(10); + expect(preview.slice(4, 6).map((line) => line.type)).toEqual(["remove", "add"]); + expect(preview.filter((line) => line.type === "remove").map((line) => line.content)).toEqual([ + "-- a", + ]); + expect(preview.filter((line) => line.type === "add").map((line) => line.content)).toEqual([ + "+- b", + ]); + }); + + it("retains edits on both sides of a long unchanged range", () => { + const context = "- a\n".repeat(5_998); + const preview = buildLineDiff(`- b\n${context}- d\n`, `- c\n${context}- e\n`); + + expect(preview.filter((line) => line.type === "remove").map((line) => line.content)).toEqual([ + "-- b", + "-- d", + ]); + expect(preview.filter((line) => line.type === "add").map((line) => line.content)).toEqual([ + "+- c", + "+- e", + ]); + expect(preview).toHaveLength(12); + }); + + it("shows a bounded replacement preview when an edit rewrites the file", () => { + const preview = buildLineDiff("- a\n".repeat(6_000), "- b\n".repeat(6_000)); + + expect(preview[0]).toEqual({ type: "remove", content: "-- a" }); + expect(preview).toContainEqual({ type: "add", content: "+- b" }); + expect(preview.at(-1)).toEqual({ type: "header", content: "…" }); + expect(preview).toHaveLength(65); + }); + it("parses unified diff", () => { const parsed = parseUnifiedDiff("@@\n-old\n+new\n"); diff --git a/packages/app/src/utils/tool-call-parsers.ts b/packages/app/src/utils/tool-call-parsers.ts index 7980d3ee5fed..c57829a16b4d 100644 --- a/packages/app/src/utils/tool-call-parsers.ts +++ b/packages/app/src/utils/tool-call-parsers.ts @@ -1,3 +1,4 @@ +import { diffArrays } from "diff"; import { z } from "zod"; import type { HighlightToken } from "@getpaseo/highlight"; @@ -52,156 +53,104 @@ function splitIntoWords(text: string): string[] { return result; } -function computeWordLevelDiff( - oldLine: string, - newLine: string, -): { oldSegments: DiffSegment[]; newSegments: DiffSegment[] } { - const oldWords = splitIntoWords(oldLine); - const newWords = splitIntoWords(newLine); - - const m = oldWords.length; - const n = newWords.length; - - // LCS to find common words - const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); - - for (let i = m - 1; i >= 0; i -= 1) { - for (let j = n - 1; j >= 0; j -= 1) { - if (oldWords[i] === newWords[j]) { - dp[i][j] = dp[i + 1][j + 1] + 1; - } else { - dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]); - } - } - } - - // Mark which words are in LCS (unchanged) - const oldInLCS = new Set(); - const newInLCS = new Set(); - - let i = 0; - let j = 0; - while (i < m && j < n) { - if (oldWords[i] === newWords[j]) { - oldInLCS.add(i); - newInLCS.add(j); - i += 1; - j += 1; - } else if (dp[i + 1][j] >= dp[i][j + 1]) { - i += 1; - } else { - j += 1; - } +const MAX_EDIT_DISTANCE = 256; +const FULL_CONTEXT_LINE_LIMIT = 128; +const CONTEXT_LINES = 3; +const REPLACEMENT_PREVIEW_LINES = 32; +const OMITTED_LINES: DiffLine = { type: "header", content: "…" }; + +function addWordHighlights(diff: DiffLine[]): void { + for (let index = 0; index + 1 < diff.length; index++) { + const before = diff[index]; + const after = diff[index + 1]; + if (before.type !== "remove" || after.type !== "add") continue; + if (before.content.length + after.content.length > 1024) continue; + + const words = diffArrays( + splitIntoWords(before.content.slice(1)), + splitIntoWords(after.content.slice(1)), + { maxEditLength: 64 }, + ); + if (!words) continue; + + before.segments = words + .filter((part) => !part.added) + .map((part) => ({ text: part.value.join(""), changed: part.removed })); + after.segments = words + .filter((part) => !part.removed) + .map((part) => ({ text: part.value.join(""), changed: part.added })); } +} - // Build segments: consecutive unchanged or changed words merged - const buildSegments = (words: string[], inLCS: Set): DiffSegment[] => { - if (words.length === 0) return []; - - const segments: DiffSegment[] = []; - let currentText = ""; - let currentChanged: boolean | null = null; - - for (let idx = 0; idx < words.length; idx++) { - const word = words[idx]; - const changed = !inLCS.has(idx); - - if (currentChanged === null) { - currentText = word; - currentChanged = changed; - } else if (changed === currentChanged) { - currentText += word; - } else { - segments.push({ text: currentText, changed: currentChanged }); - currentText = word; - currentChanged = changed; - } - } - - if (currentText) { - segments.push({ text: currentText, changed: currentChanged ?? false }); - } - - return segments; - }; +function contextPreview( + lines: string[], + hasEditBefore: boolean, + hasEditAfter: boolean, +): DiffLine[] { + const leadingCount = hasEditBefore ? CONTEXT_LINES : 0; + const trailingCount = hasEditAfter ? CONTEXT_LINES : 0; + if (lines.length <= leadingCount + trailingCount) return contextLines(lines); + + return [ + ...contextLines(lines.slice(0, leadingCount)), + OMITTED_LINES, + ...contextLines(lines.slice(lines.length - trailingCount)), + ]; +} - const oldSegments = buildSegments(oldWords, oldInLCS); - const newSegments = buildSegments(newWords, newInLCS); +function contextLines(lines: string[]): DiffLine[] { + return lines.map((line) => ({ type: "context", content: ` ${line}` })); +} +function splitLineChange(before: string[], after: string[]) { + let start = 0; + let beforeEnd = before.length; + let afterEnd = after.length; + while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++; + while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) { + beforeEnd--; + afterEnd--; + } return { - oldSegments, - newSegments, + leading: before.slice(0, start), + before: before.slice(start, beforeEnd), + after: after.slice(start, afterEnd), + trailing: before.slice(beforeEnd), }; } +function buildReplacementPreview(before: string[], after: string[]): DiffLine[] { + return [ + ...before + .slice(0, REPLACEMENT_PREVIEW_LINES) + .map((line): DiffLine => ({ type: "remove", content: `-${line}` })), + ...after + .slice(0, REPLACEMENT_PREVIEW_LINES) + .map((line): DiffLine => ({ type: "add", content: `+${line}` })), + OMITTED_LINES, + ]; +} + export function buildLineDiff(originalText: string, updatedText: string): DiffLine[] { const originalLines = splitIntoLines(originalText); const updatedLines = splitIntoLines(updatedText); - - const hasAnyContent = originalLines.length > 0 || updatedLines.length > 0; - if (!hasAnyContent) { - return []; - } - - const m = originalLines.length; - const n = updatedLines.length; - const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); - - for (let i = m - 1; i >= 0; i -= 1) { - for (let j = n - 1; j >= 0; j -= 1) { - if (originalLines[i] === updatedLines[j]) { - dp[i][j] = dp[i + 1][j + 1] + 1; - } else { - dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]); - } - } - } - - const diff: DiffLine[] = []; - - let i = 0; - let j = 0; - while (i < m && j < n) { - if (originalLines[i] === updatedLines[j]) { - diff.push({ type: "context", content: ` ${originalLines[i]}` }); - i += 1; - j += 1; - } else if (dp[i + 1][j] >= dp[i][j + 1]) { - diff.push({ type: "remove", content: `-${originalLines[i]}` }); - i += 1; - } else { - diff.push({ type: "add", content: `+${updatedLines[j]}` }); - j += 1; - } - } - - while (i < m) { - diff.push({ type: "remove", content: `-${originalLines[i]}` }); - i += 1; - } - - while (j < n) { - diff.push({ type: "add", content: `+${updatedLines[j]}` }); - j += 1; - } - - // Post-process to add word-level segments for adjacent remove/add pairs - for (let idx = 0; idx < diff.length - 1; idx++) { - const curr = diff[idx]; - const next = diff[idx + 1]; - - if (curr.type === "remove" && next.type === "add") { - // Strip the leading -/+ from content for comparison - const oldLineText = curr.content.slice(1); - const newLineText = next.content.slice(1); - - const { oldSegments, newSegments } = computeWordLevelDiff(oldLineText, newLineText); - curr.segments = oldSegments; - next.segments = newSegments; - } - } - - return diff; + // Anchor equal file edges so an edit to a repeated line stays at its original location. + const { leading, before, after, trailing } = splitLineChange(originalLines, updatedLines); + const compact = Math.max(originalLines.length, updatedLines.length) > FULL_CONTEXT_LINE_LIMIT; + if (compact && before.length === 0 && after.length === 0) return []; + + const leadingRows = compact ? contextPreview(leading, false, true) : contextLines(leading); + const changes = diffArrays(before, after, { maxEditLength: MAX_EDIT_DISTANCE }); + if (!changes) return [...leadingRows, ...buildReplacementPreview(before, after)]; + + const changedRows = changes.flatMap((part): DiffLine[] => { + if (part.removed) return part.value.map((line) => ({ type: "remove", content: `-${line}` })); + if (part.added) return part.value.map((line) => ({ type: "add", content: `+${line}` })); + return compact ? contextPreview(part.value, true, true) : contextLines(part.value); + }); + addWordHighlights(changedRows); + const trailingRows = compact ? contextPreview(trailing, true, false) : contextLines(trailing); + return [...leadingRows, ...changedRows, ...trailingRows]; } export function parseUnifiedDiff(diffText?: string): DiffLine[] { diff --git a/packages/app/src/workspace/use-workspace-archive.ts b/packages/app/src/workspace/use-workspace-archive.ts index 82255f6e910d..5a01b1015b2c 100644 --- a/packages/app/src/workspace/use-workspace-archive.ts +++ b/packages/app/src/workspace/use-workspace-archive.ts @@ -14,6 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo"; import { archiveWorkspaceOptimistically, + runWorkspaceArchiveAttempt, type WorkspaceArchiveTarget, } from "@/workspace/workspace-archive"; @@ -56,7 +57,6 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch } = input; const { t } = useTranslation(); const toast = useToast(); - const confirmingRef = useRef(false); // The archive starts after the host answers and you confirm. By then you may have opened another // workspace, so the redirect reads the selection from the latest render. const onArchiveStartedRef = useRef(onArchiveStarted); @@ -119,26 +119,12 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch }, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]); const archive = useCallback(() => { - // A second press while the host answers or the warning is open would ask twice. - if (confirmingRef.current) { - return; - } - void (async () => { - if (workspaceKind === "worktree") { - confirmingRef.current = true; - let confirmed: boolean; - try { - confirmed = await confirmWorktreeArchive(); - } finally { - confirmingRef.current = false; - } - if (!confirmed) { - return; - } - } - await archiveWorkspaceRecord(); - })(); - }, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]); + void runWorkspaceArchiveAttempt({ + workspace: { serverId, workspaceId }, + confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined, + archive: archiveWorkspaceRecord, + }); + }, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]); return { archive, diff --git a/packages/app/src/workspace/workspace-archive.ts b/packages/app/src/workspace/workspace-archive.ts index 95694557060b..fcd44abd6fd3 100644 --- a/packages/app/src/workspace/workspace-archive.ts +++ b/packages/app/src/workspace/workspace-archive.ts @@ -17,6 +17,30 @@ export interface WorkspaceArchiveTarget { workspaceId: string; } +const pendingArchiveAttempts = new Set(); + +/** Checks and starts one archive at a time for a workspace. */ +export async function runWorkspaceArchiveAttempt(input: { + workspace: WorkspaceArchiveTarget; + confirm?: () => Promise; + archive: () => Promise; +}): Promise { + const { serverId, workspaceId } = input.workspace; + const key = JSON.stringify([serverId, workspaceId]); + if (pendingArchiveAttempts.has(key)) return; + + pendingArchiveAttempts.add(key); + try { + if (input.confirm && !(await input.confirm())) return; + if (!isWorkspaceListed(input.workspace)) return; + // Archive hides the row synchronously. Undo can restore it and start a new + // archive while the previous daemon request is still settling. + return input.archive(); + } finally { + pendingArchiveAttempts.delete(key); + } +} + interface WorkspaceArchiveClient { archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>; } diff --git a/packages/app/test-stubs/lucide-react-native.ts b/packages/app/test-stubs/lucide-react-native.ts index de4d8f22d295..d390e9f32bef 100644 --- a/packages/app/test-stubs/lucide-react-native.ts +++ b/packages/app/test-stubs/lucide-react-native.ts @@ -22,6 +22,7 @@ export const AudioLines = StubIcon; export const Blocks = StubIcon; export const Bot = StubIcon; export const Brain = StubIcon; +export const ChartNoAxesColumn = StubIcon; export const Check = StubIcon; export const CheckCircle = StubIcon; export const CheckCircle2 = StubIcon; @@ -146,3 +147,5 @@ export const Ellipsis = StubIcon; export const Maximize = StubIcon; export const Minimize = StubIcon; export const Rows2 = StubIcon; +export const Gauge = StubIcon; +export const GripVertical = StubIcon; diff --git a/packages/app/test-stubs/react-native-unistyles.ts b/packages/app/test-stubs/react-native-unistyles.ts index dfd3b58d932b..0b28532b823d 100644 --- a/packages/app/test-stubs/react-native-unistyles.ts +++ b/packages/app/test-stubs/react-native-unistyles.ts @@ -4,7 +4,10 @@ import { lightTheme } from "../src/styles/theme"; const pinnedTheme = { colorScheme: "light", + // The light theme's colours, so a `withUnistyles` mapping finds every key it reads, with the + // values below pinned so a test can name the colour it expects. colors: { + ...lightTheme.colors, syntax: lightHighlightColors, foreground: "#111111", foregroundMuted: "#666666", @@ -157,12 +160,16 @@ export const StyleSheet = { type UniPropsMapping = (theme: typeof testTheme, runtime: object) => Record; -/** Applies `uniProps` with the test theme, the way Unistyles maps theme values onto props. */ -export const withUnistyles = (Component: T): T => { +/** + * Applies the theme mapping and `uniProps` with the test theme, the way Unistyles maps theme values + * onto props: mapped props first, then `uniProps`, then the props the caller passed. + */ +export const withUnistyles = (Component: T, mapping?: UniPropsMapping): T => { function ThemedComponent({ uniProps, ...props }: { uniProps?: UniPropsMapping }) { // Explicit props win over mapped ones, as in Unistyles' `deepMergeObjects(mappings, uniProps, props)`. return createElement(Component as ElementType, { - ...(uniProps ? uniProps(testTheme, {}) : {}), + ...mapping?.(testTheme, {}), + ...uniProps?.(testTheme, {}), ...props, }); } diff --git a/packages/cli/package.json b/packages/cli/package.json index 85c32956ba72..825f650e4981 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.17.0-beta.1", + "version": "0.17.4", "description": "Paseo CLI - control your AI coding agents from the command line", "license": "Apache-2.0", "bin": { @@ -29,9 +29,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.17.0-beta.1", - "@getpaseo/protocol": "0.17.0-beta.1", - "@getpaseo/server": "0.17.0-beta.1", + "@getpaseo/client": "0.17.4", + "@getpaseo/protocol": "0.17.4", + "@getpaseo/server": "0.17.4", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/cli/src/cli-surface.test.ts b/packages/cli/src/cli-surface.test.ts index 83db3408e655..cd745bb554f9 100644 --- a/packages/cli/src/cli-surface.test.ts +++ b/packages/cli/src/cli-surface.test.ts @@ -12,9 +12,11 @@ describe("canonical CLI surface", () => { expect(send.opts().behavior).toBe("interrupt"); await send.parseAsync(["target", "message", "--behavior", "steer"], { from: "user" }); expect(send.opts().behavior).toBe("steer"); + await send.parseAsync(["target", "message", "--behavior", "queue"], { from: "user" }); + expect(send.opts().behavior).toBe("queue"); send.exitOverride().configureOutput({ writeErr: () => {} }); await expect( - send.parseAsync(["target", "message", "--behavior", "queue"], { from: "user" }), + send.parseAsync(["target", "message", "--behavior", "wait"], { from: "user" }), ).rejects.toThrow(); }); diff --git a/packages/cli/src/commands/agent/send.test.ts b/packages/cli/src/commands/agent/send.test.ts new file mode 100644 index 000000000000..58249fff0f66 --- /dev/null +++ b/packages/cli/src/commands/agent/send.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { buildNoWaitResult } from "./send.js"; + +const agentId = "11111111-1111-4111-8111-111111111111"; + +describe("buildNoWaitResult", () => { + it("reports the behavior the host applied to an agent's message", () => { + expect( + buildNoWaitResult(agentId, { + deliveryStatus: "queued", + activeTurnBehavior: "steer", + guidance: "The agent is idle, so your message starts a turn now.", + }), + ).toEqual({ + agentId, + status: "queued", + activeTurnBehavior: "steer", + message: "The agent is idle, so your message starts a turn now.", + }); + }); + + it("leaves the behavior out when the host does not report one", () => { + expect(buildNoWaitResult(agentId, {})).toEqual({ + agentId, + status: "sent", + message: "Message sent, not waiting for completion", + }); + }); +}); diff --git a/packages/cli/src/commands/agent/send.ts b/packages/cli/src/commands/agent/send.ts index 9a0bc465b728..aca35128645a 100644 --- a/packages/cli/src/commands/agent/send.ts +++ b/packages/cli/src/commands/agent/send.ts @@ -1,7 +1,8 @@ import { type Command, Option } from "commander"; -import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages"; +import type { AgentActiveTurnBehavior } from "@getpaseo/protocol/messages"; import { collectMultiple } from "../../utils/command-options.js"; import { connectToDaemon } from "../../utils/client.js"; +import type { AgentMessageReceipt } from "@getpaseo/client/internal/daemon-client"; import type { CommandOptions, SingleResult, @@ -15,6 +16,8 @@ import { extname, resolve } from "node:path"; export interface AgentSendResult { agentId: string; status: "queued" | "sent" | "completed" | "timeout" | "permission" | "error"; + /** What the host applied to an agent's message with a running turn. */ + activeTurnBehavior?: AgentActiveTurnBehavior; message: string; } @@ -29,7 +32,7 @@ export const agentSendSchema: OutputSchema = { }; export interface AgentSendOptions extends CommandOptions { - behavior?: ActiveTurnBehavior; + behavior?: AgentActiveTurnBehavior; wait?: boolean; image?: string[]; prompt?: string; @@ -47,8 +50,8 @@ export function addSendOptions(cmd: Command): Command { .addOption( new Option( "--behavior ", - "Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)", - ).choices(["interrupt", "steer"]), + "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) or steer", + ).choices(["queue", "steer", "interrupt"]), ) .option("--no-wait", "Return immediately without waiting for completion"); } @@ -170,6 +173,22 @@ function buildSendResult(agentIdArg: string, state: SendWaitState): AgentSendRes return { agentId, status: "completed", message: "Agent completed processing the message" }; } +export function buildNoWaitResult(agentId: string, receipt: AgentMessageReceipt): AgentSendResult { + return { + agentId, + status: receipt.deliveryStatus ?? "sent", + ...(receipt.activeTurnBehavior ? { activeTurnBehavior: receipt.activeTurnBehavior } : {}), + message: sendReceiptMessage(receipt), + }; +} + +function sendReceiptMessage(receipt: AgentMessageReceipt): string { + if (receipt.deliveryStatus !== "queued") return "Message sent, not waiting for completion"; + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once daemon + // floor >= v0.17.2. Older hosts return no guidance. + return receipt.guidance ?? "Message queued for delivery after the current turn ends"; +} + export async function runSendCommand( agentIdArg: string, prompt: string | undefined, @@ -204,7 +223,7 @@ export async function runSendCommand( const receipt = await client.sendAgentMessage(agentIdArg, promptInput, { images, sourceAgentId, - activeTurnBehavior: options.behavior ?? (sourceAgentId ? "steer" : "interrupt"), + activeTurnBehavior: options.behavior, }); // If --no-wait, return immediately @@ -213,14 +232,7 @@ export async function runSendCommand( return { type: "single", - data: { - agentId: agentIdArg, - status: receipt.deliveryStatus ?? "sent", - message: - receipt.deliveryStatus === "queued" - ? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested" - : "Message sent, not waiting for completion", - }, + data: buildNoWaitResult(agentIdArg, receipt), schema: agentSendSchema, }; } diff --git a/packages/cli/src/commands/worktree/create-input.test.ts b/packages/cli/src/commands/worktree/create-input.test.ts index 2091fcd6e4c1..17d4ed9d450d 100644 --- a/packages/cli/src/commands/worktree/create-input.test.ts +++ b/packages/cli/src/commands/worktree/create-input.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { runCreateCommandWithDeps } from "./create.js"; import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js"; const REPO = "/tmp/repo"; @@ -77,3 +78,52 @@ describe("buildCreateWorktreeRequest", () => { }); }); }); + +it("uses the explicit worktree creation RPC and returns the created worktree details", async () => { + const result = await runCreateCommandWithDeps( + { + daemonTarget: { kind: "endpoint", host: "example.test:12345" }, + mode: "branch-off", + newBranch: "topic", + base: "main", + cwd: REPO, + }, + { + connectToDaemon: async () => ({ + createPaseoWorktree: async (input) => { + expect(input).toEqual({ + cwd: REPO, + worktreeSlug: "topic", + action: "branch-off", + refName: "main", + }); + return { + workspace: { + id: "wks_topic", + projectId: "project", + projectDisplayName: "Repo", + projectRootPath: REPO, + workspaceDirectory: `${REPO}/topic`, + projectKind: "git", + workspaceKind: "worktree", + name: "topic", + status: "idle", + statusEnteredAt: null, + activityAt: null, + archivingAt: null, + scripts: [], + }, + error: null, + requestId: "worktree-create", + }; + }, + close: async () => {}, + }), + }, + ); + expect(result.data).toEqual({ + name: "topic", + branchName: "topic", + worktreePath: `${REPO}/topic`, + }); +}); diff --git a/packages/cli/src/commands/worktree/create.ts b/packages/cli/src/commands/worktree/create.ts index da7d873b5aea..9f165316f44a 100644 --- a/packages/cli/src/commands/worktree/create.ts +++ b/packages/cli/src/commands/worktree/create.ts @@ -26,11 +26,22 @@ function cmdError(code: string, message: string, details?: string): CommandError export async function runCreateCommand( options: WorktreeCreateOptions, _command: Command, +): Promise> { + return runCreateCommandWithDeps(options, { connectToDaemon }); +} + +export async function runCreateCommandWithDeps( + options: WorktreeCreateOptions, + deps: { + connectToDaemon( + options: Parameters[0], + ): Promise>, "createPaseoWorktree" | "close">>; + }, ): Promise> { const cwd = options.cwd ?? process.cwd(); const request = buildCreateWorktreeRequest(options, cwd); - const client = await connectToDaemon({ target: options.daemonTarget }); + const client = await deps.connectToDaemon({ target: options.daemonTarget }); try { const response = await client.createPaseoWorktree(request); diff --git a/packages/cli/tests/23-daemon-sigint-supervisor.test.ts b/packages/cli/tests/23-daemon-sigint-supervisor.test.ts index 070bdb4ae019..6ba951c67024 100644 --- a/packages/cli/tests/23-daemon-sigint-supervisor.test.ts +++ b/packages/cli/tests/23-daemon-sigint-supervisor.test.ts @@ -1,234 +1,241 @@ #!/usr/bin/env npx tsx -/** - * Regression: a single SIGINT sent to the supervised supervisor entrypoint must allow - * graceful daemon lifecycle shutdown to complete (no early forced exit path). - */ - -import assert from "node:assert"; -import { spawn, type ChildProcess } from "node:child_process"; -import { mkdtemp, rm } from "node:fs/promises"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { $ } from "zx"; +import { setTimeout as delay } from "node:timers/promises"; +import { WebSocket } from "ws"; +import { DaemonClient, type WebSocketLike } from "@getpaseo/client/internal/daemon-client"; +import { readDaemonInstance } from "@getpaseo/server/daemon-control"; +import { runLocalPaseo } from "./helpers/local-cli.ts"; import { getAvailablePort } from "./helpers/network.ts"; -$.verbose = false; - -const pollIntervalMs = 100; -const testEnv = { - PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: process.env.PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD ?? "0", - PASEO_DICTATION_ENABLED: process.env.PASEO_DICTATION_ENABLED ?? "0", - PASEO_VOICE_MODE_ENABLED: process.env.PASEO_VOICE_MODE_ENABLED ?? "0", +const paseoHome = await mkdtemp(join(tmpdir(), "paseo-sigint-supervisor-")); +const cwd = join(paseoHome, "workspace"); +const eventsPath = join(paseoHome, "acp-events.jsonl"); +const resumePrompt = "Continue the interrupted test."; +const watchDependencies = process.argv.includes("--dev-watch"); +const env = { + PASEO_HOME: paseoHome, + PASEO_NODE_INSPECT: "0", + PASEO_RELAY_ENABLED: "false", + PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0", + PASEO_DICTATION_ENABLED: "0", + PASEO_VOICE_MODE_ENABLED: "0", + PASEO_LOG_FORMAT: "json", }; -function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -function isProcessRunning(pid: number): boolean { - if (!Number.isInteger(pid) || pid <= 0) { - return false; - } - - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -function signalProcessGroup(pid: number, signal: NodeJS.Signals): boolean { - if (!Number.isInteger(pid) || pid <= 0) { - return false; - } - - if (process.platform === "win32") { - try { - process.kill(pid, signal); - return true; - } catch { - return false; - } - } - - try { - process.kill(-pid, signal); - return true; - } catch { - return false; - } -} - -interface DaemonStatus { - localDaemon: string | null; - pid: number | null; -} +type AcpEvent = + | { type: "session"; pid: number; sessionId: string } + | { type: "prompt"; sessionId: string; text: string } + | { type: "sigint"; pid: number }; -async function readDaemonStatus(paseoHome: string): Promise { - const result = - await $`PASEO_HOME=${paseoHome} PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD=${testEnv.PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD} PASEO_DICTATION_ENABLED=${testEnv.PASEO_DICTATION_ENABLED} PASEO_VOICE_MODE_ENABLED=${testEnv.PASEO_VOICE_MODE_ENABLED} npx paseo daemon status --home ${paseoHome} --json`.nothrow(); - if (result.exitCode !== 0) { - return { localDaemon: null, pid: null }; - } - - try { - const parsed = JSON.parse(result.stdout) as { localDaemon?: unknown; pid?: unknown }; - const localDaemon = typeof parsed.localDaemon === "string" ? parsed.localDaemon : null; - const pid = - typeof parsed.pid === "number" && Number.isInteger(parsed.pid) && parsed.pid > 0 - ? parsed.pid - : null; - return { localDaemon, pid }; - } catch { - return { localDaemon: null, pid: null }; - } +async function readEvents(): Promise { + const contents = await readFile(eventsPath, "utf8").catch((error) => { + if (error.code === "ENOENT") return ""; + throw error; + }); + return contents + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as AcpEvent); } -async function waitFor( - check: () => Promise | boolean, - timeoutMs: number, - message: string, -): Promise { +async function waitFor(read: () => Promise, message: string, timeoutMs = 15_000) { const deadline = Date.now() + timeoutMs; - - async function poll(): Promise { - if (await check()) return; - if (Date.now() >= deadline) throw new Error(message); - await sleep(pollIntervalMs); - return poll(); + while (Date.now() < deadline) { + const value = await read(); + if (value !== undefined) return value; + await delay(50); } - - return poll(); -} - -interface ExitResult { - code: number | null; - signal: NodeJS.Signals | null; -} - -function waitForProcessExit(processRef: ChildProcess, timeoutMs: number): Promise { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - reject(new Error("timed out waiting for process exit")); - }, timeoutMs); - - processRef.once("exit", (code, signal) => { - clearTimeout(timeout); - resolve({ code, signal }); - }); - }); + throw new Error(message); } -console.log("=== Daemon SIGINT (supervisor regression) ===\n"); - -const port = await getAvailablePort(); -const paseoHome = await mkdtemp(join(tmpdir(), "paseo-sigint-supervisor-")); -const cliRoot = join(import.meta.dirname, ".."); - -let supervisorProcess: ChildProcess | null = null; -let recentSupervisorLogs = ""; - -try { - console.log("Test 1: start supervisor-entrypoint in dev mode with isolated PASEO_HOME"); - - supervisorProcess = spawn( - process.execPath, - ["--import", "tsx", "../server/scripts/supervisor-entrypoint.ts", "--dev"], +async function startSupervisor() { + const host = `127.0.0.1:${await getAvailablePort()}`; + const child = spawn( + watchDependencies ? "npm" : process.execPath, + watchDependencies + ? ["run", "dev:server:watch"] + : ["--import", "tsx", "../server/scripts/supervisor-entrypoint.ts", "--dev"], { - cwd: cliRoot, + cwd: join(import.meta.dirname, watchDependencies ? "../../.." : ".."), env: { - ...process.env, - ...testEnv, - PASEO_HOME: paseoHome, - PASEO_LISTEN: `127.0.0.1:${port}`, - PASEO_RELAY_ENABLED: "false", + ...Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")), + ), + HOME: paseoHome, + USERPROFILE: paseoHome, + ...env, + PASEO_LISTEN: host, CI: "true", }, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", }, ); - - supervisorProcess.stdout?.on("data", (chunk) => { - recentSupervisorLogs = (recentSupervisorLogs + chunk.toString()).slice(-8000); + assert(child.pid, "supervisor should have a PID"); + const exited = once(child, "close"); + const client = new DaemonClient({ + url: `ws://${host}/ws`, + clientId: "sigint-supervisor-test", + appVersion: "0.17.0-beta.1", + localCredential: async () => + (await readFile(join(paseoHome, "local-credential"), "utf8")).trim(), + webSocketFactory: (url, options) => new WebSocket(url, options) as unknown as WebSocketLike, + reconnect: { enabled: false }, }); - supervisorProcess.stderr?.on("data", (chunk) => { - recentSupervisorLogs = (recentSupervisorLogs + chunk.toString()).slice(-8000); - }); - - await waitFor( - async () => { - const status = await readDaemonStatus(paseoHome); - return ( - status.localDaemon === "running" && status.pid !== null && isProcessRunning(status.pid) - ); - }, - 120000, - "daemon did not become running in time", - ); + let output = ""; + const startedWatchers = new Set(); + function captureOutput(chunk: Buffer) { + output = (output + chunk.toString()).slice(-32000); + for (const watcher of ["protocol", "client"]) { + if (output.includes(`[${watcher}]`)) startedWatchers.add(watcher); + } + } + child.stdout.on("data", captureOutput); + child.stderr.on("data", captureOutput); + try { + await Promise.race([ + waitFor( + async () => { + const instance = await readDaemonInstance(paseoHome); + if (instance?.listen === host) return instance; + }, + "supervisor did not publish its owned endpoint", + 120_000, + ), + exited.then((result) => { + throw new Error(`supervisor exited early: ${result}\n${output}`); + }), + ]); + await client.connect(); + if (watchDependencies) { + await waitFor(async () => { + if (startedWatchers.size === 2) return true; + }, "dev runner did not start both dependency watchers"); + } + } catch (error) { + await client.close(); + child.kill("SIGTERM"); + throw error; + } + return { child, client, exited, output: () => output }; +} - console.log("✓ supervised daemon started\n"); +function assertPidExited(pid: number) { + assert.throws(() => process.kill(pid, 0), { code: "ESRCH" }, `process ${pid} survived shutdown`); +} - console.log("Test 2: single SIGINT should shutdown gracefully without forced exit"); - const exitPromise = waitForProcessExit(supervisorProcess, 30000); - const signaledGroup = signalProcessGroup(supervisorProcess.pid ?? -1, "SIGINT"); - if (!signaledGroup) { - supervisorProcess.kill("SIGINT"); +async function interruptForeground(daemon: Awaited>) { + const pid = daemon.child.pid!; + await daemon.client.close(); + process.kill(process.platform === "win32" ? pid : -pid, "SIGINT"); + const exit = await Promise.race([daemon.exited, delay(30_000, "timed out", { ref: false })]); + // npm re-raises SIGINT when its shell exits on the same foreground signal. + if (!watchDependencies || !Array.isArray(exit) || exit[1] !== "SIGINT") { + assert.deepEqual(exit, [0, null], daemon.output()); } + await waitFor(async () => { + if (!(await readDaemonInstance(paseoHome))) return true; + }, "supervisor did not release its PID lock"); + const log = await readFile(join(paseoHome, "daemon.log"), "utf8"); + assert(!log.includes("Forcing shutdown - HTTP server didn't close in time"), log.slice(-4000)); + return log; +} - const exit = await exitPromise; - assert.strictEqual( - exit.signal, - null, - `supervisor should exit cleanly, got signal=${exit.signal}`, - ); - assert.strictEqual(exit.code, 0, `supervisor should exit with status 0, got code=${exit.code}`); - - await waitFor( - async () => { - const status = await readDaemonStatus(paseoHome); - return status.localDaemon === "stopped"; - }, - 15000, - "daemon status did not transition to stopped after SIGINT", +let daemon: Awaited> | undefined; +try { + await mkdir(cwd); + const provider = join(import.meta.dirname, "helpers", "supervisor-acp.cjs"); + await writeFile( + join(paseoHome, "config.json"), + JSON.stringify({ + version: 1, + agents: { + resumeOnStartup: true, + resumePrompt, + providers: { + antigravity: { command: [process.execPath, provider, eventsPath] }, + }, + }, + }), ); + daemon = await startSupervisor(); - assert( - !recentSupervisorLogs.includes("Forcing exit..."), - `worker entered forced-exit path during single SIGINT:\n${recentSupervisorLogs}`, - ); - assert( - !recentSupervisorLogs.includes("Forcing shutdown - HTTP server didn't close in time"), - `worker hit shutdown timeout during single SIGINT:\n${recentSupervisorLogs}`, - ); + if (process.platform === "win32") { + await interruptForeground(daemon); + } else { + const idle = await daemon.client.createAgent({ provider: "antigravity", cwd }); + const running = await daemon.client.createAgent({ provider: "antigravity", cwd }); + const crashing = await daemon.client.createAgent({ provider: "antigravity", cwd }); + const opened = (await readEvents()).filter((event) => event.type === "session"); + const sessions = [idle, running, crashing].map((agent) => { + const handle = agent.persistence?.sessionId; + const session = opened.find((event) => handle?.includes(event.sessionId)); + assert(session, `missing ACP process for agent ${agent.id}`); + return session; + }); - console.log("✓ single SIGINT completed graceful shutdown without forced exit\n"); + // Exit just this provider while the host is up to prove failure reporting remains active. + process.kill(sessions[2].pid, "SIGTERM"); + await waitFor(async () => { + const { agent } = (await daemon!.client.fetchAgent(crashing.id)) ?? {}; + if (agent?.status === "error" && agent.attentionReason === "error") return agent; + }, "unexpected provider exit did not raise error attention"); + const failure = await daemon.client.fetchAgentTimeline(crashing.id, { limit: 20 }); + assert.match(JSON.stringify(failure.entries), /\[System Error\].*ACP process exited/); + console.log("Unexpected ACP exit raised error attention and added a timeline entry."); + + await daemon.client.sendMessage(running.id, "Hold the turn open."); + await waitFor(async () => { + const { agent } = (await daemon!.client.fetchAgent(running.id)) ?? {}; + if (agent?.status === "running") return agent; + }, "ACP turn did not start"); + const workerPid = (await daemon.client.getDaemonStatus()).pid; + const log = await interruptForeground(daemon); + + assert.deepEqual( + (await readEvents()).filter((event) => event.type === "sigint"), + [], + "the foreground interrupt reached an ACP process", + ); + assert(!log.includes("worker_received_SIGINT"), "the foreground interrupt reached the worker"); + assert.match(log, /supervisor_received_SIGINT/); + assertPidExited(workerPid); + for (const session of sessions) assertPidExited(session.pid); + console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited."); + + daemon = await startSupervisor(); + const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent; + assert.equal(restoredIdle?.status, "idle"); + assert.equal(restoredIdle?.requiresAttention, false); + await waitFor(async () => { + const { agent } = (await daemon!.client.fetchAgent(running.id)) ?? {}; + if (agent?.status === "idle" && agent.attentionReason === "finished") return agent; + }, "interrupted agent did not finish the restart prompt"); + assert.deepEqual( + (await readEvents()).filter((event) => event.type === "prompt"), + [ + { type: "prompt", sessionId: sessions[1].sessionId, text: "Hold the turn open." }, + { type: "prompt", sessionId: sessions[1].sessionId, text: resumePrompt }, + ], + ); + console.log( + "Idle ACP reopened without error attention. The interrupted ACP turn resumed once.", + ); + await interruptForeground(daemon); + } +} catch (error) { + console.error(daemon?.output()); + throw error; } finally { - if (supervisorProcess?.pid && isProcessRunning(supervisorProcess.pid)) { - const signaledGroup = signalProcessGroup(supervisorProcess.pid, "SIGTERM"); - if (!signaledGroup) { - supervisorProcess.kill("SIGTERM"); - } - await waitFor( - () => !isProcessRunning(supervisorProcess!.pid ?? -1), - 5000, - "supervisor cleanup timed out", - ).catch(() => { - const killedGroup = signalProcessGroup(supervisorProcess!.pid ?? -1, "SIGKILL"); - if (!killedGroup) { - supervisorProcess?.kill("SIGKILL"); - } - }); + await daemon?.client.close(); + if (await readDaemonInstance(paseoHome)) { + await runLocalPaseo(["daemon", "stop", "--home", paseoHome, "--force"], env); } - - await $`PASEO_HOME=${paseoHome} PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD=${testEnv.PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD} PASEO_DICTATION_ENABLED=${testEnv.PASEO_DICTATION_ENABLED} PASEO_VOICE_MODE_ENABLED=${testEnv.PASEO_VOICE_MODE_ENABLED} npx paseo daemon stop --home ${paseoHome} --force`.nothrow(); await rm(paseoHome, { recursive: true, force: true }); } - -if (recentSupervisorLogs.trim().length === 0) { - console.log("(no supervisor logs captured)"); -} - -console.log("=== Supervisor SIGINT regression test passed ==="); diff --git a/packages/cli/tests/helpers/supervisor-acp.cjs b/packages/cli/tests/helpers/supervisor-acp.cjs new file mode 100644 index 000000000000..658cc6c1e398 --- /dev/null +++ b/packages/cli/tests/helpers/supervisor-acp.cjs @@ -0,0 +1,58 @@ +const { randomUUID } = require("node:crypto"); +const { appendFileSync } = require("node:fs"); +const { createInterface } = require("node:readline"); + +const eventsPath = process.argv[2]; +const record = (event) => appendFileSync(eventsPath, JSON.stringify(event) + "\n"); +const modes = { + currentModeId: "default", + availableModes: [{ id: "default", name: "Default" }], +}; + +process.on("SIGINT", () => { + record({ type: "sigint", pid: process.pid }); + process.exit(0); +}); + +createInterface({ input: process.stdin }).on("line", (line) => { + const message = JSON.parse(line); + if (message.id === undefined) return; + + let result; + switch (message.method) { + case "initialize": + result = { protocolVersion: 1, agentCapabilities: { loadSession: true } }; + break; + case "session/new": { + const sessionId = randomUUID(); + record({ type: "session", pid: process.pid, sessionId }); + result = { sessionId, modes }; + break; + } + case "session/load": + result = { modes }; + break; + case "session/close": + // Keep the provider alive long enough to detect a signal sent down the dev watcher tree. + setTimeout(() => reply(message.id, {}), 400); + return; + case "session/prompt": { + const { sessionId, prompt } = message.params; + const text = prompt + .filter((part) => part.type === "text") + .map((part) => part.text) + .join(""); + record({ type: "prompt", sessionId, text }); + if (text === "Hold the turn open.") return; + result = { stopReason: "end_turn" }; + break; + } + default: + result = {}; + } + reply(message.id, result); +}); + +function reply(id, result) { + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n"); +} diff --git a/packages/client/package.json b/packages/client/package.json index 8320c37cd950..6d64229b9593 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.17.0-beta.1", + "version": "0.17.4", "description": "Paseo client SDK package", "license": "Apache-2.0", "files": [ @@ -49,8 +49,8 @@ "measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts" }, "dependencies": { - "@getpaseo/protocol": "0.17.0-beta.1", - "@getpaseo/relay": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.4", + "@getpaseo/relay": "0.17.4", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/client/src/connection/index.ts b/packages/client/src/connection/index.ts index 61a0ef8360a6..5d9837b19827 100644 --- a/packages/client/src/connection/index.ts +++ b/packages/client/src/connection/index.ts @@ -125,6 +125,7 @@ export class ConnectionSubscriptions extends OwnedSubscriptions { // Protocol support belongs to the installed client. Only browser hosting needs // a resource supplied by the caller. Keep this exhaustive as the protocol evolves. export const DEFAULT_CLIENT_CAPABILITIES = { + [CLIENT_CAPS.agentActiveTurnBehaviors]: true, [CLIENT_CAPS.terminalChunkedReplay]: true, [CLIENT_CAPS.binaryChunkingV1]: true, [CLIENT_CAPS.helloRejection]: true, diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 0ee1092124a8..068e3cbc22d5 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1127,6 +1127,7 @@ test("advertises client capabilities in hello", async () => { clientType: "cli", protocolVersion: 1, capabilities: { + agent_active_turn_behaviors: true, all_providers: true, selective_agent_timeline: true, timeline_replacement_invalidation: true, @@ -1626,6 +1627,106 @@ test("defaults session RPC waiters to sixty seconds", async () => { await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms"); }); +test.each([ + [ + "archive_workspace_request", + (client: DaemonClient) => client.archiveWorkspace("workspace-1"), + (requestId: string) => ({ + type: "archive_workspace_response" as const, + payload: { + requestId, + workspaceId: "workspace-1", + archivedAt: "2026-01-01T00:00:00.000Z", + error: null, + }, + }), + ], + [ + "paseo_worktree_archive_request", + (client: DaemonClient) => client.archivePaseoWorktree({ worktreePath: "/repo/worktree" }), + (requestId: string) => ({ + type: "paseo_worktree_archive_response" as const, + payload: { requestId, success: true, removedAgents: [], error: null }, + }), + ], + [ + "workspace.recovery.restore.request", + (client: DaemonClient) => client.restoreWorkspace("workspace-1"), + (requestId: string) => ({ + type: "workspace.recovery.restore.response" as const, + payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null }, + }), + ], + [ + "workspace.archive.undo.request", + (client: DaemonClient) => client.undoWorkspaceArchive("workspace-1"), + (requestId: string) => ({ + type: "workspace.archive.undo.response" as const, + payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null }, + }), + ], + [ + "open_project_request", + (client: DaemonClient) => client.openProject("/repo/worktree"), + (requestId: string) => ({ + type: "open_project_response" as const, + payload: { requestId, workspace: null, error: null }, + }), + ], + [ + "create_paseo_worktree_request", + (client: DaemonClient) => client.createPaseoWorktree({ cwd: "/repo", worktreeSlug: "topic" }), + (requestId: string) => ({ + type: "create_paseo_worktree_response" as const, + payload: { requestId, workspace: null, error: null, setupTerminalId: null }, + }), + ], +] as const)( + "waits on %s across queued and bounded daemon stages until response or disconnect", + async (_type, run, buildResponse) => { + useHeartbeatClock(); + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "worktree-lifecycle-wait-test", + logger: createMockLogger(), + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + + const connecting = client.connect(); + transport.triggerOpen(); + await connecting; + + const pending = run(client); + const sentFrame = JSON.parse(assertStr(transport.sent.at(-1))) as { + message: { requestId: string }; + }; + let settled = false; + void pending.then( + () => { + settled = true; + return undefined; + }, + () => { + settled = true; + return undefined; + }, + ); + await vi.advanceTimersByTimeAsync(200_000); + await Promise.resolve(); + expect(settled).toBe(false); + + transport.triggerMessage(wrapSessionMessage(buildResponse(sentFrame.message.requestId))); + await expect(pending).resolves.not.toThrow(); + + const disconnected = run(client); + transport.triggerClose({ code: 1006, reason: "gone" }); + await expect(disconnected).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); + }, +); + test("honors explicit fetchAgent timeout below the session RPC default", async () => { useHeartbeatClock(); const logger = createMockLogger(); @@ -9014,6 +9115,97 @@ test("the queue selector follows the host capability across one client's reconne await client.close(); }); +describe("agent sender active-turn behaviors", () => { + async function connect(features: Record) { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "agent-behaviors", + transportFactory: () => transport.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + transport.triggerOpen({ features: { agentMessageProvenance: true, ...features } }); + await connecting; + return { client, transport }; + } + + function respond( + transport: ReturnType, + payload: Record = {}, + ) { + const request = parseSentFrame(transport.sent.at(-1)); + transport.triggerMessage( + wrapSessionMessage({ + type: "send_agent_message_response", + payload: { + requestId: request.requestId, + agentId: "recipient", + accepted: true, + error: null, + ...payload, + }, + }), + ); + return request; + } + + test("a capable host gets the behavior as asked and returns the applied behavior with guidance", async () => { + const { client, transport } = await connect({ agentActiveTurnBehaviors: true }); + const send = client.sendAgentMessage("recipient", "review", { + sourceAgentId: "sender", + activeTurnBehavior: "steer", + }); + const request = respond(transport, { + deliveryStatus: "queued", + activeTurnBehavior: "steer", + guidance: "Steering the running turn.", + }); + expect(request.activeTurnBehavior).toBe("steer"); + await expect(send).resolves.toEqual({ + deliveryStatus: "queued", + activeTurnBehavior: "steer", + guidance: "Steering the running turn.", + }); + }); + + test("an older host gets its own agent default for queue and refuses a steer", async () => { + const { client, transport } = await connect({}); + const queued = client.sendAgentMessage("recipient", "review", { + sourceAgentId: "sender", + activeTurnBehavior: "queue", + }); + const request = respond(transport, { deliveryStatus: "queued" }); + expect("activeTurnBehavior" in request).toBe(false); + await expect(queued).resolves.toEqual({ deliveryStatus: "queued" }); + + const interrupt = client.sendAgentMessage("recipient", "stop", { + sourceAgentId: "sender", + activeTurnBehavior: "interrupt", + }); + expect(respond(transport, { deliveryStatus: "queued" }).activeTurnBehavior).toBe("interrupt"); + await interrupt; + + const sentBefore = transport.sent.length; + await expect( + client.sendAgentMessage("recipient", "now", { + sourceAgentId: "sender", + activeTurnBehavior: "steer", + }), + ).rejects.toThrow("Update the Paseo host to steer a running turn from an agent"); + expect(transport.sent).toHaveLength(sentBefore); + }); + + test("queue needs an agent sender", async () => { + const { client, transport } = await connect({ agentActiveTurnBehaviors: true }); + await expect( + client.sendAgentMessage("recipient", "review", { activeTurnBehavior: "queue" }), + ).rejects.toThrow('activeTurnBehavior "queue" needs an agent sender'); + expect(transport.sent).toHaveLength(0); + }); +}); + test("measures an outbound message in UTF-8 bytes against the daemon's message limit", async () => { const mock = createMockTransport(); const client = new DaemonClient({ diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 1b1b52e94a7b..bc41521c2171 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -49,7 +49,7 @@ import { ShutdownRequestedStatusPayloadSchema, DaemonUpdateResponseSchema, SessionInboundMessageSchema, - type ActiveTurnBehavior, + type AgentActiveTurnBehavior, type AgentAttachmentWire, type QueuedAgentDeliveryIntent, type QueuedComposerAttachment, @@ -124,6 +124,8 @@ import type { RefreshProvidersSnapshotResponseMessage, ProviderDiagnosticResponseMessage, ProviderUsageListResponseMessage, + ProviderInstallationInspectResponseMessage, + ProviderInstallationCheckUpdatesResponseMessage, UsageReportEntry, DaemonGetStatusResponse, DaemonGetPairingOfferResponse, @@ -484,6 +486,13 @@ export interface DaemonClientTrace { endSection(): void; } +/** A queued agent message carries the applied behavior and what happens next. */ +export interface AgentMessageReceipt { + deliveryStatus?: "queued"; + activeTurnBehavior?: AgentActiveTurnBehavior; + guidance?: string; +} + export interface SendMessageOptions { sourceAgentId?: string; sourceAgentServerId?: string; @@ -491,8 +500,11 @@ export interface SendMessageOptions { messageId?: string; /** A name selects an explicit skill, `null` clears it; omission leaves it unchanged. */ skill?: string | null; - /** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */ - activeTurnBehavior?: ActiveTurnBehavior; + /** + * Agent sources default to queue: wait for the running turn to end. Human sources default to + * interrupt and cannot queue. + */ + activeTurnBehavior?: AgentActiveTurnBehavior; images?: Array<{ data: string; mimeType: string }>; attachments?: SendAgentMessageRequest["attachments"]; } @@ -639,6 +651,13 @@ type GetProvidersSnapshotPayload = GetProvidersSnapshotResponseMessage["payload" type RefreshProvidersSnapshotPayload = RefreshProvidersSnapshotResponseMessage["payload"]; type ProviderDiagnosticPayload = ProviderDiagnosticResponseMessage["payload"]; type ProviderUsageListPayload = ProviderUsageListResponseMessage["payload"]; +type ProviderInstallationInspectPayload = ProviderInstallationInspectResponseMessage["payload"]; +type ProviderInstallationCheckUpdatesPayload = + ProviderInstallationCheckUpdatesResponseMessage["payload"]; +type ProviderInstallationUpdatePayload = Extract< + SessionOutboundMessage, + { type: "provider.installation.update.response" } +>["payload"]; interface UsageListReportsPayload { requestId: string; reports: UsageReportEntry[]; @@ -3240,6 +3259,9 @@ export class DaemonClient { cwd, }, responseType: "open_project_response", + // Opening a path whose checkout is currently archiving waits on the daemon checkout gate; + // wait for the terminal response or transport disconnect instead of timing out while queued. + timeout: 0, }); } @@ -3371,6 +3393,9 @@ export class DaemonClient { workspaceId, }, responseType: "archive_workspace_response", + // Archive may wait for a queued checkout operation and then run teardown/manager removal, + // each bounded on the daemon; wait for the terminal response or transport disconnect. + timeout: 0, }); } @@ -3956,7 +3981,9 @@ export class DaemonClient { type: "workspace.recovery.restore.request", workspaceId, }, - timeout: 150_000, + // Restore may wait behind an active archive/removal before running a bounded restore stage; + // wait for the terminal response or transport disconnect instead of timing out mid-workflow. + timeout: 0, }); if (!payload.accepted) { throw new Error(payload.error ?? "Workspace recovery was rejected by the host"); @@ -3972,8 +3999,9 @@ export class DaemonClient { type: "workspace.archive.undo.request", workspaceId, }, - // Undoing a finished worktree archive recreates the worktree, like recovery does. - timeout: 150_000, + // Undo may wait for an in-flight archive to settle and then recreate the worktree; + // wait for the terminal response or transport disconnect. + timeout: 0, }); if (!payload.accepted) { throw new Error(payload.error ?? "The host could not undo the workspace archive"); @@ -4368,7 +4396,7 @@ export class DaemonClient { agentId: string, text: string, options: SendMessageOptions = {}, - ): Promise<{ deliveryStatus?: "queued" }> { + ): Promise { if ( options.sourceAgentId && this.lastServerInfoMessage?.features?.agentMessageProvenance !== true @@ -4381,6 +4409,7 @@ export class DaemonClient { ) { throw new Error("Update the Paseo host to send messages with a qualified agent address."); } + const activeTurnBehavior = this.activeTurnBehaviorForHost(options); const requestId = this.createRequestId(); const messageId = options.messageId ?? crypto.randomUUID(); const message = SessionInboundMessageSchema.parse({ @@ -4393,7 +4422,7 @@ export class DaemonClient { sessionMode: options.sessionMode, ...(options.skill === undefined ? {} : { skill: options.skill }), ...(messageId ? { messageId } : {}), - activeTurnBehavior: options.activeTurnBehavior, + activeTurnBehavior, images: options.images, attachments: options.attachments, }); @@ -4414,14 +4443,39 @@ export class DaemonClient { if (!payload.accepted) { throw new Error(payload.error ?? "sendAgentMessage rejected"); } - return payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}; + return { + ...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}), + ...(payload.activeTurnBehavior ? { activeTurnBehavior: payload.activeTurnBehavior } : {}), + ...(payload.guidance ? { guidance: payload.guidance } : {}), + }; + } + + /** The behavior to put on the wire for this host. */ + private activeTurnBehaviorForHost( + options: SendMessageOptions, + ): AgentActiveTurnBehavior | undefined { + const requested = options.activeTurnBehavior; + if (!options.sourceAgentId) { + if (requested === "queue") + throw new Error('activeTurnBehavior "queue" needs an agent sender (sourceAgentId).'); + return requested; + } + if (this.lastServerInfoMessage?.features?.agentActiveTurnBehaviors === true) return requested; + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once daemon + // floor >= v0.17.2. Older hosts reject queue and read an agent's steer as queue, so queue + // goes out as the host's own agent default and a real steer needs an update. + if (requested === "steer") + throw new Error( + "Update the Paseo host to steer a running turn from an agent. Leave the behavior out to queue the message, or use interrupt.", + ); + return requested === "interrupt" ? "interrupt" : undefined; } async sendMessage( agentId: string, text: string, options?: SendMessageOptions, - ): Promise<{ deliveryStatus?: "queued" }> { + ): Promise { return this.sendAgentMessage(agentId, text, options); } @@ -5771,6 +5825,9 @@ export class DaemonClient { ...(input.scope !== undefined ? { scope: input.scope } : {}), }, responseType: "paseo_worktree_archive_response", + // Archive may wait for a queued checkout operation and then run teardown/manager removal, + // each bounded on the daemon; wait for the terminal response or transport disconnect. + timeout: 0, }); } @@ -5794,6 +5851,10 @@ export class DaemonClient { ...(input.githubPrNumber !== undefined ? { githubPrNumber: input.githubPrNumber } : {}), }, responseType: "create_paseo_worktree_response", + // Every daemon stage (before hooks, shared 120s manager budget, Git, after hooks) enforces + // its own deadline, and transport heartbeats/close reject if the host drops, so wait for the + // terminal worktree response instead of aborting prematurely mid-workflow. + timeout: 0, }); } @@ -6585,6 +6646,70 @@ export class DaemonClient { }); } + /** Install and update links plus installed state. Requires `features.providerInstallation`. */ + async inspectProviderInstallation( + provider: AgentProvider, + options?: { refresh?: boolean; requestId?: string }, + ): Promise { + return this.sendNamespacedCorrelatedSessionRequest<"provider.installation.inspect.response">({ + requestId: options?.requestId, + message: { + type: "provider.installation.inspect.request", + provider, + ...(options?.refresh ? { refresh: true } : {}), + }, + timeout: 60_000, + }); + } + + /** Whether the provider reports a newer version. Requires `features.providerInstallation`. */ + async checkProviderUpdates( + provider: AgentProvider, + options?: { refresh?: boolean; requestId?: string }, + ): Promise { + return this.sendNamespacedCorrelatedSessionRequest<"provider.installation.check_updates.response">( + { + requestId: options?.requestId, + message: { + type: "provider.installation.check_updates.request", + provider, + ...(options?.refresh ? { refresh: true } : {}), + }, + timeout: 60_000, + }, + ); + } + + /** Starts the provider's update, or joins the running one. Follow it with `observeProviderUpdates`. */ + async updateProvider( + provider: AgentProvider, + options?: { requestId?: string }, + ): Promise { + return this.sendNamespacedCorrelatedSessionRequest<"provider.installation.update.response">({ + requestId: options?.requestId, + message: { type: "provider.installation.update.request", provider }, + timeout: 60_000, + }); + } + + /** + * The provider's latest update, then `provider.installation.update.progress` as updates start, + * report output and settle, and `provider.installation.update.cleared` when a refresh drops a + * failed update. Survives reconnects: each new snapshot replaces the previous one. + */ + observeProviderUpdates( + provider: AgentProvider, + options?: { signal?: AbortSignal }, + ): OwnedSubscription< + CorrelatedResponsePayload<"provider.installation.update.subscribe.response"> + > { + return this.observe( + "provider.installation.update.subscribe.response", + { type: "provider.installation.update.subscribe.request", provider }, + options, + ); + } + async listProviderUsage(options?: { requestId?: string }): Promise { return this.sendNamespacedCorrelatedSessionRequest({ requestId: options?.requestId, diff --git a/packages/desktop/e2e/explorer-toggle.spec.ts b/packages/desktop/e2e/explorer-toggle.spec.ts new file mode 100644 index 000000000000..4448d6e3197f --- /dev/null +++ b/packages/desktop/e2e/explorer-toggle.spec.ts @@ -0,0 +1,179 @@ +import type { Locator, Page } from "@playwright/test"; +import { expect, test } from "../../app/e2e/support/fixtures"; +import { gotoWorkspace } from "../../app/e2e/support/helpers/launcher"; + +function explorerSidebar(page: Page) { + return page.getByTestId("workspace-explorer-sidebar").filter({ visible: true }); +} + +async function useDesktopWindowChrome(page: Page, mode: "native-mac" | "custom-windows") { + await page.addInitScript((windowChromeMode) => { + Object.assign(window, { + paseoDesktop: { + platform: windowChromeMode === "native-mac" ? "darwin" : "win32", + windowChromeMode, + invoke: async () => null, + events: { on: async () => () => undefined }, + getPendingOpenProject: async () => null, + window: { + getCurrentWindow: () => ({ + isFullscreen: async () => false, + onResized: async () => () => undefined, + }), + }, + }, + }); + }, mode); +} + +function explorerToggle(page: Page, expanded: boolean) { + return page.getByRole("button", { + name: expanded ? "Close Explorer sidebar" : "Open Explorer sidebar", + exact: true, + expanded, + }); +} + +async function recordExplorerToggle(button: Locator) { + const recording = await button.evaluateHandle((target) => { + const measure = () => { + const glyph = target.querySelector("svg")?.getBoundingClientRect(); + return { + connected: target.isConnected, + x: glyph?.x, + y: glyph?.y, + width: glyph?.width, + height: glyph?.height, + }; + }; + const before = measure(); + const frames: ReturnType[] = []; + const done = new Promise((resolve) => { + target.addEventListener( + "click", + () => { + const start = performance.now(); + const sample = () => { + frames.push(measure()); + if (performance.now() - start < 300) requestAnimationFrame(sample); + else resolve(); + }; + requestAnimationFrame(sample); + }, + { once: true }, + ); + }); + return { before, frames, done }; + }); + try { + await button.click(); + return await recording.evaluate(async ({ before, frames, done }) => { + await done; + return { before, frames }; + }); + } finally { + await recording.dispose(); + } +} + +async function expectExplorerToggleHasNativeClickArea(toggle: Locator) { + const regions = await toggle.evaluate((button) => { + const rect = button.getBoundingClientRect(); + const x = rect.x + rect.width / 2; + const y = rect.y + rect.height / 2; + return [ + ...document.querySelectorAll('[style*="app-region"], [data-window-no-drag], [role="button"]'), + ] + .filter((element) => { + const bounds = element.getBoundingClientRect(); + return bounds.left <= x && x < bounds.right && bounds.top <= y && y < bounds.bottom; + }) + .map((element) => getComputedStyle(element).getPropertyValue("-webkit-app-region")) + .filter((region) => region === "drag" || region === "no-drag"); + }); + expect(regions).toContain("drag"); + expect(regions.at(-1)).toBe("no-drag"); +} + +// Fork: the workspace header keeps its branch controls (current and base branch buttons) ahead of +// Workspace actions, so the toggle's next stops may be those before Workspace actions. +const MAX_BRANCH_CONTROL_STOPS = 3; + +async function expectExplorerToggleInHeaderTabOrder(page: Page, expanded: boolean) { + const toggle = explorerToggle(page, expanded); + const workspaceActions = page.getByRole("button", { name: "Workspace actions", exact: true }); + const branchControls = page.getByTestId("workspace-header-branches"); + await toggle.focus(); + let tabs = 0; + while (true) { + await page.keyboard.press("Tab"); + tabs += 1; + if (await workspaceActions.evaluate((element) => element === document.activeElement)) break; + expect(tabs).toBeLessThanOrEqual(MAX_BRANCH_CONTROL_STOPS); + expect( + await branchControls.evaluate((element) => element.contains(document.activeElement)), + ).toBe(true); + } + await expect(workspaceActions).toBeFocused(); + for (let index = 0; index < tabs; index += 1) await page.keyboard.press("Shift+Tab"); + await expect(toggle).toBeFocused(); +} + +async function expectExplorerToggleToHoldPosition(page: Page, expanded: boolean) { + const toggle = explorerToggle(page, expanded); + await expect(toggle).toBeVisible(); + await expectExplorerToggleHasNativeClickArea(toggle); + const { before, frames } = await recordExplorerToggle(toggle); + await expect(explorerToggle(page, !expanded)).toBeVisible(); + expect(before.width).toBeGreaterThan(0); + expect(frames.find((frame) => JSON.stringify(frame) !== JSON.stringify(before))).toBeUndefined(); +} + +test("keeps the Mac Explorer toggle in place across open and close", async ({ + page, + withWorkspace, +}) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await useDesktopWindowChrome(page, "native-mac"); + + const { workspaceId } = await withWorkspace(); + await gotoWorkspace(page, workspaceId); + await expectExplorerToggleInHeaderTabOrder(page, false); + await expectExplorerToggleToHoldPosition(page, false); + await expectExplorerToggleInHeaderTabOrder(page, true); + await expectExplorerToggleToHoldPosition(page, true); + + await page.setViewportSize({ width: 930, height: 900 }); + await expectExplorerToggleToHoldPosition(page, false); + await expectExplorerToggleToHoldPosition(page, true); +}); + +async function expectClearOfWindowControls(page: Page, action: Locator) { + const minimize = page.getByRole("button", { name: "Minimize window", exact: true }); + await expect(minimize).toBeVisible(); + await expect(action).toBeVisible(); + const controlBounds = await minimize.boundingBox(); + const actionBounds = await action.boundingBox(); + expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(controlBounds!.x); +} + +test("keeps the Explorer actions clear of Windows controls", async ({ page, withWorkspace }) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await useDesktopWindowChrome(page, "custom-windows"); + + const { workspaceId } = await withWorkspace(); + await gotoWorkspace(page, workspaceId); + const open = explorerToggle(page, false); + await expectClearOfWindowControls(page, open); + await open.click(); + + const close = explorerToggle(page, true); + const newExplorerTab = explorerSidebar(page).getByRole("button", { + name: "New tab", + exact: true, + }); + await expectClearOfWindowControls(page, close); + await expectClearOfWindowControls(page, newExplorerTab); + await close.click(); + await expect(open).toBeVisible(); +}); diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 06b1b6aac3b5..71161b8eb7fc 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.17.0-beta.1", + "version": "0.17.4", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/desktop/playwright.config.ts b/packages/desktop/playwright.config.ts index 3e74d1a5d0c5..67585d11ae4c 100644 --- a/packages/desktop/playwright.config.ts +++ b/packages/desktop/playwright.config.ts @@ -12,7 +12,7 @@ export default defineConfig({ timeout: 10_000, }, fullyParallel: false, - workers: 1, + workers: Number(process.env.E2E_WORKERS ?? (process.env.CI ? "2" : "1")), retries: process.env.CI ? 1 : 0, reporter: [["list"]], use: { diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 6c99857c2fa4..5b68fa035bd1 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.17.0-beta.1", + "version": "0.17.4", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 21be0606fcea..0a75058f1190 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.17.0-beta.1", + "version": "0.17.4", "license": "Apache-2.0", "files": [ "dist", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index d984ff933cb7..b8c7576c30eb 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.17.0-beta.1", + "version": "0.17.4", "description": "Paseo plugin SDK package", "license": "Apache-2.0", "files": [ @@ -78,8 +78,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.17.0-beta.1", - "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/client": "0.17.4", + "@getpaseo/protocol": "0.17.4", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -89,8 +89,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.17.0-beta.1", - "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/client": "0.17.4", + "@getpaseo/protocol": "0.17.4", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 8b8cae6630e9..eff1af756afb 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -589,3 +589,75 @@ describe("sidebar data SDK boundary", () => { ).toEqual([]); }); }); + +describe("worktree manager SDK boundary", () => { + it("types create, remove, and restore handlers with discriminated results and cleanup", () => { + expect( + typeErrors(` + import type { + PluginServerContext, + WorktreeManagerRegistration, + PluginWorktreeCreateInput, + PluginWorktreeCreateResult, + PluginWorktreeRemoveRequest, + PluginWorktreeRemoveResult, + PluginWorktreeRestoreRequest, + PluginWorktreeRestoreResult, + } from "@getpaseo/plugin/server"; + + export default function contribute(server: PluginServerContext) { + const manager: WorktreeManagerRegistration = { + async create(request: PluginWorktreeCreateInput, { paseo, signal }) { + const untrusted: boolean = request.untrusted; + const headSha: string | undefined = request.headSha; + void headSha; + // @ts-expect-error untrusted is read-only + request.untrusted = true; + // @ts-expect-error headSha is read-only + request.headSha = "deadbeef"; + if (request.kind === "branch-off") { + const start: string = request.startPoint ?? request.baseRef; + // @ts-expect-error startPoint is read-only + request.startPoint = "other"; + if (!start || untrusted) return; + } + if (signal.aborted) return; + void paseo; + const result: PluginWorktreeCreateResult = { type: "created", path: request.path }; + return result; + }, + async remove(request: PluginWorktreeRemoveRequest, { signal }) { + const reason: "archive" | "rollback" = request.reason; + const force: boolean = request.force; + const untrusted: boolean = request.untrusted; + // @ts-expect-error remove request fields are read-only + request.path = "/other"; + if (!reason || !force || untrusted || signal.aborted) return; + const result: PluginWorktreeRemoveResult = { type: "removed" }; + return result; + }, + async restore(request: PluginWorktreeRestoreRequest) { + const untrusted: boolean = request.untrusted; + void untrusted; + if (request.target.type === "commit") return; + if (request.target.type === "from-base") { + const base: string = request.target.baseRef; + void base; + } + const result: PluginWorktreeRestoreResult = { type: "restored", path: request.path }; + return result; + }, + }; + const dispose: () => void = server.registerWorktreeManager(manager); + server.registerWorktreeManager({ + // @ts-expect-error create result requires discriminant + async create() { + return { path: "/tmp/wt" }; + }, + }); + return dispose; + } + `), + ).toEqual([]); + }); +}); diff --git a/packages/plugin/src/client/contracts.ts b/packages/plugin/src/client/contracts.ts index 72dc1f954d90..13aaa9b71fbb 100644 --- a/packages/plugin/src/client/contracts.ts +++ b/packages/plugin/src/client/contracts.ts @@ -49,16 +49,25 @@ export interface PluginHostProps { interface PluginNavigableHostProps extends PluginHostProps { /** Client-owned navigation. Undefined on older hosts; hide dependent affordances when absent. */ readonly navigation?: { + /** This client supports the focusHost option on agent/workspace navigation. */ + readonly supportsFocusHost?: boolean; /** Present only on Electron. The browser runs locally; serverId selects workspace ownership. */ readonly openBrowser?: (input: { readonly url: string; readonly workspaceId: string; readonly serverId?: string; }) => void; - readonly openAgent: (input: { readonly agentId: string; readonly serverId?: string }) => void; + readonly openAgent: (input: { + readonly agentId: string; + readonly serverId?: string; + /** Select only the destination host in the sidebar and clear project/label filters. */ + readonly focusHost?: boolean; + }) => void; readonly openWorkspace: (input: { readonly workspaceId: string; readonly serverId?: string; + /** Select only the destination host in the sidebar and clear project/label filters. */ + readonly focusHost?: boolean; }) => void; }; } diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index 84f32113ecf9..09144ecce234 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -9,11 +9,11 @@ import { type Client, type AgentCapabilities, type ContentBlock, - type ListSessionsResponse, type NewSessionResponse, type RequestPermissionRequest, type RequestPermissionResponse, type SessionConfigOption, + type SessionInfo, type SessionNotification, type SessionUpdate, type ToolCall, @@ -25,13 +25,16 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { AcpConfigAccess, AcpConfigChange, + AcpConfigureContext, AcpConnectionPolicy, + AcpRequest, AcpSessionPolicy, AcpToolCallSnapshot, AcpTransformer, AcpVendorUpdate, RunAcpProviderOptions, } from "../acp.js"; +import { standardToolCallDetail } from "./tool-call-detail.js"; import { PROVIDER_PROTOCOL_VERSION, ProviderEventSchema, @@ -48,7 +51,9 @@ import { type ProviderEvent, type ProviderInput, type ProviderLaunch, + type ProviderModel, type ProviderPermissionResponse, + type ProviderToolCallDetail, type ProviderPersistence, type ProviderPrompt, type ProviderSessionConfig, @@ -126,6 +131,12 @@ export async function createAcpProviderConnection( if (probe.agentCapabilities.loadSession) { supportedCapabilities.push("session.persistence"); } + if ( + options.acpOptions?.deferTurnOnRunningTools && + !supportedCapabilities.includes("prompt.steer") + ) { + supportedCapabilities.push("prompt.steer"); + } await probe.close(); const capabilities = negotiateProviderCapabilities(request.capabilities, supportedCapabilities); const listeners = new Set<(event: ProviderEvent) => void>(); @@ -265,10 +276,13 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis await mutateSession(session, session.runtime.preparePrompt(input)); return; } - case "session.interrupt": - await requireSession(state, input.sessionId).runtime.interrupt(); + case "session.interrupt": { + const session = requireSession(state, input.sessionId); + const retired = await session.runtime.interrupt(); state.emit({ type: "request.completed", requestId: input.requestId }); + if (retired) retireSession(state, input.sessionId); return; + } case "session.detach": { const session = state.sessions.get(input.sessionId); if (session) { @@ -327,10 +341,10 @@ async function discover( }); try { let catalog = await runtime.discover(input.cwd); - const config = runtime.configAccess(); + const context = runtime.configContext(); for (const transformer of state.options.transformers ?? []) { if (transformer.discover) { - catalog = await transformer.discover(catalog, { sessionId: "catalog", config }); + catalog = await transformer.discover(catalog, context); } } state.emit({ type: "catalog", requestId: input.requestId, catalog }); @@ -351,7 +365,7 @@ async function listSessions( emit: state.emit, }); try { - const selected = await runtime.listSessions(input.cwd, input.limit); + const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit }); state.emit({ type: "sessions", requestId: input.requestId, @@ -367,6 +381,12 @@ async function listSessions( } } +function retireSession(state: AcpConnectionState, sessionId: string): void { + if (state.sessions.delete(sessionId)) { + state.emit({ type: "session.closed", sessionId }); + } +} + async function openSession( input: Extract, state: AcpConnectionState, @@ -380,9 +400,10 @@ async function openSession( cwd: input.config.cwd, env: input.config.env, emit: state.emit, + onRetired: () => retireSession(state, input.sessionId), }); try { - const capabilities = await runtime.open(input, state.capabilities); + const capabilities = await runtime.open(input, state.capabilities, state.isClosed); if (state.isClosed()) { await runtime.closeSession(); return; @@ -421,6 +442,7 @@ interface StartRuntimeOptions { cwd?: string; env: Readonly>; emit(event: ProviderEvent): void; + onRetired?: () => void; } interface PendingPermission { @@ -429,6 +451,56 @@ interface PendingPermission { resolve(response: RequestPermissionResponse): void; } +type DeferredTurnOutcome = + | { type: "complete"; terminalizeTools: boolean } + | { type: "cancel" } + | { type: "fail"; error: { message: string } }; + +interface DeferredTurnState { + timer: ReturnType | null; + resolve(outcome: DeferredTurnOutcome): void; +} + +type DeferredReplyState = "idle" | "open" | "settled_with_open_tools" | "settled"; + +interface ActivePrompt { + turnId: string; + settled: Promise; + cancelling: boolean; + wirePromptsInFlight: number; + wirePromptLane: Promise; + lastPromptResponseWireSeq: number | null; + crossedEndTurn: boolean; + replyState: DeferredReplyState; + deferred: DeferredTurnState | null; +} + +function newActivePrompt(turnId: string, settled: Promise): ActivePrompt { + return { + turnId, + settled, + cancelling: false, + wirePromptsInFlight: 1, + wirePromptLane: Promise.resolve(), + lastPromptResponseWireSeq: null, + crossedEndTurn: false, + replyState: "idle", + deferred: null, + }; +} + +const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500; +const SESSION_SCAN_LIMIT = 500; +// COMPAT(acpAutoAccept): added in v0.17.4, remove after 2027-05-23. The generic ACP adapter saves +// its Auto Accept toggle as this setting on agents that later moved to a bundled ACP provider. +const LEGACY_AUTO_ACCEPT_SETTING = "auto_accept"; +const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000; + +interface AcpToolCallState { + source: AcpToolCallSnapshot; + presentation: AcpToolCallSnapshot; +} + class AcpRuntime { readonly connection: ClientSideConnection; agentCapabilities: AgentCapabilities = {}; @@ -440,7 +512,10 @@ class AcpRuntime { private readonly transportFailure: Promise; private emit: (event: ProviderEvent) => void; private readonly messages = new Map(); - private readonly toolCalls = new Map(); + private readonly toolCalls = new Map(); + private mcpServerNames: readonly string[] = []; + private readonly liveOpenToolIds = new Set(); + private readonly canceledToolCallIds = new Set(); // Running tool rows published by transformers; the turn's terminal closes any left open. private readonly vendorToolCalls = new Map(); private readonly pendingCompactions = new Set(); @@ -467,18 +542,28 @@ class AcpRuntime { * Once ready, suppress late replay rows until the first prompt. */ private replayWindow: "replay" | "skip" | null = null; - private lastLoadUpdateAt = 0; + private lastLoadHistoryAt = 0; + private lastPartialWireAt = 0; private closing = false; + private closePromise: Promise | null = null; + private deferredRetirement: Promise | null = null; + private deferredFinalized = false; private processFailed = false; + private processFailureMessage: string | null = null; private configTransaction = false; private stagedTransformerConfig: ProviderConfigState | null = null; - private readonly closeConnector: () => Promise; + private readonly closeConnector: (options?: { + force?: boolean; + timeoutMs?: number; + }) => Promise; + private readonly whenConnectorClosed: () => Promise | null; private notificationLane: Promise = Promise.resolve(); private promptLane: Promise = Promise.resolve(); + private incomingWireSeq = 0; + private readonly sessionUpdateWireSeqs: number[] = []; private autoAccept = false; private hasToolPolicy = false; - private activePrompt: { turnId: string; settled: Promise; cancelling: boolean } | null = - null; + private activePrompt: ActivePrompt | null = null; private lastUsage: ProviderUsage = {}; private readonly outstandingSteers = new Map< string, @@ -519,7 +604,12 @@ class AcpRuntime { let child: ChildProcessWithoutNullStreams | null = null; let spawnFailure: Promise | null = null; let stream: Stream; - let closeConnector = async () => {}; + let closeConnector: (options?: { + force?: boolean; + timeoutMs?: number; + }) => Promise = async () => {}; + let whenConnectorClosed: () => Promise | null = () => null; + let onPartialWireRead: (() => void) | null = null; if (options.options.command) { // COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0. // Standalone callers and older hosts do not send a daemon-resolved launch. @@ -536,14 +626,19 @@ class AcpRuntime { spawnFailure = new Promise((_resolve, reject) => child!.once("error", reject)); child.stderr.on("data", () => undefined); const output = Writable.toWeb(child.stdin) as unknown as Parameters[0]; - const input = Readable.toWeb(child.stdout) as unknown as Parameters[1]; + const rawInput = Readable.toWeb(child.stdout) as unknown as ReadableStream; + const input = observePartialWireReads(rawInput, () => onPartialWireRead?.()) as Parameters< + typeof ndJsonStream + >[1]; stream = ndJsonStream(output, input); } else { const owned = ownConnectorStream(await options.options.connector()); stream = owned.stream; closeConnector = owned.close; + whenConnectorClosed = owned.whenClosed; } - const runtime = new AcpRuntime(stream, child, closeConnector, options); + const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options); + onPartialWireRead = () => runtime.notePartialWireRead(); try { const initialize = withTimeout( runtime.call( @@ -578,33 +673,38 @@ class AcpRuntime { private constructor( stream: Stream, child: ChildProcessWithoutNullStreams | null, - closeConnector: () => Promise, + closeConnector: (options?: { force?: boolean; timeoutMs?: number }) => Promise, + whenConnectorClosed: () => Promise | null, private readonly options: StartRuntimeOptions, ) { this.child = child; this.closeConnector = closeConnector; + this.whenConnectorClosed = whenConnectorClosed; this.emit = options.emit; this.transformers = options.options.transformers ?? []; this.vendorTurnsAreNeverForeground = options.options.acpOptions?.vendorTurnsAreNeverForeground === true; const client: Client = { requestPermission: (request) => this.requestPermission(request), - sessionUpdate: (notification) => - this.enqueueNotification(() => { + sessionUpdate: (notification) => { + const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq; + return this.enqueueNotification(() => { try { - this.sessionUpdate(notification); + this.sessionUpdate(notification, wireSeq); } finally { this.updateSlots.settleDelivered(notification); } - }), + }); + }, }; this.connection = new ClientSideConnection( () => client, - routeVendorNotifications( + routeIncomingMessages( stream, (method, params) => this.vendorNotification(method, params), this.updateSlots, this.promptResponses, + (message) => this.observeWireMessage(message), ), ); const processClosed = child @@ -618,35 +718,41 @@ class AcpRuntime { return this.handleUnexpectedTransportClose(); }); child?.on("error", (error) => { + const message = describeError(error); if (this.processFailed) return; this.processFailed = true; + this.processFailureMessage = message; if (!this.closing && this.nativeSessionId) { this.emit({ type: "session.runtime_failed", sessionId: this.options.boundarySessionId, - error: { message: describeError(error) }, + error: { message }, }); } - this.settlePendingWork(); + this.settlePendingWork(message); }); child?.once("close", (code, signal) => { if (this.closing || this.processFailed || !this.nativeSessionId) return; + const message = `ACP process exited (${signal ?? code ?? "unknown"})`; this.processFailed = true; + this.processFailureMessage = message; this.emit({ type: "session.runtime_failed", sessionId: this.options.boundarySessionId, - error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` }, + error: { message }, }); - this.settlePendingWork(); + this.settlePendingWork(message); }); } async open( input: Extract, connectionCapabilities: readonly ProviderCapability[], + isConnectionClosed: () => boolean, ): Promise { const mcpServers = this.connectionPolicy.sendSessionMcpServers === false ? [] : toAcpMcpServers(input.config); + this.mcpServerNames = mcpServers.map((server) => server.name); let nativeSessionId = readNativeSessionId(input.persistence); const metadata: Record = { _paseo: { @@ -717,15 +823,22 @@ class AcpRuntime { }); this.emitOmittedMcpNotice(input); this.emitConfig(); + await this.finishSessionOpen(isConnectionClosed); + return sessionCapabilities; + } + + private async finishSessionOpen(isConnectionClosed: () => boolean): Promise { if (this.options.options.acpOptions?.waitForInitialCommands) { await this.waitForInitialCommands(); } const quietPeriod = this.options.options.acpOptions?.loadReplayQuietPeriodMs; if (this.replayWindow && quietPeriod && quietPeriod > 0) { - await this.waitForLoadReplay(quietPeriod); + await this.waitForLoadReplay(quietPeriod, isConnectionClosed); this.replayWindow = "skip"; } - return sessionCapabilities; + if (this.processFailed && !isConnectionClosed()) { + throw new Error(this.processFailureMessage ?? "ACP process exited during session open"); + } } private prepareSessionOpen( @@ -745,6 +858,11 @@ class AcpRuntime { return nativeSessionId; } + /** The agent and this attachment negotiated steering into a running shared turn. */ + private steersSharedTurns(): boolean { + return this.connectionPolicy.steering === true && this.sessionPolicy.steering === true; + } + private sessionCapabilities( connectionCapabilities: readonly ProviderCapability[], ): ProviderCapability[] { @@ -753,7 +871,8 @@ class AcpRuntime { (capability) => capability !== "session.detach" && (capability !== "prompt.steer" || - (this.connectionPolicy.steering === true && this.sessionPolicy.steering === true)), + this.options.options.acpOptions?.deferTurnOnRunningTools !== undefined || + this.steersSharedTurns()), ); if (this.sessionPolicy.detach === true) sessionCapabilities.push("session.detach"); return sessionCapabilities; @@ -785,7 +904,10 @@ class AcpRuntime { this.nativeSessionId = response.sessionId; this.modes = response.modes ?? null; this.configOptions = response.configOptions ?? []; - const catalog = toProviderCatalog(this.modes, this.configOptions); + let catalog = toProviderCatalog(this.modes, this.configOptions); + if (this.options.options.acpOptions?.perModelThinkingOptions) { + catalog = { ...catalog, models: await this.modelsWithOwnThinkingOptions(catalog) }; + } const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode; if (!autoAcceptMode) return catalog; return { @@ -795,6 +917,33 @@ class AcpRuntime { }; } + /** + * Selects each model in the discovery session to read the thinking options the agent lists for + * it, then selects the opening model again for the transformers that run after discovery. + */ + private async modelsWithOwnThinkingOptions(catalog: ProviderCatalog): Promise { + const models: ProviderModel[] = []; + for (const model of catalog.models) { + await this.selectModel(model.id); + const { thinkingOptions, thinkingOption } = toProviderConfigState( + this.modes, + this.configOptions, + ); + models.push({ + ...model, + thinkingOptions: [...thinkingOptions], + defaultThinkingOptionId: thinkingOption, + }); + } + if (catalog.defaultModel) await this.selectModel(catalog.defaultModel); + return models; + } + + private async selectModel(model: string): Promise { + if (selectedValue(modelOption(this.configOptions)) === model) return; + await this.applyNativeConfigChange({ target: "model", value: model }); + } + preparePrompt(input: Extract): () => Promise { const stopGeneration = this.stopGeneration; return () => this.prompt(input, stopGeneration); @@ -805,8 +954,20 @@ class AcpRuntime { stopGeneration: number, ): Promise { if (this.detached) return Promise.reject(new Error("Session was detached from the agent")); + if (this.closing || this.processFailed || this.deferredRetirement) { + return Promise.reject(new Error("ACP session is closed")); + } this.assertPromptSelection(input.prompt); - if (input.prompt.delivery === "steer") return this.steer(input); + if (input.prompt.delivery === "steer") { + // A turn deferred on running background tools takes steers into its follow-up reply. An + // agent without shared-turn steering can be steered only then; the deferred path refuses + // the steer otherwise. + if (this.activePrompt?.deferred || !this.steersSharedTurns()) { + this.steerDeferredPrompt(input); + return Promise.resolve(); + } + return this.steer(input); + } // A stop cancels the prompts waiting when it is pressed, not prompts admitted after it. const admission = this.promptLane.then(() => this.admitPrompt(input, stopGeneration)); this.promptLane = admission.catch(() => undefined); @@ -850,16 +1011,14 @@ class AcpRuntime { } private classifyCommands(commands: readonly ProviderCommand[]): ProviderCommand[] { - let classified: ProviderCommand[] = [...commands]; - const context = { - sessionId: this.options.boundarySessionId, - policy: this.connectionPolicy, - }; - for (const transformer of this.transformers) { - const next = transformer.command?.(classified, context); - if (next) classified = [...next]; - } - return classified; + const context = { sessionId: this.options.boundarySessionId, policy: this.connectionPolicy }; + return commands.map((command) => { + let entry = command; + for (const transformer of this.transformers) { + entry = transformer.command?.(entry, context) ?? entry; + } + return entry; + }); } /** Terminal identities are only needed to suppress a late duplicate; bound a long session. */ @@ -893,19 +1052,11 @@ class AcpRuntime { turnId: string, state: "completed" | "failed" | "canceled", error?: ProviderError, + options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean }, ): boolean { if (this.settledLocalTurns.has(turnId)) return false; this.remember(this.settledLocalTurns, turnId); - this.finishTurnPermissions(turnId); - this.fallbackChunkIds.clear(); - this.terminalizeTransientItems(state); - this.emit({ - type: "session.turn", - sessionId: this.options.boundarySessionId, - turnId, - state, - ...(error === undefined ? {} : { error }), - }); + this.finishPromptTurn(turnId, state, error, options); return true; } @@ -1070,8 +1221,22 @@ class AcpRuntime { while (this.activePrompt) { const active = this.activePrompt; // Replacing a foreground prompt is not a user stop of the prompts queued behind it. - if (!this.sharedTurns) await this.interruptTurn(); + if (active.deferred && active.wirePromptsInFlight === 0) { + // Wire session/prompt already resolved; finish the deferred turn without sending + // session/cancel so running background tools stay alive into the follow-up turn. + this.finishDeferredTurn(active, { type: "complete", terminalizeTools: false }); + } else if (!this.sharedTurns) { + const retired = await this.interruptTurn(); + if (retired) { + // Notify caller that the session closed before failing the replacement prompt. + this.options.onRetired?.(); + throw new Error("ACP session retired after stopping deferred background work"); + } + } await active.settled; + if (this.closing || this.processFailed || this.deferredRetirement) { + throw new Error("ACP session is closed"); + } } // A vendor turn belongs to another client attached to the same agent session; the agent // queues this prompt behind it anyway. Waiting keeps the user's message after the peer @@ -1131,6 +1296,17 @@ class AcpRuntime { }); return; } + const activePrompt: ActivePrompt = { + turnId, + settled: Promise.resolve(), + cancelling: false, + wirePromptsInFlight: 1, + wirePromptLane: Promise.resolve(), + lastPromptResponseWireSeq: null, + crossedEndTurn: false, + replyState: "idle", + deferred: null, + }; // The SDK dispatches notifications without awaiting them, so the prompt response can resolve // while earlier session updates are still queued. Apply them before the turn ends. const echoText = text; @@ -1141,6 +1317,7 @@ class AcpRuntime { const settled = this.call(this.connection.prompt(this.promptParams(input.prompt))).then( async (response): Promise => { await this.drainNotifications(); + activePrompt.wirePromptsInFlight -= 1; const correlation = this.promptCorrelation(response); const sharedExecution = correlation?.turnId != null && correlation.role !== "none"; if (response.usage && !sharedExecution) { @@ -1157,8 +1334,22 @@ class AcpRuntime { usage: this.lastUsage, }); } - if (this.activePrompt?.turnId === turnId) this.activePrompt = null; const state = response.stopReason === "cancelled" ? "canceled" : "completed"; + if ( + response.stopReason === "end_turn" && + !sharedExecution && + this.options.options.acpOptions?.deferTurnOnRunningTools !== undefined + ) { + // Release the wire first: updates that follow end_turn (a tool reclassified as a + // daemon) decide whether to defer, and settling a deferred turn waits on them. + releaseResponse(); + await this.drainNotifications(); + if (this.shouldDeferTurn(activePrompt)) { + await this.settleDeferredPrompt(activePrompt); + return undefined; + } + } + if (this.activePrompt?.turnId === turnId) this.activePrompt = null; this.finishTurnPermissions(turnId); if (correlation === null || correlation.role === "none" || correlation.turnId === null) { this.endLocalTurn(turnId, state); @@ -1171,6 +1362,7 @@ class AcpRuntime { }, async (error): Promise => { await this.drainNotifications(); + activePrompt.wirePromptsInFlight -= 1; this.finishTurnPermissions(turnId); if (this.activePrompt?.turnId === turnId) this.activePrompt = null; this.endLocalTurn(turnId, "failed", { message: describeError(error) }); @@ -1178,14 +1370,15 @@ class AcpRuntime { return undefined; }, ); - this.activePrompt = { turnId, settled, cancelling: false }; + activePrompt.settled = settled; + this.activePrompt = activePrompt; void settled.finally(() => { this.expireSteerEcho(input.prompt.clientMessageId); if (this.activePrompt?.turnId === turnId) this.activePrompt = null; }); } - interrupt(): Promise { + interrupt(): Promise { // A prompt parked behind a vendor turn has not reached the agent, so a session-wide cancel // would not stop it: drop every prompt admitted before the stop here instead. this.stopGeneration += 1; @@ -1212,15 +1405,74 @@ class AcpRuntime { return this.interruptTurn(); } - private async interruptTurn(): Promise { + private async interruptTurn(): Promise { + if (this.deferredRetirement) return this.deferredRetirement; const active = this.activePrompt; + const deferredTurnId = active?.deferred ? active.turnId : null; + if (active && deferredTurnId) { + const retirement = this.retireDeferredTurn(active, deferredTurnId).catch((error) => { + if (this.deferredRetirement === retirement) this.deferredRetirement = null; + throw error; + }); + this.deferredRetirement = retirement; + return retirement; + } if (active) active.cancelling = true; try { await this.call(this.connection.cancel({ sessionId: this.nativeSessionId })); } finally { // An agent may wait for its outstanding permission replies before ending the prompt. - if (active) this.finishTurnPermissions(active.turnId); + if (active) { + this.finishTurnPermissions(active.turnId); + } + } + return false; + } + + private finalizeDeferredTurn(deferredTurnId: string, emitRetired: boolean): void { + if (this.deferredFinalized) return; + this.deferredFinalized = true; + this.endLocalTurn(deferredTurnId, "canceled", undefined, { + suppressTrailingToolEcho: true, + }); + if (emitRetired) this.options.onRetired?.(); + } + + private async retireDeferredTurn(active: ActivePrompt, deferredTurnId: string): Promise { + active.cancelling = true; + // Record open tools owned by Stop before writing session/cancel so any failure + // update arriving during cancel preserves their canceled state. + for (const id of this.liveOpenToolIds) this.canceledToolCallIds.add(id); + let cancelTimedOut = false; + if (!this.closing) { + try { + await withTimeout( + this.call(this.connection.cancel({ sessionId: this.nativeSessionId })), + 1_000, + `ACP session ${this.nativeSessionId} did not accept cancel`, + ); + } catch { + cancelTimedOut = true; + } finally { + // An agent may wait for its outstanding permission replies before ending the prompt. + this.finishTurnPermissions(active.turnId); + } } + // ACP v1 has no response or end boundary for session/cancel once session/prompt + // already returned. Close the process first while the turn still appears running, + // then emit the canceled turn synchronously before request.completed and session.closed + // so queued work and config changes immediately observe the retired session. + try { + await this.close({ force: cancelTimedOut, timeoutMs: 1_000 }); + } catch (error) { + void this.whenConnectorClosed()?.then( + () => this.finalizeDeferredTurn(deferredTurnId, true), + () => undefined, + ); + throw error; + } + this.finalizeDeferredTurn(deferredTurnId, false); + return true; } /** @@ -1237,22 +1489,23 @@ class AcpRuntime { }, VENDOR_TURN_CANCEL_GRACE_MS); } - /** Follows `nextCursor` until the requested limit is reached or the agent has no more pages. */ - async listSessions(cwd?: string, limit?: number): Promise { - const sessions: ListSessionsResponse["sessions"] = []; + /** Follows `nextCursor` until `limit` sessions, the last page, or the scan cap. */ + async listSessions({ cwd, limit }: { cwd?: string; limit?: number }): Promise { + const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT); + const sessions: SessionInfo[] = []; const seen = new Set(); - let cursor: string | null | undefined; - for (;;) { - const response = await this.call(this.connection.listSessions({ cwd, cursor })); - sessions.push(...response.sessions); - cursor = response.nextCursor; - if (!cursor) break; - // An agent that repeats a cursor would otherwise page forever. - if (seen.has(cursor)) break; - seen.add(cursor); - if (limit !== undefined && sessions.length >= limit) break; - } - return limit === undefined ? sessions : sessions.slice(0, limit); + let cursor: string | undefined; + do { + const page = await this.call(this.connection.listSessions({ cwd, cursor })); + sessions.push(...page.sessions); + cursor = page.nextCursor ?? undefined; + if (cursor !== undefined) { + // An agent that repeats a cursor would otherwise page forever. + if (seen.has(cursor)) break; + seen.add(cursor); + } + } while (cursor && sessions.length < wanted); + return sessions.slice(0, wanted); } async drainNotifications(): Promise { @@ -1301,6 +1554,7 @@ class AcpRuntime { sessionId: this.options.boundarySessionId, permissionId, }); + if (this.activePrompt?.deferred) this.scheduleDeferredSettle(); } async configure( @@ -1428,11 +1682,20 @@ class AcpRuntime { await this.close(); } - async close(): Promise { - if (this.closing) return; + close(options?: { force?: boolean; timeoutMs?: number }): Promise { + if (this.closePromise) return this.closePromise; this.closing = true; + const promise = this.closeInternal(options).catch((error) => { + if (this.closePromise === promise) this.closePromise = null; + throw error; + }); + this.closePromise = promise; + return promise; + } + + private async closeInternal(options?: { force?: boolean; timeoutMs?: number }): Promise { this.settlePendingWork(); - await this.closeConnector(); + await this.closeConnector(options); const child = this.child; if (!child) return; if (child.exitCode !== null || child.signalCode !== null) return; @@ -1451,28 +1714,62 @@ class AcpRuntime { const requested: AcpConfigChange[] = []; if (config.model) requested.push({ target: "model", value: config.model }); const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode; - const mode = config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined); + // Without an unattended mode, auto_accept is the fork's local setting, not a legacy toggle. + const { settings, legacyAutoAccept } = autoAcceptMode + ? this.withoutLegacyAutoAccept(config.settings) + : { settings: config.settings, legacyAutoAccept: false }; + // The toggle stays saved after a mode is chosen here, so it counts only while the saved mode + // is one the generic adapter wrote. + const mode = + legacyAutoAccept && autoAcceptMode && !this.offersMode(config.mode) + ? autoAcceptMode.mode.id + : (config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined)); if (mode) requested.push({ target: "mode", value: mode }); if (config.thinkingOption) { requested.push({ target: "thinking", value: config.thinkingOption }); } - for (const [id, value] of Object.entries(config.settings)) { + for (const [id, value] of Object.entries(settings)) { requested.push({ target: "setting", id, value }); } for (const change of this.inAgentOrder(requested)) { - const current = toProviderConfigState(this.modes, this.configOptions); - if (change.target === "model" && change.value === current.model) continue; - if (change.target === "mode" && change.value === current.mode) continue; - if (change.target === "thinking" && change.value === current.thinkingOption) continue; - if ( - change.target === "setting" && - change.value === configValues(this.configOptions)[change.id] - ) - continue; + if (this.isEffectiveConfig(change)) continue; await this.applyConfigChange(change); } } + /** Whether the agent already reports this value, so applying it again would be a no-op. */ + private isEffectiveConfig(change: AcpConfigChange): boolean { + const current = toProviderConfigState(this.modes, this.configOptions); + switch (change.target) { + case "model": + return change.value === current.model; + case "mode": + return change.value === current.mode; + case "thinking": + return change.value === current.thinkingOption; + case "setting": + return change.value === configValues(this.configOptions)[change.id]; + } + } + + private offersMode(mode: string | undefined): boolean { + if (mode === undefined) return false; + if (mode === this.options.options.acpOptions?.autoAcceptMode?.mode.id) return true; + return toProviderCatalog(this.modes, this.configOptions).modes.some(({ id }) => id === mode); + } + + /** Reads the generic ACP adapter's saved Auto Accept toggle unless the agent has such a setting. */ + private withoutLegacyAutoAccept(settings: Readonly>): { + settings: Readonly>; + legacyAutoAccept: boolean; + } { + if (this.configOptions.some((option) => option.id === LEGACY_AUTO_ACCEPT_SETTING)) { + return { settings, legacyAutoAccept: false }; + } + const { [LEGACY_AUTO_ACCEPT_SETTING]: saved, ...rest } = settings; + return { settings: rest, legacyAutoAccept: saved === true }; + } + // One option can reset another: choosing an fx provider also selects that provider's saved // model, so a model applied first would be lost. Agents list the option that decides first. private inAgentOrder(changes: readonly AcpConfigChange[]): AcpConfigChange[] { @@ -1519,16 +1816,13 @@ class AcpRuntime { this.autoAccept = enableAutoAccept; return; } - const access = this.configAccess(); + const context: AcpConfigureContext = { + ...this.configContext(), + catalog: () => toProviderCatalog(this.modes, this.configOptions), + apply: (nativeChange) => this.applyNativeConfigChange(nativeChange), + }; for (const transformer of this.transformers) { - if ( - (await transformer.configure?.(change, { - sessionId: this.options.boundarySessionId, - config: access, - catalog: () => toProviderCatalog(this.modes, this.configOptions), - apply: (nativeChange) => this.applyNativeConfigChange(nativeChange), - })) === "handled" - ) { + if ((await transformer.configure?.(change, context)) === "handled") { return; } } @@ -1568,7 +1862,20 @@ class AcpRuntime { this.configOptions = response.configOptions; } - configAccess(): AcpConfigAccess { + configContext() { + return { + sessionId: this.options.boundarySessionId, + config: this.configAccess(), + request: this.request, + }; + } + + private readonly request: AcpRequest = async (method, params) => + jsonValue( + await this.call(this.connection.extMethod(method, params as Record)), + ); + + private configAccess(): AcpConfigAccess { return { read: async () => configValues(this.configOptions), set: async (id, value) => { @@ -1613,6 +1920,10 @@ class AcpRuntime { modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }], }; } + const context = { sessionId: this.options.boundarySessionId }; + for (const transformer of this.transformers) { + config = transformer.config?.(config, context) ?? config; + } this.emit({ type: "session.config", sessionId: this.options.boundarySessionId, @@ -1674,8 +1985,10 @@ class AcpRuntime { } } const permissionId = `permission:${request.toolCall.toolCallId}`; + const { presentation } = this.presentToolCall(request.toolCall); return new Promise((resolve) => { this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId }); + if (this.activePrompt?.deferred) this.scheduleDeferredSettle(); this.emit({ type: "session.permission", sessionId: this.options.boundarySessionId, @@ -1685,6 +1998,7 @@ class AcpRuntime { kind: "tool", title: request.toolCall.title ?? undefined, input: jsonRecord(request.toolCall.rawInput), + detail: toolCallDetail(presentation), actions: request.options.map((option) => ({ id: option.optionId, label: option.name, @@ -1695,21 +2009,41 @@ class AcpRuntime { }); } - private sessionUpdate(notification: SessionNotification): void { + private observeWireMessage(message: unknown): void { + if (typeof message !== "object" || message === null) return; + const record = message as Record; + if (record.method === "session/update") { + this.sessionUpdateWireSeqs.push(++this.incomingWireSeq); + return; + } + if ( + !("method" in record) && + "id" in record && + typeof record.result === "object" && + record.result !== null && + typeof (record.result as Record).stopReason === "string" && + this.activePrompt && + this.activePrompt.lastPromptResponseWireSeq === null + ) { + this.activePrompt.lastPromptResponseWireSeq = ++this.incomingWireSeq; + } + } + + private isPostWirePrompt(active: ActivePrompt, wireSeq: number): boolean { + return active.lastPromptResponseWireSeq !== null && wireSeq > active.lastPromptResponseWireSeq; + } + + private sessionUpdate(notification: SessionNotification, wireSeq: number): void { // The attachment has been left. Late updates belong to work the agent kept running for // another client and must not be rendered here. if (this.detached) return; if (notification.sessionId !== this.nativeSessionId) return; - if (this.replayWindow) this.lastLoadUpdateAt = performance.now(); + if (this.replayWindow && isReplayHistoryUpdate(notification.update)) { + this.lastLoadHistoryAt = performance.now(); + } if (this.replayWindow === "skip" && !this.vendorTurn) { - const update = notification.update; - if ( - update.sessionUpdate === "available_commands_update" || - update.sessionUpdate === "config_option_update" || - update.sessionUpdate === "current_mode_update" || - update.sessionUpdate === "usage_update" - ) { - this.reduceStateUpdate(update); + if (isSessionStateUpdate(notification.update)) { + this.reduceStateUpdate(notification.update, wireSeq); } return; } @@ -1730,7 +2064,7 @@ class AcpRuntime { if (next) { const [clientMessageId, steer] = next; const turnId = `acp:${clientMessageId}`; - this.activePrompt = { turnId, settled: steer.settled, cancelling: false }; + this.activePrompt = newActivePrompt(turnId, steer.settled); this.fallbackChunkIds.clear(); this.emit({ type: "session.turn", @@ -1747,10 +2081,10 @@ class AcpRuntime { this.reduceUserMessageChunk(notification.update); return; } - this.reduceUpdate(notification.update); + this.reduceUpdate(notification.update, wireSeq); } - private reduceUpdate(update: SessionUpdate): void { + private reduceUpdate(update: SessionUpdate, wireSeq: number): void { if (update.sessionUpdate !== "user_message_chunk") this.flushBufferedUserChunk(); if ( update.sessionUpdate === "agent_message_chunk" || @@ -1785,15 +2119,16 @@ class AcpRuntime { : {}), }, }); + this.noteDeferredChunk(update.sessionUpdate, wireSeq); return; } if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") { if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear(); - this.reduceToolCall(update); + this.reduceToolCall(update, wireSeq); return; } if (update.sessionUpdate === "plan") this.fallbackChunkIds.clear(); - this.reduceStateUpdate(update); + this.reduceStateUpdate(update, wireSeq); } private reduceLiveUserChunk( @@ -1889,7 +2224,7 @@ class AcpRuntime { return id; } - private reduceStateUpdate(update: SessionUpdate): void { + private reduceStateUpdate(update: SessionUpdate, wireSeq: number): void { if (update.sessionUpdate === "plan") { this.emit({ type: "timeline.item", @@ -1951,6 +2286,7 @@ class AcpRuntime { turnId: this.vendorTurn?.turnId ?? this.activePrompt?.turnId, usage: this.lastUsage, }); + this.noteDeferredUsageUpdate(wireSeq); return; } if (update.sessionUpdate === "compaction_update") { @@ -1965,17 +2301,29 @@ class AcpRuntime { status: update.status === "completed" ? "completed" : "loading", }, }); + if (this.activePrompt?.deferred) this.scheduleDeferredSettle(); } } - private terminalizeTransientItems(state: "completed" | "failed" | "canceled"): void { - for (const [id, snapshot] of this.toolCalls) { + private terminalizeTransientItems( + state: "completed" | "failed" | "canceled", + options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean }, + ): void { + const preserve = options?.preserveQualifyingOpenTools === true; + for (const [id, tool] of this.toolCalls) { + const snapshot = tool.presentation; if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue; + if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot)) continue; + this.liveOpenToolIds.delete(id); + if (options?.suppressTrailingToolEcho) this.canceledToolCallIds.add(id); const completed: AcpToolCallSnapshot = { ...snapshot, status: state === "completed" ? "completed" : "failed", }; - this.toolCalls.set(id, completed); + this.toolCalls.set(id, { + source: { ...tool.source, status: completed.status }, + presentation: completed, + }); this.emit({ type: "timeline.item", sessionId: this.options.boundarySessionId, @@ -2000,18 +2348,55 @@ class AcpRuntime { this.pendingCompactions.clear(); } - private reduceToolCall(update: ToolCall | ToolCallUpdate): void { - const current = this.toolCalls.get(update.toolCallId); - let snapshot = mergeToolCallSnapshot(update, current); - const context = { sessionId: this.options.boundarySessionId }; + /** Merges an update into the call's earlier updates and runs it through the transformers. */ + private presentToolCall(update: ToolCall | ToolCallUpdate): AcpToolCallState { + const tool = this.toolCalls.get(update.toolCallId); + const source = mergeToolCallSnapshot(update, tool?.source); + const context = { + sessionId: this.options.boundarySessionId, + mcpServerNames: this.mcpServerNames, + previous: tool?.presentation, + }; + let presentation: AcpToolCallSnapshot = source; for (const transformer of this.transformers) - snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot; - this.toolCalls.set(snapshot.id, snapshot); + presentation = transformer.toolCall?.(presentation, context) ?? presentation; + return { source, presentation }; + } + + private reduceToolCall( + update: Extract, + wireSeq: number, + ): void { + if ( + update.sessionUpdate === "tool_call_update" && + this.canceledToolCallIds.has(update.toolCallId) + ) { + return; + } + if (update.sessionUpdate === "tool_call") { + this.canceledToolCallIds.delete(update.toolCallId); + } + const tool = this.toolCalls.get(update.toolCallId); + const current = tool?.presentation; + const wasOpenQualifying = + current !== undefined && + this.liveOpenToolIds.has(current.id) && + this.toolKeepsTurnOpen(current); + const { source, presentation: snapshot } = this.presentToolCall(update); + this.toolCalls.set(snapshot.id, { source, presentation: snapshot }); + const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress"; + if (this.replayWindow === null) { + if (isOpen) this.liveOpenToolIds.add(snapshot.id); + else this.liveOpenToolIds.delete(snapshot.id); + } this.emit({ type: "timeline.item", sessionId: this.options.boundarySessionId, item: toolTimelineItem(snapshot), }); + const isOpenQualifying = + this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot); + this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq); } /** @@ -2181,16 +2566,18 @@ class AcpRuntime { private handleUnexpectedTransportClose(): void { if (this.closing || this.processFailed) return; + const message = "ACP transport closed unexpectedly"; this.processFailed = true; + this.processFailureMessage = message; this.endVendorTurn("failed", { message: "ACP transport closed" }); if (this.nativeSessionId) { this.emit({ type: "session.runtime_failed", sessionId: this.options.boundarySessionId, - error: { message: "ACP transport closed unexpectedly" }, + error: { message }, }); } - this.settlePendingWork(); + this.settlePendingWork(message); } private emitPendingWork(pending: boolean): void { @@ -2203,7 +2590,7 @@ class AcpRuntime { if (wasPending) this.emitPendingWork(false); } - private settlePendingWork(): void { + private settlePendingWork(failureMessage?: string): void { this.promptResponses.flush(); this.clearOutstandingSteers(); // A user-initiated close leaves the peer turn running on the agent's side, so it was @@ -2217,10 +2604,281 @@ class AcpRuntime { permission.resolve({ outcome: { outcome: "cancelled" } }); } this.permissions.clear(); + if (this.activePrompt?.deferred) { + this.finishDeferredTurn( + this.activePrompt, + failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" }, + ); + } this.commandWaiter?.(); this.commandWaiter = null; } + private finishPromptTurn( + turnId: string, + state: "completed" | "failed" | "canceled", + error?: { message: string }, + options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean }, + ): void { + this.fallbackChunkIds.clear(); + this.terminalizeTransientItems(state, options); + this.finishTurnPermissions(turnId); + this.emit({ + type: "session.turn", + sessionId: this.options.boundarySessionId, + turnId, + state, + ...(error === undefined ? {} : { error }), + }); + } + + private steerDeferredPrompt(input: Extract): void { + const active = this.activePrompt; + const deferred = active?.deferred; + if (!active || !deferred || active.cancelling || this.closing || this.processFailed) { + this.emit({ + type: "session.prompt_result", + sessionId: this.options.boundarySessionId, + clientMessageId: input.prompt.clientMessageId, + result: { + type: "failed", + error: { + message: "ACP session can only steer while waiting on deferred background tools", + }, + }, + }); + return; + } + if (input.prompt.clearPendingPermissions) { + this.finishTurnPermissions(active.turnId); + } + const prompt = toAcpPrompt(input.prompt); + active.wirePromptsInFlight += 1; + this.scheduleDeferredSettle(); + this.replayWindow = null; + this.fallbackChunkIds.clear(); + this.emit({ + type: "timeline.item", + sessionId: this.options.boundarySessionId, + item: { + type: "user_message", + id: input.prompt.clientMessageId, + text: prompt + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"), + clientMessageId: input.prompt.clientMessageId, + }, + }); + this.emit({ + type: "session.prompt_result", + sessionId: this.options.boundarySessionId, + clientMessageId: input.prompt.clientMessageId, + result: { type: "steer", turnId: active.turnId }, + }); + const runSteer = async (): Promise => { + try { + if ( + this.closing || + this.processFailed || + active.cancelling || + active.deferred !== deferred + ) { + return; + } + this.fallbackChunkIds.clear(); + active.lastPromptResponseWireSeq = null; + if (active.replyState === "settled_with_open_tools") active.replyState = "idle"; + const response = await this.call( + this.connection.prompt({ sessionId: this.nativeSessionId, prompt }), + ); + await this.drainNotifications(); + if (this.closing || this.deferredRetirement || active.deferred !== deferred) return; + if (response.usage) { + this.lastUsage = { + ...this.lastUsage, + inputTokens: response.usage.inputTokens, + outputTokens: response.usage.outputTokens, + cachedInputTokens: response.usage.cachedReadTokens ?? undefined, + }; + this.emit({ + type: "session.usage", + sessionId: this.options.boundarySessionId, + turnId: active.turnId, + usage: this.lastUsage, + }); + } + if (response.stopReason === "cancelled") { + this.finishDeferredTurn(active, { type: "cancel" }); + return; + } + if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) { + this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true }); + } + } catch (error) { + await this.drainNotifications(); + if (this.closing || this.deferredRetirement || active.deferred !== deferred) return; + if (this.processFailed) { + this.finishDeferredTurn(active, { + type: "fail", + error: { message: describeError(error) }, + }); + } else { + this.emit({ + type: "session.notice", + sessionId: this.options.boundarySessionId, + notice: { + id: `acp:steer-error:${input.prompt.clientMessageId}`, + severity: "error", + title: "Follow-up prompt failed", + description: describeError(error), + }, + }); + } + } finally { + if (active.lastPromptResponseWireSeq === null) { + active.lastPromptResponseWireSeq = this.incomingWireSeq; + } + active.wirePromptsInFlight -= 1; + this.scheduleDeferredSettle(); + } + }; + active.wirePromptLane = active.wirePromptLane.then(runSteer); + } + + private async settleDeferredPrompt(active: ActivePrompt): Promise { + this.fallbackChunkIds.clear(); + const outcome = await new Promise((resolve) => { + active.deferred = { timer: null, resolve }; + this.scheduleDeferredSettle(); + }); + if (this.closing || this.deferredRetirement) return; + if (outcome.type === "fail") { + this.endLocalTurn(active.turnId, "failed", outcome.error); + return; + } + this.endLocalTurn( + active.turnId, + outcome.type === "cancel" ? "canceled" : "completed", + undefined, + { + preserveQualifyingOpenTools: outcome.type === "complete" && !outcome.terminalizeTools, + suppressTrailingToolEcho: outcome.type === "cancel", + }, + ); + } + + private toolKeepsTurnOpen(snapshot: AcpToolCallSnapshot): boolean { + const defer = this.options.options.acpOptions?.deferTurnOnRunningTools; + if (!defer) return false; + return defer.keepsTurnOpen ? defer.keepsTurnOpen(snapshot) : true; + } + + private hasQualifyingOpenTools(): boolean { + for (const id of this.liveOpenToolIds) { + const snapshot = this.toolCalls.get(id)?.presentation; + if (snapshot && this.toolKeepsTurnOpen(snapshot)) return true; + } + return false; + } + + private hasDeferredBlockers(): boolean { + return ( + (this.activePrompt?.wirePromptsInFlight ?? 0) > 0 || + this.hasQualifyingOpenTools() || + this.permissions.size > 0 || + this.pendingCompactions.size > 0 + ); + } + + private shouldDeferTurn(active: ActivePrompt): boolean { + if (!this.options.options.acpOptions?.deferTurnOnRunningTools) return false; + if (active.cancelling || this.closing || this.processFailed) return false; + return this.hasQualifyingOpenTools() || active.crossedEndTurn; + } + + private finishDeferredTurn(active: ActivePrompt, outcome: DeferredTurnOutcome): void { + const deferred = active.deferred; + if (!deferred) return; + if (deferred.timer) clearTimeout(deferred.timer); + active.deferred = null; + deferred.resolve(outcome); + } + + private noteDeferredToolTransition( + wasOpenQualifying: boolean, + isOpenQualifying: boolean, + isOpen: boolean, + snapshot: AcpToolCallSnapshot, + wireSeq: number, + ): void { + const active = this.activePrompt; + if (!active || wasOpenQualifying === isOpenQualifying) return; + if (!active.deferred && !this.isPostWirePrompt(active, wireSeq)) return; + if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) { + active.crossedEndTurn = true; + } + if (isOpenQualifying) active.replyState = "idle"; + if (active.deferred) this.scheduleDeferredSettle(); + } + + private noteDeferredChunk( + kind: "agent_message_chunk" | "agent_thought_chunk", + wireSeq: number, + ): void { + const active = this.activePrompt; + if (!active || !this.isPostWirePrompt(active, wireSeq)) return; + if (kind === "agent_message_chunk") active.replyState = "open"; + else if (active.replyState !== "open") active.replyState = "idle"; + if (active.deferred) this.scheduleDeferredSettle(); + } + + private noteDeferredUsageUpdate(wireSeq: number): void { + const active = this.activePrompt; + if (!active || !this.isPostWirePrompt(active, wireSeq) || active.replyState !== "open") return; + active.replyState = this.hasQualifyingOpenTools() ? "settled_with_open_tools" : "settled"; + if (active.deferred) this.scheduleDeferredSettle(); + } + + private scheduleDeferredSettle(): void { + const active = this.activePrompt; + const deferred = active?.deferred; + const config = this.options.options.acpOptions?.deferTurnOnRunningTools; + if (!active || !deferred || !config || active.cancelling) return; + if (deferred.timer) { + clearTimeout(deferred.timer); + deferred.timer = null; + } + if (this.hasDeferredBlockers()) return; + const settled = + active.replyState === "settled" || active.replyState === "settled_with_open_tools"; + const delayMs = settled + ? (config.settleDelayMs ?? DEFAULT_DEFERRED_SETTLE_DELAY_MS) + : (config.quietLimitMs ?? DEFAULT_DEFERRED_QUIET_LIMIT_MS); + deferred.timer = setTimeout(() => { + deferred.timer = null; + void this.trySettleDeferredTurn(active, deferred); + }, delayMs); + } + + private async trySettleDeferredTurn( + active: ActivePrompt, + deferred: DeferredTurnState, + ): Promise { + await this.drainNotifications(); + if ( + this.closing || + this.processFailed || + active.cancelling || + active.deferred !== deferred || + deferred.timer !== null || + this.hasDeferredBlockers() + ) { + return; + } + this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true }); + } + private waitForInitialCommands(): Promise { if (this.receivedInitialCommands) return Promise.resolve(); const timeoutMs = this.options.options.acpOptions?.initialCommandsTimeoutMs ?? 1_000; @@ -2234,24 +2892,92 @@ class AcpRuntime { }); } - private async waitForLoadReplay(quietPeriod: number): Promise { + private notePartialWireRead(): void { + if (this.replayWindow) this.lastPartialWireAt = performance.now(); + } + + // An agent that streams history after its session/load response sends no end marker, + // so the history ends once a quiet period passes without a history update. + private async waitForLoadReplay( + quietPeriod: number, + isConnectionClosed: () => boolean, + ): Promise { const start = performance.now(); - const deadline = start + 5 * quietPeriod; - while (!this.closing && !this.processFailed) { - const idleAt = Math.max(start, this.lastLoadUpdateAt) + quietPeriod; - const remaining = Math.min(deadline, idleAt) - performance.now(); - if (remaining <= 0) return; - await new Promise((resolve) => setTimeout(resolve, remaining)); + while (!this.closing && !this.processFailed && !isConnectionClosed()) { + const lastActivityAt = Math.max(start, this.lastLoadHistoryAt, this.lastPartialWireAt); + const remaining = lastActivityAt + quietPeriod - performance.now(); + // A stalled event loop reaches the quiet period with history still unread in the pipe. + // setImmediate lets the loop read pending input once before the silence is trusted. + await new Promise((resolve) => { + if (remaining > 0) setTimeout(resolve, remaining); + else setImmediate(resolve); + }); await this.notificationLane; + if ( + remaining <= 0 && + Math.max(start, this.lastLoadHistoryAt, this.lastPartialWireAt) === lastActivityAt + ) { + return; + } } } } -function routeVendorNotifications( +function observePartialWireReads( + input: ReadableStream, + onPartialRead: () => void, +): ReadableStream { + let incompleteLine = false; + return input.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + const wasIncomplete = incompleteLine; + incompleteLine = hasTrailingIncompleteLine(chunk, incompleteLine); + if (wasIncomplete || incompleteLine) onPartialRead(); + controller.enqueue(chunk); + }, + }), + ); +} + +function hasTrailingIncompleteLine(chunk: Uint8Array, incompleteLine: boolean): boolean { + const newline = chunk.lastIndexOf(0x0a); + const start = newline === -1 ? 0 : newline + 1; + if (newline !== -1) incompleteLine = false; + for (let index = start; index < chunk.length; index += 1) { + const byte = chunk[index]; + if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0d) return true; + } + return incompleteLine; +} + +function isReplayHistoryUpdate(update: SessionUpdate): boolean { + return ( + update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" || + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "compaction_update" + ); +} + +function isSessionStateUpdate(update: SessionUpdate): boolean { + return ( + update.sessionUpdate === "available_commands_update" || + update.sessionUpdate === "config_option_update" || + update.sessionUpdate === "current_mode_update" || + update.sessionUpdate === "usage_update" + ); +} + +function routeIncomingMessages( stream: Stream, - receive: (method: string, params: unknown) => Promise, + receiveVendor: (method: string, params: unknown) => Promise, updateSlots: UpdateSlots, promptResponses: PromptResponseOrder, + observeWire: (message: unknown) => void, ): Stream { const clientMethods = new Set(Object.values(CLIENT_METHODS)); const writer = stream.writable.getWriter(); @@ -2276,7 +3002,7 @@ function routeVendorNotifications( // Awaiting holds every later message back until this one's updates are applied, so a // session/update that follows it on the wire cannot reach the lane ahead of it. try { - await receive(message.method, message.params); + await receiveVendor(message.method, message.params); } catch (error) { console.error("Error handling ACP vendor notification", error); } @@ -2288,6 +3014,7 @@ function routeVendorNotifications( updateSlots.admit(message.params); } } + observeWire(message); if (!("method" in message) && "id" in message) { const boundary = promptResponses.response(message.id); if (boundary) { @@ -2491,11 +3218,12 @@ function permissionOptionBehavior( function ownConnectorStream(source: Stream): { stream: Stream; - close(): Promise; + close(options?: { force?: boolean; timeoutMs?: number }): Promise; + whenClosed(): Promise | null; } { const reader = source.readable.getReader(); const writer = source.writable.getWriter(); - let closed = false; + let closing: Promise | null = null; const stream: Stream = { readable: new ReadableStream({ async pull(controller) { @@ -2517,13 +3245,29 @@ function ownConnectorStream(source: Stream): { }; return { stream, - async close() { - if (closed) return; - closed = true; - await Promise.allSettled([ - reader.cancel(new Error("Paseo closed the ACP connector")), - writer.close(), - ]); + whenClosed: () => closing, + async close(options?: { force?: boolean; timeoutMs?: number }) { + if (!closing) { + const closeWrite = options?.force + ? writer.abort(new Error("Paseo aborted the ACP connector")) + : writer.close(); + closing = Promise.allSettled([ + reader.cancel(new Error("Paseo closed the ACP connector")), + closeWrite, + ]).then((results) => { + if (options?.timeoutMs === undefined) return undefined; + const rejected = results.find( + (result): result is PromiseRejectedResult => result.status === "rejected", + ); + if (rejected) throw rejected.reason; + return undefined; + }); + } + if (options?.timeoutMs !== undefined) { + await withTimeout(closing, options.timeoutMs, "ACP connector did not close"); + } else { + await closing.catch(() => undefined); + } }, }; } @@ -2541,6 +3285,7 @@ function mergeToolCallSnapshot( input: jsonValue(firstDefined(update.rawInput, current?.input, null)), output: jsonValue(firstDefined(update.rawOutput, current?.output, null)), locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [], + content: update.content === undefined ? current?.content : jsonValue(update.content), }; } @@ -2740,21 +3485,12 @@ function configValues( type ToolCallTimelineItem = Extract; +function toolCallDetail(snapshot: AcpToolCallSnapshot): ProviderToolCallDetail { + return snapshot.detail ?? standardToolCallDetail(snapshot); +} + function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem { - const input = jsonRecord(snapshot.input); - const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true; - const detail = - snapshot.detail ?? - (isEdit - ? { - type: "edit" as const, - filePath: - typeof input.filePath === "string" ? input.filePath : (snapshot.locations[0] ?? ""), - oldString: typeof input.oldString === "string" ? input.oldString : undefined, - newString: typeof input.newString === "string" ? input.newString : undefined, - unifiedDiff: typeof input.unifiedDiff === "string" ? input.unifiedDiff : undefined, - } - : { type: "unknown" as const, input: snapshot.input, output: snapshot.output }); + const detail = toolCallDetail(snapshot); const status = snapshot.status === "in_progress" || snapshot.status === "pending" ? "running" @@ -2789,6 +3525,7 @@ function jsonValue(value: unknown) { } function jsonRecord(value: unknown): Record> { + if (value === undefined) return {}; const parsed = jsonValue(value); if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; return parsed; diff --git a/packages/plugin/src/server/acp-internal/tool-call-detail.ts b/packages/plugin/src/server/acp-internal/tool-call-detail.ts new file mode 100644 index 000000000000..ce46b505d819 --- /dev/null +++ b/packages/plugin/src/server/acp-internal/tool-call-detail.ts @@ -0,0 +1,164 @@ +import type { JsonValue } from "@getpaseo/protocol/agent-types"; +import type { AcpToolCallSnapshot } from "../acp.js"; +import type { ProviderToolCallDetail } from "../provider.js"; + +type JsonRecord = Readonly>; + +interface ToolCallParts { + call: AcpToolCallSnapshot; + input: JsonRecord; + output: JsonRecord; + text: string | undefined; +} + +type KindDetail = (parts: ToolCallParts) => ProviderToolCallDetail; + +const KIND_DETAILS = new Map( + Object.entries({ + read: ({ call, input, output, text }) => ({ + type: "read", + filePath: call.locations[0] ?? string(input, "path", "filePath", "file") ?? call.title, + content: text ?? string(output, "content", "text"), + offset: number(input, "offset", "line"), + limit: number(input, "limit"), + }), + edit: editDetail, + delete: editDetail, + search: ({ call, input, output, text }) => ({ + type: "search", + query: string(input, "query", "pattern") ?? call.title, + toolName: "search", + content: text ?? string(output, "content", "text"), + filePaths: call.locations.length > 0 ? [...call.locations] : undefined, + }), + execute: ({ call, input, output, text }) => ({ + type: "shell", + command: shellCommand(input) ?? call.title, + cwd: string(input, "cwd"), + output: text ?? string(output, "output", "text"), + exitCode: number(output, "exitCode"), + }), + fetch: ({ call, input, output, text }) => ({ + type: "fetch", + url: string(input, "url") ?? call.title, + prompt: string(input, "prompt"), + result: text ?? string(output, "result", "text", "content"), + code: number(output, "status", "code"), + }), + think: ({ call, text }) => ({ type: "plain_text", label: call.title, icon: "brain", text }), + switch_mode: ({ call, text }) => ({ + type: "plain_text", + label: call.title, + icon: "sparkles", + text, + }), + } satisfies Record), +); + +/** + * The row for a tool call whose transformers set no detail, read from the call's ACP `kind`, + * `rawInput`, `rawOutput`, `content` and `locations` the way the ACP spec defines them. + */ +export function standardToolCallDetail(call: AcpToolCallSnapshot): ProviderToolCallDetail { + const parts: ToolCallParts = { + call, + input: record(call.input), + output: record(call.output), + text: contentText(call.content), + }; + const kindDetail = call.kind === undefined ? undefined : KIND_DETAILS.get(call.kind); + if (kindDetail) return kindDetail(parts); + if (call.name?.toLowerCase().includes("edit")) return editDetail(parts); + // Raw input or output is the most a client can show for a tool it does not know. + if (parts.text !== undefined && call.input === null && call.output === null) { + return { type: "plain_text", label: call.title, icon: "wrench", text: parts.text }; + } + return { type: "unknown", input: call.input, output: call.output }; +} + +function editDetail({ call, input, text }: ToolCallParts): ProviderToolCallDetail { + const diff = contentDiff(call.content); + const filePath = + diff?.path ?? string(input, "filePath", "path", "file") ?? call.locations[0] ?? ""; + if (call.kind === "delete") { + return { + type: "edit", + filePath, + oldString: diff?.oldText ?? fileText(input, "oldText"), + newString: "", + unifiedDiff: text, + }; + } + return { + type: "edit", + filePath, + oldString: diff?.oldText ?? fileText(input, "oldString", "oldText"), + newString: diff?.newText ?? fileText(input, "newString", "newText"), + unifiedDiff: string(input, "unifiedDiff") ?? text, + }; +} + +function shellCommand(input: JsonRecord): string | undefined { + const command = string(input, "command"); + if (!command) return undefined; + const args = Array.isArray(input.args) + ? input.args.filter((arg): arg is string => typeof arg === "string") + : []; + return args.length > 0 ? `${command} ${args.join(" ")}` : command; +} + +function contentText(content: JsonValue | undefined): string | undefined { + const parts = contentBlocks(content).flatMap((block) => { + if (block.type !== "content") return []; + const body = record(block.content ?? null); + return body.type === "text" && typeof body.text === "string" && body.text.length > 0 + ? [body.text] + : []; + }); + return parts.length > 0 ? parts.join("\n") : undefined; +} + +function contentDiff( + content: JsonValue | undefined, +): { path?: string; oldText?: string; newText?: string } | undefined { + const diff = contentBlocks(content).find((block) => block.type === "diff"); + if (!diff) return undefined; + return { + path: string(diff, "path"), + oldText: typeof diff.oldText === "string" ? diff.oldText : undefined, + newText: typeof diff.newText === "string" ? diff.newText : undefined, + }; +} + +function contentBlocks(content: JsonValue | undefined): JsonRecord[] { + return Array.isArray(content) ? content.map((block) => record(block)) : []; +} + +function record(value: JsonValue): JsonRecord { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; +} + +function string(value: JsonRecord, ...keys: string[]): string | undefined { + for (const key of keys) { + const entry = value[key]; + if (typeof entry === "string" && entry.trim().length > 0) return entry; + } + return undefined; +} + +/** File text is kept as written: whitespace or an empty string is the edit itself. */ +function fileText(value: JsonRecord, ...keys: string[]): string | undefined { + for (const key of keys) { + const entry = value[key]; + if (typeof entry === "string") return entry; + } + return undefined; +} + +function number(value: JsonRecord, ...keys: string[]): number | undefined { + for (const key of keys) { + const entry = value[key]; + if (typeof entry === "number" && Number.isFinite(entry)) return entry; + } + return undefined; +} diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index 62acef8a5790..86ede8eba9ea 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -1,5 +1,5 @@ import { readFileSync } from "node:fs"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { @@ -16,6 +16,7 @@ import type { } from "./provider.js"; import { afterEach, describe, expect, it, vi } from "vitest"; import { runAcpProvider, type AcpOptions, type AcpStreamMessage } from "./acp.js"; +import type { JsonValue } from "@getpaseo/protocol/agent-types"; // Captured from camerontaylor/jcode 101858d8bc38328cd1bcc148e3973b9cb499a7d6, tests/fixtures/acp. function jcodeCorpusUpdates(name: string, throughResponse?: number): SessionUpdate[] { @@ -89,6 +90,24 @@ async function waitForEvent( return events.find(predicate)!; } +interface ModelThinking { + id: string; + thinkingOptions?: readonly { id: string }[]; + defaultThinkingOptionId?: string; +} + +function modelThinking(model: ModelThinking) { + return { + id: model.id, + thinkingOptions: model.thinkingOptions?.map(optionId), + defaultThinkingOptionId: model.defaultThinkingOptionId, + }; +} + +function optionId(option: { id: string }): string { + return option.id; +} + type AcpRequestMessage = Extract; interface ConnectorInstance { @@ -353,6 +372,378 @@ describe("runAcpProvider", () => { }, ); + it("keeps history that streams after session/load for longer than five quiet periods", async () => { + const sessionId = "connector-session"; + const historyLength = 40; + let stream: ReturnType | undefined; + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + let sent = 0; + stream = setInterval(() => { + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + messageId: `answer-${sent}`, + content: { type: "text", text: `previous answer ${sent}` }, + }, + }); + sent += 1; + if (sent === historyLength) clearInterval(stream); + }, 20); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect(events.filter((event) => event.type === "timeline.item")).toHaveLength(historyLength); + } finally { + clearInterval(stream); + await connection.close(); + } + }); + + it("closes without waiting for history that is still streaming after session/load", async () => { + const sessionId = "connector-session"; + let stream: ReturnType | undefined; + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + stream = setInterval(() => { + if (runtime.readsCanceled) return; + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "previous answer" }, + }, + }); + }, 20); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + await waitForEvent(events, (event) => event.type === "timeline.item"); + const outcome = await Promise.race([ + connection.close().then(() => "closed"), + new Promise((resolve) => setTimeout(() => resolve("still replaying"), 1_000)), + ]); + expect(outcome).toBe("closed"); + } finally { + clearInterval(stream); + } + }); + + it("keeps history left unread while the event loop stalled past the quiet period", async () => { + const sessionId = "connector-session"; + const notifyAnswer = (runtime: ConnectorInstance, text: string) => + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + messageId: text, + content: { type: "text", text }, + }, + }); + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + notifyAnswer(runtime, "read before the stall"); + // Stall after the timers phase, so the overdue quiet timer runs before the next I/O poll. + const stall = () => { + // Like bytes waiting in the agent's pipe: readable only once the loop polls I/O again. + setImmediate(() => notifyAnswer(runtime, "unread during the stall")); + const stalledUntil = performance.now() + 250; + while (performance.now() < stalledUntil); + }; + setTimeout(() => setImmediate(stall), 30); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect( + events.filter((event) => event.type === "timeline.item").map((event) => event.item), + ).toEqual([ + expect.objectContaining({ text: "read before the stall" }), + expect.objectContaining({ text: "unread during the stall" }), + ]); + } finally { + await connection.close(); + } + }); + + it("does not extend the load replay wait for session_info_update notifications", async () => { + const sessionId = "connector-session"; + let stream: ReturnType | undefined; + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "answer-1", + content: { type: "text", text: "previous answer" }, + }, + }); + stream = setInterval(() => { + if (runtime.readsCanceled) return; + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "session_info_update", + title: "Updated title", + }, + }); + }, 20); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + const outcome = await Promise.race([ + waitForEvent(events, (event) => event.type === "session.ready").then(() => "ready"), + new Promise((resolve) => setTimeout(() => resolve("still waiting"), 1_000)), + ]); + expect(outcome).toBe("ready"); + expect(events.filter((event) => event.type === "timeline.item")).toHaveLength(1); + } finally { + clearInterval(stream); + await connection.close(); + } + }); + + it("fails session open without emitting session.ready or leaking the session when the ACP process crashes mid-replay", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-crash-replay-")); + const script = path.join(dir, "crash-replay-agent.mjs"); + await writeFile( + script, + ` + import { createInterface } from "node:readline"; + const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n"); + createInterface({ input: process.stdin }).on("line", (line) => { + if (!line.trim()) return; + const msg = JSON.parse(line); + if (msg.method === "initialize") { + send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } }); + } else if (msg.method === "session/load") { + const sid = msg.params.sessionId; + send({ id: msg.id, result: { configOptions: [] } }); + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "m-1", + content: { type: "text", text: "partial history" }, + }, + }, + }); + if (sid === "crash-session") { + setTimeout(() => process.exit(1), 20); + } + } else if (msg.method === "session/close") { + send({ id: msg.id, result: {} }); + } + }); + `, + ); + const connection = await runAcpProvider({ + id: "crash-replay", + label: "Crash Replay", + command: [process.execPath, script], + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + requestId: "req-crash", + sessionId: "session-1", + history: "replay", + persistence: { version: 1, data: { sessionId: "crash-session" } }, + }); + await waitForEvent( + events, + (event) => event.type === "request.failed" && event.requestId === "req-crash", + ); + expect(events.some((event) => event.type === "session.ready")).toBe(false); + + // The failed open must not leave a dead session registered under "session-1". + await connection.send({ + ...openInput(), + requestId: "req-retry", + sessionId: "session-1", + history: "replay", + persistence: { version: 1, data: { sessionId: "healthy-session" } }, + }); + await waitForEvent( + events, + (event) => event.type === "session.ready" && event.requestId === "req-retry", + ); + } finally { + await connection.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + + it("keeps a multi-read tool result started during an event-loop stall past the quiet period", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-large-stall-replay-")); + const script = path.join(dir, "large-stall-agent.mjs"); + const outputBytes = 256 * 1024; + await writeFile( + script, + ` + import { createInterface } from "node:readline"; + const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n"); + createInterface({ input: process.stdin }).on("line", (line) => { + if (!line.trim()) return; + const msg = JSON.parse(line); + if (msg.method === "initialize") { + send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } }); + } else if (msg.method === "session/load") { + const sid = msg.params.sessionId; + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "m-before", + content: { type: "text", text: "before the stall" }, + }, + }, + }); + send({ id: msg.id, result: { configOptions: [] } }); + setTimeout(() => { + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "tool_call", + toolCallId: "shell-large", + name: "run_command", + title: "Large output", + kind: "execute", + status: "completed", + rawInput: { CommandLine: "cat large.log" }, + rawOutput: { output: "x".repeat(${outputBytes}), exit_code: 0 }, + }, + }, + }); + }, 50); + } else if (msg.method === "session/close") { + send({ id: msg.id, result: {} }); + } + }); + `, + ); + const connection = await runAcpProvider({ + id: "large-stall", + label: "Large Stall", + command: [process.execPath, script], + acpOptions: { loadReplayQuietPeriodMs: 200 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + let stalled = false; + const stallEventLoop = () => { + const until = performance.now() + 350; + while (performance.now() < until); + }; + const scheduleStall = () => setImmediate(stallEventLoop); + connection.onEvent((event) => { + events.push(event); + if (!stalled && event.type === "session.config") { + stalled = true; + // Stall after the timers phase so the overdue quiet timer runs before the next I/O poll; + // the 256 KiB tool result fills the pipe during the stall and spans multiple stdout reads. + setTimeout(scheduleStall, 20); + } + }); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId: "large-session" } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + const items = events + .filter((event) => event.type === "timeline.item") + .map((event) => event.item); + expect(items).toEqual([ + expect.objectContaining({ type: "assistant_message", text: "before the stall" }), + expect.objectContaining({ type: "tool_call", callId: "shell-large", status: "completed" }), + ]); + } finally { + await connection.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + it("auto-accepts ordinary permissions only in the unattended mode and refuses to switch while busy", async () => { const modeConfig = { id: "mode", @@ -1962,6 +2353,70 @@ lines.on("line", (line) => { }, ); + it("discovers each model's own thinking options when the agent describes only the selected model", async () => { + const executable = await fakeAcp(`const readline = require("node:readline"); +const lines = readline.createInterface({ input: process.stdin }); +const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); +const levels = (values) => values.map((value) => ({ name: value[0].toUpperCase() + value.slice(1), value })); +const thinking = { + neon: { currentValue: "high", options: levels(["low", "high", "xhigh"]) }, + carbon: { currentValue: "medium", options: levels(["low", "medium", "high"]) }, +}; +let model = "neon"; +const options = () => [ + { id: "model", name: "Model", category: "model", type: "select", currentValue: model, options: [{ name: "Neon", value: "neon" }, { name: "Carbon", value: "carbon" }, { name: "Orchestrator", value: "orchestrator" }] }, + ...(thinking[model] ? [{ id: "thought_level", name: "Thinking", category: "thought_level", type: "select", ...thinking[model] }] : []), +]; +lines.on("line", (line) => { + const message = JSON.parse(line); + if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } }); + else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-1", modes: null, configOptions: options() } }); + else if (message.method === "session/set_config_option") { + if (message.params.configId === "model") model = message.params.value; + send({ jsonrpc: "2.0", id: message.id, result: { configOptions: options() } }); + } +});`); + let modelSeenByTransformer: unknown; + const registration = runAcpProvider({ + id: "test-acp", + label: "Test ACP", + command: [process.execPath, executable], + acpOptions: { perModelThinkingOptions: true }, + transformers: [ + { + async discover(catalog, { config }) { + modelSeenByTransformer = (await config.read()).model; + return catalog; + }, + }, + ], + }); + const connection = await registration.connect({ versions: [1], capabilities: [] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ type: "catalog", requestId: "catalog-1", cwd: process.cwd() }); + const event = await waitForEvent( + events, + (candidate) => candidate.type === "catalog" || candidate.type === "request.failed", + ); + if (event.type !== "catalog") throw new Error(`Expected catalog, got ${event.type}`); + expect(event.catalog.defaultModel).toBe("neon"); + expect(event.catalog.models.map(modelThinking)).toEqual([ + { id: "neon", thinkingOptions: ["low", "high", "xhigh"], defaultThinkingOptionId: "high" }, + { + id: "carbon", + thinkingOptions: ["low", "medium", "high"], + defaultThinkingOptionId: "medium", + }, + { id: "orchestrator", thinkingOptions: [], defaultThinkingOptionId: undefined }, + ]); + expect(modelSeenByTransformer).toBe("neon"); + } finally { + await connection.close(); + } + }); + it("selects the model control when an agent files several controls under the model category", async () => { const executable = await fakeAcp(`const readline = require("node:readline"); const lines = readline.createInterface({ input: process.stdin }); @@ -5417,3 +5872,4353 @@ lines.on("line", (line) => { } }); }); + +it("sends extension requests from discovery and configure and preserves JSON-RPC errors", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method === "_example/catalog") { + instance.respond(request, { model: "vendor-model" }); + return true; + } + if (request.method === "_example/select") { + instance.reject(request, "Vendor rejected the selection"); + return true; + } + return false; + }, + }); + const registration = runAcpProvider({ + id: "extensions", + label: "Extensions", + connector, + transformers: [ + { + async discover(catalog, { request }) { + expect(await request("_example/catalog", { scope: "all" })).toEqual({ + model: "vendor-model", + }); + return { ...catalog, defaultModel: "vendor-model" }; + }, + async configure(change, { request }) { + await expect(request("_example/select", { model: change.value })).rejects.toMatchObject({ + code: -32603, + message: "Vendor rejected the selection", + }); + return "handled"; + }, + }, + ], + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["session.configure"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ type: "catalog", requestId: "catalog" }); + expect( + await waitForEvent( + events, + (event) => event.type === "catalog" || event.type === "request.failed", + ), + ).toMatchObject({ type: "catalog", catalog: { defaultModel: "vendor-model" } }); + expect(instances[1].requests).toContainEqual( + expect.objectContaining({ + method: "_example/catalog", + params: { scope: "all" }, + }), + ); + + const input = openInput(); + await connection.send({ ...input, config: { ...input.config, model: "vendor-model" } }); + expect( + await waitForEvent( + events, + (event) => event.type === "session.ready" || event.type === "request.failed", + ), + ).toMatchObject({ type: "session.ready" }); + expect(instances[2].requests).toContainEqual( + expect.objectContaining({ + method: "_example/select", + params: { model: "vendor-model" }, + }), + ); + } finally { + await connection.close(); + } +}); + +it("rewrites the session-ready, notification and configure-commit config snapshots", async () => { + const modelOption = { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "first", + options: ["first", "second", "third"].map((value) => ({ name: value, value })), + }; + const { connector, instances } = connectorHarness({ configOptions: [modelOption] }); + const registration = runAcpProvider({ + id: "config-transformer", + label: "Config Transformer", + connector, + transformers: [ + { + config(state, { sessionId }) { + return { ...state, model: `${sessionId}/${state.model}` }; + }, + }, + ], + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["session.configure"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + const models = () => + events.flatMap((event) => (event.type === "session.config" ? [event.config.model] : [])); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect(models()).toEqual(["session-1/first"]); + + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "config_option_update", + configOptions: [{ ...modelOption, currentValue: "second" }], + }, + }); + await expect.poll(models).toEqual(["session-1/first", "session-1/second"]); + + await connection.send({ + type: "session.configure", + requestId: "configure", + sessionId: "session-1", + changes: { model: "third" }, + }); + await expect.poll(models).toEqual(["session-1/first", "session-1/second", "session-1/third"]); + } finally { + await connection.close(); + } +}); + +describe("deferTurnOnRunningTools", () => { + it("keeps the turn open across end_turn until a running tool completes and the reply settles", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "cmd-1", + name: "run_command", + title: "Run background job", + status: "in_progress", + rawInput: { CommandLine: "sleep 10" }, + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Started in background."), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 100, size: 1000 }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-turn", + label: "Deferred Turn", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "turn-1", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "cmd-1" && + event.item.status === "running", + ); + // Give end_turn time to drain; the turn must remain open while cmd-1 is in_progress. + await new Promise((resolve) => setTimeout(resolve, 60)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-1" && + event.state !== "started", + ), + ).toBe(false); + + // Tool completes, followed by a usage_update before any assistant text: must NOT settle yet. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "cmd-1", + status: "completed", + rawOutput: { stdout: "DONE" }, + }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 150, size: 1000 }, + }); + await new Promise((resolve) => setTimeout(resolve, 60)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-1" && + event.state !== "started", + ), + ).toBe(false); + + // Model emits follow-up reply and usage_update: turn settles after settleDelayMs. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background job finished: DONE."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 200, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-1" && + event.state === "completed", + ); + expect( + events.filter((event) => event.type === "session.turn").map((event) => event.state), + ).toEqual(["started", "completed"]); + } finally { + await connection.close(); + } + }); + + it("does not defer when keepsTurnOpen excludes the running tool", async () => { + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "daemon-1", + name: "run_command", + title: "Start dev server", + status: "in_progress", + rawInput: { CommandLine: "npm run dev", IsDaemon: true }, + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-daemon", + label: "Deferred Daemon", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 30, + quietLimitMs: 500, + keepsTurnOpen(toolCall) { + const input = toolCall.input; + return !( + typeof input === "object" && + input !== null && + !Array.isArray(input) && + input.IsDaemon === true + ); + }, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "daemon-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start server" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:daemon-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("settles via quietLimitMs when a background tool finishes with no follow-up reply", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "silent-1", + name: "run_command", + title: "Silent job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-quiet", + label: "Deferred Quiet", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 20, quietLimitMs: 50 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "quiet-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run silent" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "silent-1", + ); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "silent-1", status: "completed" }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:quiet-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("preserves running tools across a follow-up prompt without sending session/cancel", async () => { + let promptCount = 0; + let cancelCount = 0; + const { connector, instances } = connectorHarness({ + handleMessage(_instance, message) { + if ("method" in message && message.method === "session/cancel") { + cancelCount += 1; + return true; + } + return false; + }, + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-1", + name: "run_command", + title: "Long job", + status: "in_progress", + }, + }); + } else { + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("ACK"), + }); + } + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-followup", + label: "Deferred Followup", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "turn-1", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start long job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-1", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // Send a follow-up prompt while bg-1 is still running. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "turn-2", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "ping" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-1" && + event.state === "completed", + ); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "ACK", + ); + // No session/cancel was sent, and turn-2 stays deferred while bg-1 is still running. + expect(cancelCount).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-2" && + event.state !== "started", + ), + ).toBe(false); + + // Now bg-1 finishes and the agent replies. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-1", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Long job done."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 220, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-2" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("cancels a deferred turn on interrupt and ignores trailing cancellation tool failures", async () => { + let cancelCount = 0; + const { connector, instances } = connectorHarness({ + handleMessage(_instance, message) { + if ("method" in message && message.method === "session/cancel") { + cancelCount += 1; + return true; + } + return false; + }, + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "cancel-me", + name: "run_command", + title: "Cancelable job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-cancel", + label: "Deferred Cancel", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "cancel-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "cancel-me", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + await connection.send({ + type: "session.interrupt", + requestId: "stop-1", + sessionId: "session-1", + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:cancel-turn" && + event.state === "canceled", + ); + await waitForEvent(events, (event) => event.type === "session.closed"); + expect(cancelCount).toBe(1); + expect(instances[1].readsCanceled).toBe(true); + const toolEvents = events.filter( + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "cancel-me", + ); + expect(toolEvents.at(-1)).toMatchObject({ + type: "timeline.item", + item: { id: "cancel-me", status: "canceled" }, + }); + } finally { + await connection.close(); + } + }); + + it("fails a deferred turn cleanly when the transport closes unexpectedly", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "crash-1", + name: "run_command", + title: "Crashing job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-crash", + label: "Deferred Crash", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "crash-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "crash-1", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + instances[1].closeFromAgent(); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:crash-turn" && + event.state === "failed", + ); + } finally { + await connection.close(); + } + }); + + it("steers a deferred turn without session/cancel and refuses steering while a wire prompt is in flight", async () => { + let promptCount = 0; + let cancelCount = 0; + let holdFirstPrompt: (() => void) | null = null; + const { connector, instances } = connectorHarness({ + handleMessage(_instance, message) { + if ("method" in message && message.method === "session/cancel") { + cancelCount += 1; + return true; + } + return false; + }, + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-steer", + name: "run_command", + title: "Long background job", + status: "in_progress", + }, + }); + holdFirstPrompt = () => instance.respond(request, { stopReason: "end_turn" }); + return true; + } + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steered ACK"), + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-steer", + label: "Deferred Steer", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + expect(connection.capabilities).toContain("prompt.steer"); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "turn-1", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-steer", + ); + + // Steering while the wire prompt is still in flight is rejected so callers can fall back. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-too-early", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "early steer" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "steer-too-early" && + event.result.type === "failed", + ); + + // Resolve the wire prompt so the turn enters deferred mode. + holdFirstPrompt!(); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // Steering while deferred succeeds in-turn without sending session/cancel. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-1", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "status?" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "steer-1" && + event.result.type === "steer" && + event.result.turnId === "acp:turn-1", + ); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "Steered ACK", + ); + expect(cancelCount).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 40)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-1" && + event.state !== "started", + ), + ).toBe(false); + + // Background job finishes and replies: the single turn completes cleanly. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-steer", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Job complete."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 300, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:turn-1" && + event.state === "completed", + ); + expect(cancelCount).toBe(0); + } finally { + await connection.close(); + } + }); + + it("keeps the turn open if a new qualifying tool arrives as the settle timer expires", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-1", + name: "run_command", + title: "First job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-race", + label: "Deferred Race", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "race-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run jobs" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "tool-1", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // First tool completes and arms the 30ms settle timer. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "tool-1", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Starting second job."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 100, size: 1000 }, + }); + + // Right as the 30ms timer fires, a second qualifying tool starts. + await new Promise((resolve) => setTimeout(resolve, 28)); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-2", + name: "run_command", + title: "Second job", + status: "in_progress", + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "tool-2" && + event.item.status === "running", + ); + await new Promise((resolve) => setTimeout(resolve, 60)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:race-turn" && + event.state !== "started", + ), + ).toBe(false); + + // Once tool-2 finishes and the model replies, the turn completes. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "tool-2", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Second job done."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 200, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:race-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("suppresses deferred cancel echoes across a new prompt without filtering opt-out providers", async () => { + // Part 1: Opt-out provider (no deferTurnOnRunningTools) still receives late tool updates after cancel. + let optOutPrompt: AcpRequestMessage | null = null; + const optOut = connectorHarness({ + handleMessage(instance, message) { + if ("method" in message && message.method === "session/cancel" && optOutPrompt) { + instance.respond(optOutPrompt, { stopReason: "cancelled" }); + optOutPrompt = null; + return true; + } + return false; + }, + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + optOutPrompt = request; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "optout-tool", + name: "run_command", + title: "Opt-out tool", + status: "in_progress", + }, + }); + return true; + }, + }); + const optOutReg = runAcpProvider({ + id: "optout-cancel", + label: "Opt-out Cancel", + connector: optOut.connector, + }); + const optOutConn = await optOutReg.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const optOutEvents: ProviderEvent[] = []; + optOutConn.onEvent((event) => optOutEvents.push(event)); + try { + await optOutConn.send(openInput()); + await waitForEvent(optOutEvents, (event) => event.type === "session.ready"); + await optOutConn.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "optout-1", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "go" }] }, + }, + }); + await waitForEvent( + optOutEvents, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "optout-tool", + ); + await optOutConn.send({ + type: "session.interrupt", + requestId: "optout-stop", + sessionId: "session-1", + }); + await waitForEvent( + optOutEvents, + (event) => + event.type === "session.turn" && + event.turnId === "acp:optout-1" && + event.state === "canceled", + ); + optOut.instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "optout-tool", + status: "completed", + rawOutput: { ok: true }, + }, + }); + await waitForEvent( + optOutEvents, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "optout-tool" && + event.item.status === "completed", + ); + } finally { + await optOutConn.close(); + } + + // Part 2: Deferred-canceled tool echo arriving AFTER a new prompt starts is still suppressed. + let promptNum = 0; + const deferred = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptNum += 1; + if (promptNum === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "late-echo", + name: "run_command", + title: "Canceled tool", + status: "in_progress", + }, + }); + } else { + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Second turn"), + }); + } + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const deferredReg = runAcpProvider({ + id: "deferred-echo", + label: "Deferred Echo", + connector: deferred.connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const deferredConn = await deferredReg.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const deferredEvents: ProviderEvent[] = []; + deferredConn.onEvent((event) => deferredEvents.push(event)); + try { + await deferredConn.send(openInput()); + await waitForEvent(deferredEvents, (event) => event.type === "session.ready"); + await deferredConn.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "echo-turn-1", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "first" }] }, + }, + }); + await waitForEvent( + deferredEvents, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "late-echo", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + await deferredConn.send({ + type: "session.interrupt", + requestId: "echo-stop", + sessionId: "session-1", + }); + await waitForEvent( + deferredEvents, + (event) => + event.type === "session.turn" && + event.turnId === "acp:echo-turn-1" && + event.state === "canceled", + ); + await waitForEvent(deferredEvents, (event) => event.type === "session.closed"); + expect(deferred.instances[1].readsCanceled).toBe(true); + const toolEvents = deferredEvents.filter( + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "late-echo", + ); + expect(toolEvents.at(-1)).toMatchObject({ + type: "timeline.item", + item: { id: "late-echo", status: "canceled" }, + }); + } finally { + await deferredConn.close(); + } + }); + + it("does not defer when stopReason is not end_turn", async () => { + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "limit-tool", + name: "run_command", + title: "Stopped at limit", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "max_turn_requests" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-stop-reason", + label: "Deferred Stop Reason", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "limit-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:limit-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("queues back-to-back steers without cancel and waits for a streaming background reply after steer end_turn", async () => { + let promptCount = 0; + let cancelCount = 0; + let finishFirstSteer: (() => void) | null = null; + const { connector, instances } = connectorHarness({ + handleMessage(_instance, message) { + if ("method" in message && message.method === "session/cancel") { + cancelCount += 1; + return true; + } + return false; + }, + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-multi", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 2) { + finishFirstSteer = () => { + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer 1 ACK"), + }); + instance.respond(request, { stopReason: "end_turn" }); + }; + return true; + } + // During steer 2, the background tool finishes and begins streaming its reply before end_turn. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-multi", + status: "completed", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background reply part 1 "), + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-multi-steer", + label: "Deferred Multi Steer", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 50, quietLimitMs: 1_500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "multi-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-multi", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + // Send two back-to-back steers while steer 1 is still awaiting its wire response. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-a", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "first follow-up" }] }, + }, + }); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-b", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "second follow-up" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "steer-a" && + event.result.type === "steer", + ); + expect(cancelCount).toBe(0); + + // Release steer 1; steer 2 runs next, gets accepted, and completes bg-multi while starting its reply. + await expect.poll(() => finishFirstSteer).not.toBeNull(); + finishFirstSteer!(); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "steer-b" && + event.result.type === "steer", + ); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text.includes("Background reply part 1"), + ); + + // Turn must remain open past settleDelayMs (50ms) until part 2 and usage_update arrive. + await new Promise((resolve) => setTimeout(resolve, 150)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:multi-turn" && + event.state !== "started", + ), + ).toBe(false); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("part 2."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 350, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:multi-turn" && + event.state === "completed", + ); + expect(cancelCount).toBe(0); + expect(events).toContainEqual( + expect.objectContaining({ + type: "timeline.item", + item: expect.objectContaining({ + type: "assistant_message", + text: "Background reply part 1 part 2.", + }), + }), + ); + } finally { + await connection.close(); + } + }); + + it("delivers a queued steer even when an earlier steer returns max_turn_requests", async () => { + let promptCount = 0; + let finishFirstSteer: (() => void) | null = null; + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-drop", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 2) { + finishFirstSteer = () => instance.respond(request, { stopReason: "max_turn_requests" }); + return true; + } + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Second steer delivered"), + }); + instance.respond(request, { stopReason: "max_turn_requests" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-steer-deliver", + label: "Deferred Steer Deliver", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "drop-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-drop", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-1", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "first steer" }] }, + }, + }); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-2", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "second steer" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "steer-2" && + event.result.type === "steer", + ); + await expect.poll(() => finishFirstSteer).not.toBeNull(); + finishFirstSteer!(); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "Second steer delivered", + ); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:drop-turn" && + event.state === "completed", + ); + expect(promptCount).toBe(3); + } finally { + await connection.close(); + } + }); + + it("ignores steer usage_update from before a background tool finishes so the background reply is not cut short", async () => { + let promptCount = 0; + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-usage", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + } else { + // Steer replies and emits usage_update while bg-usage is still in_progress. + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer reply"), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 150, size: 1000 }, + }); + } + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-steer-usage", + label: "Deferred Steer Usage", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 40, quietLimitMs: 1_500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "usage-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-usage", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + // Steer completes with its own reply + usage_update while bg-usage is still running. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-usage", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "status?" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "Steer reply", + ); + + // Now bg-usage completes. The earlier steer usage_update must NOT trigger the 40ms timer. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-usage", status: "completed" }, + }); + await new Promise((resolve) => setTimeout(resolve, 120)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:usage-turn" && + event.state !== "started", + ), + ).toBe(false); + + // Background reply arrives after the thinking gap and closes with usage_update. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background result ready."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 250, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:usage-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("ignores steer usage_update when the background tool completes during the steer request", async () => { + let promptCount = 0; + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-mid-steer", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + } else { + // Tool completes while steer is in flight, followed by steer reply + steer usage_update. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-mid-steer", + status: "completed", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer reply"), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 180, size: 1000 }, + }); + } + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-mid-steer-usage", + label: "Deferred Mid-Steer Usage", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 40, quietLimitMs: 1_500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "mid-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-mid-steer", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-mid", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "status?" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "Steer reply", + ); + + // Must NOT settle after 40ms settleDelayMs using the steer's usage_update. + await new Promise((resolve) => setTimeout(resolve, 120)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:mid-turn" && + event.state !== "started", + ), + ).toBe(false); + + // Background reply arrives after the steer and settles via its own usage_update. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background result."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 260, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:mid-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("reports a notice and still delivers a queued steer when an earlier steer rejects with an RPC error", async () => { + let promptCount = 0; + let failFirstSteer: (() => void) | null = null; + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-rpc-err", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 2) { + failFirstSteer = () => instance.reject(request, "Transient steer error"); + return true; + } + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Second steer succeeded"), + }); + instance.respond(request, { stopReason: "max_turn_requests" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-steer-rpc-err", + label: "Deferred Steer RPC Err", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "rpc-err-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-rpc-err", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-fail", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "first" }] }, + }, + }); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-next", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "second" }] }, + }, + }); + await expect.poll(() => failFirstSteer).not.toBeNull(); + failFirstSteer!(); + + await waitForEvent( + events, + (event) => + event.type === "session.notice" && + event.notice.severity === "error" && + event.notice.description?.includes("Transient steer error") === true, + ); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "Second steer succeeded", + ); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:rpc-err-turn" && + event.state === "completed", + ); + expect(promptCount).toBe(3); + } finally { + await connection.close(); + } + }); + + it("keeps the background job running when a lone steer rejects and cancels cleanly if Stop raced the rejection", async () => { + let promptCount = 0; + let rejectHeldSteer: (() => void) | null = null; + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-keep-alive", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 2) { + instance.reject(request, "Steer rejected"); + return true; + } + if (promptCount === 3) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-cancel-race", + name: "run_command", + title: "Cancelable job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 4) { + rejectHeldSteer = () => instance.reject(request, "Request aborted"); + return true; + } + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-lone-steer-reject", + label: "Deferred Lone Steer Reject", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + + // Case 1: Lone steer rejects while bg-keep-alive is still running -> notice emitted, turn stays open. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "keep-alive-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-keep-alive", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "lone-steer-fail", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "status?" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.notice" && + event.notice.severity === "error" && + event.notice.description?.includes("Steer rejected") === true, + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:keep-alive-turn" && + event.state !== "started", + ), + ).toBe(false); + + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-keep-alive", + status: "completed", + }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Job finished."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 200, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:keep-alive-turn" && + event.state === "completed", + ); + + // Case 2: Explicit Stop before steer rejects -> turn reports canceled, not failed. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "cancel-race-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start 2" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-cancel-race", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "raced-steer", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "follow up" }] }, + }, + }); + await expect.poll(() => rejectHeldSteer).not.toBeNull(); + await connection.send({ + type: "session.interrupt", + requestId: "stop-race", + sessionId: "session-1", + }); + // Unanswered steer past cancelTimeoutMs cancels the turn and fails the wedged runtime + // so the session is recovered instead of overlapping late updates with a new prompt. + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:cancel-race-turn" && + event.state === "canceled", + ); + await waitForEvent(events, (event) => event.type === "session.closed"); + expect(instances[1].readsCanceled).toBe(true); + + // Direct prompts to the retired session must fail cleanly instead of reusing it. + await expect( + connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "after-retire", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "should fail" }] }, + }, + }), + ).rejects.toThrow("Unknown session"); + } finally { + await connection.close(); + } + }); + + it("terminates a command-backed ACP child process when an interrupted steer retires the session", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-wedged-steer-")); + const pidFile = path.join(dir, "session.pid"); + const script = path.join(dir, "wedged-agent.cjs"); + await writeFile( + script, + ` + const { writeFileSync } = require("node:fs"); + const { createInterface } = require("node:readline"); + const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n"); + let promptCount = 0; + createInterface({ input: process.stdin }).on("line", (line) => { + const msg = JSON.parse(line); + if (msg.method === "initialize") { + send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } }); + } else if (msg.method === "session/new") { + writeFileSync(process.env.PID_FILE, String(process.pid)); + send({ id: msg.id, result: { sessionId: "wedged-s1", configOptions: [] } }); + } else if (msg.method === "session/prompt") { + promptCount += 1; + if (promptCount === 1) { + send({ method: "session/update", params: { sessionId: "wedged-s1", update: { + sessionUpdate: "tool_call", toolCallId: "bg-wedged", name: "run_command", + title: "Background job", status: "in_progress", + } } }); + send({ id: msg.id, result: { stopReason: "end_turn" } }); + } + // Prompt 2 (the steer) is intentionally never answered, even after session/cancel. + } else if (msg.method === "session/close") { + send({ id: msg.id, result: {} }); + } + }); + `, + ); + const registration = runAcpProvider({ + id: "wedged-command-acp", + label: "Wedged Command ACP", + command: [process.execPath, script], + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + const open = openInput(); + await connection.send({ + ...open, + config: { ...open.config, env: { PID_FILE: pidFile } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + const pid = Number((await readFile(pidFile, "utf8")).trim()); + expect(Number.isInteger(pid) && pid > 0).toBe(true); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "wedged-1", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-wedged", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "wedged-steer", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "hang here" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "wedged-steer" && + event.result.type === "steer", + ); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "wedged-replacement", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "replace wedged turn" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:wedged-1" && + event.state === "canceled", + ); + await waitForEvent(events, (event) => event.type === "session.closed"); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "wedged-replacement" && + event.result.type === "failed", + ); + expect( + events.some( + (event) => event.type === "session.turn" && event.turnId === "acp:wedged-replacement", + ), + ).toBe(false); + + // The wedged child process must actually be terminated. + await expect + .poll(() => { + try { + process.kill(pid, 0); + return "alive"; + } catch { + return "dead"; + } + }) + .toBe("dead"); + } finally { + await connection.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + + it("does not let excluded daemon tool updates delay settlement of a completed background job", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "daemon-chatty", + name: "run_command", + title: "Dev server", + status: "in_progress", + rawInput: { CommandLine: "npm run dev", IsDaemon: true }, + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "build-job", + name: "run_command", + title: "Build", + status: "in_progress", + rawInput: { CommandLine: "npm run build" }, + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-chatty-daemon", + label: "Deferred Chatty Daemon", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 60, + quietLimitMs: 1_500, + keepsTurnOpen(toolCall) { + const input = toolCall.input; + return !( + typeof input === "object" && + input !== null && + !Array.isArray(input) && + input.IsDaemon === true + ); + }, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + let daemonTicker: ReturnType | null = null; + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "chatty-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "build" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "build-job", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + // Build completes and sends reply + usage_update while daemon emits updates every 20ms. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "build-job", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Build succeeded."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 120, size: 1000 }, + }); + let tick = 0; + daemonTicker = setInterval(() => { + tick += 1; + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "daemon-chatty", + status: "in_progress", + rawOutput: { stdout: `log ${tick}` }, + }, + }); + }, 20); + + // Turn must still settle in ~60ms despite the daemon updates every 20ms. + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:chatty-turn" && + event.state === "completed", + ); + } finally { + if (daemonTicker) clearInterval(daemonTicker); + await connection.close(); + } + }); + + it("releases a deferred turn when a running tool is later reclassified as an excluded daemon", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "late-daemon", + name: "run_command", + title: "Dev server", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-late-daemon", + label: "Deferred Late Daemon", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 25, + quietLimitMs: 60, + keepsTurnOpen(toolCall) { + const input = toolCall.input; + return !( + typeof input === "object" && + input !== null && + !Array.isArray(input) && + input.IsDaemon === true + ); + }, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "late-daemon-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start dev server" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "late-daemon", + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + + // Late update supplies IsDaemon: true -> leaves qualifying work and arms quietLimitMs. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "late-daemon", + rawInput: { CommandLine: "npm run dev", IsDaemon: true }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:late-daemon-turn" && + event.state === "completed", + ); + } finally { + await connection.close(); + } + }); + + it("does not delay reply settlement when a completed tool receives late output", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "late-out-tool", + name: "run_command", + title: "Build", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-late-output", + label: "Deferred Late Output", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 30, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "late-out-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "build" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "late-out-tool", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Tool completes, post-tool reply and usage_update arm the short settleDelayMs timer. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "late-out-tool", + status: "completed", + }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Build succeeded."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 200, size: 1000 }, + }); + // Late output on the already-completed tool must not reset the short reply timer to quietLimitMs. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "late-out-tool", + rawOutput: { output: "trailing log line" }, + }, + }); + + const startedAt = Date.now(); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:late-out-turn" && + event.state === "completed", + 400, + ); + expect(Date.now() - startedAt).toBeLessThan(400); + } finally { + await connection.close(); + } + }); + + it("settles on the reply timer when reply text starts before the last background tool completes", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-a", + name: "run_command", + title: "Job A", + status: "in_progress", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-b", + name: "run_command", + title: "Job B", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-overlap-reply", + label: "Deferred Overlap Reply", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 30, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "overlap-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run both jobs" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-b", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Job A finishes and assistant starts streaming the reply while Job B is still running. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-a", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Both jobs are finishing up."), + }); + // Job B completes, then the reply's usage_update arrives -> should settle via settleDelayMs. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-b", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 300, size: 1000 }, + }); + + const startedAt = Date.now(); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:overlap-turn" && + event.state === "completed", + 400, + ); + expect(Date.now() - startedAt).toBeLessThan(400); + } finally { + await connection.close(); + } + }); + + it("settles on the reply timer when reply usage arrives before the final background tool completes", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-u1", + name: "run_command", + title: "Job 1", + status: "in_progress", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-u2", + name: "run_command", + title: "Job 2", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-usage-before-tool", + label: "Deferred Usage Before Tool", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 30, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "usage-first-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run jobs" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-u2", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Job 1 finishes, reply + usage_update arrive while Job 2 is still running. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u1", status: "completed" }, + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("All done."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 300, size: 1000 }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + // Still running because Job 2 has not completed yet. + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:usage-first-turn" && + event.state !== "started", + ), + ).toBe(false); + + // Job 2 completes -> should settle via settleDelayMs, not quietLimitMs. + const startedAt = Date.now(); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u2", status: "completed" }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:usage-first-turn" && + event.state === "completed", + 400, + ); + expect(Date.now() - startedAt).toBeLessThan(400); + } finally { + await connection.close(); + } + }); + + it("defers the turn when a running tool completes immediately after end_turn in the same batch", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-race", + name: "run_command", + title: "Fast background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + // Completion arrives right after end_turn in the same wire batch. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-race", + status: "completed", + }, + }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-post-end-turn-race", + label: "Deferred Post End Turn Race", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 30, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "race-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run fast bg job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-race" && + event.item.status === "completed", + ); + await new Promise((resolve) => setTimeout(resolve, 60)); + // Turn must still be open waiting for the post-tool reply. + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:race-turn" && + event.state !== "started", + ), + ).toBe(false); + + // Post-tool reply + usage_update arrive and settle the deferred turn. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background job finished."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 250, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:race-turn" && + event.state === "completed", + 400, + ); + expect( + events.some( + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text === "Background job finished.", + ), + ).toBe(true); + } finally { + await connection.close(); + } + }); + + it("does not defer when an open tool is reclassified as an excluded daemon immediately after end_turn", async () => { + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "daemon-race", + name: "run_command", + title: "Dev server", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + // Reclassification to IsDaemon: true arrives in the same batch right after end_turn. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "daemon-race", + rawInput: { CommandLine: "npm run dev", IsDaemon: true }, + }, + }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-daemon-race", + label: "Deferred Daemon Race", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 30, + quietLimitMs: 1_500, + keepsTurnOpen(toolCall) { + const input = toolCall.input; + return !( + typeof input === "object" && + input !== null && + !Array.isArray(input) && + input.IsDaemon === true + ); + }, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + const startedAt = Date.now(); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "daemon-race-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "start dev server" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:daemon-race-turn" && + event.state === "completed", + 400, + ); + expect(Date.now() - startedAt).toBeLessThan(400); + } finally { + await connection.close(); + } + }); + + it("settles on the reply timer when background completion and reply arrive immediately after steer end_turn", async () => { + let promptCount = 0; + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-after-steer", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + // Steer response followed immediately in the same wire batch by background completion + reply + usage. + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer ACK"), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 100, size: 1000 }, + }); + instance.respond(request, { stopReason: "end_turn" }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-after-steer", + status: "completed", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background finished."), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 300, size: 1000 }, + }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-post-steer-batch", + label: "Deferred Post Steer Batch", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 40, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "post-steer-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run bg" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-after-steer", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + const startedAt = Date.now(); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "post-steer-followup", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "status?" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:post-steer-turn" && + event.state === "completed", + 400, + ); + expect(Date.now() - startedAt).toBeLessThan(400); + } finally { + await connection.close(); + } + }); + + it("preserves a settled background reply across a second queued steer with no new background work", async () => { + let promptCount = 0; + let releaseSteer1: (() => void) | null = null; + const { connector } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-two-steers", + name: "run_command", + title: "Background job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 2) { + releaseSteer1 = () => { + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer 1 ACK"), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 100, size: 1000 }, + }); + instance.respond(request, { stopReason: "end_turn" }); + // Background job finishes and replies immediately after Steer 1 returns end_turn. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-two-steers", + status: "completed", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Background finished."), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 250, size: 1000 }, + }); + }; + return true; + } + // Steer 2 returns end_turn with no new background work. + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer 2 ACK"), + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-two-steers-settled", + label: "Deferred Two Steers Settled", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 40, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "two-steers-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run bg" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-two-steers", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Queue two steers back-to-back. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-one", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "first steer" }] }, + }, + }); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "steer-two", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "second steer" }] }, + }, + }); + await new Promise((resolve) => setTimeout(resolve, 20)); + + const startedAt = Date.now(); + releaseSteer1!(); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:two-steers-turn" && + event.state === "completed", + 400, + ); + expect(Date.now() - startedAt).toBeLessThan(400); + expect(promptCount).toBe(3); + } finally { + await connection.close(); + } + }); + + it("keeps the turn open for a second background tool reply that starts during a second steer", async () => { + let promptCount = 0; + let releaseSteer1: (() => void) | null = null; + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-s1", + name: "run_command", + title: "Job 1", + status: "in_progress", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-s2", + name: "run_command", + title: "Job 2", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + if (promptCount === 2) { + releaseSteer1 = () => { + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Steer 1 ACK"), + }); + instance.respond(request, { stopReason: "end_turn" }); + // Job 1 finishes and sends its reply + usage while Job 2 is STILL running. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-s1", + status: "completed", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Job 1 done."), + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 200, size: 1000 }, + }); + }; + return true; + } + // During Steer 2, Job 2 completes and starts streaming its reply before Steer 2 ends. + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "bg-s2", + status: "completed", + }, + }); + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Job 2 part 1 "), + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const registration = runAcpProvider({ + id: "deferred-second-tool-steer", + label: "Deferred Second Tool Steer", + connector, + acpOptions: { + deferTurnOnRunningTools: { + settleDelayMs: 40, + quietLimitMs: 1_500, + }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "two-tool-steer-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run two jobs" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-s2", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "two-tool-steer-1", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "steer 1" }] }, + }, + }); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "two-tool-steer-2", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "steer 2" }] }, + }, + }); + await new Promise((resolve) => setTimeout(resolve, 20)); + + releaseSteer1!(); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "assistant_message" && + event.item.text.includes("Job 2 part 1"), + ); + + // Pause longer than settleDelayMs (40ms): turn must stay open for Job 2's remaining chunks. + await new Promise((resolve) => setTimeout(resolve, 160)); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:two-tool-steer-turn" && + event.state !== "started", + ), + ).toBe(false); + + // Job 2 finishes streaming and sends usage_update -> turn now completes cleanly. + instances[1].notify("session/update", { + sessionId: "connector-session", + update: textChunk("and part 2."), + }); + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { sessionUpdate: "usage_update", used: 350, size: 1000 }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:two-tool-steer-turn" && + event.state === "completed", + 400, + ); + } finally { + await connection.close(); + } + }); + + it("waits for process exit and emits terminal events once across overlapping interrupts", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-overlap-interrupt-")); + temporaryDirectories.push(dir); + const scriptPath = path.join(dir, "slow-exit-acp.mjs"); + const pidFile = path.join(dir, "child.pid"); + await writeFile( + scriptPath, + [ + `import { writeFileSync } from "node:fs";`, + `import { createInterface } from "node:readline";`, + `writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));`, + `process.on("SIGTERM", () => { setTimeout(() => process.exit(0), 250); });`, + `const write = (msg) => process.stdout.write(JSON.stringify(msg) + "\\n");`, + `let prompts = 0;`, + `createInterface({ input: process.stdin }).on("line", (line) => {`, + ` if (!line.trim()) return;`, + ` const msg = JSON.parse(line);`, + ` if (msg.method === "initialize") {`, + ` write({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });`, + ` return;`, + ` }`, + ` if (msg.method === "session/new") {`, + ` write({ jsonrpc: "2.0", id: msg.id, result: { sessionId: "slow-session" } });`, + ` return;`, + ` }`, + ` if (msg.method === "session/prompt") {`, + ` prompts += 1;`, + ` if (prompts === 1) {`, + ` write({ jsonrpc: "2.0", method: "session/update", params: { sessionId: "slow-session", update: { sessionUpdate: "tool_call", toolCallId: "slow-bg", name: "run_command", title: "Job", status: "in_progress" } } });`, + ` write({ jsonrpc: "2.0", id: msg.id, result: { stopReason: "end_turn" } });`, + ` }`, + ` }`, + `});`, + ].join("\n"), + "utf8", + ); + const registration = runAcpProvider({ + id: "deferred-overlap-interrupt", + label: "Deferred Overlap Interrupt", + command: [process.execPath, scriptPath], + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 1_500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "slow-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "slow-bg", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // Start a hung steer so the session is actively awaiting a steer response. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "slow-steer", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "steer" }] }, + }, + }); + await waitForEvent( + events, + (event) => event.type === "session.prompt_result" && event.clientMessageId === "slow-steer", + ); + + const childPid = Number((await readFile(pidFile, "utf8")).trim()); + const startedAt = Date.now(); + await Promise.all([ + connection.send({ + type: "session.interrupt", + requestId: "int-1", + sessionId: "session-1", + }), + connection.send({ + type: "session.interrupt", + requestId: "int-2", + sessionId: "session-1", + }), + ]); + await waitForEvent( + events, + (event) => event.type === "request.completed" && event.requestId === "int-1", + ); + await waitForEvent( + events, + (event) => event.type === "request.completed" && event.requestId === "int-2", + ); + + // Both interrupts waited for the 250ms SIGTERM exit, and process is now dead. + expect(Date.now() - startedAt).toBeGreaterThanOrEqual(200); + expect(() => process.kill(childPid, 0)).toThrow(); + + // Canceled turn and session.closed were each emitted exactly once. + expect( + events.filter( + (event) => + event.type === "session.turn" && + event.turnId === "acp:slow-turn" && + event.state === "canceled", + ), + ).toHaveLength(1); + expect(events.filter((event) => event.type === "session.closed")).toHaveLength(1); + } finally { + await connection.close(); + } + }); + + it("lets deferred retirement be the sole emitter of cancellation when a steer returns cancelled during a slow cancel write", async () => { + let promptCount = 0; + let respondSteerCancelled: (() => void) | null = null; + let releaseCancelWrite: (() => void) | null = null; + let closedConnector = false; + const base = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + promptCount += 1; + if (promptCount === 1) { + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "bg-slow-cancel", + name: "run_command", + title: "Job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + } + respondSteerCancelled = () => instance.respond(request, { stopReason: "cancelled" }); + return true; + }, + }); + const connector = async () => { + const inner = await base.connector(); + closedConnector = false; + const writer = inner.writable.getWriter(); + const writable = new WritableStream({ + async write(message) { + if ("method" in message && message.method === "session/cancel") { + respondSteerCancelled?.(); + await new Promise((resolve) => { + releaseCancelWrite = resolve; + }); + } + await writer.write(message); + }, + async close() { + closedConnector = true; + await writer.close(); + }, + async abort(reason) { + closedConnector = true; + await writer.abort(reason); + }, + }); + return { readable: inner.readable, writable }; + }; + const registration = runAcpProvider({ + id: "deferred-slow-cancel-steer", + label: "Deferred Slow Cancel Steer", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 1_500 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "slow-cancel-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "bg-slow-cancel", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Start an in-flight steer, then initiate Stop while session/cancel write is held open. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "slow-cancel-steer", + delivery: "steer", + input: { type: "message", content: [{ type: "text", text: "steer" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && event.clientMessageId === "slow-cancel-steer", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + const interruptPromise = connection.send({ + type: "session.interrupt", + requestId: "slow-cancel-int", + sessionId: "session-1", + }); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // Even though steer returned stopReason: "cancelled", retirement has not closed yet: + // no canceled turn should be emitted yet, and a replacement prompt must be rejected. + expect(closedConnector).toBe(false); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:slow-cancel-turn" && + event.state === "canceled", + ), + ).toBe(false); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "replacement-during-retire", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "too early" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && + event.clientMessageId === "replacement-during-retire" && + event.result.type === "failed", + ); + + // Release the cancel write: retirement closes the transport and emits cancellation once. + releaseCancelWrite!(); + await interruptPromise; + await waitForEvent( + events, + (event) => event.type === "request.completed" && event.requestId === "slow-cancel-int", + ); + expect(closedConnector).toBe(true); + expect( + events.filter( + (event) => + event.type === "session.turn" && + event.turnId === "acp:slow-cancel-turn" && + event.state === "canceled", + ), + ).toHaveLength(1); + expect(events.filter((event) => event.type === "session.closed")).toHaveLength(1); + } finally { + releaseCancelWrite?.(); + await connection.close(); + } + }); + + it("tears down a deferred ACP child when stdin stalls behind a large steer", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-stalled-stdin-")); + temporaryDirectories.push(dir); + const scriptPath = path.join(dir, "stalled-stdin-acp.mjs"); + const pidFile = path.join(dir, "child.pid"); + await writeFile( + scriptPath, + [ + `import { writeFileSync } from "node:fs";`, + `writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));`, + `const write = (msg) => process.stdout.write(JSON.stringify(msg) + "\\n");`, + `let buffer = "";`, + `const onData = (chunk) => {`, + ` buffer += chunk.toString("utf8");`, + ` let idx;`, + ` while ((idx = buffer.indexOf("\\n")) !== -1) {`, + ` const line = buffer.slice(0, idx).trim();`, + ` buffer = buffer.slice(idx + 1);`, + ` if (!line) continue;`, + ` const msg = JSON.parse(line);`, + ` if (msg.method === "initialize") {`, + ` write({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });`, + ` } else if (msg.method === "session/new") {`, + ` write({ jsonrpc: "2.0", id: msg.id, result: { sessionId: "stalled-session" } });`, + ` } else if (msg.method === "session/prompt") {`, + ` write({ jsonrpc: "2.0", method: "session/update", params: { sessionId: "stalled-session", update: { sessionUpdate: "tool_call", toolCallId: "stalled-bg", name: "run_command", title: "Job", status: "in_progress" } } });`, + ` write({ jsonrpc: "2.0", id: msg.id, result: { stopReason: "end_turn" } });`, + ` // Stop reading stdin so a large follow-up steer fills the pipe buffer.`, + ` process.stdin.off("data", onData);`, + ` process.stdin.pause();`, + ` setInterval(() => {}, 10_000);`, + ` return;`, + ` }`, + ` }`, + `};`, + `process.stdin.on("data", onData);`, + ].join("\n"), + "utf8", + ); + const registration = runAcpProvider({ + id: "deferred-stalled-stdin", + label: "Deferred Stalled Stdin", + command: [process.execPath, scriptPath], + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 5_000 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "prompt.steer"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "stalled-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "stalled-bg", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // Fill the child's stdin pipe buffer with a 2 MB steer while the child is paused. + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "stalled-steer", + delivery: "steer", + input: { + type: "message", + content: [{ type: "text", text: "x".repeat(2 * 1024 * 1024) }], + }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "session.prompt_result" && event.clientMessageId === "stalled-steer", + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + const childPid = Number((await readFile(pidFile, "utf8")).trim()); + await connection.send({ + type: "session.interrupt", + requestId: "stalled-int", + sessionId: "session-1", + }); + await waitForEvent( + events, + (event) => event.type === "request.completed" && event.requestId === "stalled-int", + 3_000, + ); + expect(() => process.kill(childPid, 0)).toThrow(); + expect( + events.filter( + (event) => + event.type === "session.turn" && + event.turnId === "acp:stalled-turn" && + event.state === "canceled", + ), + ).toHaveLength(1); + expect(events.filter((event) => event.type === "session.closed")).toHaveLength(1); + } finally { + await connection.close(); + } + }); + + it("reports interrupt failure when a connector refuses to confirm shutdown within the deadline", async () => { + let releaseStalledWrite: (() => void) | null = null; + const base = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "stalled-conn-bg", + name: "run_command", + title: "Job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const connector = async () => { + const inner = await base.connector(); + const writer = inner.writable.getWriter(); + const writable = new WritableStream({ + async write(message) { + if ("method" in message && message.method === "session/cancel") { + await new Promise((resolve) => { + releaseStalledWrite = resolve; + }); + } + await writer.write(message); + }, + close: () => writer.close(), + abort: (reason) => writer.abort(reason), + }); + return { readable: inner.readable, writable }; + }; + const registration = runAcpProvider({ + id: "deferred-stalled-connector", + label: "Deferred Stalled Connector", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 5_000 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "stalled-conn-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "stalled-conn-bg", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + await connection.send({ + type: "session.interrupt", + requestId: "stalled-conn-int", + sessionId: "session-1", + }); + const failed = await waitForEvent( + events, + (event) => event.type === "request.failed" && event.requestId === "stalled-conn-int", + 3_000, + ); + expect(failed.type === "request.failed" && failed.error.message).toContain( + "ACP connector did not close", + ); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:stalled-conn-turn" && + event.state === "canceled", + ), + ).toBe(false); + + // Once the connector finishes closing after the deadline, the turn and session retire cleanly. + releaseStalledWrite!(); + await waitForEvent( + events, + (event) => + event.type === "session.turn" && + event.turnId === "acp:stalled-conn-turn" && + event.state === "canceled", + 2_000, + ); + await waitForEvent(events, (event) => event.type === "session.closed", 2_000); + expect(events.filter((event) => event.type === "session.closed")).toHaveLength(1); + } finally { + releaseStalledWrite?.(); + await connection.close(); + } + }); + + it("reports interrupt failure when a connector rejects readable shutdown", async () => { + let connectorCall = 0; + const base = connectorHarness({ + handleRequest(instance, request) { + if (request.method !== "session/prompt") return false; + instance.notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "tool_call", + toolCallId: "reject-cancel-bg", + name: "run_command", + title: "Job", + status: "in_progress", + }, + }); + instance.respond(request, { stopReason: "end_turn" }); + return true; + }, + }); + const connector = async () => { + connectorCall += 1; + const inner = await base.connector(); + if (connectorCall === 1) return inner; + const reader = inner.readable.getReader(); + const readable = new ReadableStream({ + async pull(controller) { + const next = await reader.read(); + if (next.done) controller.close(); + else controller.enqueue(next.value); + }, + async cancel() { + await reader.cancel(); + throw new Error("connector cancel rejected"); + }, + }); + return { readable, writable: inner.writable }; + }; + const registration = runAcpProvider({ + id: "deferred-reject-cancel", + label: "Deferred Reject Cancel", + connector, + acpOptions: { + deferTurnOnRunningTools: { settleDelayMs: 30, quietLimitMs: 5_000 }, + }, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "reject-cancel-turn", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "run job" }] }, + }, + }); + await waitForEvent( + events, + (event) => + event.type === "timeline.item" && + event.item.type === "tool_call" && + event.item.id === "reject-cancel-bg", + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + await connection.send({ + type: "session.interrupt", + requestId: "reject-cancel-int", + sessionId: "session-1", + }); + const failed = await waitForEvent( + events, + (event) => event.type === "request.failed" && event.requestId === "reject-cancel-int", + 2_000, + ); + expect(failed.type === "request.failed" && failed.error.message).toContain( + "connector cancel rejected", + ); + expect( + events.some( + (event) => + event.type === "session.turn" && + event.turnId === "acp:reject-cancel-turn" && + event.state === "canceled", + ), + ).toBe(false); + } finally { + await connection.close(); + } + }); + + it("does not enforce the deferred Stop deadline on non-deferred probe shutdown", async () => { + const base = connectorHarness(); + const connector = async () => { + const inner = await base.connector(); + const writer = inner.writable.getWriter(); + const writable = new WritableStream({ + write: (message) => writer.write(message), + async close() { + await new Promise((resolve) => setTimeout(resolve, 1_100)); + await writer.close(); + }, + abort: (reason) => writer.abort(reason), + }); + return { readable: inner.readable, writable }; + }; + const registration = runAcpProvider({ + id: "slow-probe-close", + label: "Slow Probe Close", + connector, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + await connection.close(); + }); +}); + +describe("ACP tool call rows", () => { + function jsonRecord(value: JsonValue | undefined): Readonly> { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; + } + + function text(value: string) { + return [{ type: "content", content: { type: "text", text: value } }]; + } + + async function toolRows( + updates: unknown[], + transformers?: Parameters[0]["transformers"], + ) { + const harness = connectorHarness({ promptUpdates: () => updates }); + const registration = runAcpProvider({ + id: "tool-rows-acp", + label: "Tool rows ACP", + connector: harness.connector, + transformers, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "first", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "Use a tool" }] }, + }, + }); + await waitForEvent( + events, + (event) => event.type === "session.turn" && event.state === "completed", + ); + const rows = events.flatMap((event) => + event.type === "timeline.item" && event.item.type === "tool_call" ? [event.item] : [], + ); + for (const row of rows) { + expect(AgentTimelineItemPayloadSchema.safeParse(row).success).toBe(true); + } + return rows; + } finally { + await connection.close(); + } + } + + it.each([ + { + kind: "execute", + start: { title: "Run tests", rawInput: { command: "npm", args: ["test"], cwd: "/repo" } }, + end: { content: text("passed"), rawOutput: { exitCode: 0 } }, + detail: { type: "shell", command: "npm test", cwd: "/repo", output: "passed", exitCode: 0 }, + }, + { + kind: "execute", + start: { title: "Run tests" }, + end: { content: text("passed") }, + detail: { type: "shell", command: "Run tests", output: "passed" }, + }, + { + kind: "read", + start: { title: "Read a.ts", locations: [{ path: "/repo/a.ts" }], rawInput: { offset: 3 } }, + end: { content: text("const a = 1;") }, + detail: { type: "read", filePath: "/repo/a.ts", content: "const a = 1;", offset: 3 }, + }, + { + kind: "search", + start: { title: "Search TODO", rawInput: { pattern: "TODO" } }, + end: { content: text("a.ts:1"), locations: [{ path: "/repo/a.ts" }] }, + detail: { + type: "search", + query: "TODO", + toolName: "search", + content: "a.ts:1", + filePaths: ["/repo/a.ts"], + }, + }, + { + kind: "fetch", + start: { title: "Fetch example", rawInput: { url: "https://example.com" } }, + end: { content: text("Example Domain") }, + detail: { type: "fetch", url: "https://example.com", result: "Example Domain" }, + }, + { + kind: "edit", + start: { + title: "Edit a.ts", + content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }], + }, + end: {}, + detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" }, + }, + { + kind: "edit", + start: { title: "Edit a.ts", locations: [{ path: "/repo/a.ts" }] }, + end: { content: text("Replaced 1 occurrence") }, + detail: { type: "edit", filePath: "/repo/a.ts", unifiedDiff: "Replaced 1 occurrence" }, + }, + { + kind: "edit", + start: { + title: "Edit a.ts", + rawInput: { filePath: "/repo/a.ts", oldString: "remove me", newString: " " }, + }, + end: {}, + detail: { type: "edit", filePath: "/repo/a.ts", oldString: "remove me", newString: " " }, + }, + { + kind: "delete", + start: { title: "Delete a.ts", locations: [{ path: "/repo/a.ts" }] }, + end: {}, + detail: { type: "edit", filePath: "/repo/a.ts", newString: "" }, + }, + { + kind: "think", + start: { title: "Plan" }, + end: { content: text("First read the tests") }, + detail: { type: "plain_text", label: "Plan", icon: "brain", text: "First read the tests" }, + }, + { + kind: "other", + start: { title: "Update todos" }, + end: { content: text("2 open") }, + detail: { type: "plain_text", label: "Update todos", icon: "wrench", text: "2 open" }, + }, + { + kind: "other", + start: { title: "Custom tool", rawInput: { value: 1 } }, + end: { content: text("done"), rawOutput: { ok: true } }, + detail: { type: "unknown", input: { value: 1 }, output: { ok: true } }, + }, + ])("presents a completed $kind call as its standard row ($start.title)", async (example) => { + const rows = await toolRows([ + { + sessionUpdate: "tool_call", + toolCallId: "tool-1", + kind: example.kind, + status: "in_progress", + ...example.start, + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "tool-1", + status: "completed", + ...example.end, + }, + ]); + expect(rows.at(-1)?.detail).toEqual(example.detail); + }); + + it("gives transformers the call's content and the call as it was last presented", async () => { + const commandFromStart: NonNullable< + NonNullable[0]["transformers"]>[number]["toolCall"] + > = (call, { previous }) => { + const first = Array.isArray(call.content) ? call.content[0] : undefined; + const startText = jsonRecord(jsonRecord(first).content).text; + if (typeof startText === "string" && startText.startsWith("$ ")) { + return { ...call, input: { command: startText.slice(2) } }; + } + const command = jsonRecord(previous?.input).command; + return typeof command === "string" ? { ...call, input: { command } } : call; + }; + const rows = await toolRows( + [ + { + sessionUpdate: "tool_call", + toolCallId: "tool-1", + title: "git status + 1 command", + kind: "execute", + status: "in_progress", + content: text("$ git status && git diff"), + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "tool-1", + status: "completed", + content: text("clean"), + }, + ], + [{ toolCall: commandFromStart }], + ); + expect(rows.map((row) => row.detail)).toEqual([ + { type: "shell", command: "git status && git diff", output: "$ git status && git diff" }, + { type: "shell", command: "git status && git diff", output: "clean" }, + ]); + }); + + it("keeps a transformer's own detail over the standard row", async () => { + const rows = await toolRows( + [ + { + sessionUpdate: "tool_call", + toolCallId: "tool-1", + title: "Run tests", + kind: "execute", + status: "completed", + rawInput: { command: "npm test" }, + }, + ], + [ + { + toolCall: (call) => ({ + ...call, + detail: { type: "unknown", input: call.input, output: null }, + }), + }, + ], + ); + expect(rows.at(-1)?.detail).toEqual({ + type: "unknown", + input: { command: "npm test" }, + output: null, + }); + }); + + it("shows the call's row on its approval", async () => { + const harness = connectorHarness({ + handleRequest(runtime, request) { + if (request.method !== "session/prompt") return false; + void runtime.request("session/request_permission", { + sessionId: "connector-session", + toolCall: { + toolCallId: "edit-1", + title: "Edit a.ts", + kind: "edit", + status: "pending", + content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }], + }, + options: [ + { optionId: "allow", name: "Allow edit", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "approval-rows", + label: "Approval rows", + connector: harness.connector, + }).connect({ versions: [1], capabilities: ["prompt.message", "permission"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "edit", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "Edit a.ts" }] }, + }, + }); + expect( + await waitForEvent(events, (event) => event.type === "session.permission"), + ).toMatchObject({ + request: { + id: "permission:edit-1", + title: "Edit a.ts", + detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" }, + }, + }); + } finally { + await connection.close(); + } + }); + + it("lists sessions across every page the agent returns", async () => { + const pages: Record = { + first: { + sessions: [{ sessionId: "s1", cwd: "/repo", title: "One" }], + nextCursor: "second", + }, + second: { sessions: [{ sessionId: "s2", cwd: "/repo", title: "Two" }] }, + }; + const harness = connectorHarness({ + capabilities: { sessionCapabilities: { list: {} } }, + handleRequest(runtime, request) { + if (request.method !== "session/list") return false; + const { cursor } = request.params as { cursor?: string }; + runtime.respond(request, pages[cursor ?? "first"]); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "paged-sessions", + label: "Paged sessions", + connector: harness.connector, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.list"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ type: "sessions", requestId: "list" }); + const listed = await waitForEvent(events, (event) => event.type === "sessions"); + expect(listed.type === "sessions" && listed.sessions.map((session) => session.title)).toEqual( + ["One", "Two"], + ); + } finally { + await connection.close(); + } + }); + + it("resumes the generic ACP adapter's saved Auto Accept toggle in the unattended mode", async () => { + const harness = connectorHarness({ + configOptions: [ + { + id: "edit_approval_policy", + name: "Edits", + category: "mode", + type: "select", + currentValue: "ask", + options: [ + { value: "ask", name: "Default" }, + { value: "session", name: "Don't Ask" }, + ], + }, + ], + }); + const connection = await runAcpProvider({ + id: "former-generic", + label: "Former generic", + connector: harness.connector, + acpOptions: { + autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" }, + }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + const input = openInput(); + input.config.settings = { auto_accept: true }; + await connection.send(input); + await waitForEvent(events, (event) => event.type === "session.ready"); + const configs = events.flatMap((event) => + event.type === "session.config" ? [event.config.mode] : [], + ); + expect(configs.at(-1)).toBe("full-access"); + const sentOptions = harness.instances + .flatMap((instance) => instance.requests) + .filter((request) => request.method === "session/set_config_option") + .map((request) => (request.params as { configId: string }).configId); + expect(sentOptions).not.toContain("auto_accept"); + expect(events.some((event) => event.type === "request.failed")).toBe(false); + } finally { + await connection.close(); + } + }); + + it("keeps a mode chosen after the generic ACP adapter's Auto Accept toggle was saved", async () => { + const harness = connectorHarness({ + configOptions: [ + { + id: "edit_approval_policy", + name: "Edits", + category: "mode", + type: "select", + currentValue: "session", + options: [ + { value: "ask", name: "Default" }, + { value: "session", name: "Don't Ask" }, + ], + }, + ], + }); + const connection = await runAcpProvider({ + id: "former-generic", + label: "Former generic", + connector: harness.connector, + acpOptions: { + autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" }, + }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + const input = openInput(); + input.config.mode = "ask"; + input.config.settings = { auto_accept: true }; + await connection.send(input); + await waitForEvent(events, (event) => event.type === "session.ready"); + const configs = events.flatMap((event) => + event.type === "session.config" ? [event.config.mode] : [], + ); + expect(configs.at(-1)).toBe("ask"); + } finally { + await connection.close(); + } + }); +}); diff --git a/packages/plugin/src/server/acp.ts b/packages/plugin/src/server/acp.ts index 166d6ed8a5dd..8e115e7a5a65 100644 --- a/packages/plugin/src/server/acp.ts +++ b/packages/plugin/src/server/acp.ts @@ -57,10 +57,30 @@ export interface AcpOptions { * vendor turn is open instead of treating it as the prompt's echo. */ vendorTurnsAreNeverForeground?: boolean; + /** + * For an agent that lists thinking options only for the selected model: discovery selects each + * model in turn and records the thinking options the agent lists for it, or none. + */ + perModelThinkingOptions?: boolean; waitForInitialCommands?: boolean; initialCommandsTimeoutMs?: number; - /** Allow delayed session/load updates before publishing the session as ready. */ + /** + * For an agent that streams history after its session/load response: publish the session + * as ready once this long passes without a history update. + */ loadReplayQuietPeriodMs?: number; + /** + * Keep a turn open after `end_turn` while qualifying tool calls are still running, + * settling once those tools finish and the agent finishes its follow-up reply. + */ + deferTurnOnRunningTools?: { + /** Delay after `usage_update` closes a follow-up reply before settling. Defaults to 500ms. */ + settleDelayMs?: number; + /** Quiet limit after qualifying tools finish if no reply settles via `usage_update`. Defaults to 120_000ms. */ + quietLimitMs?: number; + /** Predicate deciding whether an open tool call keeps the turn open. Defaults to all running tools. */ + keepsTurnOpen?: (toolCall: AcpToolCallSnapshot) => boolean; + }; /** An unattended mode that approves ACP allow-once requests in the specified native mode. */ autoAcceptMode?: { mode: Omit; @@ -111,12 +131,17 @@ export interface AcpConfigAccess { set(id: string, value: JsonValue): Promise; } +/** Sends an ACP extension request to the agent. Rejects with the agent's JSON-RPC error. */ +export type AcpRequest = (method: string, params: JsonValue) => Promise; + export interface AcpDiscoveryContext extends AcpContext { config: AcpConfigAccess; + request: AcpRequest; } export interface AcpConfigureContext extends AcpContext { config: AcpConfigAccess; + request: AcpRequest; catalog(): ProviderCatalog; apply(change: AcpConfigChange): Promise; } @@ -133,9 +158,14 @@ export interface AcpToolCallSnapshot { title: string; kind?: string; status: "pending" | "in_progress" | "completed" | "failed"; + /** The call's ACP `rawInput`. */ input: JsonValue; + /** The call's ACP `rawOutput`. */ output: JsonValue; + /** The call's ACP `content` blocks. An update that sends `content` replaces them. */ + content?: JsonValue; locations: readonly string[]; + /** The row Paseo shows. Without it, Paseo builds the standard row for the call's ACP `kind`. */ detail?: ProviderToolCallDetail; } @@ -157,11 +187,6 @@ export interface AcpTransformer { attach?(info: { response: JsonValue }, context: AcpContext): AcpSessionPolicy | null; /** Vendor metadata for a prompt. The shim sends it as `_meta` on `session/prompt`. */ prompt?(info: AcpPromptInfo, context: AcpPolicyContext): AcpPromptMetadata | null; - /** Classify advertised commands before the shim publishes them. */ - command?( - commands: readonly ProviderCommand[], - context: AcpPolicyContext, - ): readonly ProviderCommand[] | null; /** Decode an older saved session and supply extension metadata for session/new or session/load. */ sessionOpen?(context: { persistence?: ProviderPersistence; @@ -174,11 +199,26 @@ export interface AcpTransformer { context: AcpDiscoveryContext, ): Promise | ProviderCatalog; configure?(change: AcpConfigChange, context: AcpConfigureContext): Promise<"handled" | "pass">; + /** Rewrites every session config snapshot before Paseo sees it. */ + config?(state: ProviderConfigState, context: AcpContext): ProviderConfigState; + /** + * Rewrites each advertised ACP slash command before Paseo sees it. The connection policy lets a + * transformer classify skills only when the agent negotiated explicit skill selection. + */ + command?(command: ProviderCommand, context: AcpPolicyContext): ProviderCommand; notification?( notification: { method: string; params: JsonValue }, context: AcpContext, ): AcpVendorUpdate | readonly AcpVendorUpdate[] | null; - toolCall?(toolCall: AcpToolCallSnapshot, context: AcpContext): AcpToolCallSnapshot; + /** Rewrites each update of a tool call, merged with the call's earlier updates. */ + toolCall?( + toolCall: AcpToolCallSnapshot, + context: AcpContext & { + mcpServerNames?: readonly string[]; + /** The call as Paseo last presented it, after every transformer. Absent on its first update. */ + previous?: AcpToolCallSnapshot; + }, + ): AcpToolCallSnapshot; } export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistration { diff --git a/packages/plugin/src/server/contracts.ts b/packages/plugin/src/server/contracts.ts index 45b283743dd4..8c46d3a14a53 100644 --- a/packages/plugin/src/server/contracts.ts +++ b/packages/plugin/src/server/contracts.ts @@ -5,6 +5,7 @@ import type { PluginCleanup } from "../contracts.js"; import type { ProviderRegistration } from "./provider.js"; import type { UsageSourceRegistration } from "./usage.js"; import type { PluginLifecycleRegistration } from "./lifecycle.js"; +import type { WorktreeManagerRegistration } from "./worktree.js"; export interface PluginHandlerContext { paseo: PaseoApi; @@ -64,6 +65,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration { ): void; registerProvider(provider: ProviderRegistration): void; registerUsageSource(source: UsageSourceRegistration): void; + registerWorktreeManager(manager: WorktreeManagerRegistration): () => void; } export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup; diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index 4ff70ae74dd8..fe41fac10c96 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -35,3 +35,14 @@ export { spawnProcess, execCommand, terminateProcess } from "./process.js"; export { defineAgentTool } from "./agent-tools.js"; export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js"; +export type { + PluginWorktreeContext, + PluginWorktreeCreateInput, + PluginWorktreeCreateResult, + PluginWorktreeRemoveRequest, + PluginWorktreeRemoveResult, + PluginWorktreeRestoreTarget, + PluginWorktreeRestoreRequest, + PluginWorktreeRestoreResult, + WorktreeManagerRegistration, +} from "./worktree.js"; diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index cedc2e301929..133e718b120f 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -37,7 +37,12 @@ export type PluginWorktreeCreateRequest = { slug: string; path: string; } & ( - | { kind: "branch-off"; baseRef: string } + | { + kind: "branch-off"; + baseRef: string; + /** Where the new branch starts when that is not `baseRef`, such as a fork's head. */ + readonly startPoint?: string; + } | { kind: "checkout-branch" } | { kind: "checkout-change-request"; diff --git a/packages/plugin/src/server/provider.test.ts b/packages/plugin/src/server/provider.test.ts index 7020c9a5269d..909acf17858f 100644 --- a/packages/plugin/src/server/provider.test.ts +++ b/packages/plugin/src/server/provider.test.ts @@ -1,5 +1,12 @@ import { describe, expect, it } from "vitest"; -import { ProviderInputSchema, type ProviderInput } from "./provider.js"; +import { + ProviderEventSchema, + ProviderInputSchema, + negotiateProviderCapabilities, + type ProviderEvent, + type ProviderInput, + type ProviderMetric, +} from "./provider.js"; type ReviewMode = "uncommitted" | "base" | "all"; type Delivery = "auto" | "steer"; @@ -64,3 +71,57 @@ describe("Provider review attachments", () => { }, ); }); + +describe("Provider metrics", () => { + const metrics: ProviderMetric[] = [ + { label: "Model", value: "agent-large" }, + { label: "Cache", value: "82%", tone: "ok" }, + ]; + + it("publishes the session's metrics as one replaceable list", () => { + const event: ProviderEvent = { type: "session.metrics", sessionId: "session-1", metrics }; + expect(ProviderEventSchema.parse(event)).toEqual(event); + }); + + it("attaches metrics to the turn they describe when it completes", () => { + const event: ProviderEvent = { + type: "session.turn", + sessionId: "session-1", + turnId: "turn-1", + state: "completed", + metrics, + }; + expect(ProviderEventSchema.parse(event)).toEqual(event); + }); + + it("keeps completing turns without metrics", () => { + const event: ProviderEvent = { + type: "session.turn", + sessionId: "session-1", + turnId: "turn-1", + state: "completed", + }; + expect(ProviderEventSchema.parse(event)).toEqual(event); + }); + + it("tells a provider whether this Paseo shows session metrics", () => { + const supported = ["prompt.message", "session.metrics"] as const; + expect( + negotiateProviderCapabilities(["prompt.message", "session.metrics"], supported), + ).toContain("session.metrics"); + // A Paseo from before session metrics never offers them. + expect(negotiateProviderCapabilities(["prompt.message"], supported)).toEqual([ + "prompt.message", + ]); + }); + + it("refuses a metric whose value is not text Paseo can show as given", () => { + expect( + ProviderEventSchema.safeParse({ + type: "session.metrics", + sessionId: "session-1", + metrics: [{ label: "Cost", value: 1.23 }], + }).success, + ).toBe(false); + }); +}); diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index 2256ef980669..ec56f51c6955 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -14,6 +14,7 @@ export const PROVIDER_CAPABILITIES = [ "session.archive", "session.configure", "session.list", + "session.metrics", "session.persistence", // Provider-reported peer turns belong to another client and are canceled only by explicit Stop. "session.shared_turns", @@ -50,9 +51,98 @@ export interface ProviderRegistration { description?: string; /** Plugin-directory-relative path to a self-contained SVG file. */ icon?: string; + /** http(s) page that helps users set up and troubleshoot the provider. Paseo opens it. */ + docsUrl?: string; + /** How users install the provider's CLI and which version they run. Every member is optional. */ + installation?: ProviderInstallation; connect(request: ProviderConnectRequest): Promise; } +export interface ProviderInstallation { + /** http(s) page that explains how to install the provider. Paseo opens it; it never installs. */ + installUrl?: string; + /** http(s) page that explains how to update the provider. */ + updateUrl?: string; + /** Report whether the provider is installed and which version. Runs only when a user asks. */ + inspect?(context: ProviderInstallationContext): Promise; + /** + * Report whether a newer version than `installedVersion` is available. The provider decides how + * to find out and what counts as newer; Paseo shows the result as written. Return `unknown` when + * it cannot tell. Runs only when a user asks, never before a session, and only after `inspect` + * reports the provider installed. Paseo reuses the answer while `inspect` reports the same + * version. + */ + checkForUpdates?(context: ProviderUpdateCheckContext): Promise; + /** + * Update the provider, usually by running its CLI's own updater. Paseo shows everything passed + * to `report` while it runs, then the returned message. A throw is a failure with its message. + * Runs only when a user asks. Paseo sets no deadline; `signal` aborts when the daemon stops. + */ + update?(context: ProviderUpdateContext): Promise; +} + +export interface ProviderUpdateCheckContext extends ProviderInstallationContext { + /** + * The version `inspect` reported, as written. Absent when `inspect` reported none or the + * provider declares no `inspect`. + */ + installedVersion?: string; +} + +export interface ProviderUpdateContext extends ProviderInstallationContext { + /** Shows output to the user as it happens, unchanged and in order. */ + report(event: ProviderUpdateReport): void; +} + +export const ProviderUpdateReportSchema = z + .object({ type: z.enum(["stdout", "stderr", "message"]), text: z.string() }) + .strip(); + +export type ProviderUpdateReport = z.infer; + +export const ProviderUpdateResultSchema = z.discriminatedUnion("status", [ + /** `message` is shown as written, such as which version is now installed. */ + z.object({ status: z.literal("succeeded"), message: z.string().optional() }).strip(), + z.object({ status: z.literal("failed"), message: z.string() }).strip(), +]); + +export type ProviderUpdateResult = z.infer; + +export interface ProviderInstallationContext { + /** The launch a session would use. Absent when the provider declares no `command`. */ + launch?: ProviderInstallationLaunch; + /** Aborted when Paseo stops waiting for the result. */ + signal: AbortSignal; +} + +export interface ProviderInstallationLaunch extends ProviderLaunch { + /** False when the executable was not found; `command` is then the configured command as written. */ + resolved: boolean; +} + +export const ProviderInspectionSchema = z.discriminatedUnion("status", [ + /** `version` is shown as written and passed to `checkForUpdates`; Paseo does not parse it. */ + z.object({ status: z.literal("installed"), version: z.string().optional() }).strip(), + z.object({ status: z.literal("not_installed") }).strip(), +]); + +export type ProviderInspection = z.infer; + +export const ProviderUpdateCheckSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("current") }).strip(), + /** `versions` and `message` are shown as written; Paseo does not parse, sort or compare them. */ + z + .object({ + status: z.literal("available"), + versions: z.array(z.string()).optional(), + message: z.string().optional(), + }) + .strip(), + z.object({ status: z.literal("unknown"), message: z.string().optional() }).strip(), +]); + +export type ProviderUpdateCheck = z.infer; + export type ProviderCatalogOptions = | { scope: "global"; force?: boolean; launch?: ProviderLaunch } | { scope: "workspace"; cwd: string; force?: boolean; launch?: ProviderLaunch }; @@ -485,6 +575,17 @@ export interface ProviderUsage { contextWindowUsedTokens?: number; } +/** + * One row of provider-owned detail about a session or a turn. Format `value` for + * reading: Paseo shows it as given. + */ +export interface ProviderMetric { + label: string; + value: string; + /** Colors the value. Omit it for an ordinary value. */ + tone?: "default" | "ok" | "warning" | "danger"; +} + interface ProviderTimelineIdentity { id: string; revertToken?: JsonValue; @@ -660,10 +761,21 @@ export type ProviderEvent = turnId: string; state: "started" | "completed" | "failed" | "canceled"; error?: ProviderError; + /** Shown on the turn's footer. Read when `state` is `"completed"`. */ + metrics?: readonly ProviderMetric[]; } /** Submitted work can remain pending between native turn brackets. */ | { type: "session.pending_work"; sessionId: string; pending: boolean } | { type: "session.usage"; sessionId: string; turnId?: string; usage: ProviderUsage } + | { + type: "session.metrics"; + sessionId: string; + /** + * Replaces the metrics shown for the session. An empty list clears them. Publish only when + * `session.metrics` was negotiated: a Paseo that does not offer it rejects this event. + */ + metrics: readonly ProviderMetric[]; + } | { type: "session.config"; sessionId: string; config: ProviderConfigState } | { type: "session.commands"; sessionId: string; commands: ProviderCommand[] } | { type: "session.permission"; sessionId: string; request: ProviderPermissionRequest } @@ -1176,6 +1288,13 @@ const usageSchema = z contextWindowUsedTokens: z.number().optional(), }) .strip(); +const metricSchema = z + .object({ + label: z.string(), + value: z.string(), + tone: z.enum(["default", "ok", "warning", "danger"]).optional(), + }) + .strip(); const worktreeCommandSchema = z .object({ index: z.number().int().positive(), @@ -1496,6 +1615,7 @@ export const ProviderEventSchema: z.ZodType = z.discriminatedUnio turnId: idSchema, state: z.enum(["started", "completed", "failed", "canceled"]), error: providerErrorSchema.optional(), + metrics: z.array(metricSchema).optional(), }) .strip(), z @@ -1509,6 +1629,13 @@ export const ProviderEventSchema: z.ZodType = z.discriminatedUnio usage: usageSchema, }) .strip(), + z + .object({ + type: z.literal("session.metrics"), + sessionId: idSchema, + metrics: z.array(metricSchema), + }) + .strip(), z .object({ type: z.literal("session.config"), sessionId: idSchema, config: configStateSchema }) .strip(), diff --git a/packages/plugin/src/server/usage.test.ts b/packages/plugin/src/server/usage.test.ts index b70e8d6d0119..81813654f21e 100644 --- a/packages/plugin/src/server/usage.test.ts +++ b/packages/plugin/src/server/usage.test.ts @@ -96,12 +96,12 @@ test.each([ ])( "duration %s owns the window's identity and both names", (durationSeconds, id, label, shortLabel) => { - expect( - windowFromReportedDuration({ - durationSeconds: durationSeconds as number | null, - unknown: { id: "primary", label: "Primary limit", shortLabel: "" }, - utilizationPct: 11, - }), - ).toMatchObject({ id, label, shortLabel, usedPct: 11 }); + const window = windowFromReportedDuration({ + durationSeconds: durationSeconds as number | null, + unknown: { id: "primary", label: "Primary limit", shortLabel: "" }, + utilizationPct: 11, + }); + expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 }); + expect(window.durationSeconds).toBe(durationSeconds ?? undefined); }, ); diff --git a/packages/plugin/src/server/usage.ts b/packages/plugin/src/server/usage.ts index fa23ca9c915c..67b0cb507139 100644 --- a/packages/plugin/src/server/usage.ts +++ b/packages/plugin/src/server/usage.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import { z, type ZodType } from "zod"; +import { ProviderLaunchSchema } from "./provider.js"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; export interface UsageWindow { @@ -15,6 +16,8 @@ export interface UsageWindow { usedPct?: number | null; remainingPct?: number | null; resetsAt?: string | null; + /** Full length of the quota window when known. */ + durationSeconds?: number; runsOutAt?: string | null; shortfallPct?: number | null; tone?: "default" | "ok" | "warning" | "danger"; @@ -47,6 +50,8 @@ export type UsageReport = | { status: "available"; planLabel?: string; + /** When the provider measured the quota, if the report returns a previous reading. */ + observedAt?: string; windows: UsageWindow[]; balances?: UsageBalance[]; details?: UsageDetail[]; @@ -60,17 +65,20 @@ export interface UsageAccount { label?: string; /** Harness owning this login, e.g. Codex, OpenCode, Pi or OMP. */ harness?: string; + /** Provider ID associated with this login, used as a hint for default visibility. */ + provider?: string; /** Store locator, opaque to the daemon. */ input: JsonValue; } export const UsageScopeSchema = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("global") }), + z.object({ kind: z.literal("global"), launch: ProviderLaunchSchema.optional() }), z.object({ kind: z.literal("session"), provider: z.string(), model: z.string().optional(), env: z.record(z.string(), z.string()), + launch: ProviderLaunchSchema.optional(), }), ]); export type UsageScope = z.infer; @@ -79,6 +87,10 @@ export interface UsageSourceRegistration { id: string; label: string; icon?: string; + /** Provider whose resolved launch is needed for discovery. */ + provider?: string; + /** Provider IDs associated with this source, used as a hint for default visibility. */ + providers?: readonly string[]; input: ZodType; /** Accounts for this scope only. The same key in any scope identifies the same account. */ discover(scope: UsageScope): Promise; @@ -92,6 +104,7 @@ export function windowFromUsedPct(input: { shortLabel?: string; summary?: boolean; utilizationPct: number | null | undefined; + durationSeconds?: number; resetsAt?: string | null; tone?: UsageWindow["tone"]; }): UsageWindow { @@ -103,6 +116,7 @@ export function windowFromUsedPct(input: { remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct), resetsAt: input.resetsAt ?? null, }; + if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds; if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel; if (input.summary) window.summary = true; if (input.tone) window.tone = input.tone; @@ -125,11 +139,10 @@ export function windowFromReportedDuration(input: { summary?: boolean; tone?: UsageWindow["tone"]; }): UsageWindow { - const duration = input.durationSeconds; - const name = - duration !== null && Number.isFinite(duration) && duration > 0 - ? durationWindowName(duration) - : input.unknown; + const reported = input.durationSeconds; + const duration = + reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined; + const name = duration === undefined ? input.unknown : durationWindowName(duration); const scope = input.scope; return windowFromUsedPct({ id: scope ? `${scope.id}:${name.id}` : name.id, @@ -138,6 +151,7 @@ export function windowFromReportedDuration(input: { ? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}` : name.shortLabel, utilizationPct: input.utilizationPct, + durationSeconds: duration, resetsAt: input.resetsAt, summary: input.summary, tone: input.tone, diff --git a/packages/plugin/src/server/worktree.ts b/packages/plugin/src/server/worktree.ts new file mode 100644 index 000000000000..511f442d36ee --- /dev/null +++ b/packages/plugin/src/server/worktree.ts @@ -0,0 +1,69 @@ +import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle.js"; + +/** Context passed to worktree manager callbacks. */ +export type PluginWorktreeContext = PluginHookContext; + +/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */ +export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest & { + /** True when the worktree comes from an untrusted source such as a fork change request; skip repository-defined hooks. */ + readonly untrusted: boolean; + /** Resolved remote head commit SHA for change-request checkouts when available. */ + readonly headSha?: string; +}; + +/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */ +export interface PluginWorktreeCreateResult { + type: "created"; + path: string; +} + +export interface PluginWorktreeRemoveRequest { + readonly repoRoot: string | null; + readonly path: string; + readonly branch: string | null; + readonly reason: "archive" | "rollback"; + readonly force: boolean; + /** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */ + readonly untrusted: boolean; +} + +/** Return `{ type: "removed" }` after removing the worktree, or `undefined` to fall back to Git. */ +export interface PluginWorktreeRemoveResult { + type: "removed"; +} + +export type PluginWorktreeRestoreTarget = + | { readonly type: "branch"; readonly branch: string } + | { readonly type: "commit"; readonly commit: string } + | { readonly type: "from-base"; readonly branch: string; readonly baseRef: string }; + +export interface PluginWorktreeRestoreRequest { + readonly repoRoot: string; + /** Recorded path the worktree must be restored to. */ + readonly path: string; + readonly target: PluginWorktreeRestoreTarget; + readonly baseRef: string | null; + /** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */ + readonly untrusted: boolean; +} + +/** Return `{ type: "restored", path }` after recreating the worktree, or `undefined` to fall back to Git. */ +export interface PluginWorktreeRestoreResult { + type: "restored"; + path: string; +} + +export interface WorktreeManagerRegistration { + create( + request: PluginWorktreeCreateInput, + context: PluginWorktreeContext, + ): Promise; + remove?( + request: PluginWorktreeRemoveRequest, + context: PluginWorktreeContext, + ): Promise; + restore?( + request: PluginWorktreeRestoreRequest, + context: PluginWorktreeContext, + ): Promise; +} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 2a44a96e725f..6ba2736445ea 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.17.0-beta.1", + "version": "0.17.4", "description": "Paseo shared protocol schemas and wire types", "license": "Apache-2.0", "files": [ diff --git a/packages/protocol/src/agent-types.ts b/packages/protocol/src/agent-types.ts index d9da3cb54a5d..2bbcca7675f0 100644 --- a/packages/protocol/src/agent-types.ts +++ b/packages/protocol/src/agent-types.ts @@ -147,6 +147,8 @@ export interface ProviderSnapshotEntry { label?: string; description?: string; iconSvg?: string; + /** The page that helps users set up and troubleshoot this provider. */ + docsUrl?: string; defaultModeId?: string | null; } @@ -233,6 +235,18 @@ export interface AgentUsage { contextWindowUsedTokens?: number; } +export type AgentMetricTone = "default" | "ok" | "warning" | "danger"; + +/** + * One provider-owned label/value row. The provider formats `value`; Paseo renders + * it as given and never interprets it. + */ +export interface AgentMetric { + label: string; + value: string; + tone?: AgentMetricTone; +} + export const TOOL_CALL_ICON_NAMES = [ "wrench", "square_terminal", @@ -425,7 +439,13 @@ export type AgentTimelineItem = export type AgentStreamEvent = | { type: "thread_started"; sessionId: string; provider: AgentProvider } | { type: "turn_started"; provider: AgentProvider; turnId?: string } - | { type: "turn_completed"; provider: AgentProvider; usage?: AgentUsage; turnId?: string } + | { + type: "turn_completed"; + provider: AgentProvider; + usage?: AgentUsage; + turnId?: string; + metrics?: AgentMetric[]; + } | { type: "usage_updated"; provider: AgentProvider; usage: AgentUsage; turnId?: string } | { type: "mode_changed"; diff --git a/packages/protocol/src/client-capabilities.ts b/packages/protocol/src/client-capabilities.ts index 68243d99cd4d..9c2abd389ba0 100644 --- a/packages/protocol/src/client-capabilities.ts +++ b/packages/protocol/src/client-capabilities.ts @@ -69,6 +69,10 @@ export const CLIENT_CAPS = { // agent-snapshot fields. Paired with the `agent.companion.update_entry.*` // operations; not the source fork's `companionStream` capability name. companionStreamPortV1: "companion_stream_port_v1", + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once client floor >= v0.17.2. + // An agent sender's steer means wait-for-turn-end from clients without it, because older + // CLIs and connected hosts send an explicit steer for every default agent send. + agentActiveTurnBehaviors: "agent_active_turn_behaviors", } as const; export type ClientCapability = (typeof CLIENT_CAPS)[keyof typeof CLIENT_CAPS]; diff --git a/packages/protocol/src/messages.active-turn-behavior.test.ts b/packages/protocol/src/messages.active-turn-behavior.test.ts index 729e3ade4f8c..597daae97aa0 100644 --- a/packages/protocol/src/messages.active-turn-behavior.test.ts +++ b/packages/protocol/src/messages.active-turn-behavior.test.ts @@ -2,6 +2,8 @@ import { AgentStreamEventPayloadSchema, AgentTimelineEntryPayloadSchema, SendAgentMessageRequestSchema, + SendAgentMessageResponseMessageSchema, + SendAgentMessageSchema, } from "./messages"; import { describe, expect, it } from "vitest"; import { z } from "zod"; @@ -29,6 +31,46 @@ describe("send_agent_message_request active-turn behavior", () => { }); }); +describe("agent sender active-turn behaviors", () => { + it("accepts queue on a send request and reports the applied behavior in the response", () => { + expect( + SendAgentMessageRequestSchema.parse({ + type: "send_agent_message_request", + requestId: "request-3", + agentId: "agent-1", + text: "Report when you are done", + sourceAgentId: "parent", + activeTurnBehavior: "queue", + }).activeTurnBehavior, + ).toBe("queue"); + expect( + SendAgentMessageResponseMessageSchema.parse({ + type: "send_agent_message_response", + payload: { + requestId: "request-3", + agentId: "agent-1", + accepted: true, + deliveryStatus: "queued", + activeTurnBehavior: "queue", + guidance: "Queued.", + error: null, + }, + }).payload, + ).toMatchObject({ activeTurnBehavior: "queue", guidance: "Queued." }); + }); + + it("keeps a person's send_agent_message to interrupt and steer", () => { + expect( + SendAgentMessageSchema.safeParse({ + type: "send_agent_message", + agentId: "agent-1", + text: "hello", + activeTurnBehavior: "queue", + }).success, + ).toBe(false); + }); +}); + describe("canonical timeline turn ID compatibility", () => { it("accepts both new turn-tagged wire rows and legacy rows without IDs", () => { const entry = { diff --git a/packages/protocol/src/messages.checkout-pr-schema.test.ts b/packages/protocol/src/messages.checkout-pr-schema.test.ts index 121efccbcd3d..0a7eb8a26f24 100644 --- a/packages/protocol/src/messages.checkout-pr-schema.test.ts +++ b/packages/protocol/src/messages.checkout-pr-schema.test.ts @@ -834,7 +834,7 @@ describe("checkout PR schemas", () => { }); test.each( - ["hopliteProvider", "fxProvider"].flatMap((name) => + ["hopliteProvider", "fxProvider", "gooseProvider", "hermesProvider"].flatMap((name) => [undefined, false, true].map((value) => [name, value] as const), ), )("accepts optional bundled provider capability (%s: %s)", (name, value) => { diff --git a/packages/protocol/src/messages.hub.test.ts b/packages/protocol/src/messages.hub.test.ts index 57f10ecdb931..125c2ea79697 100644 --- a/packages/protocol/src/messages.hub.test.ts +++ b/packages/protocol/src/messages.hub.test.ts @@ -94,6 +94,19 @@ describe("Hub session protocol", () => { expect(SessionOutboundMessageSchema.parse(response)).toEqual(response); }); + test("round-trips the working directory on named-agent validation", () => { + const request = { + type: "hub.execution.agent.validate.request", + requestId: "validate-workspace", + provider: "opencode", + model: "workspace-model", + cwd: "/workspace", + }; + + expect(SessionInboundMessageSchema.parse(request)).toEqual(request); + expect(SessionInboundMessageSchema.safeParse({ ...request, cwd: 123 }).success).toBe(false); + }); + test("accepts the Hub execution create request", () => { const message = { type: "hub.execution.agent.create.request", diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index b86de38980fc..c8f8d21487d8 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -301,6 +301,7 @@ export type MutableDaemonConfig = z.infer; export type MutableDaemonConfigPatch = z.infer; import type { AgentCapabilityFlags, + AgentMetric, AgentModelDefinition, AgentMode, AgentPermissionRequest, @@ -442,6 +443,7 @@ export const ProviderSnapshotEntrySchema = z.object({ label: z.string().optional(), description: z.string().optional(), iconSvg: z.string().optional(), + docsUrl: z.string().optional(), defaultModeId: z.string().nullable().optional(), }); @@ -495,6 +497,12 @@ const AgentUsageSchema: z.ZodType = z.object({ contextWindowUsedTokens: z.number().optional(), }); +export const AgentMetricSchema: z.ZodType = z.object({ + label: z.string(), + value: z.string(), + tone: z.enum(["default", "ok", "warning", "danger"]).optional(), +}); + const McpStdioServerConfigSchema = z.object({ type: z.literal("stdio"), command: z.string(), @@ -840,6 +848,7 @@ export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [ provider: AgentProviderSchema, turnId: z.string().optional(), usage: AgentUsageSchema.optional(), + metrics: z.array(AgentMetricSchema).optional(), }), z.object({ type: z.literal("turn_failed"), @@ -964,6 +973,7 @@ export const AgentSnapshotPayloadSchema = z.object({ /** Opaque. Changes whenever the accounts this agent reports usage for can change. */ usageScopeKey: z.string().optional(), lastUsage: AgentUsageSchema.optional(), + sessionMetrics: z.array(AgentMetricSchema).optional(), lastError: z.string().optional(), title: z.string().nullable(), labels: z.record(z.string(), z.string()).default({}), @@ -1480,6 +1490,9 @@ const ImageAttachmentSchema = z.object({ export const ActiveTurnBehaviorSchema = z.enum(["interrupt", "steer"]); export type ActiveTurnBehavior = z.infer; +/** An agent sender may also queue: wait until the recipient's running turn ends. */ +export const AgentActiveTurnBehaviorSchema = z.enum(["interrupt", "steer", "queue"]); +export type AgentActiveTurnBehavior = z.infer; export const SendAgentMessageSchema = z.object({ type: z.literal("send_agent_message"), @@ -1659,7 +1672,8 @@ export const SendAgentMessageRequestSchema = z.object({ sourceAgentServerId: z.string().min(1).optional(), sessionMode: z.string().optional(), messageId: z.string().optional(), // Client-provided ID for deduplication - activeTurnBehavior: ActiveTurnBehaviorSchema.optional(), + /** queue needs an agent sender. */ + activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(), images: z.array(ImageAttachmentSchema).optional(), attachments: AgentAttachmentsSchema, }); @@ -2117,6 +2131,34 @@ export const ProviderDiagnosticRequestMessageSchema = z.object({ requestId: z.string(), }); +export const ProviderInstallationInspectRequestMessageSchema = z.object({ + type: z.literal("provider.installation.inspect.request"), + provider: AgentProviderSchema, + /** Skip the daemon's short result cache and ask the provider again. */ + refresh: z.boolean().optional(), + requestId: z.string(), +}); + +export const ProviderInstallationCheckUpdatesRequestMessageSchema = z.object({ + type: z.literal("provider.installation.check_updates.request"), + provider: AgentProviderSchema, + /** Skip the daemon's update-check cache and ask the provider again. */ + refresh: z.boolean().optional(), + requestId: z.string(), +}); + +export const ProviderInstallationUpdateRequestMessageSchema = z.object({ + type: z.literal("provider.installation.update.request"), + provider: AgentProviderSchema, + requestId: z.string(), +}); + +export const ProviderInstallationUpdateSubscribeRequestMessageSchema = z.object({ + type: z.literal("provider.installation.update.subscribe.request"), + provider: AgentProviderSchema, + requestId: z.string(), +}); + export const ProviderUsageListRequestMessageSchema = z.object({ type: z.literal("provider.usage.list.request"), requestId: z.string(), @@ -3861,6 +3903,7 @@ export const HubExecutionAgentValidateRequestSchema = z.object({ type: z.literal("hub.execution.agent.validate.request"), requestId: z.string(), provider: z.string(), + cwd: z.string().optional(), model: z.string().optional(), modeId: z.string().optional(), thinkingOptionId: z.string().optional(), @@ -4073,6 +4116,10 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ GetProvidersSnapshotRequestMessageSchema, RefreshProvidersSnapshotRequestMessageSchema, ProviderDiagnosticRequestMessageSchema, + ProviderInstallationInspectRequestMessageSchema, + ProviderInstallationCheckUpdatesRequestMessageSchema, + ProviderInstallationUpdateRequestMessageSchema, + ProviderInstallationUpdateSubscribeRequestMessageSchema, ProviderUsageListRequestMessageSchema, UsageListReportsRequestMessageSchema, ResumeAgentRequestMessageSchema, @@ -4428,6 +4475,8 @@ export const ServerInfoStatusPayloadSchema = z usageSetting: z.boolean().optional(), usageSources: z.boolean().optional(), usageReportsStreaming: z.boolean().optional(), + // COMPAT(providerInstallation): added in v0.17.0, remove gate after 2027-05-13. + providerInstallation: z.boolean().optional(), // COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10. providersSnapshotCwd: z.boolean().optional(), // COMPAT(directorySync): added in v0.3.x, remove gate after 2027-02-12. @@ -4620,6 +4669,10 @@ export const ServerInfoStatusPayloadSchema = z // COMPAT(providerConfigRename): added in v0.2.X, remove after 2027-02-02 when old daemons are unsupported. // Daemon migrates persisted agents when a provider account is renamed. providerConfigRename: z.boolean().optional(), + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter. + gooseProvider: z.boolean().optional(), + // COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter. + hermesProvider: z.boolean().optional(), // COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16. importSessionWorkspaceTarget: z.boolean().optional(), // COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02. @@ -4645,6 +4698,8 @@ export const ServerInfoStatusPayloadSchema = z canonicalSubmittedPrompts: z.boolean().optional(), agentMessageProvenance: z.boolean().optional(), agentMessageBatching: z.boolean().optional(), + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove gate after 2027-05-22. + agentActiveTurnBehaviors: z.boolean().optional(), // COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31. agentTurnIdentity: z.boolean().optional(), // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. @@ -5596,6 +5651,8 @@ export const AgentTimelineEntryPayloadSchema = z.object({ seqEnd: z.number().int().nonnegative(), sourceSeqRanges: z.array(AgentTimelineSeqRangeSchema), collapsed: z.array(z.enum(["assistant_merge", "reasoning_merge", "tool_lifecycle", "identity"])), + /** Set on the row that carries the turn footer: the turn's last assistant message, else its last tool call. */ + turnMetrics: z.array(AgentMetricSchema).optional(), }); export const FetchAgentTimelineResponseMessageSchema = z.object({ @@ -6073,6 +6130,10 @@ export const SendAgentMessageResponseMessageSchema = z.object({ agentId: z.string(), accepted: z.boolean(), deliveryStatus: z.literal("queued").optional(), + /** The behavior applied to a queued agent message. */ + activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(), + /** What happens to a queued agent message, and how the sender can change it. */ + guidance: z.string().optional(), error: z.string().nullable(), }), }); @@ -6343,6 +6404,17 @@ const CheckoutStatusCommonSchema = z.object({ // upstream branch name is not necessarily currentBranch, so composing one is wrong. // aheadOfOrigin/behindOfOrigin are measured against exactly this ref. upstreamRef: z.string().nullable().optional(), + // How currentBranch relates to its upstream: "tracked" (upstreamRef and the counts are set), + // "none" (never pushed; Push does a first push), "gone" (the upstream's remote-tracking ref no + // longer exists, as after the remote branch is deleted), or "unknown" (the daemon cannot tell, + // as when the clone keeps no remote-tracking ref for the upstream). Absent from daemons that + // predate it, which report all but "tracked" as a null upstreamRef. + upstreamState: z.enum(["tracked", "none", "gone", "unknown"]).optional(), + // The remote a first push publishes currentBranch to, when the daemon can confirm git would + // push the branch there too. Null when there is no such remote, as when origin is missing or + // git is set to push the branch to another remote (branch..pushRemote, + // remote.pushDefault). Absent from daemons that predate it. + firstPushRemote: z.string().nullable().optional(), forgeWeb: ForgeWebSchema.optional(), }); @@ -7404,6 +7476,142 @@ export const ProviderDiagnosticResponseMessageSchema = z.object({ }), }); +/** Provider-owned facts; `version` is an opaque string the app shows as written. */ +export const ProviderInstallationInspectionSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("installed"), version: z.string().optional() }), + z.object({ status: z.literal("not_installed") }), + z.object({ status: z.literal("error"), message: z.string() }), +]); + +export const ProviderInstallationSchema = z.object({ + installUrl: z.string().optional(), + updateUrl: z.string().optional(), + /** Absent when the provider does not report its installation. */ + inspection: ProviderInstallationInspectionSchema.optional(), + /** True when the provider can run its own update through `provider.installation.update`. */ + canUpdate: z.boolean().optional(), +}); + +export const ProviderInstallationInspectResponseMessageSchema = z.object({ + type: z.literal("provider.installation.inspect.response"), + payload: z.object({ + provider: AgentProviderSchema, + /** Null when the provider declares no installation contract. */ + installation: ProviderInstallationSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +/** + * The provider's answer to "is a newer version available". `versions` and `message` are opaque + * strings the app shows as written. `error` means the check threw or missed its deadline. + */ +export const ProviderInstallationUpdateCheckSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("current") }), + z.object({ + status: z.literal("available"), + versions: z.array(z.string()).optional(), + message: z.string().optional(), + }), + z.object({ status: z.literal("unknown"), message: z.string().optional() }), + z.object({ status: z.literal("error"), message: z.string() }), +]); + +export const ProviderInstallationCheckUpdatesResponseMessageSchema = z.object({ + type: z.literal("provider.installation.check_updates.response"), + payload: z.object({ + provider: AgentProviderSchema, + /** Null when the provider cannot check for updates. */ + updateCheck: ProviderInstallationUpdateCheckSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +/** One piece of updater output, shown unchanged and in order. */ +export const ProviderInstallationUpdateOutputSchema = z.object({ + type: z.enum(["stdout", "stderr", "message"]), + text: z.string(), +}); + +/** The state of one provider update. Messages are the provider's, shown as written. */ +export const ProviderInstallationUpdateOperationSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("running"), id: z.string(), startedAt: z.string() }), + z.object({ + status: z.literal("succeeded"), + id: z.string(), + startedAt: z.string(), + finishedAt: z.string(), + message: z.string().optional(), + }), + z.object({ + status: z.literal("failed"), + id: z.string(), + startedAt: z.string(), + finishedAt: z.string(), + message: z.string(), + }), +]); + +/** The latest update of a provider since the daemon started, with its retained output. */ +export const ProviderInstallationUpdateSchema = z.object({ + operation: ProviderInstallationUpdateOperationSchema, + output: z.array(ProviderInstallationUpdateOutputSchema), + /** True when the oldest output was dropped to stay within the daemon's output limit. */ + truncated: z.boolean().optional(), +}); + +export const ProviderInstallationUpdateResponseMessageSchema = z.object({ + type: z.literal("provider.installation.update.response"), + payload: z.object({ + provider: AgentProviderSchema, + /** The update this request started, or the one already running. */ + update: ProviderInstallationUpdateSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +export const ProviderInstallationUpdateSubscribeResponseMessageSchema = z.object({ + type: z.literal("provider.installation.update.subscribe.response"), + payload: z.object({ + provider: AgentProviderSchema, + subscriptionId: z.string().optional(), + /** Null when the provider has not been updated since the daemon started. */ + update: ProviderInstallationUpdateSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +/** + * Sent to `provider.installation.update.subscribe` owners when an update starts, reports output + * or finishes. `output` holds only the entries new since the previous progress for `operation.id`. + */ +export const ProviderInstallationUpdateProgressMessageSchema = z.object({ + type: z.literal("provider.installation.update.progress"), + payload: z.object({ + subscriptionId: z.string().optional(), + provider: AgentProviderSchema, + operation: ProviderInstallationUpdateOperationSchema, + output: z.array(ProviderInstallationUpdateOutputSchema), + }), +}); + +/** + * Sent to `provider.installation.update.subscribe` owners when a refresh of the provider drops + * the failed update `operationId`, so the provider has no current update. + */ +export const ProviderInstallationUpdateClearedMessageSchema = z.object({ + type: z.literal("provider.installation.update.cleared"), + payload: z.object({ + subscriptionId: z.string().optional(), + provider: AgentProviderSchema, + operationId: z.string(), + }), +}); + export const ProviderUsageToneSchema = z.enum(["default", "ok", "warning", "danger"]); export const ProviderUsageStatusSchema = z.enum(["available", "unavailable", "error"]); @@ -7420,6 +7628,7 @@ export const ProviderUsageWindowSchema = z.object({ usedPct: z.number().nullable().optional(), remainingPct: z.number().nullable().optional(), resetsAt: z.string().nullable().optional(), + durationSeconds: z.number().optional(), runsOutAt: z.string().nullable().optional(), shortfallPct: z.number().nullable().optional(), tone: ProviderUsageToneSchema.optional(), @@ -7484,6 +7693,7 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [ const AvailableUsageReportSchema = z.object({ status: z.literal("available"), planLabel: z.string().optional(), + observedAt: z.string().optional(), windows: z.array(ProviderUsageWindowSchema), balances: z.array(ProviderUsageBalanceSchema).optional(), details: z.array(ProviderUsageDetailSchema).optional(), @@ -7500,6 +7710,8 @@ export const UsageReportEntrySchema = z.object({ sourceId: z.string(), sourceLabel: z.string(), icon: z.string().optional(), + /** Host hint for whether this report starts shown until the user overrides it. Absent means true. */ + defaultEnabled: z.boolean().optional(), report: UsageReportSchema, // Successful completion time; fetchedAt remains the attempt timestamp for ordering. successfulAt: z.string().optional(), @@ -8296,6 +8508,12 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ ProvidersSnapshotUpdateMessageSchema, RefreshProvidersSnapshotResponseMessageSchema, ProviderDiagnosticResponseMessageSchema, + ProviderInstallationInspectResponseMessageSchema, + ProviderInstallationCheckUpdatesResponseMessageSchema, + ProviderInstallationUpdateResponseMessageSchema, + ProviderInstallationUpdateSubscribeResponseMessageSchema, + ProviderInstallationUpdateProgressMessageSchema, + ProviderInstallationUpdateClearedMessageSchema, ProviderUsageListResponseMessageSchema, UsageListReportsUpdateMessageSchema, UsageListReportsResponseMessageSchema, @@ -8483,6 +8701,30 @@ export type RefreshProvidersSnapshotResponseMessage = z.infer< export type ProviderDiagnosticResponseMessage = z.infer< typeof ProviderDiagnosticResponseMessageSchema >; +export type ProviderInstallation = z.infer; +export type ProviderInstallationInspection = z.infer; +export type ProviderInstallationInspectResponseMessage = z.infer< + typeof ProviderInstallationInspectResponseMessageSchema +>; +export type ProviderInstallationUpdateCheck = z.infer; +export type ProviderInstallationCheckUpdatesResponseMessage = z.infer< + typeof ProviderInstallationCheckUpdatesResponseMessageSchema +>; +export type ProviderInstallationUpdateOutput = z.infer< + typeof ProviderInstallationUpdateOutputSchema +>; +export type ProviderInstallationUpdateOperation = z.infer< + typeof ProviderInstallationUpdateOperationSchema +>; +export type ProviderInstallationUpdate = z.infer; +export type ProviderInstallationUpdateProgress = Omit< + z.infer["payload"], + "subscriptionId" +>; +export type ProviderInstallationUpdateCleared = Omit< + z.infer["payload"], + "subscriptionId" +>; export type ProviderUsageTone = z.infer; export type UsageProblem = z.infer; export type UsageReport = z.infer; diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index 9de54653418b..b5346ec56bfa 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -5,6 +5,7 @@ import { MutableDaemonConfigPatchSchema, UsageReportEntrySchema, AgentSnapshotPayloadSchema, + AgentStreamEventPayloadSchema, AgentTimelineItemPayloadSchema, BranchSuggestionsResponseSchema, ServerInfoStatusPayloadSchema, @@ -675,6 +676,9 @@ test("usage entries accept older failures and additive successful snapshots", () successfulAt: "2026-10-17T10:00:15Z", }; expect(UsageReportEntrySchema.parse(available)).toEqual(available); + const hintedOff = { ...available, defaultEnabled: false }; + expect(UsageReportEntrySchema.parse(hintedOff)).toEqual(hintedOff); + expect(UsageReportEntrySchema.omit({ defaultEnabled: true }).parse(hintedOff)).toEqual(available); expect( UsageReportEntrySchema.omit({ lastSuccessful: true, successfulAt: true }).parse(available), ).toEqual({ ...oldEntry, report: available.report }); @@ -785,3 +789,91 @@ test("speech config reads remain compatible with clients before features and fut }).features?.voiceMode?.stt, ).toEqual({ provider: "future", region: "eu" }); }); + +describe("provider metrics", () => { + const metrics = [ + { label: "Model", value: "gpt-5.5" }, + { label: "Cache", value: "82%", tone: "ok" }, + ]; + const snapshot = { + id: "agent-1", + provider: "codex", + cwd: "/tmp/project", + model: null, + thinkingOptionId: null, + effectiveThinkingOptionId: null, + createdAt: "2026-11-22T00:00:00.000Z", + updatedAt: "2026-11-22T00:00:00.000Z", + lastUserMessageAt: null, + status: "idle", + capabilities: { + supportsStreaming: true, + supportsSessionPersistence: true, + supportsDynamicModes: true, + supportsMcpServers: true, + supportsReasoningStream: true, + supportsToolInvocations: true, + }, + currentModeId: null, + availableModes: [], + pendingPermissions: [], + persistence: null, + title: null, + labels: {}, + }; + const turnCompleted = { type: "turn_completed", provider: "codex", turnId: "turn-1" }; + const entry = { + provider: "codex", + item: { type: "assistant_message", text: "Done" }, + timestamp: "2026-11-22T00:00:00.000Z", + seqStart: 1, + seqEnd: 1, + sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }], + collapsed: [], + }; + + test("new apps read session, turn and timeline metrics from a new daemon", () => { + expect( + AgentSnapshotPayloadSchema.parse({ ...snapshot, sessionMetrics: metrics }).sessionMetrics, + ).toEqual(metrics); + expect(AgentStreamEventPayloadSchema.parse({ ...turnCompleted, metrics })).toEqual({ + ...turnCompleted, + metrics, + }); + expect(AgentTimelineEntryPayloadSchema.parse({ ...entry, turnMetrics: metrics })).toEqual({ + ...entry, + turnMetrics: metrics, + }); + }); + + test("new apps accept payloads from daemons that send no metrics", () => { + expect(AgentSnapshotPayloadSchema.parse(snapshot).sessionMetrics).toBeUndefined(); + expect(AgentStreamEventPayloadSchema.parse(turnCompleted)).toEqual(turnCompleted); + expect(AgentTimelineEntryPayloadSchema.parse(entry)).toEqual(entry); + }); + + test("apps released before metrics drop the fields they do not know", () => { + const legacySnapshot = AgentSnapshotPayloadSchema.omit({ sessionMetrics: true }); + const legacyTurnCompleted = z.object({ + type: z.literal("turn_completed"), + provider: z.string(), + turnId: z.string().optional(), + }); + const legacyEntry = AgentTimelineEntryPayloadSchema.omit({ turnMetrics: true }); + + expect(legacySnapshot.parse({ ...snapshot, sessionMetrics: metrics })).not.toHaveProperty( + "sessionMetrics", + ); + expect(legacyTurnCompleted.parse({ ...turnCompleted, metrics })).toEqual(turnCompleted); + expect(legacyEntry.parse({ ...entry, turnMetrics: metrics })).toEqual(entry); + }); + + test("metric tone is a closed set, so a new tone needs a capability gate", () => { + expect( + AgentTimelineEntryPayloadSchema.safeParse({ + ...entry, + turnMetrics: [{ label: "Cache", value: "82%", tone: "sparkly" }], + }).success, + ).toBe(false); + }); +}); diff --git a/packages/protocol/src/provider-manifest.ts b/packages/protocol/src/provider-manifest.ts index 2192d5c05a85..a3d31b771149 100644 --- a/packages/protocol/src/provider-manifest.ts +++ b/packages/protocol/src/provider-manifest.ts @@ -27,6 +27,8 @@ export interface AgentProviderDefinition { description: string; /** Builtin provider this definition extends, when it comes from a custom provider account. */ baseProviderId?: string; + /** The page that helps users set up and troubleshoot this provider. */ + docsUrl?: string; enabledByDefault?: boolean; defaultModeId: string | null; modes: AgentProviderModeDefinition[]; @@ -201,6 +203,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [ id: "claude", label: "Claude", description: "Anthropic's multi-tool assistant with MCP support, streaming, and deep reasoning", + docsUrl: "https://paseo.sh/docs/supported-providers/claude-code", defaultModeId: "auto", modes: CLAUDE_MODES, voice: { @@ -213,6 +216,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [ id: "codex", label: "Codex", description: "OpenAI's Codex workspace agent with sandbox controls and optional network access", + docsUrl: "https://paseo.sh/docs/supported-providers/codex", defaultModeId: "auto-review", modes: CODEX_MODES, voice: { @@ -225,6 +229,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [ id: "copilot", label: "Copilot", description: "GitHub Copilot via Agent Client Protocol with dynamic modes and session support", + docsUrl: "https://paseo.sh/docs/supported-providers/github-copilot", defaultModeId: "https://agentclientprotocol.com/protocol/session-modes#agent", modes: COPILOT_MODES, }, @@ -232,6 +237,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [ id: "opencode", label: "OpenCode", description: "Open-source coding assistant with multi-provider model support", + docsUrl: "https://paseo.sh/docs/supported-providers/opencode", // No static default: OpenCode users can rename or delete any agent, // including "build". Leaving this unset means the daemon and OpenCode // itself decide (see normalizeOpenCodeModeId in opencode-agent.ts). @@ -246,6 +252,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [ id: "pi", label: "Pi", description: "Minimal terminal-based coding agent with multi-provider LLM support", + docsUrl: "https://paseo.sh/docs/supported-providers/pi", defaultModeId: null, modes: [], }, @@ -253,6 +260,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [ id: "omp", label: "Oh My Pi", description: "Multi-provider coding agent with native approvals, host tools, and subagents", + docsUrl: "https://paseo.sh/docs/supported-providers/omp", enabledByDefault: false, defaultModeId: "full", modes: OMP_MODES, diff --git a/packages/protocol/tests/validation/ws-outbound.test.ts b/packages/protocol/tests/validation/ws-outbound.test.ts index 18b0cd999fba..7009bdcc9efc 100644 --- a/packages/protocol/tests/validation/ws-outbound.test.ts +++ b/packages/protocol/tests/validation/ws-outbound.test.ts @@ -260,6 +260,62 @@ const SourceSchema = z.object({ }); }); + it("preserves turn metrics on a completed turn and on its timeline row", () => { + const metrics = [ + { label: "Model", value: "gpt-5.5" }, + { label: "Cache", value: "82%", tone: "ok" }, + ]; + const completed = { + type: "session", + message: { + type: "agent_stream", + payload: { + agentId: "agent-1", + event: { type: "turn_completed", provider: "codex", turnId: "turn-1", metrics }, + timestamp: "2026-11-22T00:00:00.000Z", + }, + }, + }; + const timeline = { + type: "session", + message: { + type: "fetch_agent_timeline_response", + payload: { + requestId: "timeline", + agentId: "agent-1", + agent: null, + direction: "tail", + projection: "projected", + epoch: "epoch-1", + reset: false, + staleCursor: false, + gap: false, + window: { minSeq: 1, maxSeq: 1, nextSeq: 2 }, + startCursor: null, + endCursor: null, + hasOlder: false, + hasNewer: false, + entries: [ + { + provider: "codex", + item: { type: "assistant_message", text: "Done" }, + timestamp: "2026-11-22T00:00:00.000Z", + seqStart: 1, + seqEnd: 1, + sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }], + collapsed: [], + turnMetrics: metrics, + }, + ], + error: null, + }, + }, + }; + + expect(validateWSOutboundMessage(completed)).toEqual({ success: true, data: completed }); + expect(validateWSOutboundMessage(timeline)).toEqual({ success: true, data: timeline }); + }); + it("emits runtime imports with .js extensions", async () => { const generated = await readFile(generatedWSOutboundPath, "utf8"); expect(generated).toContain('from "./ws-outbound-schema-metadata.js"'); diff --git a/packages/react-native-enriched-markdown/.gitignore b/packages/react-native-enriched-markdown/.gitignore new file mode 100644 index 000000000000..79ebd0345640 --- /dev/null +++ b/packages/react-native-enriched-markdown/.gitignore @@ -0,0 +1,10 @@ +# Native assets the postinstall script downloads (see postinstall.mjs). +/cpp/highlight/vendor/grammars/ +/cpp/highlight/vendor/tree-sitter/ +/ios/vendor/ +/ios/vendor.staging/ +/ios/vendor.backup/ + +# Android build output when Gradle builds this library from source. +/android/.cxx/ +/android/.gradle/ diff --git a/packages/react-native-enriched-markdown/LICENSE b/packages/react-native-enriched-markdown/LICENSE new file mode 100644 index 000000000000..8d721058611c --- /dev/null +++ b/packages/react-native-enriched-markdown/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2025 Software Mansion +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/react-native-enriched-markdown/README.md b/packages/react-native-enriched-markdown/README.md new file mode 100644 index 000000000000..9bb27e015774 --- /dev/null +++ b/packages/react-native-enriched-markdown/README.md @@ -0,0 +1,287 @@ + + + + Enriched Markdown by Software Mansion + + + + + +# react-native-enriched-markdown + +`react-native-enriched-markdown` is a powerful React Native library that renders Markdown content as native text and provides a rich text input with Markdown output. It supports iOS, Android, macOS, and Web, and requires the New Architecture (Fabric) for native platforms. + +### EnrichedMarkdownText + +- ⚡ Fully native text rendering (no WebView) +- 🌐 Web support via [react-native-web](https://necolas.github.io/react-native-web/) + [md4c](https://github.com/mity/md4c) compiled to WebAssembly +- 🎯 High-performance Markdown parsing with [md4c](https://github.com/mity/md4c) +- 📐 CommonMark standard compliant +- 📊 GitHub Flavored Markdown (GFM) +- 🧮 LaTeX math rendering (block `$$...$$` with `flavor="github"`, inline `$...$` in all flavors) +- 🔀 [Markdown Streaming](../../docs-md/MARKDOWN_STREAMING.md) support (via [react-native-streamdown](https://github.com/software-mansion-labs/react-native-streamdown)) +- 🎨 Fully customizable styles for all elements +- ✨ Text selection and copy support +- 📌 Custom text selection context menu items +- 🔗 Interactive link handling with [per-URL-pattern styling](../../docs-md/MENTIONS.md#link-variants-styling) (`linkVariants`) +- 💊 [Native link pills](../../docs-md/MENTIONS.md#native-link-pills) — links as rounded chips with an icon and label, per URL pattern or per link (iOS, Android) +- 📎 [Long-press menus for links](../../docs-md/API_REFERENCE.md#linkcontextmenuitems) with your own items per URL pattern (`linkContextMenuItems`, iOS 17+) +- 👤 Renders mentions as styled links (compatible with `EnrichedMarkdownTextInput` mention output) +- 🙈 Spoiler text with animated particle overlay and tap-to-reveal +- 🖼️ Native image interactions (iOS: Copy, Save to Camera Roll) +- 🎬 Native video playback — block-level videos via HTML `