diff --git a/.github/ci-paths.yml b/.github/ci-paths.yml index 87fc924b6b..baf6de02e7 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 c14e060e0f..a75764aa25 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: @@ -20,6 +20,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: @@ -56,7 +58,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 @@ -165,8 +167,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 @@ -276,10 +299,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 @@ -307,6 +327,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 @@ -460,9 +498,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 @@ -576,9 +614,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 77e2735c6a..08cbf0055b 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 26be12291b..7004f0b5e0 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -170,33 +170,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") @@ -502,6 +480,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 aa53f3ec81..1a243dea7f 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 b653564793..72db40e230 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 5838c7dc1a..e5fab8507f 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -11,5 +11,10 @@ "arrowParens": "always", "bracketSameLine": false, "bracketSpacing": true, - "ignorePatterns": ["*.lock", "**/*.gen.ts", "**/*.gen.tsx"] + "ignorePatterns": [ + "*.lock", + "**/*.gen.ts", + "**/*.gen.tsx", + "packages/react-native-enriched-markdown/**" + ] } diff --git a/.oxlintrc.json b/.oxlintrc.json index fdbb917302..474a249b06 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 18ee4a999a..6cd57b7486 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,168 @@ # Changelog +## 0.17.4 - 2026-11-23 + +### 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:** 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 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)) + +### 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 ([#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 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 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 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)) + +### 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 + +### Fixed + +- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092)) +- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan)) +- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067)) +- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113)) +- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan)) +- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath)) +- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery)) +- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto)) +- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035)) +- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82)) +- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974)) +- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid)) +- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem)) +- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010)) +- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun)) +- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0)) + ## 0.16.1 - 2026-11-17 ### Fixed diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index d2d8b12e5f..74a27729ad 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,5 +1,168 @@ # Changelog +## 0.17.4 - 2026-11-23 + +### 修复 + +- 修复 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), [#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)) +- 新增 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)) + +### 修复 + +- 修复在线主机的工作区不显示的问题 ([#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)) +- 修复空对话在回复中途重连后丢失提示词和回复开头的问题 ([#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)) +- 修复在预览和源码之间切换时 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)) +- 修复 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)) + +### 插件 + +- 新增插件对 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 + +### 修复 + +- 修复启用“折叠轮次”时,Claude 回复后续后台任务通知导致上一条已完成的回复被折叠的问题 ([#10092](https://github.com/getpaseo/paseo/pull/10092)) +- 修复归档工作区时丢失分离 HEAD 的 worktree 提交的问题 ([#10009](https://github.com/getpaseo/paseo/pull/10009),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复 Desktop 更新后,由上一次 Desktop 会话启动的旧版 daemon 仍在运行的问题 ([#10067](https://github.com/getpaseo/paseo/pull/10067)) +- 修复更改执行权限后 daemon 与 Hub 断开连接的问题 ([#10113](https://github.com/getpaseo/paseo/pull/10113)) +- 修复一条已保存的主机记录无法读取时,其他主机也消失的问题 ([#9847](https://github.com/getpaseo/paseo/pull/9847),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复创建 worktree 时,扫描 `.worktreeinclude` 未指定的大型忽略目录导致超时的问题 ([#10020](https://github.com/getpaseo/paseo/pull/10020),贡献者:[@mgranderath](https://github.com/mgranderath)) +- 修复发送引导消息时取消 Claude 正在进行的上下文压缩的问题 ([#10028](https://github.com/getpaseo/paseo/pull/10028),贡献者:[@NightMachinery](https://github.com/NightMachinery)) +- 修复 Provider 重用已取消的轮次 ID 时,再次停止导致 Agent 卡住的问题 ([#9774](https://github.com/getpaseo/paseo/pull/9774),贡献者:[@DAnaeto](https://github.com/DAnaeto)) +- 修复 Desktop 渲染进程意外退出后窗口一直空白的问题 ([#10035](https://github.com/getpaseo/paseo/pull/10035)) +- 修复 Web 和 Desktop 上文件下载失败时,错误页面占据应用窗口的问题 ([#9937](https://github.com/getpaseo/paseo/pull/9937),贡献者:[@panta82](https://github.com/panta82)) +- 修复在“导入会话”中选择“加载更多”时丢失滚动位置的问题 ([#9974](https://github.com/getpaseo/paseo/pull/9974)) +- 修复主目录所在的文件系统拒绝 Unix 套接字时无法打开终端的问题,例如 AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214),贡献者:[@bendavid](https://github.com/bendavid)) +- 修复 Git 监视器设置超时后反复扫描大型仓库的问题 ([#9828](https://github.com/getpaseo/paseo/pull/9828),贡献者:[@Spshulem](https://github.com/Spshulem)) +- 修复 `paseo workspace create --path .` 使用本地 daemon 的目录而非命令所在目录的问题 ([#10010](https://github.com/getpaseo/paseo/pull/10010)) +- 修复针对空闲 Agent 查询 MCP 状态或列表时漏报后台任务的问题 ([#10022](https://github.com/getpaseo/paseo/pull/10022),贡献者:[@ortschun](https://github.com/ortschun)) +- 修复 OMP 更改思考级别后,选择器仍显示旧级别的问题 ([#9841](https://github.com/getpaseo/paseo/pull/9841),贡献者:[@dsingal0](https://github.com/dsingal0)) + ## 0.16.1 - 2026-11-17 ### 修复 diff --git a/CLAUDE.md b/CLAUDE.md index f09b420056..7167251d03 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the | [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica | | [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 0000000000..805b84a054 --- /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 0000000000..4bc84ca540 --- /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 0000000000..ea69b0ca12 --- /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 0000000000..c12d4b0e72 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 0000000000..41adbc9020 --- /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 0000000000..3fb1c65928 --- /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 0000000000..104dfefa44 --- /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 0000000000..849f5fae24 --- /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 0000000000..0174e895bb --- /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 0000000000..a14ccab72d --- /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 0000000000..b6f1db1f3e --- /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 0000000000..51d22edb5b --- /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 0000000000..882db41661 --- /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 0000000000..6fb1dac7ed --- /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 0000000000..1a15ec539c --- /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 0000000000..152c280e8c --- /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 7bc91d9347..9ff30eff98 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -150,13 +150,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/agent-stream-disclosure.md b/docs/agent-stream-disclosure.md index ec320dc916..fe054c960b 100644 --- a/docs/agent-stream-disclosure.md +++ b/docs/agent-stream-disclosure.md @@ -163,8 +163,16 @@ override a scroll away because they can arrive after the action that requested t ### Draw distance -`drawDistance` is 2000 px on each side of the viewport. A fling over rows that were never measured -blanks the viewport until LegendList renders and measures them. Twelve flings over a chat with a +The native timeline starts with one window-height of draw distance, up to 2000 px. This keeps +nearby rows ready for a fling during placement. Once the chat is placed, history is visible, and +the sidebar has settled, the timeline schedules expansion to 2000 px through two frame callbacks. +The callbacks leave time for the reveal to paint. Verify the actual reveal on the device. +A drag cancels a pending expansion and uses the existing buffer as the window moves. Expansion +resumes when the gesture settles, including momentum. In an Android emulator capture, expanding +the full buffer during the first fling changed the measured content height and returned the chat +to the end mid-fling. +A fling over rows that were never measured blanks the viewport +until LegendList renders and measures them. Twelve flings over a chat with a 15,000 px turn expanded, Android emulator, dev build: | List | Blank viewport | Janky frames | p50 / p90 / p99 | @@ -179,9 +187,8 @@ With every turn collapsed, flinging from a cold open into history did not blank ### LegendList patch -`patches/@legendapp+list+3.7.1.patch` carries twelve changes for the timeline. Its header lists -them by purpose, and -[legend-list #593](https://github.com/LegendApp/legend-list/issues/593) reports each upstream. +`patches/@legendapp+list+3.7.1.patch` lists its changes by purpose. +[legend-list #593](https://github.com/LegendApp/legend-list/issues/593) reports the first twelve. Drop a hunk when the installed LegendList ships its fix. ### Scroll view corrections diff --git a/docs/android.md b/docs/android.md index f4fcfa27c0..55d2c6e1bb 100644 --- a/docs/android.md +++ b/docs/android.md @@ -121,6 +121,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 ef0281ec7f..d9ff8a1e5d 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -514,7 +514,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 @@ -627,32 +627,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: @@ -853,12 +827,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 349cffd464..14c8d3941f 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 | @@ -194,11 +195,13 @@ imports provider history. See [owned history](timeline-sync.md#owned-history). 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 @@ -588,12 +591,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 810b10c582..ba9c6b41c3 100644 --- a/docs/design.md +++ b/docs/design.md @@ -78,7 +78,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/initial-draw-distance.test.ts b/packages/app/src/agent-stream/initial-draw-distance.test.ts new file mode 100644 index 0000000000..185e8e4622 --- /dev/null +++ b/packages/app/src/agent-stream/initial-draw-distance.test.ts @@ -0,0 +1,85 @@ +import { expect, it } from "vitest"; +import { createInitialDrawDistanceExpansion } from "./initial-draw-distance"; + +function mountInitialBuffer() { + let nextId = 0; + const pending = new Map void>(); + const expansions: string[] = []; + const buffer = createInitialDrawDistanceExpansion( + { + requestFrame(callback) { + const id = ++nextId; + pending.set(id, callback); + return id; + }, + cancelFrame(id) { + pending.delete(id); + }, + }, + () => expansions.push("full draw distance"), + ); + function advanceFrame() { + const callbacks = [...pending.values()]; + pending.clear(); + for (const callback of callbacks) callback(); + } + return { buffer, expansions, advanceFrame }; +} + +it("requests the full draw distance after two frame callbacks once the reveal is eligible", () => { + const { buffer, expansions, advanceFrame } = mountInitialBuffer(); + buffer.schedule(); + advanceFrame(); + expect(expansions).toEqual([]); + advanceFrame(); + expect(expansions).toEqual(["full draw distance"]); +}); + +it.each([0, 1])( + "leaves initial draw distance in place during a gesture after %i frames", + (elapsed) => { + const { buffer, expansions, advanceFrame } = mountInitialBuffer(); + buffer.schedule(); + if (elapsed === 1) advanceFrame(); + + buffer.pauseForScroll(); + advanceFrame(); + advanceFrame(); + expect(expansions).toEqual([]); + + buffer.resumeAfterScroll(); + advanceFrame(); + expect(expansions).toEqual([]); + advanceFrame(); + expect(expansions).toEqual(["full draw distance"]); + }, +); + +it("cancels a covered reveal and schedules again when it is eligible", () => { + const { buffer, expansions, advanceFrame } = mountInitialBuffer(); + const cancel = buffer.schedule(); + advanceFrame(); + cancel(); + advanceFrame(); + expect(expansions).toEqual([]); + + buffer.schedule(); + advanceFrame(); + advanceFrame(); + expect(expansions).toEqual(["full draw distance"]); +}); + +it("keeps a covered list at its initial draw distance when a gesture ends", () => { + const { buffer, expansions, advanceFrame } = mountInitialBuffer(); + buffer.pauseForScroll(); + const cover = buffer.schedule(); + advanceFrame(); + advanceFrame(); + expect(expansions).toEqual([]); + + cover(); + buffer.resumeAfterScroll(); + advanceFrame(); + advanceFrame(); + expect(expansions).toEqual([]); +}); diff --git a/packages/app/src/agent-stream/initial-draw-distance.ts b/packages/app/src/agent-stream/initial-draw-distance.ts new file mode 100644 index 0000000000..a4c3b74397 --- /dev/null +++ b/packages/app/src/agent-stream/initial-draw-distance.ts @@ -0,0 +1,50 @@ +interface InitialDrawDistanceFrames { + requestFrame(callback: () => void): number; + cancelFrame(id: number): void; +} + +export function createInitialDrawDistanceExpansion( + frames: InitialDrawDistanceFrames, + expand: () => void, +) { + let frame: number | null = null; + let eligible = false; + let scrolling = false; + let expanded = false; + + function cancel() { + if (frame === null) return; + frames.cancelFrame(frame); + frame = null; + } + + function scheduleIfIdle() { + if (!eligible || scrolling || expanded || frame !== null) return; + frame = frames.requestFrame(() => { + frame = frames.requestFrame(() => { + frame = null; + expanded = true; + expand(); + }); + }); + } + + return { + schedule() { + eligible = true; + scheduleIfIdle(); + return () => { + eligible = false; + cancel(); + }; + }, + pauseForScroll() { + scrolling = true; + cancel(); + }, + resumeAfterScroll() { + scrolling = false; + scheduleIfIdle(); + }, + }; +} diff --git a/packages/app/src/agent-stream/layout.test.ts b/packages/app/src/agent-stream/layout.test.ts index fde9a3a342..e41c05dec9 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 924d9d75ec..e1918ddc4f 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/legend-list-held-row.browser.test.tsx b/packages/app/src/agent-stream/legend-list-held-row.browser.test.tsx index 338fa84008..08cc98e436 100644 --- a/packages/app/src/agent-stream/legend-list-held-row.browser.test.tsx +++ b/packages/app/src/agent-stream/legend-list-held-row.browser.test.tsx @@ -40,6 +40,7 @@ function wait(ms: number): Promise { } const LIST_STYLE = { flex: 1 }; +const ESTIMATED_LIST_SIZE = { width: 300, height: VIEWPORT_HEIGHT }; const rowStyles = new Map(); function rowStyle(height: number) { @@ -89,6 +90,10 @@ function keyExtractor(item: Row) { return item.id; } +function estimateRowSize(item: Row) { + return item.height; +} + function mountList(heldRowId: string) { const listRef = React.createRef(); const maintainVisibleContentPosition = holdOnly(heldRowId); @@ -264,3 +269,49 @@ it("keeps measured row sizes while the list is not laid out", async () => { expect(rows.map((row) => list.rowSize(row.id))).toEqual([40, 40, 40]); }); + +it("expands the draw distance of a placed end-anchored list without moving its bottom row", async () => { + const rows: Row[] = Array.from({ length: 99 }, (_, index) => ({ + id: `row-${index}`, + height: index % 2 === 0 ? 20 : 60, + })); + const lastRow = { id: "last-row", height: 180 }; + rows.push(lastRow); + const listRef = React.createRef(); + + function render(drawDistance: number) { + act(() => { + root.render( + , + ); + }); + } + + render(50); + await wait(300); + const initial = listRef.current?.getState(); + const lastRowTop = initial?.positionByKey(lastRow.id); + expect(initial?.sizes.get(lastRow.id)).toBe(lastRow.height); + expect(initial?.sizes.size).toBeLessThan(8); + expect(initial?.scroll).toBe(Number(lastRowTop) + lastRow.height - VIEWPORT_HEIGHT); + + render(1000); + await wait(150); + + const expanded = listRef.current?.getState(); + expect(expanded?.sizes.size).toBeGreaterThan(20); + expect(expanded?.scroll).toBe(initial?.scroll); + expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop); +}); diff --git a/packages/app/src/agent-stream/strategy-native.tsx b/packages/app/src/agent-stream/strategy-native.tsx index 106c9c3bb4..6b7b6c3a08 100644 --- a/packages/app/src/agent-stream/strategy-native.tsx +++ b/packages/app/src/agent-stream/strategy-native.tsx @@ -9,6 +9,7 @@ import { useState, } from "react"; import { + Dimensions, View, type LayoutChangeEvent, type NativeScrollEvent, @@ -31,6 +32,7 @@ import { useTranslation } from "react-i18next"; import type { StreamItem } from "@/types/stream"; import type { Theme } from "@/styles/theme"; import { useStableEvent } from "@/hooks/use-stable-event"; +import { useIsMobilePanelActive } from "@/mobile-panels/provider"; import { shouldAnimateNativeScrollToBottom } from "./native-scroll-animation"; import { useRevisedHistoryRows } from "./history-row-revision"; import { useBottomAnchorController } from "./bottom-anchor-controller"; @@ -43,6 +45,7 @@ import { } from "./native-disclosure-hold"; import { EndPinnedScrollView } from "./native-end-pin"; import { createNewRowEstimates } from "./new-row-estimates"; +import { createInitialDrawDistanceExpansion } from "./initial-draw-distance"; import type { DisclosureTriggerEdge, StreamRenderInput, @@ -132,6 +135,14 @@ function keyExtractor(item: { id: string }): string { return item.id; } +function InitialDrawDistanceExpansion({ schedule }: { schedule: () => () => void }) { + const isSidebarActive = useIsMobilePanelActive("agent-list"); + useLayoutEffect(() => { + if (!isSidebarActive) return schedule(); + }, [schedule, isSidebarActive]); + return null; +} + function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrategy }) { const { agentId, @@ -157,6 +168,16 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat strategy, } = props; const isActive = useRetainedPanelActive(); + // Keep a screenful in reserve for a fling that starts before the full buffer mounts. + const [drawDistance, setDrawDistance] = useState(() => + Math.min(Dimensions.get("window").height, NATIVE_STREAM_DRAW_DISTANCE), + ); + const [drawDistanceExpansion] = useState(() => + createInitialDrawDistanceExpansion( + { requestFrame: requestAnimationFrame, cancelFrame: cancelAnimationFrame }, + () => setDrawDistance(NATIVE_STREAM_DRAW_DISTANCE), + ), + ); const { t } = useTranslation(); const { renderHistoryMountedRow, renderLiveHeadRow, renderLiveAuxiliary } = renderers; const listRef = useRef(null); @@ -569,6 +590,9 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat cancelDisclosureHold(); bottomAnchorController.beginUserScroll(); historyStartPagination.rearm(); + // The reserve follows the gesture. Expanding the buffer here shifted the measured + // content and returned the viewport to the end during an Android fling. + drawDistanceExpansion.pauseForScroll(); }); useEffect(() => { @@ -591,6 +615,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat bottomAnchorController.endUserScroll({ isAtEnd: isReleasedAtEndRef.current || isAtEnd(), }); + drawDistanceExpansion.resumeAfterScroll(); }); }); @@ -610,6 +635,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat bottomAnchorController.endUserScroll({ isAtEnd: isReleasedAtEndRef.current || isScrollEventAtEnd(event), }); + drawDistanceExpansion.resumeAfterScroll(); }, ); @@ -732,6 +758,11 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat ); }, [historyStartPaginationState, hasOlderHistory, retryHistoryStart, t]); + const canExpandDrawDistance = + drawDistance < NATIVE_STREAM_DRAW_DISTANCE && + isActive && + isListPlaced && + historyStartPaginationState.visible; return ( @@ -764,11 +795,14 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat recycleItems={false} alignItemsAtEnd initialScrollAtEnd - drawDistance={NATIVE_STREAM_DRAW_DISTANCE} + drawDistance={drawDistance} getEstimatedItemSize={getEstimatedItemSize} scrollEnabled={scrollEnabled} showsVerticalScrollIndicator /> + {canExpandDrawDistance ? ( + + ) : null} {!historyStartPaginationState.visible ? ( diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index 465d98e8d8..e4e5b23825 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!; @@ -1215,17 +1229,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 aab5b0413e..7507f3442b 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 dec9b7fe15..46a51c0f34 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"; @@ -92,3 +96,57 @@ it.each([ "Friday 11:11 PM": 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 6699fb800b..93574a61d2 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"; @@ -81,6 +82,7 @@ export const TurnFooter = memo(function TurnFooter({ items={host.items} timing={host.timing} startIndex={host.startIndex} + turnMetrics={host.turnMetrics} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} /> @@ -92,6 +94,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ items, timing, startIndex, + turnMetrics, supportsTimelineCursor, onForkAssistantTurn, }: { @@ -99,6 +102,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ items: StreamItem[]; timing?: TurnTiming; startIndex: number; + turnMetrics?: AgentMetric[]; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; }) { @@ -109,6 +113,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ items={items} timing={timing} startIndex={startIndex} + turnMetrics={turnMetrics} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} /> @@ -165,6 +170,7 @@ function CompletedTurnFooter({ items, timing, startIndex, + turnMetrics, supportsTimelineCursor, onForkAssistantTurn, }: { @@ -172,6 +178,7 @@ function CompletedTurnFooter({ items: StreamItem[]; timing?: TurnTiming; startIndex: number; + turnMetrics?: AgentMetric[]; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; }) { @@ -205,6 +212,7 @@ function CompletedTurnFooter({ completedAt={timing?.completedAt} durationMs={timing?.durationMs} onFork={boundary && onForkAssistantTurn ? handleFork : undefined} + metrics={turnMetrics} /> ); diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index ff48cc34b1..eb5079781e 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -82,6 +82,7 @@ import { renderStreamRow, type RenderStreamItem } from "./stream-row"; import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom"; import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail"; import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline"; +import { CHAT_COLUMN_RAIL_DATASET, useChatOutlineRail } from "@/chat-rail"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; import { @@ -187,6 +188,7 @@ function renderStreamItemWithTurnFooter(input: { items={footerHost.items} timing={footerHost.timing} startIndex={footerHost.startIndex} + turnMetrics={footerHost.turnMetrics} supportsTimelineCursor={input.supportsTimelineCursor} onForkAssistantTurn={input.onForkAssistantTurn} /> @@ -322,7 +324,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( @@ -404,10 +405,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, ); @@ -621,13 +618,15 @@ const AgentStreamViewComponent = forwardRef - + {outlineInset > 0 && chatOutline.prompts.length >= 2 ? ( + + ) : null} {workspaceChrome} + {!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? ( @@ -936,6 +938,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 0000000000..adad9c6f6a --- /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 e18eaa6555..2b7ab833f8 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 04032a00b0..ea4486fe63 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 77addad9a3..6466221197 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/audio/audio-engine-types.ts b/packages/app/src/audio/audio-engine-types.ts index d96f9c5ef9..9e46ddaf21 100644 --- a/packages/app/src/audio/audio-engine-types.ts +++ b/packages/app/src/audio/audio-engine-types.ts @@ -3,7 +3,6 @@ export interface AudioEngineCallbacks { onVolumeLevel(level: number): void; onInterruption?(): void; onCaptureAvailabilityChange?(available: boolean): void; - onError?(error: Error): void; } export interface AudioPlaybackSource { @@ -31,3 +30,21 @@ export interface AudioEngineOptions { traceLabel?: string; captureMode?: "conversation" | "dictation"; } + +export type AudioCaptureStartFailure = + | "permissionDenied" + | "insecureContext" + | "unsupported" + | "noMicrophone" + | "startFailed"; + +export class AudioCaptureStartError extends Error { + constructor( + readonly reason: AudioCaptureStartFailure, + message: string, + options?: ErrorOptions, + ) { + super(message, options); + this.name = "AudioCaptureStartError"; + } +} diff --git a/packages/app/src/audio/audio-engine.native.ts b/packages/app/src/audio/audio-engine.native.ts index ed9f15a765..c6dc61054a 100644 --- a/packages/app/src/audio/audio-engine.native.ts +++ b/packages/app/src/audio/audio-engine.native.ts @@ -1,239 +1,60 @@ -import type { - AudioEngine, - AudioEngineCallbacks, - AudioEngineOptions, - AudioPlaybackSource, -} from "./audio-engine-types"; +import type { AudioEngine, AudioEngineCallbacks, AudioEngineOptions } from "./audio-engine-types"; import { createAudioPlayer, setAudioModeAsync } from "expo-audio"; import { File, Paths } from "expo-file-system"; -import { createPlaybackQueue } from "./playback"; import { playFile } from "./file-playback"; -import { playPcm16 } from "./pcm"; +import { createNativeAudioEngine, type NativeAudioEngineDeps } from "./native-audio-engine"; + +// AVPlayer needs a file extension to recognize local encoded audio on iOS. +const FILE_EXTENSIONS: Record = { + "audio/wav": "wav", + "audio/x-wav": "wav", + "audio/wave": "wav", + "audio/mpeg": "mp3", + "audio/mp3": "mp3", + "audio/mp4": "m4a", + "audio/aac": "aac", + "audio/ogg": "ogg", + "audio/flac": "flac", +}; + +let nextFileId = 0; + +async function playEncodedAudio( + bytes: Uint8Array, + mimeType: string, + signal: AbortSignal, + context: { isCaptureActive(): boolean }, +): Promise { + // Capture owns its audio session while active. File playback alone must not + // initialize the microphone or the native two-way engine. + if (!context.isCaptureActive()) { + await setAudioModeAsync({ + playsInSilentMode: true, + allowsRecording: false, + interruptionMode: "duckOthers", + interruptionModeAndroid: "duckOthers", + }); + } + if (signal.aborted) throw new Error("Playback stopped"); + const extension = FILE_EXTENSIONS[mimeType.split(";")[0].trim()] ?? "audio"; + const file = new File(Paths.cache, `paseo-audio-${Date.now()}-${nextFileId++}.${extension}`); + try { + file.write(bytes); + const player = createAudioPlayer(file.uri, { + updateInterval: 100, + keepAudioSessionActive: context.isCaptureActive(), + }); + return await playFile(player, signal); + } finally { + if (file.exists) file.delete(); + } +} export function createAudioEngine( callbacks: AudioEngineCallbacks, options?: AudioEngineOptions, ): AudioEngine { - const native = require("@getpaseo/expo-two-way-audio"); - - const refs: { - initialized: boolean; - captureActive: boolean; - muted: boolean; - destroyed: boolean; - } = { - initialized: false, - captureActive: false, - muted: false, - destroyed: false, - }; - - const microphoneSubscription = native.addExpoTwoWayAudioEventListener( - "onMicrophoneData", - (event: { data: Uint8Array }) => { - if (!refs.captureActive || refs.muted) { - return; - } - const pcm = event.data; - callbacks.onCaptureData(pcm); - }, - ); - const volumeSubscription = native.addExpoTwoWayAudioEventListener( - "onInputVolumeLevelData", - (event: { data: number }) => { - if (!refs.captureActive) { - return; - } - const level = refs.muted ? 0 : event.data; - callbacks.onVolumeLevel(level); - }, - ); - const interruptionSubscription = native.addExpoTwoWayAudioEventListener( - "onAudioInterruption", - (event: { data: string }) => { - if (event.data === "capture_paused" || event.data === "capture_resumed") { - if (refs.captureActive) { - callbacks.onCaptureAvailabilityChange?.(event.data === "capture_resumed"); - } - return; - } - if (event.data !== "blocked") { - return; - } - const wasCaptureActive = refs.captureActive; - refs.captureActive = false; - refs.muted = false; - callbacks.onVolumeLevel(0); - if (wasCaptureActive) { - callbacks.onInterruption?.(); - } - }, - ); - - async function ensureInitialized(): Promise { - if (refs.initialized) { - return; - } - const success = await native.initialize(); - if (!success) { - throw new Error("expo-two-way-audio: native initialize() returned false"); - } - refs.initialized = true; - } - - /** - * Release the OS audio session as soon as we are neither capturing nor playing. - * Holding it keeps the user's background music paused — on iOS the non-mixing - * `.playAndRecord` category survives backgrounding and is re-asserted on every - * foreground, so an unreleased session means their music never comes back. - */ - function releaseSessionIfIdle(): void { - if (!refs.initialized || refs.destroyed) { - return; - } - if (refs.captureActive || playback.isPlaying()) { - return; - } - // The wrapper no-ops on binaries whose native module predates this function. - native.releaseAudioSession(); - } - - async function ensureMicrophonePermission(): Promise { - let permission = await native.getMicrophonePermissionsAsync().catch(() => null); - if (!permission?.granted) { - permission = await native.requestMicrophonePermissionsAsync().catch(() => null); - } - if (!permission?.granted) { - throw new Error( - "Microphone permission is required to capture audio. Please enable microphone access in system settings.", - ); - } - } - - let nextFileId = 0; - async function playAudio(audio: AudioPlaybackSource, signal: AbortSignal): Promise { - const bytes = new Uint8Array(await audio.arrayBuffer()); - if (signal.aborted) throw new Error("Playback stopped"); - if (audio.type.startsWith("audio/pcm")) { - await ensureInitialized(); - return playPcm16(bytes, audio.type, signal, native); - } - // Capture owns its audio session while active. File playback alone must not - // initialize the microphone or the native two-way engine. - if (!refs.captureActive) { - await setAudioModeAsync({ - playsInSilentMode: true, - allowsRecording: false, - interruptionMode: "duckOthers", - interruptionModeAndroid: "duckOthers", - }); - } - if (signal.aborted) throw new Error("Playback stopped"); - // AVPlayer needs a file extension to recognize local encoded audio on iOS. - const extension = - { - "audio/wav": "wav", - "audio/x-wav": "wav", - "audio/wave": "wav", - "audio/mpeg": "mp3", - "audio/mp3": "mp3", - "audio/mp4": "m4a", - "audio/aac": "aac", - "audio/ogg": "ogg", - "audio/flac": "flac", - }[audio.type.split(";")[0].trim()] ?? "audio"; - const file = new File(Paths.cache, `paseo-audio-${Date.now()}-${nextFileId++}.${extension}`); - try { - file.write(bytes); - const player = createAudioPlayer(file.uri, { - updateInterval: 100, - keepAudioSessionActive: refs.captureActive, - }); - return await playFile(player, signal); - } finally { - if (file.exists) file.delete(); - } - } - const playback = createPlaybackQueue(playAudio, releaseSessionIfIdle); - - return { - async initialize() { - await ensureInitialized(); - }, - - async destroy() { - if (refs.destroyed) { - return; - } - refs.destroyed = true; - playback.destroy(); - if (refs.captureActive) { - native.toggleRecording(false); - refs.captureActive = false; - } - refs.muted = false; - callbacks.onVolumeLevel(0); - if (refs.initialized) { - native.tearDown(); - refs.initialized = false; - } - microphoneSubscription.remove(); - volumeSubscription.remove(); - interruptionSubscription.remove(); - }, - - async startCapture() { - if (refs.captureActive) { - return; - } - - try { - await ensureMicrophonePermission(); - await ensureInitialized(); - const isRecording = - options?.captureMode === "dictation" - ? native.startDictation() - : native.toggleRecording(true); - if (!isRecording) { - throw new Error( - "Microphone capture could not start because Android audio focus is unavailable.", - ); - } - refs.captureActive = true; - } catch (error) { - const wrapped = error instanceof Error ? error : new Error(String(error)); - callbacks.onError?.(wrapped); - throw wrapped; - } - }, - - async stopCapture() { - if (refs.captureActive) { - native.toggleRecording(false); - } - refs.captureActive = false; - refs.muted = false; - callbacks.onVolumeLevel(0); - callbacks.onCaptureAvailabilityChange?.(true); - releaseSessionIfIdle(); - }, - - toggleMute() { - refs.muted = !refs.muted; - if (refs.muted) { - callbacks.onVolumeLevel(0); - } - return refs.muted; - }, - - isMuted() { - return refs.muted; - }, - - play: playback.play, - stop: playback.stop, - clearQueue: playback.clearQueue, - isPlaying: playback.isPlaying, - }; + const native: NativeAudioEngineDeps["native"] = require("@getpaseo/expo-two-way-audio"); + return createNativeAudioEngine({ native, playEncodedAudio }, callbacks, options); } diff --git a/packages/app/src/audio/audio-engine.web.ts b/packages/app/src/audio/audio-engine.web.ts index 5516575e69..2ed61a648c 100644 --- a/packages/app/src/audio/audio-engine.web.ts +++ b/packages/app/src/audio/audio-engine.web.ts @@ -292,9 +292,7 @@ export function createAudioEngine( refs.gain = gain; } catch (error) { await stopCapture(); - const wrapped = error instanceof Error ? error : new Error(String(error)); - callbacks.onError?.(wrapped); - throw wrapped; + throw error; } }, diff --git a/packages/app/src/audio/index.ts b/packages/app/src/audio/index.ts index fd5bbfd221..c8e7f7929e 100644 --- a/packages/app/src/audio/index.ts +++ b/packages/app/src/audio/index.ts @@ -1,3 +1,4 @@ export { createAudioEngine } from "./audio-engine"; export type { AudioEngine, AudioEngineCallbacks, AudioPlaybackSource } from "./audio-engine-types"; export { createPlayAudio } from "./play-audio"; +export { AudioCaptureStartError, type AudioCaptureStartFailure } from "./audio-engine-types"; diff --git a/packages/app/src/audio/native-audio-engine.test.ts b/packages/app/src/audio/native-audio-engine.test.ts new file mode 100644 index 0000000000..b946e782fa --- /dev/null +++ b/packages/app/src/audio/native-audio-engine.test.ts @@ -0,0 +1,188 @@ +import { expect, test } from "vitest"; +import type { AudioEngineCallbacks } from "./audio-engine-types"; +import { createNativeAudioEngine, type NativeAudioEngineDeps } from "./native-audio-engine"; + +// In-memory stand-in for `@getpaseo/expo-two-way-audio`, matching its iOS and Android modules: +// one native engine per app, `initialize()` reuses it, `tearDown()` frees it, and +// `toggleRecording(true)` / `startDictation()` return false while no engine exists. +// Session handling follows iOS: recording activates the OS audio session, stopping does not +// deactivate it, and `releaseAudioSession()` deactivates it only while nothing is recording. +function fakeTwoWayAudio({ + captureAvailable = true, + permissionRequestError, +}: { captureAvailable?: boolean; permissionRequestError?: Error } = {}) { + let engine: { recording: boolean; sessionActive: boolean } | null = null; + const calls = { initialize: 0, tearDown: 0 }; + const native: NativeAudioEngineDeps["native"] = { + async initialize() { + calls.initialize += 1; + engine ??= { recording: false, sessionActive: false }; + return true; + }, + tearDown() { + calls.tearDown += 1; + engine = null; + }, + toggleRecording(value: boolean) { + if (!engine) return false; + engine.recording = value; + if (value) engine.sessionActive = true; + return value; + }, + startDictation() { + if (!engine || !captureAvailable) return false; + engine.recording = true; + engine.sessionActive = true; + return true; + }, + releaseAudioSession() { + if (engine && !engine.recording) engine.sessionActive = false; + }, + playPCMData() {}, + resumePlayback() {}, + stopPlayback() {}, + async getMicrophonePermissionsAsync() { + return { granted: !permissionRequestError }; + }, + async requestMicrophonePermissionsAsync() { + if (permissionRequestError) throw permissionRequestError; + return { granted: true }; + }, + addExpoTwoWayAudioEventListener() { + return { remove() {} }; + }, + }; + return { + native, + calls, + hasEngine: () => engine !== null, + sessionActive: () => engine?.sessionActive ?? false, + }; +} + +const recordingCallbacks: AudioEngineCallbacks = { + onCaptureData() {}, + onVolumeLevel() {}, +}; + +function deps(native: NativeAudioEngineDeps["native"]): NativeAudioEngineDeps { + return { + native, + playEncodedAudio: async () => 0, + }; +} + +// Issue #4147: on iPhone, voice mode failed with "Android audio focus is unavailable" +// after the dictation engine was destroyed. +test("voice capture starts after the dictation engine is destroyed", async () => { + const fake = fakeTwoWayAudio(); + const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks); + await voiceEngine.initialize(); + + const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + await dictationEngine.startCapture(); + await dictationEngine.stopCapture(); + await dictationEngine.destroy(); + + await expect(voiceEngine.startCapture()).resolves.toBeUndefined(); +}); + +test("destroying dictation while voice is capturing keeps the native engine", async () => { + const fake = fakeTwoWayAudio(); + const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks); + await voiceEngine.startCapture(); + + const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + await dictationEngine.initialize(); + await dictationEngine.destroy(); + + expect(fake.hasEngine()).toBe(true); + expect(fake.calls.tearDown).toBe(0); +}); + +// Review on #9051: with voice holding the engine, destroying an active dictation engine must +// still hand back the idle OS audio session so background music resumes (#2866). +test("destroying active dictation releases the idle audio session while voice keeps the engine", async () => { + const fake = fakeTwoWayAudio(); + const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks); + await voiceEngine.initialize(); + + const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + await dictationEngine.startCapture(); + await dictationEngine.destroy(); + + expect(fake.hasEngine()).toBe(true); + expect(fake.sessionActive()).toBe(false); +}); + +test("destroying dictation does not release the session while voice is recording", async () => { + const fake = fakeTwoWayAudio(); + const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks); + await voiceEngine.startCapture(); + + const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + await dictationEngine.initialize(); + await dictationEngine.destroy(); + + expect(fake.sessionActive()).toBe(true); +}); + +test("destroying the last engine tears the native engine down", async () => { + const fake = fakeTwoWayAudio(); + const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks); + const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + await voiceEngine.initialize(); + await dictationEngine.initialize(); + + await dictationEngine.destroy(); + await voiceEngine.destroy(); + + expect(fake.calls.tearDown).toBe(1); + expect(fake.hasEngine()).toBe(false); +}); + +test("an engine destroyed while initializing does not keep the native engine", async () => { + const fake = fakeTwoWayAudio(); + const engine = createNativeAudioEngine(deps(fake.native), recordingCallbacks); + + const initializing = expect(engine.initialize()).rejects.toThrow("Audio engine destroyed"); + await engine.destroy(); + await initializing; + + expect(fake.hasEngine()).toBe(false); +}); + +test("a failed native recording start rejects with a platform-neutral error", async () => { + const fake = fakeTwoWayAudio({ captureAvailable: false }); + const engine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + + await expect(engine.startCapture()).rejects.toThrow(/^Microphone capture could not start\.$/); + await engine.destroy(); +}); + +test("a failed native permission request retains the permission reason and original error", async () => { + const permissionRequestError = new Error("The current activity is not available."); + const fake = fakeTwoWayAudio({ permissionRequestError }); + const engine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, { + captureMode: "dictation", + }); + + await expect(engine.startCapture()).rejects.toMatchObject({ + reason: "permissionDenied", + cause: permissionRequestError, + }); + expect(fake.hasEngine()).toBe(false); + await engine.destroy(); +}); diff --git a/packages/app/src/audio/native-audio-engine.ts b/packages/app/src/audio/native-audio-engine.ts new file mode 100644 index 0000000000..57aaa5fac5 --- /dev/null +++ b/packages/app/src/audio/native-audio-engine.ts @@ -0,0 +1,292 @@ +import type { + AudioEngine, + AudioEngineCallbacks, + AudioEngineOptions, + AudioPlaybackSource, +} from "./audio-engine-types"; + +import { AudioCaptureStartError } from "./audio-engine-types"; +import { createNativeEngineLease, type NativeEngineLease } from "./native-engine-lease"; +import { createPlaybackQueue } from "./playback"; +import { playPcm16 } from "./pcm"; + +interface NativeSubscription { + remove(): void; +} + +interface MicrophonePermission { + granted: boolean; +} + +/** The surface of `@getpaseo/expo-two-way-audio` the engine drives. */ +export interface TwoWayAudioModule { + initialize(): Promise; + tearDown(): void; + toggleRecording(value: boolean): boolean; + startDictation(): boolean; + releaseAudioSession(): void; + playPCMData(data: Uint8Array): void; + getMicrophonePermissionsAsync(): Promise; + requestMicrophonePermissionsAsync(): Promise; + addExpoTwoWayAudioEventListener( + event: "onMicrophoneData", + listener: (event: { data: Uint8Array }) => void, + ): NativeSubscription; + addExpoTwoWayAudioEventListener( + event: "onInputVolumeLevelData", + listener: (event: { data: number }) => void, + ): NativeSubscription; + addExpoTwoWayAudioEventListener( + event: "onAudioInterruption", + listener: (event: { data: string }) => void, + ): NativeSubscription; +} + +export interface NativeAudioEngineDeps { + native: TwoWayAudioModule & Parameters[3]; + /** Plays encoded audio (wav, mp3, ...) through the platform player. */ + playEncodedAudio( + bytes: Uint8Array, + mimeType: string, + signal: AbortSignal, + context: { isCaptureActive(): boolean }, + ): Promise; +} + +// Voice mode and dictation each create an engine, but the native module holds a single engine +// per app. Every JS engine on the same module shares one lease, so one engine's teardown +// cannot free the native engine another still uses (#4147). +const leases = new WeakMap(); + +function leaseFor(native: TwoWayAudioModule): NativeEngineLease { + let lease = leases.get(native); + if (!lease) { + lease = createNativeEngineLease(native); + leases.set(native, lease); + } + return lease; +} + +export function createNativeAudioEngine( + deps: NativeAudioEngineDeps, + callbacks: AudioEngineCallbacks, + options?: AudioEngineOptions, +): AudioEngine { + const { native } = deps; + const lease = leaseFor(native); + + const refs: { + initialized: boolean; + captureActive: boolean; + muted: boolean; + destroyed: boolean; + } = { + initialized: false, + captureActive: false, + muted: false, + destroyed: false, + }; + + const microphoneSubscription = native.addExpoTwoWayAudioEventListener( + "onMicrophoneData", + (event: { data: Uint8Array }) => { + if (!refs.captureActive || refs.muted) { + return; + } + const pcm = event.data; + callbacks.onCaptureData(pcm); + }, + ); + const volumeSubscription = native.addExpoTwoWayAudioEventListener( + "onInputVolumeLevelData", + (event: { data: number }) => { + if (!refs.captureActive) { + return; + } + const level = refs.muted ? 0 : event.data; + callbacks.onVolumeLevel(level); + }, + ); + const interruptionSubscription = native.addExpoTwoWayAudioEventListener( + "onAudioInterruption", + (event: { data: string }) => { + if (event.data === "capture_paused" || event.data === "capture_resumed") { + if (refs.captureActive) { + callbacks.onCaptureAvailabilityChange?.(event.data === "capture_resumed"); + } + return; + } + if (event.data !== "blocked") { + return; + } + const wasCaptureActive = refs.captureActive; + refs.captureActive = false; + refs.muted = false; + callbacks.onVolumeLevel(0); + if (wasCaptureActive) { + callbacks.onInterruption?.(); + } + }, + ); + + let initializing: Promise | null = null; + async function ensureInitialized(): Promise { + if (refs.destroyed) { + throw new Error("Audio engine destroyed"); + } + if (refs.initialized) { + return; + } + initializing ??= (async () => { + try { + await lease.acquire(); + if (refs.destroyed) { + releaseNativeEngine(); + throw new Error("Audio engine destroyed"); + } + refs.initialized = true; + } finally { + initializing = null; + } + })(); + await initializing; + } + + /** + * Release the OS audio session as soon as we are neither capturing nor playing. + * Holding it keeps the user's background music paused — on iOS the non-mixing + * `.playAndRecord` category survives backgrounding and is re-asserted on every + * foreground, so an unreleased session means their music never comes back. + */ + function releaseSessionIfIdle(): void { + if (!refs.initialized || refs.destroyed) { + return; + } + if (refs.captureActive || playback.isPlaying()) { + return; + } + // The wrapper no-ops on binaries whose native module predates this function. + native.releaseAudioSession(); + } + + async function ensureMicrophonePermission(): Promise { + const permission = await native.getMicrophonePermissionsAsync().catch(() => null); + if (permission?.granted) return; + + let cause: unknown; + try { + if ((await native.requestMicrophonePermissionsAsync()).granted) return; + } catch (error) { + cause = error; + } + throw new AudioCaptureStartError( + "permissionDenied", + "Allow microphone access in system settings and try again.", + { cause }, + ); + } + + function releaseNativeEngine(): void { + try { + // Native keeps the session active while any wrapper is capturing or playing. + native.releaseAudioSession(); + } finally { + lease.release(); + } + } + + async function playAudio(audio: AudioPlaybackSource, signal: AbortSignal): Promise { + const bytes = new Uint8Array(await audio.arrayBuffer()); + if (signal.aborted) throw new Error("Playback stopped"); + if (audio.type.startsWith("audio/pcm")) { + await ensureInitialized(); + if (signal.aborted) throw new Error("Playback stopped"); + return playPcm16(bytes, audio.type, signal, native); + } + return deps.playEncodedAudio(bytes, audio.type, signal, { + isCaptureActive: () => refs.captureActive, + }); + } + const playback = createPlaybackQueue(playAudio, releaseSessionIfIdle); + + return { + async initialize() { + await ensureInitialized(); + }, + + async destroy() { + if (refs.destroyed) { + return; + } + refs.destroyed = true; + try { + playback.destroy(); + if (refs.captureActive) { + refs.captureActive = false; + native.toggleRecording(false); + } + refs.muted = false; + callbacks.onVolumeLevel(0); + } finally { + microphoneSubscription.remove(); + volumeSubscription.remove(); + interruptionSubscription.remove(); + if (refs.initialized) { + refs.initialized = false; + releaseNativeEngine(); + } + } + }, + + async startCapture() { + if (refs.captureActive) { + return; + } + + await ensureMicrophonePermission(); + await ensureInitialized(); + if (refs.destroyed) { + throw new Error("Audio engine destroyed"); + } + if (refs.captureActive) { + return; + } + const isRecording = + options?.captureMode === "dictation" + ? native.startDictation() + : native.toggleRecording(true); + if (!isRecording) { + throw new Error("Microphone capture could not start."); + } + refs.captureActive = true; + }, + + async stopCapture() { + if (refs.captureActive) { + native.toggleRecording(false); + } + refs.captureActive = false; + refs.muted = false; + callbacks.onVolumeLevel(0); + callbacks.onCaptureAvailabilityChange?.(true); + releaseSessionIfIdle(); + }, + + toggleMute() { + refs.muted = !refs.muted; + if (refs.muted) { + callbacks.onVolumeLevel(0); + } + return refs.muted; + }, + + isMuted() { + return refs.muted; + }, + + play: playback.play, + stop: playback.stop, + clearQueue: playback.clearQueue, + isPlaying: playback.isPlaying, + }; +} diff --git a/packages/app/src/audio/native-engine-lease.test.ts b/packages/app/src/audio/native-engine-lease.test.ts new file mode 100644 index 0000000000..5612a8fb9f --- /dev/null +++ b/packages/app/src/audio/native-engine-lease.test.ts @@ -0,0 +1,116 @@ +import { expect, test } from "vitest"; +import { createNativeEngineLease, type NativeAudioEngineLifecycle } from "./native-engine-lease"; + +// Mirrors the iOS and Android modules: one engine per app, `initialize()` reuses it, +// `tearDown()` frees it, and `toggleRecording(true)` returns false once it is gone. +function fakeNativeModule(options: { initializeResult?: boolean } = {}) { + let engine: object | null = null; + const calls = { initialize: 0, tearDown: 0 }; + let finishInitialize: (() => void) | null = null; + let deferInitialize = false; + const native: NativeAudioEngineLifecycle & { + toggleRecording(value: boolean): boolean; + } = { + initialize() { + calls.initialize += 1; + const complete = () => { + if (options.initializeResult === false) { + return false; + } + engine ??= {}; + return true; + }; + if (!deferInitialize) { + return Promise.resolve(complete()); + } + return new Promise((resolve) => { + finishInitialize = () => resolve(complete()); + }); + }, + tearDown() { + calls.tearDown += 1; + engine = null; + }, + toggleRecording(value: boolean) { + return engine !== null && value; + }, + }; + return { + native, + calls, + deferNextInitialize() { + deferInitialize = true; + }, + finishInitialize() { + finishInitialize?.(); + }, + }; +} + +test("dictation releasing the engine keeps it for voice mode", async () => { + const fake = fakeNativeModule(); + const lease = createNativeEngineLease(fake.native); + + await lease.acquire(); // voice mode + await lease.acquire(); // dictation + lease.release(); // dictation unmounts + + expect(fake.calls.tearDown).toBe(0); + expect(fake.native.toggleRecording(true)).toBe(true); +}); + +test("the last release tears the native engine down and the next acquire rebuilds it", async () => { + const fake = fakeNativeModule(); + const lease = createNativeEngineLease(fake.native); + + await lease.acquire(); + lease.release(); + expect(fake.calls.tearDown).toBe(1); + expect(fake.native.toggleRecording(true)).toBe(false); + + await lease.acquire(); + expect(fake.calls.initialize).toBe(2); + expect(fake.native.toggleRecording(true)).toBe(true); +}); + +test("concurrent acquires share one native initialize", async () => { + const fake = fakeNativeModule(); + fake.deferNextInitialize(); + const lease = createNativeEngineLease(fake.native); + + const first = lease.acquire(); + const second = lease.acquire(); + fake.finishInitialize(); + await Promise.all([first, second]); + + expect(fake.calls.initialize).toBe(1); + lease.release(); + expect(fake.calls.tearDown).toBe(0); + lease.release(); + expect(fake.calls.tearDown).toBe(1); +}); + +test("a failed initialize is not counted as a holder and can be retried", async () => { + const fake = fakeNativeModule({ initializeResult: false }); + const lease = createNativeEngineLease(fake.native); + + await expect(lease.acquire()).rejects.toThrow("native initialize() returned false"); + lease.release(); + expect(fake.calls.tearDown).toBe(0); + + await expect(lease.acquire()).rejects.toThrow(); + expect(fake.calls.initialize).toBe(2); +}); + +test("a release with no holders is a no-op", async () => { + const fake = fakeNativeModule(); + const lease = createNativeEngineLease(fake.native); + + await lease.acquire(); + lease.release(); + lease.release(); + await lease.acquire(); + lease.release(); + + expect(fake.calls.tearDown).toBe(2); +}); diff --git a/packages/app/src/audio/native-engine-lease.ts b/packages/app/src/audio/native-engine-lease.ts new file mode 100644 index 0000000000..07f74e300a --- /dev/null +++ b/packages/app/src/audio/native-engine-lease.ts @@ -0,0 +1,57 @@ +/** + * The part of `@getpaseo/expo-two-way-audio` that owns the native engine's lifetime. + * Each platform keeps a single engine per app: `initialize()` reuses it, `tearDown()` frees it. + */ +export interface NativeAudioEngineLifecycle { + initialize(): Promise; + tearDown(): void; +} + +export interface NativeEngineLease { + /** Ensure the native engine exists and count the caller as a holder. */ + acquire(): Promise; + /** Drop one holder; the native engine is torn down when the last holder releases. */ + release(): void; +} + +/** + * Voice mode and dictation each create their own JS audio engine, but both drive the one + * native engine. Counting holders keeps one consumer's teardown from freeing the engine + * the other still uses (issue #4147: voice mode on iOS could not start after dictation). + */ +export function createNativeEngineLease(native: NativeAudioEngineLifecycle): NativeEngineLease { + let holders = 0; + let ready: Promise | null = null; + + async function initialize(): Promise { + const success = await native.initialize(); + if (!success) { + throw new Error("expo-two-way-audio: native initialize() returned false"); + } + } + + return { + async acquire() { + holders += 1; + ready ??= initialize(); + try { + await ready; + } catch (error) { + holders -= 1; + ready = null; + throw error; + } + }, + + release() { + if (holders === 0) { + return; + } + holders -= 1; + if (holders === 0) { + ready = null; + native.tearDown(); + } + }, + }; +} 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 0000000000..245fdc0374 --- /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 0000000000..9db1ad9b11 --- /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 0000000000..89f50dade6 --- /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 0000000000..3669dcf1fc --- /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 0000000000..51a5483f22 --- /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/command-center/root-registration.tsx b/packages/app/src/command-center/root-registration.tsx index 9978aed6e1..adf3190784 100644 --- a/packages/app/src/command-center/root-registration.tsx +++ b/packages/app/src/command-center/root-registration.tsx @@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next"; import { CalendarClock, CircleDashed, + Copy, Folder, FolderPlus, History, @@ -17,6 +18,8 @@ import { } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-context"; +import { getDesktopHost } from "@/desktop/host"; import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides"; import { useOpenAddProject } from "@/hooks/use-open-add-project"; import { useImportSession } from "@/hooks/use-import-session"; @@ -27,6 +30,7 @@ import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store"; import { usePanelStore } from "@/stores/panel-store"; import { useSidebarViewStore } from "@/stores/sidebar-view-store"; import { clearCommandCenterFocusRestoreElement } from "@/utils/command-center-focus-restore"; +import { copyToClipboard } from "@/utils/copy-to-clipboard"; import { buildOpenProjectRoute, buildSchedulesRoute, @@ -35,6 +39,7 @@ import { } from "@/utils/host-routes"; import { getShortcutOs } from "@/utils/shortcut-platform"; import type { CommandCenterContribution, CommandCenterIconProps } from "./contributions"; +import { getCommandCenterIcon } from "./icon"; import { useCommandCenterActions } from "./provider"; import { buildGroupingContribution } from "./root-contributions"; @@ -63,6 +68,7 @@ const ThemedCircleDashed = withUnistyles(CircleDashed, (theme) => ({ const ThemedPanelLeft = withUnistyles(PanelLeft, (theme) => ({ color: theme.colors.foregroundMuted, })); +const BrowserHostCopyIcon = getCommandCenterIcon(Copy); function PlusIcon({ size }: CommandCenterIconProps) { return ; @@ -111,6 +117,8 @@ function PanelLeftIcon({ size }: CommandCenterIconProps) { export function CommandCenterRootActions() { const keyboardActionDispatcher = useKeyboardActionDispatcher(); const { t } = useTranslation(); + const toast = useToast(); + const browserHostLabel = getDesktopHost()?.browserHostLabel; const { overrides } = useKeyboardShortcutOverrides(); const shortcutsAvailable = useHardwareKeyboardPresent(); const openAddProject = useOpenAddProject(); @@ -296,6 +304,32 @@ export function CommandCenterRootActions() { }, ]; + if (browserHostLabel) { + availableActions.push({ + id: "copy-browser-host-name", + group: "actions", + groupRank: 0, + rank: 9, + keywords: ["browser", "host", "window", browserHostLabel], + visibility: "query", + run: async () => { + try { + await copyToClipboard(browserHostLabel); + toast.copied(); + } catch { + toast.error(t("common.errors.unableToCopy")); + } + }, + presentation: { + kind: "action", + title: t("shell.commandCenter.copyBrowserHostName"), + subtitle: browserHostLabel, + sectionTitle: t("shell.commandCenter.actions"), + icon: BrowserHostCopyIcon, + }, + }); + } + if (shortcutsAvailable) { availableActions.push({ id: "keyboard-shortcuts", @@ -332,6 +366,7 @@ export function CommandCenterRootActions() { return availableActions; }, [ + browserHostLabel, groupMode, homeRoute, keyboardActionDispatcher, @@ -346,6 +381,7 @@ export function CommandCenterRootActions() { shortcutPlatform, shortcutsAvailable, t, + toast, toggleAgentList, ]); diff --git a/packages/app/src/components/adaptive-modal-sheet.tsx b/packages/app/src/components/adaptive-modal-sheet.tsx index a20c4a1a47..193ef7ad31 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/combined-model-selector.tsx b/packages/app/src/components/combined-model-selector.tsx index 05b118b866..a6fb8c302a 100644 --- a/packages/app/src/components/combined-model-selector.tsx +++ b/packages/app/src/components/combined-model-selector.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { Pressable, Text, View, type PressableStateCallbackType } from "react-native"; import { useTranslation } from "react-i18next"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; @@ -19,7 +19,10 @@ import { type ToolbarGlyph, } from "@/components/ui/control-geometry"; +import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle"; + const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = []; +const DEFAULT_TRIGGER_DECORATION = { showCaret: true, tooltip: undefined }; const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); const foregroundMutedMapping = (theme: Theme) => ({ @@ -47,6 +50,7 @@ interface CombinedModelSelectorProps { hovered: boolean; pressed: boolean; }) => React.ReactNode; + toggleAction?: KeyboardToggleAction; onOpen?: () => void; onClose?: () => void; onRetryProvider?: (provider: AgentProvider) => void; @@ -67,6 +71,7 @@ interface CombinedModelSelectorProps { toolbar?: { glyph: ToolbarGlyph; showCaret: boolean; + tooltip?: ReactNode; }; } @@ -82,6 +87,7 @@ export function CombinedModelSelector({ onCreateProfile, onEditProfile, renderTrigger, + toggleAction, onOpen, onClose, onRetryProvider, @@ -147,6 +153,14 @@ export function CombinedModelSelector({ handleOpenChange(!isOpen); }, [handleOpenChange, isOpen]); + useKeyboardToggle({ + action: toggleAction, + disabled, + open: isOpen, + searchFocused: browser.isSearchFocused, + onToggle: handleTriggerPress, + }); + const triggerStyle = useCallback( ({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => { if (triggerFill) { @@ -216,6 +230,8 @@ export function CombinedModelSelector({ ); + const { showCaret, tooltip } = toolbar ?? DEFAULT_TRIGGER_DECORATION; + return ( <> {renderTrigger ? ( @@ -254,7 +270,8 @@ export function CombinedModelSelector({ model: browser.selectedModelLabel, })} testID="combined-model-selector" - chevron={toolbar?.showCaret === false ? null : undefined} + chevron={showCaret === false ? null : undefined} + tooltip={tooltip} > {selectedProvider.trim().length > 0 ? ( 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 0000000000..30867283c6 --- /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 3221539cec..dba07eb245 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 e0ed5b22a8..a1bd689517 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 e39e211bf1..aa35181a71 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 5dd454e048..56cb66b0ba 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 ced0be3d55..c8a7c0060c 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/markdown/fence/mermaid/runtime/html.gen.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts index 082c07321d..fc1cea90e7 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts @@ -1,4 +1,4 @@ // Generated by packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs. // Do not edit by hand. -export const mermaidRuntimeHtml = "\n\n \n \n \n \n \n \n \n
\n
\n \n \n"; +export const mermaidRuntimeHtml = "\n\n \n \n \n \n \n \n \n
\n
\n \n \n"; diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts index a9727900ff..f21b840649 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts @@ -215,6 +215,32 @@ describe("Mermaid sandbox runtime", () => { expect(widths).toEqual([240, 350, 900]); }); + /** + * Agents often write a label that starts with a mention or holds an email address. Mermaid 11 + * read the text up to the "@" as an edge id, so these diagrams failed to parse. + */ + it.each([ + "flowchart LR\n F[@mention in any workspace] --> G[Look up token]", + "flowchart LR\n A[ops@example.com] --> B", + "flowchart LR\n A -->|@user approves| B", + "graph TD\n A(@x) --> B{@x?}", + ])("renders a flowchart whose label contains an @: %s", async (source) => { + const frame = await mountRuntime(); + + const result = await render(frame, { revision: 1, source }); + + expect(result).toMatchObject({ type: "rendered", revision: 1, source }); + }); + + it("still renders a flowchart edge id", async () => { + const frame = await mountRuntime(); + const source = "flowchart LR\n A[Start] e1@--> B[End]"; + + const result = await render(frame, { revision: 1, source }); + + expect(result).toMatchObject({ type: "rendered", revision: 1, source }); + }); + it("coalesces queued input and never reports an obsolete result", async () => { const frame = await mountRuntime(); const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`; diff --git a/packages/app/src/components/markdown/images.test.tsx b/packages/app/src/components/markdown/images.test.tsx new file mode 100644 index 0000000000..0633e73fda --- /dev/null +++ b/packages/app/src/components/markdown/images.test.tsx @@ -0,0 +1,103 @@ +// @vitest-environment jsdom +import type { ReactNode } from "react"; +import { cleanup, renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, expect, it } from "vitest"; +import type { FileReadResult } from "@getpaseo/client/internal/daemon-client"; +import { __setAttachmentStoreForTests } from "@/attachments/store"; +import type { AttachmentStore } from "@/attachments/types"; +import { useMarkdownSource, type MarkdownImageContext } from "./images"; +import { PENDING_MARKDOWN_IMAGE } from "./source"; + +const memoryStore: AttachmentStore = { + storageType: "web-indexeddb", + async save(input) { + return { + id: input.id ?? "att_chart", + mimeType: input.mimeType ?? "image/png", + storageType: "web-indexeddb", + storageKey: input.id ?? "att_chart", + fileName: input.fileName, + createdAt: 1, + }; + }, + async encodeBase64() { + return ""; + }, + async resolvePreviewUrl() { + return "blob:chart"; + }, + async releasePreviewUrl() {}, + async delete() {}, + async garbageCollect() {}, +}; + +function createHostFiles() { + const reads: { cwd: string; path: string }[] = []; + return { + reads, + async readFile(cwd: string, path: string): Promise { + reads.push({ cwd, path }); + return { + kind: "image", + path, + mime: "image/png", + size: 4, + modifiedAt: "2026-11-18T00:00:00.000Z", + bytes: new Uint8Array([1, 2, 3, 4]), + }; + }, + }; +} + +beforeEach(() => { + __setAttachmentStoreForTests(memoryStore); +}); + +afterEach(() => { + cleanup(); + __setAttachmentStoreForTests(null); +}); + +function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) { + // No retries: a failed read settles at once. For a host's Markdown this is the state once the + // retries have run out on a host that is slow to connect. + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), { + wrapper, + initialProps, + }); + return { ...rendered, queryClient }; +} + +it("waits for the host's client before reading a workspace image", async () => { + const context = { serverId: "srv_test", workspaceRoot: "/repo" }; + const { result, rerender, queryClient } = renderMarkdownSource("![Chart](chart.png)", { + ...context, + client: null, + }); + + await waitFor(() => { + expect(queryClient.isFetching()).toBe(0); + expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe( + "![Chart]()", + ); + }); + + const files = createHostFiles(); + rerender({ ...context, client: files }); + + await waitFor(() => expect(result.current.imageSources).toEqual({ "blob:chart": "chart.png" })); + expect(files.reads).toEqual([{ cwd: "/repo", path: "chart.png" }]); +}); + +it("shows the alt text of a file image in Markdown that belongs to no host", async () => { + const { result } = renderMarkdownSource("![Chart](/tmp/chart.png)", {}); + + await waitFor(() => + expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"), + ); +}); diff --git a/packages/app/src/components/markdown/images.ts b/packages/app/src/components/markdown/images.ts index 5df2e18dc4..d816fa96b1 100644 --- a/packages/app/src/components/markdown/images.ts +++ b/packages/app/src/components/markdown/images.ts @@ -81,7 +81,10 @@ export function useMarkdownSource( const results = useFetchQueries( acquisitions.map((acquisition, index) => ({ queryKey: ["markdownImage", acquisition?.key ?? sources[index]], - enabled: acquisition !== null, + // A host that hasn't connected yet has no client. Its images stay pending until it does: the + // key doesn't change when the client arrives, so a read that already failed would not run + // again. Markdown with no host has no client to wait for and falls back to its alt text. + enabled: acquisition !== null && (context.client != null || !context.serverId), immutableWhen: () => true, dataShape: "value", gcTime: 0, diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index f119e55e97..99639fff42 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, @@ -11,8 +12,12 @@ import { } from "@/components/attachment-pill"; import { MarkdownRenderer } from "@/components/markdown/renderer"; import { useRetainedPanelActive } from "@/components/retained-panel"; -import { RewindMenu, type RewindMode } from "@/components/rewind/rewind-menu"; -import { useRewindAgentMutation } from "@/components/rewind/use-rewind-agent-mutation"; +import { + isRewindableMessage, + RewindMenu, + useRewindAgentMutation, + type RewindMode, +} from "@/components/rewind"; import { TaskListRow } from "@/components/task-list-row"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useIsCompactFormFactor } from "@/constants/layout"; @@ -32,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 { @@ -530,7 +539,7 @@ export const UserMessage = memo(function UserMessage({ {formattedTimestamp} - {capabilities && messageId ? ( + {capabilities && isRewindableMessage(messageId, message) ? ( Promise | void; + /** What the provider reported about the turn. Without any, the footer has no stats button. */ + metrics?: AgentMetric[]; } const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ @@ -592,6 +603,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%", @@ -613,6 +626,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ completedAt, durationMs, onFork, + metrics, }: AssistantTurnFooterProps) { const { t } = useTranslation(); const [hovered, setHovered] = useState(false); @@ -662,10 +676,11 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ [onFork], ); const canFork = Boolean(onFork); + const hasMetrics = metrics !== undefined && metrics.length > 0; return ( - {getContent || canFork ? ( + {getContent || canFork || hasMetrics ? ( {getContent ? ( ) : null} {canFork ? : null} + {hasMetrics ? : null} ) : null} {primaryLabel ? ( diff --git a/packages/app/src/components/metrics-list.tsx b/packages/app/src/components/metrics-list.tsx new file mode 100644 index 0000000000..90d0a40f4b --- /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 cf70d5c31d..3498e3e50c 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 b911f10553..0000000000 --- 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 904ba17e8b..0000000000 --- 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 0000000000..facb39b2a7 --- /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 0000000000..59373d9af5 --- /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 0000000000..957301a7d2 --- /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 f6ff75c74e..c717a2705c 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 0000000000..ad72471d4c --- /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/rewind/command-center-registration.tsx b/packages/app/src/components/rewind/command-center-registration.tsx new file mode 100644 index 0000000000..1e5a33ab2f --- /dev/null +++ b/packages/app/src/components/rewind/command-center-registration.tsx @@ -0,0 +1,91 @@ +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { Undo2 } from "lucide-react-native"; +import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types"; +import type { CommandCenterContribution } from "@/command-center/contributions"; +import { getCommandCenterIcon } from "@/command-center/icon"; +import { useCommandCenterActions } from "@/command-center/provider"; +import { hasActiveMessageSubmission } from "@/composer/submission/model"; +import { useToast } from "@/contexts/toast-context"; +import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine"; +import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store"; +import { useRewindAgentMutation } from "./use-rewind-agent-mutation"; +import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities"; + +export function RewindCommandCenterRegistration({ + serverId, + agentId, + capabilities, + timelineSync, + enabled, +}: { + serverId: string; + agentId: string; + capabilities: AgentCapabilityFlags | null | undefined; + timelineSync: AgentScreenReadySyncState | null; + enabled: boolean; +}) { + const { t } = useTranslation(); + const toast = useToast(); + const canSelectLatestMessage = enabled && timelineSync?.status === "idle"; + const client = useSessionStore((state) => state.sessions[serverId]?.client); + const message = useSessionStore((state) => { + const session = state.sessions[serverId]; + if ( + !canSelectLatestMessage || + !session || + hasActiveMessageSubmission(session.messageSubmissions.get(agentId)) + ) { + return undefined; + } + const timeline = selectAgentTimelineState(session, agentId); + if (timeline.status !== "synced" || timeline.newer === "available") { + return undefined; + } + return ( + session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ?? + timeline.items.findLast((item) => item.kind === "user_message") + ); + }); + const { rewindAgent, isPending } = useRewindAgentMutation({ + serverId, + agentId, + client, + messageId: message?.messageId, + }); + const items = useRewindMenuItems(capabilities); + const actions = useMemo(() => { + if (!message || !isRewindableMessage(message.messageId, message.text)) return []; + return items.map((item, rank) => ({ + id: `rewind:${item.mode}`, + group: "rewind", + groupRank: 1.5, + rank, + visibility: "query", + keywords: ["rewind last turn", ...(item.mode === "files" ? [] : ["rewind chat"])], + presentation: { + kind: "action", + title: item.label, + subtitle: t("rewind.warning"), + icon: getCommandCenterIcon(Undo2), + }, + run: async () => { + const dismiss = toast.show(`${item.label}…`, { durationMs: null }); + try { + await rewindAgent({ mode: item.mode, rewoundText: message.text }); + } catch { + // The mutation reports the failure through the app toast. + } finally { + dismiss(); + } + }, + })); + }, [items, message, rewindAgent, t, toast]); + + useCommandCenterActions({ + sourceId: `rewind:${serverId}:${agentId}`, + enabled: canSelectLatestMessage && Boolean(client) && !isPending, + actions, + }); + return null; +} diff --git a/packages/app/src/components/rewind/composer-restore.tsx b/packages/app/src/components/rewind/composer-restore.tsx index 07e645d225..cdded3c4c8 100644 --- a/packages/app/src/components/rewind/composer-restore.tsx +++ b/packages/app/src/components/rewind/composer-restore.tsx @@ -8,7 +8,7 @@ interface RewindComposerRestoreContextValue { interface RewindComposerRestoreProviderProps { textSource: ComposerTextSource; setText: (text: string) => void; - onRewindComplete: () => void; + onRewindComplete: (restoredComposerText: boolean) => void; children: ReactNode; } @@ -37,10 +37,11 @@ export function RewindComposerRestoreProvider({ currentText: currentText, rewoundText, }); - if (nextText !== currentText) { + const restoredComposerText = nextText !== currentText; + if (restoredComposerText) { setText(nextText); } - onRewindComplete(); + onRewindComplete(restoredComposerText); }, [onRewindComplete, setText, textSource], ); diff --git a/packages/app/src/components/rewind/index.ts b/packages/app/src/components/rewind/index.ts new file mode 100644 index 0000000000..0cf69aa966 --- /dev/null +++ b/packages/app/src/components/rewind/index.ts @@ -0,0 +1,5 @@ +export { RewindCommandCenterRegistration } from "./command-center-registration"; +export { RewindComposerRestoreProvider } from "./composer-restore"; +export { RewindMenu } from "./rewind-menu"; +export { useRewindAgentMutation } from "./use-rewind-agent-mutation"; +export { isRewindableMessage, type RewindMode } from "./use-rewind-capabilities"; diff --git a/packages/app/src/components/rewind/rewind-menu.tsx b/packages/app/src/components/rewind/rewind-menu.tsx index ca13d0ad2d..7d500123c5 100644 --- a/packages/app/src/components/rewind/rewind-menu.tsx +++ b/packages/app/src/components/rewind/rewind-menu.tsx @@ -11,11 +11,9 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -import { type RewindMode, useRewindCapabilities } from "./use-rewind-capabilities"; +import { type RewindMode, useRewindMenuItems } from "./use-rewind-capabilities"; import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types"; -export type { RewindMode }; - interface RewindMenuProps { capabilities: AgentCapabilityFlags; rewoundText: string; @@ -44,15 +42,7 @@ export const RewindMenu = memo(function RewindMenu({ }: RewindMenuProps) { const { theme } = useUnistyles(); const { t } = useTranslation(); - const rewindLabels = useMemo( - () => ({ - conversation: t("rewind.actions.conversation"), - files: t("rewind.actions.files"), - both: t("rewind.actions.both"), - }), - [t], - ); - const items = useRewindCapabilities(capabilities, rewindLabels); + const items = useRewindMenuItems(capabilities); const [isOpen, setIsOpen] = useState(false); const [pendingMode, setPendingMode] = useState(null); const isLocked = isPendingProp || pendingMode !== null; diff --git a/packages/app/src/components/rewind/use-rewind-agent-mutation.ts b/packages/app/src/components/rewind/use-rewind-agent-mutation.ts index c8a8aa040c..ca754a2b9c 100644 --- a/packages/app/src/components/rewind/use-rewind-agent-mutation.ts +++ b/packages/app/src/components/rewind/use-rewind-agent-mutation.ts @@ -1,7 +1,7 @@ import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; -import { useCallback } from "react"; +import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { useMutation } from "@tanstack/react-query"; +import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query"; import { useToast } from "@/contexts/toast-context"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import type { RewindMode } from "./use-rewind-capabilities"; @@ -30,7 +30,14 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): { const toast = useToast(); const { t } = useTranslation(); const composerRestore = useRewindComposerRestore(); - const { isPending, mutateAsync } = useMutation({ + const queryClient = useQueryClient(); + const mutationKey = useMemo( + () => ["agent-rewind", input.serverId, input.agentId], + [input.serverId, input.agentId], + ); + const isPending = useIsMutating({ mutationKey, exact: true }) > 0; + const { mutateAsync } = useMutation({ + mutationKey, mutationFn: async ({ mode }: RewindAgentInput) => { if (!input.client || !input.agentId || !input.messageId) { throw new Error(t("common.errors.daemonClientUnavailable")); @@ -71,12 +78,12 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): { const rewindAgent = useCallback( async (rewindInput: RewindAgentInput) => { - if (isPending) { + if (queryClient.isMutating({ mutationKey, exact: true }) > 0) { return; } await mutateAsync(rewindInput); }, - [isPending, mutateAsync], + [mutateAsync, mutationKey, queryClient], ); return { diff --git a/packages/app/src/components/rewind/use-rewind-capabilities.ts b/packages/app/src/components/rewind/use-rewind-capabilities.ts index d125bfce37..0249335a03 100644 --- a/packages/app/src/components/rewind/use-rewind-capabilities.ts +++ b/packages/app/src/components/rewind/use-rewind-capabilities.ts @@ -1,4 +1,5 @@ import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types"; export type RewindMode = "conversation" | "files" | "both"; @@ -21,6 +22,10 @@ const DEFAULT_REWIND_MENU_LABELS: RewindMenuLabels = { both: "Rewind conversation and files", }; +export function isRewindableMessage(messageId: string | undefined, text: string): boolean { + return Boolean(messageId) && text.trim().length > 0; +} + export function resolveRewindMenuItems( capabilities: | Pick< @@ -60,9 +65,17 @@ export function resolveRewindMenuItems( return items; } -export function useRewindCapabilities( +export function useRewindMenuItems( capabilities: Parameters[0], - labels?: Partial, ): RewindMenuItem[] { - return useMemo(() => resolveRewindMenuItems(capabilities, labels), [capabilities, labels]); + const { t } = useTranslation(); + return useMemo( + () => + resolveRewindMenuItems(capabilities, { + conversation: t("rewind.actions.conversation"), + files: t("rewind.actions.files"), + both: t("rewind.actions.both"), + }), + [capabilities, t], + ); } diff --git a/packages/app/src/components/schedules/schedule-form-sheet.tsx b/packages/app/src/components/schedules/schedule-form-sheet.tsx index f66e70b520..3d12599350 100644 --- a/packages/app/src/components/schedules/schedule-form-sheet.tsx +++ b/packages/app/src/components/schedules/schedule-form-sheet.tsx @@ -825,20 +825,22 @@ function ScheduleIsolationField({ { id: "local", value: "local", - label: "Local", + label: "Project directory", testID: "schedule-isolation-local", }, { id: "worktree", value: "worktree", - label: "Worktree", + label: "New worktree", testID: "schedule-isolation-worktree", }, ], [], ); const selectedDisplay = useMemo( - () => ({ label: state.effectiveIsolation === "worktree" ? "Worktree" : "Local" }), + () => ({ + label: state.effectiveIsolation === "worktree" ? "New worktree" : "Project directory", + }), [state.effectiveIsolation], ); const triggerLeading = useMemo( 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 0000000000..41bf0d11b9 --- /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 0000000000..47508ad77f --- /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 0838d06ca4..a1d96c79b6 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 0000000000..20654b750b --- /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 e13bc6017a..a9018d2368 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 d651a47825..f393a50423 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 567becfd01..f8153b0ff2 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 d2742e3172..cbe24e0a60 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 + + + ) : null} - {fullscreen ? null : toolbar} + {/* Keep the agent controls mounted for composer commands in fullscreen. */} + {toolbar} {fullscreen ? ( diff --git a/packages/app/src/composer/keyboard-scope.tsx b/packages/app/src/composer/keyboard-scope.tsx index f8087bf420..b56b54985e 100644 --- a/packages/app/src/composer/keyboard-scope.tsx +++ b/packages/app/src/composer/keyboard-scope.tsx @@ -18,21 +18,25 @@ interface ComposerKeyboardScopeValue { * pane, which does not take pane focus. */ isActiveComposer: boolean; + /** The composer whose settings appear in Command Center. */ + isCommandCenterTarget: boolean; } const ComposerKeyboardScopeContext = createContext({ isPaneFocused: false, isActiveComposer: false, + isCommandCenterTarget: false, }); export function ComposerKeyboardScopeProvider({ isPaneFocused, isActiveComposer, + isCommandCenterTarget, children, }: PropsWithChildren): ReactElement { const value = useMemo( - () => ({ isPaneFocused, isActiveComposer }), - [isPaneFocused, isActiveComposer], + () => ({ isPaneFocused, isActiveComposer, isCommandCenterTarget }), + [isPaneFocused, isActiveComposer, isCommandCenterTarget], ); return ( diff --git a/packages/app/src/composer/session.tsx b/packages/app/src/composer/session.tsx index cb46f2b3dd..491f66d524 100644 --- a/packages/app/src/composer/session.tsx +++ b/packages/app/src/composer/session.tsx @@ -25,6 +25,7 @@ export interface ComposerInput { */ revealed: boolean; isRevealed: () => boolean; + isFocused: () => boolean; focus: (options?: ComposerFocusOptions) => Promise; textSource: ComposerTextSource; setText: (text: string) => void; diff --git a/packages/app/src/composer/tracks.tsx b/packages/app/src/composer/tracks.tsx index 44906333d8..7ae42e8122 100644 --- a/packages/app/src/composer/tracks.tsx +++ b/packages/app/src/composer/tracks.tsx @@ -21,6 +21,7 @@ import { useHorizontalScrollBoundary, } from "@/components/ui/horizontal-scroll-boundary"; import { STATUS_RING_HALO_INSET } from "@/components/status-ring/geometry"; +import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail"; import { isWeb } from "@/constants/platform"; import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures"; import { getStatusDotColor } from "@/utils/status-dot-color"; @@ -45,7 +46,7 @@ export function ComposerTrackBar({ children }: { children: ReactNode }): ReactEl const scrollGesture = usePanelAwareHorizontalScrollGesture(); const scrollBoundary = useHorizontalScrollBoundary(); return ( - + { - console.error("[VoiceEngine] Capture error:", error); - }, }); runtime = createVoiceRuntime({ diff --git a/packages/app/src/data/acp-provider-catalog.ts b/packages/app/src/data/acp-provider-catalog.ts index bfa7ffe3cf..23c388e5b8 100644 --- a/packages/app/src/data/acp-provider-catalog.ts +++ b/packages/app/src/data/acp-provider-catalog.ts @@ -224,6 +224,7 @@ const CATALOG_DATA = [ }, { id: "goose", + bundledProvider: { hostFeature: "gooseProvider" }, title: "goose", description: "A local, extensible, open source AI agent that automates engineering tasks", version: "1.33.1", @@ -243,6 +244,7 @@ const CATALOG_DATA = [ }, { id: "hermes", + bundledProvider: { hostFeature: "hermesProvider" }, title: "Hermes", description: "Nous Research self-improving AI agent", version: "manual", diff --git a/packages/app/src/data/provider-snapshot-cache.test.ts b/packages/app/src/data/provider-snapshot-cache.test.ts index 424657e3fa..aee5f22516 100644 --- a/packages/app/src/data/provider-snapshot-cache.test.ts +++ b/packages/app/src/data/provider-snapshot-cache.test.ts @@ -637,7 +637,7 @@ it("stores and expands identical content once across directory associations", as }); it("coalesces missing bodies and keeps a newer pushed association when an older pull completes", async () => { - const { QueryClient } = await import("@tanstack/react-query"); + const { QueryClient, QueryObserver } = await import("@tanstack/react-query"); const { applyProvidersSnapshotUpdate } = await import("./push-router"); const { fetchProvidersSnapshot, providersSnapshotQueryKey } = await import("./providers-snapshot"); @@ -653,6 +653,16 @@ it("coalesces missing bodies and keeps a newer pushed association when an older fetchedAt: { pi: fetchedAt }, requestId: hash, }); + // Announcements only download for directories a screen is showing. + const unsubscribers = ["/a", "/b", "/c"].map((cwd) => { + const queryKey = providersSnapshotQueryKey(serverId, cwd); + queryClient.setQueryData(queryKey, snapshot("seed")); + return new QueryObserver(queryClient, { + queryKey, + queryFn: async () => snapshot("seed"), + staleTime: Infinity, + }).subscribe(() => {}); + }); let transfers = 0; const client = { async getProvidersSnapshot() { @@ -776,6 +786,7 @@ it("coalesces missing bodies and keeps a newer pushed association when an older entries: [{ models: [{ id: "shared" }] }], }); } finally { + for (const unsubscribe of unsubscribers) unsubscribe(); queryClient.clear(); } }); diff --git a/packages/app/src/data/providers-snapshot.test.ts b/packages/app/src/data/providers-snapshot.test.ts index c69eff9225..dca3dff406 100644 --- a/packages/app/src/data/providers-snapshot.test.ts +++ b/packages/app/src/data/providers-snapshot.test.ts @@ -1,5 +1,5 @@ import { createRequire } from "node:module"; -import { QueryClient, CancelledError } from "@tanstack/react-query"; +import { QueryClient, CancelledError, QueryObserver } from "@tanstack/react-query"; import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; import type { GetProvidersSnapshotResponseMessage } from "@getpaseo/protocol/messages"; import { compactProviderSnapshot } from "@getpaseo/protocol/provider-snapshot-codec"; @@ -307,6 +307,14 @@ describe("provider snapshot publication identity", () => { snapshotHash: "next-hash", compactSnapshot: compactProviderSnapshot([{ ...entries[0]!, label: "Updated provider" }]), }; + // Announcements only publish into a directory a screen is showing. + const shownKey = providersSnapshotQueryKey(serverId, snapshot.cwd); + queryClient.setQueryData(shownKey, snapshot); + const unsubscribe = new QueryObserver(queryClient, { + queryKey: shownKey, + queryFn: async () => snapshot, + staleTime: Infinity, + }).subscribe(() => {}); try { for (const body of [snapshot, changed, changed]) { await applyProvidersSnapshotUpdate({ @@ -325,6 +333,7 @@ describe("provider snapshot publication identity", () => { expect(published.entries[0]!.models).toBe(canonical.entries[0]!.models); } } finally { + unsubscribe(); queryClient.clear(); } }); diff --git a/packages/app/src/data/push-router.test.ts b/packages/app/src/data/push-router.test.ts index cf5a4d5af6..00493d9aa4 100644 --- a/packages/app/src/data/push-router.test.ts +++ b/packages/app/src/data/push-router.test.ts @@ -8,8 +8,12 @@ import { checkoutDiffQueryKey } from "@/git/query-keys"; import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state"; import { daemonConfigQueryKey } from "@/data/daemon-config"; import { daemonPairingOfferQueryKey } from "@/data/daemon-pairing"; -import { providersSnapshotQueryKey } from "@/data/providers-snapshot"; +import { providersSnapshotQuery, providersSnapshotQueryKey } from "@/data/providers-snapshot"; +import { replicaQueryOptions } from "@/data/query"; +import { createProviderSnapshotCache } from "@/data/provider-snapshot-cache"; +import { draftAgentCommandsQueryKey } from "@/agent-commands/cache"; import { + applyProvidersSnapshotUpdate, checkoutDiffPushRoute, invalidateServerDataQueriesAfterReconnect, mountServerDataPushRouter, @@ -594,6 +598,13 @@ describe("server data push router", () => { const serverId = "server-1"; const pairingOfferKey = daemonPairingOfferQueryKey(serverId); queryClient.setQueryData(pairingOfferKey, { relayEnabled: true, url: "https://pairing" }); + const snapshotKey = providersSnapshotQueryKey(serverId); + queryClient.setQueryData(snapshotKey, { entries: [], generatedAt: "seed", requestId: "seed" }); + const unsubscribeSnapshot = new QueryObserver(queryClient, { + queryKey: snapshotKey, + queryFn: async () => ({ entries: [], generatedAt: "seed", requestId: "seed" }), + staleTime: Infinity, + }).subscribe(() => undefined); const unmount = mountServerDataPushRouter({ client: fake.client, queryClient, serverId }); fake.emit(providerUpdate("2026-01-01T00:00:00.000Z")); @@ -622,6 +633,7 @@ describe("server data push router", () => { generatedAt: "2026-01-01T00:00:00.000Z", requestId: "providers_snapshot_update", }); + unsubscribeSnapshot(); }); it.each(["base", "all"] as const)("routes %s diff snapshots and updates", (mode) => { @@ -982,3 +994,158 @@ describe("server data push router", () => { expect(queryClient.getQueryState(otherProviderKey)?.isInvalidated).toBe(false); }); }); + +describe("applyProvidersSnapshotUpdate by observation", () => { + const serverId = "observed-host"; + const cwd = "/repo"; + + function createStorage() { + const values = new Map(); + return { + values, + async getItem(key: string) { + return values.get(key) ?? null; + }, + async setItem(key: string, value: string) { + values.set(key, value); + }, + async removeItem(key: string) { + values.delete(key); + }, + async getAllKeys() { + return [...values.keys()]; + }, + async multiGet(keys: readonly string[]) { + return keys.map((key) => [key, values.get(key) ?? null] as const); + }, + async multiRemove(keys: readonly string[]) { + for (const key of keys) values.delete(key); + }, + }; + } + + function snapshotFor(label: string) { + return { + requestId: label, + cwd, + entries: [ + { + provider: "codex", + status: "ready", + enabled: true, + label, + models: [{ provider: "codex", id: label, label, thinkingOptions: [] }], + }, + ], + generatedAt: "2026-01-01T00:00:00.000Z", + } as never; + } + + function setup() { + const storage = createStorage(); + const cache = createProviderSnapshotCache(storage); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const calls: unknown[] = []; + let current = "v1"; + const client = { + async getProvidersSnapshot(options?: unknown) { + calls.push(options); + return snapshotFor(current); + }, + }; + const observe = () => + new QueryObserver( + queryClient, + replicaQueryOptions( + providersSnapshotQuery({ serverId, cwd, client: () => client, queryClient, cache }), + ), + ); + const announce = () => + applyProvidersSnapshotUpdate({ + serverId, + queryClient, + cache, + client, + message: { + type: "providers_snapshot_update", + payload: { + cwd, + entries: [], + snapshotHash: "hash-v2", + generatedAt: "2026-01-01T00:00:01Z", + }, + } as never, + }); + return { + queryClient, + calls, + storage, + observe, + announce, + setCurrent: (value: string) => { + current = value; + }, + }; + } + + it("does nothing for a directory this client never opened", async () => { + const { queryClient, calls, storage, announce } = setup(); + + await announce(); + + expect(calls).toEqual([]); + expect( + queryClient.getQueryCache().find({ queryKey: providersSnapshotQueryKey(serverId, cwd) }), + ).toBeUndefined(); + expect(storage.values.size).toBe(0); + queryClient.clear(); + }); + + it("marks an unobserved cached directory stale without downloading and refetches it on mount", async () => { + const { queryClient, calls, observe, announce, setCurrent } = setup(); + const queryKey = providersSnapshotQueryKey(serverId, cwd); + const commandsKey = draftAgentCommandsQueryKey({ + serverId, + draftConfig: { provider: "codex", cwd }, + }); + queryClient.setQueryData(queryKey, snapshotFor("v1")); + queryClient.setQueryData(commandsKey, [{ name: "review" }]); + setCurrent("v2"); + + await announce(); + + expect(calls).toEqual([]); + expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true); + expect(queryClient.getQueryState(commandsKey)?.isInvalidated).toBe(true); + + const observer = observe(); + const unsubscribe = observer.subscribe(() => {}); + await queryClient.getQueryCache().find({ queryKey })?.promise; + + expect(calls).toHaveLength(1); + expect( + (queryClient.getQueryData(queryKey) as { entries: Array<{ label: string }> }).entries[0]! + .label, + ).toBe("v2"); + unsubscribe(); + queryClient.clear(); + }); + + it("keeps the reference-aware fetch for an observed directory", async () => { + const { queryClient, calls, observe, announce } = setup(); + const queryKey = providersSnapshotQueryKey(serverId, cwd); + const observer = observe(); + const unsubscribe = observer.subscribe(() => {}); + await queryClient.getQueryCache().find({ queryKey })?.promise; + expect(calls).toHaveLength(1); + + await announce(); + + // The announced hash is not resident, so exactly one content transfer is fetched and + // published to the observed query. + expect(calls).toHaveLength(2); + expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false); + unsubscribe(); + queryClient.clear(); + }); +}); diff --git a/packages/app/src/data/push-router.ts b/packages/app/src/data/push-router.ts index 5e51ded0d4..45d305616a 100644 --- a/packages/app/src/data/push-router.ts +++ b/packages/app/src/data/push-router.ts @@ -8,7 +8,10 @@ import type { MutableDaemonConfig, SessionOutboundMessage, } from "@getpaseo/protocol/messages"; -import { invalidateCommandsForProviderChange } from "@/agent-commands/cache"; +import { + invalidateCommandsForDirectory, + invalidateCommandsForProviderChange, +} from "@/agent-commands/cache"; import { shareCheckoutDiff } from "@/git/diff-sharing"; import { orderCheckoutDiffFiles } from "@/git/diff-order"; import { daemonConfigQueryKey } from "@/data/daemon-config"; @@ -184,6 +187,20 @@ export async function applyProvidersSnapshotUpdate(input: { const snapshot = { ...input.message.payload, requestId: "providers_snapshot_update" }; const cwd = normalizeProvidersSnapshotCwd(snapshot.cwd); const queryKey = providersSnapshotQueryKey(input.serverId, cwd); + const cached = input.queryClient.getQueryCache().find({ queryKey, exact: true }); + // Only a screen showing this directory is worth a download. A cached but unobserved + // directory refetches on its next mount; one this client never opened needs nothing. + if (!cached) return; + if (!cached.isActive()) { + await input.queryClient.cancelQueries({ queryKey, exact: true }); + await input.queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "none" }); + await invalidateCommandsForDirectory({ + queryClient: input.queryClient, + serverId: input.serverId, + cwd, + }); + return; + } const previous = input.queryClient.getQueryData<{ entries: ProviderSnapshotEntry[] }>(queryKey); let announcement: typeof snapshot | undefined = snapshot; void input.queryClient.cancelQueries({ queryKey, exact: true }); diff --git a/packages/app/src/data/query.test.ts b/packages/app/src/data/query.test.ts new file mode 100644 index 0000000000..eab4a2f9c3 --- /dev/null +++ b/packages/app/src/data/query.test.ts @@ -0,0 +1,50 @@ +import { QueryClient, QueryObserver } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import { replicaQueryOptions } from "./query"; + +function setup() { + const queryClient = new QueryClient(); + const queryKey = ["replica", "value"] as const; + let fetches = 0; + const options = replicaQueryOptions({ + queryKey, + pushEvent: "value_update", + queryFn: async () => { + fetches++; + return `fetch-${fetches}`; + }, + }); + return { queryClient, queryKey, options, fetchCount: () => fetches }; +} + +describe("replicaQueryOptions mount behavior", () => { + it("does not refetch on mount while the cached value is not invalidated", async () => { + const { queryClient, queryKey, options, fetchCount } = setup(); + queryClient.setQueryData(queryKey, "cached"); + + const observer = new QueryObserver(queryClient, options); + const unsubscribe = observer.subscribe(() => {}); + await Promise.resolve(); + + expect(fetchCount()).toBe(0); + expect(observer.getCurrentResult().data).toBe("cached"); + unsubscribe(); + queryClient.clear(); + }); + + it("refetches on mount when the cached value was invalidated while unobserved", async () => { + const { queryClient, queryKey, options, fetchCount } = setup(); + queryClient.setQueryData(queryKey, "cached"); + await queryClient.invalidateQueries({ queryKey, refetchType: "none" }); + expect(fetchCount()).toBe(0); + + const observer = new QueryObserver(queryClient, options); + const unsubscribe = observer.subscribe(() => {}); + await queryClient.getQueryCache().find({ queryKey })?.promise; + + expect(fetchCount()).toBe(1); + expect(observer.getCurrentResult().data).toBe("fetch-1"); + unsubscribe(); + queryClient.clear(); + }); +}); diff --git a/packages/app/src/data/query.ts b/packages/app/src/data/query.ts index 07f7a622ee..1ee22eab0a 100644 --- a/packages/app/src/data/query.ts +++ b/packages/app/src/data/query.ts @@ -86,7 +86,9 @@ export function replicaQueryOptions< }, }, queryFn: options.queryFn ?? skipToken, - refetchOnMount: false, + // Pushes keep a replica fresh; a mount only refetches what an invalidation marked stale + // while nothing observed it. + refetchOnMount: (query) => query.state.isInvalidated, refetchOnReconnect: false, refetchOnWindowFocus: false, staleTime: Infinity, diff --git a/packages/app/src/desktop/browser/automation/handler.ts b/packages/app/src/desktop/browser/automation/handler.ts index 08bb9927e5..e566d89767 100644 --- a/packages/app/src/desktop/browser/automation/handler.ts +++ b/packages/app/src/desktop/browser/automation/handler.ts @@ -1,4 +1,5 @@ import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas"; +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages"; import { getDesktopHost, type DesktopHostBridge } from "@/desktop/host"; import { @@ -26,6 +27,7 @@ type BrowserAutomationExecuteResponse = Extract< type BrowserAutomationResponsePayload = BrowserAutomationExecuteResponse["payload"]; type BrowserAutomationFailurePayload = Extract; type BrowserAutomationErrorCode = BrowserAutomationFailurePayload["error"]["code"]; +type BrowserHostRegistration = Parameters[0]; interface BrowserAutomationClient { on( @@ -69,14 +71,24 @@ export function mountBrowserAutomationHandler( }; } +export function getDesktopBrowserHostRegistration(): BrowserHostRegistration | null { + const desktop = getDesktopHost(); + if (typeof desktop?.browser?.executeAutomationCommand !== "function") return null; + + return { + hostKind: "desktop app", + label: desktop.browserHostLabel, + instanceId: desktop.browserHostInstanceId, + supportedCommands: [...BROWSER_AUTOMATION_COMMAND_NAMES], + }; +} + export function mountBrowserAutomationDaemonClientHandler( - client: import("@getpaseo/client/internal/daemon-client").DaemonClient, + client: DaemonClient, + registration: BrowserHostRegistration, options?: { serverId?: string }, ): () => void { - const observation = client.registerBrowserHost({ - hostKind: "desktop app", - supportedCommands: [...BROWSER_AUTOMATION_COMMAND_NAMES], - }); + const observation = client.registerBrowserHost(registration); const unmount = mountBrowserAutomationHandler({ client: { on: (_type, handler) => diff --git a/packages/app/src/desktop/host.ts b/packages/app/src/desktop/host.ts index 2541da9f79..71a8489469 100644 --- a/packages/app/src/desktop/host.ts +++ b/packages/app/src/desktop/host.ts @@ -175,6 +175,8 @@ export interface DesktopInvokeBridge { export interface DesktopHostBridge { platform?: string; windowChromeMode?: string; + browserHostLabel?: string; + browserHostInstanceId?: string; invoke?: DesktopInvokeBridge["invoke"]; getPendingOpenProject?: () => Promise; agentNavigation?: DesktopAgentNavigationBridge; diff --git a/packages/app/src/file-panels/html-preview-navigation-guard.test.tsx b/packages/app/src/file-panels/html-preview-navigation-guard.test.tsx new file mode 100644 index 0000000000..d9e03ad658 --- /dev/null +++ b/packages/app/src/file-panels/html-preview-navigation-guard.test.tsx @@ -0,0 +1,48 @@ +// @vitest-environment jsdom + +import { renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { describe, expect, it } from "vitest"; +import { RetainedPanelActivity } from "@/components/retained-panel"; +import { useHtmlPreviewNavigationGuard } from "./html-preview-navigation"; + +const DOCUMENT = "report"; + +function renderGuard(initialActive: boolean) { + let active = initialActive; + const view = renderHook(() => useHtmlPreviewNavigationGuard(DOCUMENT), { + wrapper: ({ children }: { children: ReactNode }) => ( + {children} + ), + }); + return { + navigate: (url: string) => view.result.current({ url }), + setActive(next: boolean) { + active = next; + view.rerender(); + }, + }; +} + +describe("useHtmlPreviewNavigationGuard", () => { + it("loads the document once and refuses the page loading it again", () => { + const guard = renderGuard(true); + + expect(guard.navigate("about:blank")).toBe(true); + expect(guard.navigate("about:blank")).toBe(false); + expect(guard.navigate("https://example.com/leak")).toBe(false); + expect(guard.navigate("about:blank#section")).toBe(true); + }); + + it("loads the document again in the WebView that shows after the panel was hidden", () => { + const guard = renderGuard(true); + expect(guard.navigate("about:blank")).toBe(true); + + // iOS destroys the native WebView of a hidden panel and makes a new one when it shows. + guard.setActive(false); + guard.setActive(true); + + expect(guard.navigate("about:blank")).toBe(true); + expect(guard.navigate("about:blank")).toBe(false); + }); +}); diff --git a/packages/app/src/file-panels/html-preview-navigation.ts b/packages/app/src/file-panels/html-preview-navigation.ts index fafd4e5793..151dd1657f 100644 --- a/packages/app/src/file-panels/html-preview-navigation.ts +++ b/packages/app/src/file-panels/html-preview-navigation.ts @@ -1,3 +1,6 @@ +import { useCallback, useEffect, useRef } from "react"; +import { useRetainedPanelActive } from "@/components/retained-panel"; + export type HtmlPreviewNavigationKind = "initialDocument" | "fragment" | "blocked"; const INITIAL_DOCUMENT_URLS = new Set(["about:blank", "about:srcdoc", ""]); @@ -7,3 +10,35 @@ export function htmlPreviewNavigationKind(url: string): HtmlPreviewNavigationKin if (url.startsWith("about:blank#") || url.startsWith("about:srcdoc#")) return "fragment"; return "blocked"; } + +/** + * Decides each navigation the native WebView asks about: the document loads once, a fragment + * moves within it, and anything else is refused. + */ +export function useHtmlPreviewNavigationGuard( + document: string, +): (request: { url: string }) => boolean { + // Latched per document rather than once for the lifetime of the WebView: the + // file pane re-renders with new content on every live-file refresh, and each of + // those is a fresh initial load that has to be allowed through. + const loadedDocumentRef = useRef(null); + // The latch belongs to one native WebView, not to this component. iOS destroys the WebView of a + // hidden retained panel and makes a new one when the panel shows, and that one loads the + // document again. Releasing the latch while hidden lets that load through; a page on a kept + // WebView gains at most a load of an inert initial URL. + const active = useRetainedPanelActive(); + useEffect(() => { + if (!active) loadedDocumentRef.current = null; + }, [active]); + return useCallback( + ({ url }: { url: string }) => { + const navigationKind = htmlPreviewNavigationKind(url); + if (navigationKind === "fragment") return true; + if (navigationKind === "blocked") return false; + if (loadedDocumentRef.current === document) return false; + loadedDocumentRef.current = document; + return true; + }, + [document], + ); +} diff --git a/packages/app/src/file-panels/html-preview.tsx b/packages/app/src/file-panels/html-preview.tsx index 08ded111e7..752a048390 100644 --- a/packages/app/src/file-panels/html-preview.tsx +++ b/packages/app/src/file-panels/html-preview.tsx @@ -1,8 +1,8 @@ -import { useCallback, useMemo, useRef } from "react"; +import { useMemo } from "react"; import { StyleSheet } from "react-native-unistyles"; import { WebView } from "react-native-webview"; import { withPreviewCsp } from "./html-preview-csp"; -import { htmlPreviewNavigationKind } from "./html-preview-navigation"; +import { useHtmlPreviewNavigationGuard } from "./html-preview-navigation"; // A preview is a viewer, not a browser. Only the document Paseo hands the WebView // loads; navigations the page attempts afterwards are refused, so a link, a @@ -35,21 +35,7 @@ const BASE_URL = "about:blank"; export function FileHtmlPreview({ html, testID }: { html: string; testID?: string }) { const document = useMemo(() => withPreviewCsp(html), [html]); const source = useMemo(() => ({ html: document, baseUrl: BASE_URL }), [document]); - // Latched per document rather than once for the lifetime of the WebView: the - // file pane re-renders with new content on every live-file refresh, and each of - // those is a fresh initial load that has to be allowed through. - const loadedDocumentRef = useRef(null); - const allowOnlyInitialDocument = useCallback( - ({ url }: { url: string }) => { - const navigationKind = htmlPreviewNavigationKind(url); - if (navigationKind === "fragment") return true; - if (navigationKind === "blocked") return false; - if (loadedDocumentRef.current === document) return false; - loadedDocumentRef.current = document; - return true; - }, - [document], - ); + const allowOnlyInitialDocument = useHtmlPreviewNavigationGuard(document); return ( { + it("loads a changed document in a new frame", () => { + const view = render(); + const firstFrame = view.getByTestId("preview"); + + view.rerender(); + const changedFrame = view.getByTestId("preview"); + + expect(changedFrame).not.toBe(firstFrame); + expect(decodeURIComponent(changedFrame.getAttribute("src") ?? "")).toContain("Changed plan"); + }); +}); diff --git a/packages/app/src/file-panels/html-preview.web.tsx b/packages/app/src/file-panels/html-preview.web.tsx index eac275bfe8..fc56a4038b 100644 --- a/packages/app/src/file-panels/html-preview.web.tsx +++ b/packages/app/src/file-panels/html-preview.web.tsx @@ -32,7 +32,11 @@ export function FileHtmlPreview({ html, testID }: { html: string; testID?: strin [html], ); return ( + // Each document loads in a new frame. The Source view keeps this preview mounted and hidden, + // and it gets a changed document in the same render that shows it again. Chromium can leave a + // reused frame blank when it navigates at that moment.